diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e9cd798..4779a4e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,12 @@ # CONTRIBUTING +## PRE-COMMIT + +**RUN BEFORE COMMIT** +``` +pre-commit install +``` + ## WORKFLOW 1. Create your **proposal/bug** in an _issue_. diff --git a/main.py b/main.py new file mode 100644 index 0000000..4780450 --- /dev/null +++ b/main.py @@ -0,0 +1,8 @@ +""" +Testing Merkle Tree +""" + +from merkly.accelerator.mtreers import MTreers + +treers = MTreers() +treers.make_root() diff --git a/merkly/accelerator/build.sh b/merkly/accelerator/build.sh new file mode 100755 index 0000000..3fa42c0 --- /dev/null +++ b/merkly/accelerator/build.sh @@ -0,0 +1 @@ +rustc --crate-type cdylib libmerkle_root.rs -o libmerkle_root.dylib diff --git a/merkly/accelerator/libmerkle_root.dylib b/merkly/accelerator/libmerkle_root.dylib new file mode 100755 index 0000000..8988aa1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root.dylib differ diff --git a/merkly/accelerator/libmerkle_root.rs b/merkly/accelerator/libmerkle_root.rs new file mode 100644 index 0000000..40fbdfb --- /dev/null +++ b/merkly/accelerator/libmerkle_root.rs @@ -0,0 +1,48 @@ +use std::slice; + +/// # Safety +/// +#[no_mangle] +pub unsafe extern "C" fn free_32(ptr: *mut u8) { + unsafe { + let _ = Box::from_raw(slice::from_raw_parts_mut(ptr, 32)); + } +} + +/// # Safety +/// +#[no_mangle] +pub unsafe extern "C" fn make_root( + callback: extern "C" fn(input: *const u8, output: *mut u8), + leafs_ptr: *const *const u8, + len: usize, +) -> *mut u8 { + let leafs = unsafe { slice::from_raw_parts(leafs_ptr, len) } + .iter() + .map(|&ptr| unsafe { Vec::from(slice::from_raw_parts(ptr, 1)) }) + .collect::>>(); + + + let mut nodes = leafs.clone(); + while nodes.len() > 1 { + nodes = nodes + .chunks(2) + .map(|chunk| { + let result = if chunk.len() == 2 { + let concat = [chunk[0].as_slice(), chunk[1].as_slice()].concat(); + let mut buffer: [u8; 32] = [0; 32]; + callback(concat.as_ptr(), buffer.as_mut_ptr()); + buffer.to_vec() + } else { + chunk[0].to_vec() + }; + result + }) + .collect() + } + + let root = nodes.into_iter().next().unwrap_or_default(); + let boxed_array = root.into_boxed_slice(); + Box::into_raw(boxed_array) as *mut u8 +} + diff --git a/merkly/accelerator/libmerkle_root/Cargo.toml b/merkly/accelerator/libmerkle_root/Cargo.toml new file mode 100644 index 0000000..ad366ff --- /dev/null +++ b/merkly/accelerator/libmerkle_root/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "libmerkle_root" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] + +[lib] +type = "cdylib" \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/src/lib.rs b/merkly/accelerator/libmerkle_root/src/lib.rs new file mode 100644 index 0000000..82c5135 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/src/lib.rs @@ -0,0 +1,45 @@ +use std::slice; + +/// # Safety +/// +#[no_mangle] +pub unsafe extern "C" fn free_32(ptr: *mut u8) { + unsafe { + let _ = Box::from_raw(slice::from_raw_parts_mut(ptr, 32)); + } +} + +/// # Safety +/// +#[no_mangle] +pub unsafe extern "C" fn make_root( + callback: extern "C" fn(input: *const u8, output: *mut u8), + leafs_ptr: *const *const u8, + len: usize, +) -> *mut u8 { + let leafs = unsafe { slice::from_raw_parts(leafs_ptr, len) } + .iter() + .map(|&ptr| unsafe { Vec::from(slice::from_raw_parts(ptr, 32)) }) + .collect::>>(); + + let mut nodes = leafs.clone(); + while nodes.len() > 1 { + nodes = nodes + .chunks(2) + .map(|chunk| { + if chunk.len() == 2 { + let concat = [chunk[0].as_slice(), chunk[1].as_slice()].concat(); + let mut buffer: [u8; 32] = [0; 32]; + callback(concat.as_ptr(), buffer.as_mut_ptr()); + return buffer.to_vec(); + } else { + return chunk[0].to_vec(); + }; + }) + .collect() + } + + let root = nodes.into_iter().next().unwrap_or_default(); + let boxed_array = root.into_boxed_slice(); + Box::into_raw(boxed_array) as *mut u8 +} diff --git a/merkly/accelerator/libmerkle_root/target/.rustc_info.json b/merkly/accelerator/libmerkle_root/target/.rustc_info.json new file mode 100644 index 0000000..f1d3683 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/.rustc_info.json @@ -0,0 +1 @@ +{"rustc_fingerprint":12933837335906766648,"outputs":{"13614503371424085932":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n","stderr":""},"9855854040982113140":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n/Users/olivmath/.rustup/toolchains/nightly-aarch64-apple-darwin\ndebug_assertions\npanic=\"unwind\"\nproc_macro\ntarget_abi=\"\"\ntarget_arch=\"aarch64\"\ntarget_endian=\"little\"\ntarget_env=\"\"\ntarget_family=\"unix\"\ntarget_feature=\"aes\"\ntarget_feature=\"crc\"\ntarget_feature=\"dit\"\ntarget_feature=\"dotprod\"\ntarget_feature=\"dpb\"\ntarget_feature=\"dpb2\"\ntarget_feature=\"fcma\"\ntarget_feature=\"fhm\"\ntarget_feature=\"flagm\"\ntarget_feature=\"fp16\"\ntarget_feature=\"frintts\"\ntarget_feature=\"jsconv\"\ntarget_feature=\"llvm14-builtins-abi\"\ntarget_feature=\"lor\"\ntarget_feature=\"lse\"\ntarget_feature=\"neon\"\ntarget_feature=\"paca\"\ntarget_feature=\"pacg\"\ntarget_feature=\"pan\"\ntarget_feature=\"pmuv3\"\ntarget_feature=\"ras\"\ntarget_feature=\"rcpc\"\ntarget_feature=\"rcpc2\"\ntarget_feature=\"rdm\"\ntarget_feature=\"sb\"\ntarget_feature=\"sha2\"\ntarget_feature=\"sha3\"\ntarget_feature=\"ssbs\"\ntarget_feature=\"v8.1a\"\ntarget_feature=\"v8.2a\"\ntarget_feature=\"v8.3a\"\ntarget_feature=\"v8.4a\"\ntarget_feature=\"vh\"\ntarget_has_atomic=\"128\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_has_atomic_equal_alignment=\"128\"\ntarget_has_atomic_equal_alignment=\"16\"\ntarget_has_atomic_equal_alignment=\"32\"\ntarget_has_atomic_equal_alignment=\"64\"\ntarget_has_atomic_equal_alignment=\"8\"\ntarget_has_atomic_equal_alignment=\"ptr\"\ntarget_has_atomic_load_store=\"128\"\ntarget_has_atomic_load_store=\"16\"\ntarget_has_atomic_load_store=\"32\"\ntarget_has_atomic_load_store=\"64\"\ntarget_has_atomic_load_store=\"8\"\ntarget_has_atomic_load_store=\"ptr\"\ntarget_os=\"macos\"\ntarget_pointer_width=\"64\"\ntarget_thread_local\ntarget_vendor=\"apple\"\nunix\n","stderr":""},"10376369925670944939":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n/Users/olivmath/.rustup/toolchains/nightly-aarch64-apple-darwin\ndebug_assertions\npanic=\"unwind\"\nproc_macro\ntarget_abi=\"\"\ntarget_arch=\"aarch64\"\ntarget_endian=\"little\"\ntarget_env=\"\"\ntarget_family=\"unix\"\ntarget_feature=\"aes\"\ntarget_feature=\"crc\"\ntarget_feature=\"dit\"\ntarget_feature=\"dotprod\"\ntarget_feature=\"dpb\"\ntarget_feature=\"dpb2\"\ntarget_feature=\"fcma\"\ntarget_feature=\"fhm\"\ntarget_feature=\"flagm\"\ntarget_feature=\"fp16\"\ntarget_feature=\"frintts\"\ntarget_feature=\"jsconv\"\ntarget_feature=\"llvm14-builtins-abi\"\ntarget_feature=\"lor\"\ntarget_feature=\"lse\"\ntarget_feature=\"neon\"\ntarget_feature=\"paca\"\ntarget_feature=\"pacg\"\ntarget_feature=\"pan\"\ntarget_feature=\"pmuv3\"\ntarget_feature=\"ras\"\ntarget_feature=\"rcpc\"\ntarget_feature=\"rcpc2\"\ntarget_feature=\"rdm\"\ntarget_feature=\"sb\"\ntarget_feature=\"sha2\"\ntarget_feature=\"sha3\"\ntarget_feature=\"ssbs\"\ntarget_feature=\"v8.1a\"\ntarget_feature=\"v8.2a\"\ntarget_feature=\"v8.3a\"\ntarget_feature=\"v8.4a\"\ntarget_feature=\"vh\"\ntarget_has_atomic=\"128\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_has_atomic_equal_alignment=\"128\"\ntarget_has_atomic_equal_alignment=\"16\"\ntarget_has_atomic_equal_alignment=\"32\"\ntarget_has_atomic_equal_alignment=\"64\"\ntarget_has_atomic_equal_alignment=\"8\"\ntarget_has_atomic_equal_alignment=\"ptr\"\ntarget_has_atomic_load_store=\"128\"\ntarget_has_atomic_load_store=\"16\"\ntarget_has_atomic_load_store=\"32\"\ntarget_has_atomic_load_store=\"64\"\ntarget_has_atomic_load_store=\"8\"\ntarget_has_atomic_load_store=\"ptr\"\ntarget_os=\"macos\"\ntarget_pointer_width=\"64\"\ntarget_thread_local\ntarget_vendor=\"apple\"\nunix\n","stderr":""},"15697416045686424142":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n","stderr":""},"4614504638168534921":{"success":true,"status":"","code":0,"stdout":"rustc 1.68.0-nightly (574b64a97 2022-12-31)\nbinary: rustc\ncommit-hash: 574b64a97f52162f965bc201e47f0af8279ca65d\ncommit-date: 2022-12-31\nhost: aarch64-apple-darwin\nrelease: 1.68.0-nightly\nLLVM version: 15.0.6\n","stderr":""}},"successes":{}} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/dep-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/dep-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/dep-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/lib-libmerkle_root new file mode 100644 index 0000000..df70ab9 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/lib-libmerkle_root @@ -0,0 +1 @@ +9ac9c4e50d77e129 \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/lib-libmerkle_root.json new file mode 100644 index 0000000..0bfdf05 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-08b9c19391970bd1/lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":17004773524947412777,"features":"[]","target":14212015080961893296,"profile":17483045194147818835,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-08b9c19391970bd1/dep-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/dep-test-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/dep-test-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/dep-test-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/test-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/test-lib-libmerkle_root new file mode 100644 index 0000000..40dad96 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/test-lib-libmerkle_root @@ -0,0 +1 @@ +e525b7dfa2d5050a \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/test-lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/test-lib-libmerkle_root.json new file mode 100644 index 0000000..222f693 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/test-lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":17004773524947412777,"features":"[]","target":14212015080961893296,"profile":11506243869495082934,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-402adff2cbbfb7d3/dep-test-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/dep-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/dep-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/dep-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/lib-libmerkle_root new file mode 100644 index 0000000..8599b69 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/lib-libmerkle_root @@ -0,0 +1 @@ +3e9ee6cfee97481a \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/lib-libmerkle_root.json new file mode 100644 index 0000000..7e5f224 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-609819427e5e50ec/lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":15699327122048238920,"features":"[]","target":14212015080961893296,"profile":237655285757591511,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-609819427e5e50ec/dep-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/dep-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/dep-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/dep-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/lib-libmerkle_root new file mode 100644 index 0000000..7590a07 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/lib-libmerkle_root @@ -0,0 +1 @@ +943edaf6053ac7b8 \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/lib-libmerkle_root.json new file mode 100644 index 0000000..1453dc6 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":17004773524947412777,"features":"[]","target":14212015080961893296,"profile":11736316127369858332,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-69736f07527c1baf/dep-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/output-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/output-lib-libmerkle_root new file mode 100644 index 0000000..e3236bb --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-69736f07527c1baf/output-lib-libmerkle_root @@ -0,0 +1,3 @@ +{"message":"unused variable: `callback`","code":{"code":"unused_variables","explanation":null},"level":"warning","spans":[{"file_name":"src/lib.rs","byte_start":255,"byte_end":263,"line_start":16,"line_end":16,"column_start":5,"column_end":13,"is_primary":true,"text":[{"text":" callback: extern \"C\" fn(input: *const u8, output: *mut u8),","highlight_start":5,"highlight_end":13}],"label":null,"suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"`#[warn(unused_variables)]` on by default","code":null,"level":"note","spans":[],"children":[],"rendered":null},{"message":"if this is intentional, prefix it with an underscore","code":null,"level":"help","spans":[{"file_name":"src/lib.rs","byte_start":255,"byte_end":263,"line_start":16,"line_end":16,"column_start":5,"column_end":13,"is_primary":true,"text":[{"text":" callback: extern \"C\" fn(input: *const u8, output: *mut u8),","highlight_start":5,"highlight_end":13}],"label":null,"suggested_replacement":"_callback","suggestion_applicability":"MachineApplicable","expansion":null}],"children":[],"rendered":null}],"rendered":"\u001b[0m\u001b[1m\u001b[33mwarning\u001b[0m\u001b[0m\u001b[1m: unused variable: `callback`\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m--> \u001b[0m\u001b[0msrc/lib.rs:16:5\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\n\u001b[0m\u001b[1m\u001b[38;5;12m16\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m callback: extern \"C\" fn(input: *const u8, output: *mut u8),\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[33m^^^^^^^^\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[33mhelp: if this is intentional, prefix it with an underscore: `_callback`\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m= \u001b[0m\u001b[0m\u001b[1mnote\u001b[0m\u001b[0m: `#[warn(unused_variables)]` on by default\u001b[0m\n\n"} +{"message":"variable does not need to be mutable","code":{"code":"unused_mut","explanation":null},"level":"warning","spans":[{"file_name":"src/lib.rs","byte_start":579,"byte_end":588,"line_start":25,"line_end":25,"column_start":9,"column_end":18,"is_primary":true,"text":[{"text":" let mut nodes = leafs.clone();","highlight_start":9,"highlight_end":18}],"label":null,"suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"`#[warn(unused_mut)]` on by default","code":null,"level":"note","spans":[],"children":[],"rendered":null},{"message":"remove this `mut`","code":null,"level":"help","spans":[{"file_name":"src/lib.rs","byte_start":579,"byte_end":583,"line_start":25,"line_end":25,"column_start":9,"column_end":13,"is_primary":true,"text":[{"text":" let mut nodes = leafs.clone();","highlight_start":9,"highlight_end":13}],"label":null,"suggested_replacement":"","suggestion_applicability":"MachineApplicable","expansion":null}],"children":[],"rendered":null}],"rendered":"\u001b[0m\u001b[1m\u001b[33mwarning\u001b[0m\u001b[0m\u001b[1m: variable does not need to be mutable\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m--> \u001b[0m\u001b[0msrc/lib.rs:25:9\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\n\u001b[0m\u001b[1m\u001b[38;5;12m25\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m let mut nodes = leafs.clone();\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m----\u001b[0m\u001b[0m\u001b[1m\u001b[33m^^^^^\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12mhelp: remove this `mut`\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\n\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m= \u001b[0m\u001b[0m\u001b[1mnote\u001b[0m\u001b[0m: `#[warn(unused_mut)]` on by default\u001b[0m\n\n"} +{"message":"2 warnings emitted","code":null,"level":"warning","spans":[],"children":[],"rendered":"\u001b[0m\u001b[1m\u001b[33mwarning\u001b[0m\u001b[0m\u001b[1m: 2 warnings emitted\u001b[0m\n\n"} diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/dep-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/dep-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/dep-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/lib-libmerkle_root new file mode 100644 index 0000000..04b2b74 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/lib-libmerkle_root @@ -0,0 +1 @@ +50fac16352fd4033 \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/lib-libmerkle_root.json new file mode 100644 index 0000000..ab65a07 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":15699327122048238920,"features":"[]","target":14212015080961893296,"profile":13396965805329499462,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-a127695c2afe5bc3/dep-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/dep-test-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/dep-test-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/dep-test-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/test-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/test-lib-libmerkle_root new file mode 100644 index 0000000..b1c6661 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/test-lib-libmerkle_root @@ -0,0 +1 @@ +b31a33733f0d9c77 \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/test-lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/test-lib-libmerkle_root.json new file mode 100644 index 0000000..8f8772e --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/test-lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":15699327122048238920,"features":"[]","target":14212015080961893296,"profile":6823863257117401121,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-cc456d9e613e2a16/dep-test-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/dep-test-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/dep-test-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/dep-test-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/test-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/test-lib-libmerkle_root new file mode 100644 index 0000000..9273159 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/test-lib-libmerkle_root @@ -0,0 +1 @@ +0c398f6cfdb186f5 \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/test-lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/test-lib-libmerkle_root.json new file mode 100644 index 0000000..b5e0d94 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/test-lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":15699327122048238920,"features":"[]","target":14212015080961893296,"profile":13053956386274884697,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/libmerkle_root-f8b0ececa86b90d9/dep-test-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-08b9c19391970bd1.rmeta b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-08b9c19391970bd1.rmeta new file mode 100644 index 0000000..6161d56 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-08b9c19391970bd1.rmeta differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-402adff2cbbfb7d3.rmeta b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-402adff2cbbfb7d3.rmeta new file mode 100644 index 0000000..e69de29 diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rlib b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rlib new file mode 100644 index 0000000..3f611dc Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rlib differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rmeta b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rmeta new file mode 100644 index 0000000..e851a69 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rmeta differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rlib b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rlib new file mode 100644 index 0000000..7c8becb Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rlib differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rmeta b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rmeta new file mode 100644 index 0000000..79a9a85 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rmeta differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-a127695c2afe5bc3.rmeta b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-a127695c2afe5bc3.rmeta new file mode 100644 index 0000000..04d2c2b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-a127695c2afe5bc3.rmeta differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-f8b0ececa86b90d9.rmeta b/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-f8b0ececa86b90d9.rmeta new file mode 100644 index 0000000..e69de29 diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-08b9c19391970bd1.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-08b9c19391970bd1.d new file mode 100644 index 0000000..a08b521 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-08b9c19391970bd1.d @@ -0,0 +1,5 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-08b9c19391970bd1.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-08b9c19391970bd1.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-402adff2cbbfb7d3.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-402adff2cbbfb7d3.d new file mode 100644 index 0000000..3f7281b --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-402adff2cbbfb7d3.d @@ -0,0 +1,5 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-402adff2cbbfb7d3.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-402adff2cbbfb7d3.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.116uv8vccxu807yd.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.116uv8vccxu807yd.rcgu.o new file mode 100644 index 0000000..e7d5588 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.116uv8vccxu807yd.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1ate79qeqzc8412p.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1ate79qeqzc8412p.rcgu.o new file mode 100644 index 0000000..5b3bade Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1ate79qeqzc8412p.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1e7fxhs9zssle0t5.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1e7fxhs9zssle0t5.rcgu.o new file mode 100644 index 0000000..5b416ef Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1e7fxhs9zssle0t5.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1gcplpalj8ese60m.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1gcplpalj8ese60m.rcgu.o new file mode 100644 index 0000000..379c9c1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1gcplpalj8ese60m.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1hnu1y4fyriyg0i3.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1hnu1y4fyriyg0i3.rcgu.o new file mode 100644 index 0000000..7571de5 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1hnu1y4fyriyg0i3.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1wupq9zs5cmos8wf.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1wupq9zs5cmos8wf.rcgu.o new file mode 100644 index 0000000..faeb416 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.1wupq9zs5cmos8wf.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.206h5i00gbgfybn.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.206h5i00gbgfybn.rcgu.o new file mode 100644 index 0000000..e523212 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.206h5i00gbgfybn.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2dmgbgnq77y9ero6.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2dmgbgnq77y9ero6.rcgu.o new file mode 100644 index 0000000..79c58f3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2dmgbgnq77y9ero6.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2gedv8wr3mty4h60.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2gedv8wr3mty4h60.rcgu.o new file mode 100644 index 0000000..df42487 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2gedv8wr3mty4h60.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2u9acbpjvtx1eq8q.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2u9acbpjvtx1eq8q.rcgu.o new file mode 100644 index 0000000..780f71b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2u9acbpjvtx1eq8q.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2wwdlzh2z1v0r6ae.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2wwdlzh2z1v0r6ae.rcgu.o new file mode 100644 index 0000000..8d2d0ac Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.2wwdlzh2z1v0r6ae.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.31pcdyjginr68kqh.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.31pcdyjginr68kqh.rcgu.o new file mode 100644 index 0000000..3c93d68 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.31pcdyjginr68kqh.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.375qayi6zlzjyqyj.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.375qayi6zlzjyqyj.rcgu.o new file mode 100644 index 0000000..68883f3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.375qayi6zlzjyqyj.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.38vwlwctmn2m7toq.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.38vwlwctmn2m7toq.rcgu.o new file mode 100644 index 0000000..574ef5f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.38vwlwctmn2m7toq.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3w56pvea64kbjmi7.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3w56pvea64kbjmi7.rcgu.o new file mode 100644 index 0000000..9e04a49 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3w56pvea64kbjmi7.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3xma82rcr3j3qc3x.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3xma82rcr3j3qc3x.rcgu.o new file mode 100644 index 0000000..e746ec0 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3xma82rcr3j3qc3x.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3zrrz0d4xwyf7dag.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3zrrz0d4xwyf7dag.rcgu.o new file mode 100644 index 0000000..4d0786d Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.3zrrz0d4xwyf7dag.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4875ae6zchc0wzui.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4875ae6zchc0wzui.rcgu.o new file mode 100644 index 0000000..064ca6e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4875ae6zchc0wzui.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4ho8wmbl6suaks8u.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4ho8wmbl6suaks8u.rcgu.o new file mode 100644 index 0000000..ba57320 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4ho8wmbl6suaks8u.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4iz4bxszsr312yf2.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4iz4bxszsr312yf2.rcgu.o new file mode 100644 index 0000000..91a1683 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4iz4bxszsr312yf2.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4wf6c26q0f86w3t9.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4wf6c26q0f86w3t9.rcgu.o new file mode 100644 index 0000000..e73c060 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4wf6c26q0f86w3t9.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4x6fvacpt1rfumdb.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4x6fvacpt1rfumdb.rcgu.o new file mode 100644 index 0000000..d09da7f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.4x6fvacpt1rfumdb.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.54vqnaddmjzgrlmd.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.54vqnaddmjzgrlmd.rcgu.o new file mode 100644 index 0000000..05aa878 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.54vqnaddmjzgrlmd.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.5dddrcdzjmktdh5f.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.5dddrcdzjmktdh5f.rcgu.o new file mode 100644 index 0000000..59fbe56 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.5dddrcdzjmktdh5f.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.72vm43wmorsd0cy.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.72vm43wmorsd0cy.rcgu.o new file mode 100644 index 0000000..8d76ea7 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.72vm43wmorsd0cy.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.d new file mode 100644 index 0000000..56500de --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.d @@ -0,0 +1,7 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-609819427e5e50ec.rlib: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.hv6g3sp4bf42v5c.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.hv6g3sp4bf42v5c.rcgu.o new file mode 100644 index 0000000..5c76e56 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.hv6g3sp4bf42v5c.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.j197lqtzrrbnv19.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.j197lqtzrrbnv19.rcgu.o new file mode 100644 index 0000000..663af54 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.j197lqtzrrbnv19.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.xwz2jmu4t993gy5.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.xwz2jmu4t993gy5.rcgu.o new file mode 100644 index 0000000..8671761 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-609819427e5e50ec.xwz2jmu4t993gy5.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-69736f07527c1baf.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-69736f07527c1baf.d new file mode 100644 index 0000000..29f0f47 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-69736f07527c1baf.d @@ -0,0 +1,7 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-69736f07527c1baf.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/liblibmerkle_root-69736f07527c1baf.rlib: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-69736f07527c1baf.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-a127695c2afe5bc3.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-a127695c2afe5bc3.d new file mode 100644 index 0000000..b1e02cd --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-a127695c2afe5bc3.d @@ -0,0 +1,5 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-a127695c2afe5bc3.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-a127695c2afe5bc3.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16 b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16 new file mode 100755 index 0000000..5694b15 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16 differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.11gte0iv5e4z8m6m.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.11gte0iv5e4z8m6m.rcgu.o new file mode 100644 index 0000000..c8d6863 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.11gte0iv5e4z8m6m.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.134o7w07bvbbf03t.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.134o7w07bvbbf03t.rcgu.o new file mode 100644 index 0000000..1ae6435 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.134o7w07bvbbf03t.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.19kam0utf5i6quqv.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.19kam0utf5i6quqv.rcgu.o new file mode 100644 index 0000000..6f5ef46 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.19kam0utf5i6quqv.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1bxnftd0p43ts3el.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1bxnftd0p43ts3el.rcgu.o new file mode 100644 index 0000000..562b097 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1bxnftd0p43ts3el.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1fnzzprxdooscpd5.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1fnzzprxdooscpd5.rcgu.o new file mode 100644 index 0000000..1417789 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1fnzzprxdooscpd5.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1hiommyz5h8l3dfx.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1hiommyz5h8l3dfx.rcgu.o new file mode 100644 index 0000000..c29519d Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1hiommyz5h8l3dfx.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1j5muv973o2pd7a1.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1j5muv973o2pd7a1.rcgu.o new file mode 100644 index 0000000..b947ddf Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1j5muv973o2pd7a1.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1t840ymqtacuyacj.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1t840ymqtacuyacj.rcgu.o new file mode 100644 index 0000000..951b150 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.1t840ymqtacuyacj.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.235a1l1ddj12o18s.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.235a1l1ddj12o18s.rcgu.o new file mode 100644 index 0000000..6972bb7 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.235a1l1ddj12o18s.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.240029ztm5jgrcdj.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.240029ztm5jgrcdj.rcgu.o new file mode 100644 index 0000000..b4e549c Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.240029ztm5jgrcdj.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.24085ez8gjs3opl7.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.24085ez8gjs3opl7.rcgu.o new file mode 100644 index 0000000..34507e8 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.24085ez8gjs3opl7.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.267pewnge3tf9k1v.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.267pewnge3tf9k1v.rcgu.o new file mode 100644 index 0000000..9b3b54e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.267pewnge3tf9k1v.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.27vdrohnb5rqcdkx.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.27vdrohnb5rqcdkx.rcgu.o new file mode 100644 index 0000000..30a2b11 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.27vdrohnb5rqcdkx.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2a19hifneoek6kdh.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2a19hifneoek6kdh.rcgu.o new file mode 100644 index 0000000..be087ad Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2a19hifneoek6kdh.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2cninvxvnahrz4fz.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2cninvxvnahrz4fz.rcgu.o new file mode 100644 index 0000000..ce2044a Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2cninvxvnahrz4fz.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2gea5anoi6q7liyy.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2gea5anoi6q7liyy.rcgu.o new file mode 100644 index 0000000..82d889b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2gea5anoi6q7liyy.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2ki3xa9qkawwqsce.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2ki3xa9qkawwqsce.rcgu.o new file mode 100644 index 0000000..ec26eda Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2ki3xa9qkawwqsce.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2mg85y40pd7lg4jt.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2mg85y40pd7lg4jt.rcgu.o new file mode 100644 index 0000000..55ba9f6 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2mg85y40pd7lg4jt.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2obyt0rtqx0htme6.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2obyt0rtqx0htme6.rcgu.o new file mode 100644 index 0000000..3f42a3c Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2obyt0rtqx0htme6.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2skpv6s52tugkwcs.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2skpv6s52tugkwcs.rcgu.o new file mode 100644 index 0000000..456d7bf Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.2skpv6s52tugkwcs.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.300cigv47oec1wel.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.300cigv47oec1wel.rcgu.o new file mode 100644 index 0000000..af55172 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.300cigv47oec1wel.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.3fm2idareggq9o79.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.3fm2idareggq9o79.rcgu.o new file mode 100644 index 0000000..12c1012 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.3fm2idareggq9o79.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.3g61tr4m5u6pw72j.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.3g61tr4m5u6pw72j.rcgu.o new file mode 100644 index 0000000..04b77d3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.3g61tr4m5u6pw72j.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.44i5adwfp3vedij9.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.44i5adwfp3vedij9.rcgu.o new file mode 100644 index 0000000..951b340 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.44i5adwfp3vedij9.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.472br0c3gp2rwaj2.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.472br0c3gp2rwaj2.rcgu.o new file mode 100644 index 0000000..76e0683 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.472br0c3gp2rwaj2.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.47gbxfjitzmdpvyd.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.47gbxfjitzmdpvyd.rcgu.o new file mode 100644 index 0000000..5dd059a Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.47gbxfjitzmdpvyd.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.49qbxnwqvfumjby1.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.49qbxnwqvfumjby1.rcgu.o new file mode 100644 index 0000000..3200697 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.49qbxnwqvfumjby1.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4ep58uens277nq39.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4ep58uens277nq39.rcgu.o new file mode 100644 index 0000000..13da2b3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4ep58uens277nq39.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4hu09c5sivwee5x5.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4hu09c5sivwee5x5.rcgu.o new file mode 100644 index 0000000..36bd42e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4hu09c5sivwee5x5.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4q4qsb447g0bc06m.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4q4qsb447g0bc06m.rcgu.o new file mode 100644 index 0000000..aa8d5cb Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4q4qsb447g0bc06m.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4w1bcg5560r07s6o.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4w1bcg5560r07s6o.rcgu.o new file mode 100644 index 0000000..849a839 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.4w1bcg5560r07s6o.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.5by4fptvldljw9y.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.5by4fptvldljw9y.rcgu.o new file mode 100644 index 0000000..c060bad Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.5by4fptvldljw9y.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.9cavfn4u1sdc9tm.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.9cavfn4u1sdc9tm.rcgu.o new file mode 100644 index 0000000..7fc1474 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.9cavfn4u1sdc9tm.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.9drm4asduuvxia2.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.9drm4asduuvxia2.rcgu.o new file mode 100644 index 0000000..813a4df Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.9drm4asduuvxia2.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.d new file mode 100644 index 0000000..edc2944 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.d @@ -0,0 +1,5 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.ks0ispdl57p7kxk.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.ks0ispdl57p7kxk.rcgu.o new file mode 100644 index 0000000..2714d51 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.ks0ispdl57p7kxk.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.o0yfi52jfgmml97.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.o0yfi52jfgmml97.rcgu.o new file mode 100644 index 0000000..c03e3b1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.o0yfi52jfgmml97.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.qeo72tmrhnd9ihe.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.qeo72tmrhnd9ihe.rcgu.o new file mode 100644 index 0000000..5b2d55e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.qeo72tmrhnd9ihe.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.qho42zv5gjff26r.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.qho42zv5gjff26r.rcgu.o new file mode 100644 index 0000000..284c262 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.qho42zv5gjff26r.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.rpz4p19h0p4b2ym.rcgu.o b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.rpz4p19h0p4b2ym.rcgu.o new file mode 100644 index 0000000..b7cf52c Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-cc456d9e613e2a16.rpz4p19h0p4b2ym.rcgu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-f8b0ececa86b90d9.d b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-f8b0ececa86b90d9.d new file mode 100644 index 0000000..40f58aa --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-f8b0ececa86b90d9.d @@ -0,0 +1,5 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-f8b0ececa86b90d9.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/deps/libmerkle_root-f8b0ececa86b90d9.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/116uv8vccxu807yd.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/116uv8vccxu807yd.o new file mode 100644 index 0000000..e7d5588 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/116uv8vccxu807yd.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1ate79qeqzc8412p.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1ate79qeqzc8412p.o new file mode 100644 index 0000000..5b3bade Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1ate79qeqzc8412p.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1e7fxhs9zssle0t5.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1e7fxhs9zssle0t5.o new file mode 100644 index 0000000..5b416ef Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1e7fxhs9zssle0t5.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1gcplpalj8ese60m.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1gcplpalj8ese60m.o new file mode 100644 index 0000000..379c9c1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1gcplpalj8ese60m.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1hnu1y4fyriyg0i3.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1hnu1y4fyriyg0i3.o new file mode 100644 index 0000000..7571de5 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1hnu1y4fyriyg0i3.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1wupq9zs5cmos8wf.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1wupq9zs5cmos8wf.o new file mode 100644 index 0000000..faeb416 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/1wupq9zs5cmos8wf.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/206h5i00gbgfybn.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/206h5i00gbgfybn.o new file mode 100644 index 0000000..e523212 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/206h5i00gbgfybn.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2dmgbgnq77y9ero6.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2dmgbgnq77y9ero6.o new file mode 100644 index 0000000..79c58f3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2dmgbgnq77y9ero6.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2gedv8wr3mty4h60.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2gedv8wr3mty4h60.o new file mode 100644 index 0000000..df42487 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2gedv8wr3mty4h60.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2u9acbpjvtx1eq8q.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2u9acbpjvtx1eq8q.o new file mode 100644 index 0000000..780f71b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2u9acbpjvtx1eq8q.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2wwdlzh2z1v0r6ae.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2wwdlzh2z1v0r6ae.o new file mode 100644 index 0000000..8d2d0ac Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/2wwdlzh2z1v0r6ae.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/31pcdyjginr68kqh.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/31pcdyjginr68kqh.o new file mode 100644 index 0000000..3c93d68 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/31pcdyjginr68kqh.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/375qayi6zlzjyqyj.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/375qayi6zlzjyqyj.o new file mode 100644 index 0000000..68883f3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/375qayi6zlzjyqyj.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/38vwlwctmn2m7toq.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/38vwlwctmn2m7toq.o new file mode 100644 index 0000000..574ef5f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/38vwlwctmn2m7toq.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3w56pvea64kbjmi7.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3w56pvea64kbjmi7.o new file mode 100644 index 0000000..9e04a49 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3w56pvea64kbjmi7.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3xma82rcr3j3qc3x.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3xma82rcr3j3qc3x.o new file mode 100644 index 0000000..e746ec0 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3xma82rcr3j3qc3x.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3zrrz0d4xwyf7dag.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3zrrz0d4xwyf7dag.o new file mode 100644 index 0000000..4d0786d Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/3zrrz0d4xwyf7dag.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4875ae6zchc0wzui.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4875ae6zchc0wzui.o new file mode 100644 index 0000000..064ca6e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4875ae6zchc0wzui.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4ho8wmbl6suaks8u.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4ho8wmbl6suaks8u.o new file mode 100644 index 0000000..ba57320 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4ho8wmbl6suaks8u.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4iz4bxszsr312yf2.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4iz4bxszsr312yf2.o new file mode 100644 index 0000000..91a1683 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4iz4bxszsr312yf2.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4wf6c26q0f86w3t9.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4wf6c26q0f86w3t9.o new file mode 100644 index 0000000..e73c060 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4wf6c26q0f86w3t9.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4x6fvacpt1rfumdb.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4x6fvacpt1rfumdb.o new file mode 100644 index 0000000..d09da7f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/4x6fvacpt1rfumdb.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/54vqnaddmjzgrlmd.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/54vqnaddmjzgrlmd.o new file mode 100644 index 0000000..05aa878 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/54vqnaddmjzgrlmd.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/5dddrcdzjmktdh5f.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/5dddrcdzjmktdh5f.o new file mode 100644 index 0000000..59fbe56 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/5dddrcdzjmktdh5f.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/72vm43wmorsd0cy.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/72vm43wmorsd0cy.o new file mode 100644 index 0000000..8d76ea7 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/72vm43wmorsd0cy.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/dep-graph.bin new file mode 100644 index 0000000..bbfe036 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/hv6g3sp4bf42v5c.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/hv6g3sp4bf42v5c.o new file mode 100644 index 0000000..5c76e56 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/hv6g3sp4bf42v5c.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/j197lqtzrrbnv19.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/j197lqtzrrbnv19.o new file mode 100644 index 0000000..663af54 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/j197lqtzrrbnv19.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/work-products.bin new file mode 100644 index 0000000..c76bea1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/xwz2jmu4t993gy5.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/xwz2jmu4t993gy5.o new file mode 100644 index 0000000..8671761 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-12x3wrwca7ux8/s-gr1riwaqnh-18t9bel-a9cmj88h1oudpx459bwp8gc51/xwz2jmu4t993gy5.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-1ar4gddrxpwly/s-gr1suze3tg-1n2pngf-71ucmv3fjtfabz2quhla3ou9s/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-1ar4gddrxpwly/s-gr1suze3tg-1n2pngf-71ucmv3fjtfabz2quhla3ou9s/dep-graph.bin new file mode 100644 index 0000000..ddf86d8 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-1ar4gddrxpwly/s-gr1suze3tg-1n2pngf-71ucmv3fjtfabz2quhla3ou9s/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-1ar4gddrxpwly/s-gr1suze3tg-1n2pngf-71ucmv3fjtfabz2quhla3ou9s/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-1ar4gddrxpwly/s-gr1suze3tg-1n2pngf-71ucmv3fjtfabz2quhla3ou9s/work-products.bin new file mode 100644 index 0000000..0bb9438 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-1ar4gddrxpwly/s-gr1suze3tg-1n2pngf-71ucmv3fjtfabz2quhla3ou9s/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/137eka8q8s27lcoj.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/137eka8q8s27lcoj.o new file mode 100644 index 0000000..f5d08b8 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/137eka8q8s27lcoj.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/13cf16h2zyc5yjxo.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/13cf16h2zyc5yjxo.o new file mode 100644 index 0000000..c5bdc9f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/13cf16h2zyc5yjxo.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/15sztf3v1fp39u8j.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/15sztf3v1fp39u8j.o new file mode 100644 index 0000000..d49cd06 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/15sztf3v1fp39u8j.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/17vke8wtm5x3tydj.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/17vke8wtm5x3tydj.o new file mode 100644 index 0000000..2c578da Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/17vke8wtm5x3tydj.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/1poywm2wzk5oxvkh.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/1poywm2wzk5oxvkh.o new file mode 100644 index 0000000..3bd9bec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/1poywm2wzk5oxvkh.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/1qzcdnha9lb2961z.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/1qzcdnha9lb2961z.o new file mode 100644 index 0000000..4d10edb Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/1qzcdnha9lb2961z.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/25sd6xx6wrnwx32v.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/25sd6xx6wrnwx32v.o new file mode 100644 index 0000000..2c0acef Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/25sd6xx6wrnwx32v.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2c0u6qykd0rw83ui.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2c0u6qykd0rw83ui.o new file mode 100644 index 0000000..00b3e31 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2c0u6qykd0rw83ui.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2r0utn377y6zydsn.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2r0utn377y6zydsn.o new file mode 100644 index 0000000..cc0b591 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2r0utn377y6zydsn.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2v0i25asdxkr6nsx.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2v0i25asdxkr6nsx.o new file mode 100644 index 0000000..d044098 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2v0i25asdxkr6nsx.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2y6t0pkldoshbrk6.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2y6t0pkldoshbrk6.o new file mode 100644 index 0000000..39e19a8 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2y6t0pkldoshbrk6.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2yvjw37ycsr8t9cx.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2yvjw37ycsr8t9cx.o new file mode 100644 index 0000000..80bcf38 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2yvjw37ycsr8t9cx.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2zi8q3e5akh2mbdu.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2zi8q3e5akh2mbdu.o new file mode 100644 index 0000000..5c939f2 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/2zi8q3e5akh2mbdu.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3db1gexh9lpnpess.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3db1gexh9lpnpess.o new file mode 100644 index 0000000..eac64e8 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3db1gexh9lpnpess.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3ffeqgupda2thzce.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3ffeqgupda2thzce.o new file mode 100644 index 0000000..94fca6f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3ffeqgupda2thzce.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3gobo0eopq5qssge.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3gobo0eopq5qssge.o new file mode 100644 index 0000000..0826b38 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3gobo0eopq5qssge.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3nbmgvzzqe07f04k.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3nbmgvzzqe07f04k.o new file mode 100644 index 0000000..6018fad Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3nbmgvzzqe07f04k.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3o9rowgzcky109x3.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3o9rowgzcky109x3.o new file mode 100644 index 0000000..628899f Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/3o9rowgzcky109x3.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/40jz8z49k44kyxf0.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/40jz8z49k44kyxf0.o new file mode 100644 index 0000000..f5c8546 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/40jz8z49k44kyxf0.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4b55stavk2m1tsap.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4b55stavk2m1tsap.o new file mode 100644 index 0000000..da93bc7 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4b55stavk2m1tsap.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4fwa70wu78sb6b3z.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4fwa70wu78sb6b3z.o new file mode 100644 index 0000000..26ef232 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4fwa70wu78sb6b3z.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4kp7ro4yjoqwm24n.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4kp7ro4yjoqwm24n.o new file mode 100644 index 0000000..2722622 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4kp7ro4yjoqwm24n.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4vde6q6o8u9ykhrq.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4vde6q6o8u9ykhrq.o new file mode 100644 index 0000000..05212cd Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4vde6q6o8u9ykhrq.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4x8axuelgnmq0q0q.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4x8axuelgnmq0q0q.o new file mode 100644 index 0000000..05ca9da Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4x8axuelgnmq0q0q.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4z97br7u6vequopx.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4z97br7u6vequopx.o new file mode 100644 index 0000000..6447b67 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/4z97br7u6vequopx.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/53vkmnd2f9qgekhy.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/53vkmnd2f9qgekhy.o new file mode 100644 index 0000000..79a7dc6 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/53vkmnd2f9qgekhy.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/597c4d5ezto1a4qx.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/597c4d5ezto1a4qx.o new file mode 100644 index 0000000..82cd744 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/597c4d5ezto1a4qx.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/dep-graph.bin new file mode 100644 index 0000000..e7e913e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/ghornw718j3d1wg.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/ghornw718j3d1wg.o new file mode 100644 index 0000000..a3db418 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/ghornw718j3d1wg.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/im2dn8gfiv5igex.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/im2dn8gfiv5igex.o new file mode 100644 index 0000000..0733e94 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/im2dn8gfiv5igex.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/kle2ihi6sgmobno.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/kle2ihi6sgmobno.o new file mode 100644 index 0000000..ab49b65 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/kle2ihi6sgmobno.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/m4usw6ztczme1go.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/m4usw6ztczme1go.o new file mode 100644 index 0000000..d3563a1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/m4usw6ztczme1go.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/nscsxfdq7xmu1m5.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/nscsxfdq7xmu1m5.o new file mode 100644 index 0000000..689c6d1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/nscsxfdq7xmu1m5.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/o5ktyj0m7tdwmft.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/o5ktyj0m7tdwmft.o new file mode 100644 index 0000000..74bd9e7 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/o5ktyj0m7tdwmft.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/so98krvmwgeb8kw.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/so98krvmwgeb8kw.o new file mode 100644 index 0000000..24219b4 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/so98krvmwgeb8kw.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/wbngvl5w2ab872f.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/wbngvl5w2ab872f.o new file mode 100644 index 0000000..6c315b0 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/wbngvl5w2ab872f.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/work-products.bin new file mode 100644 index 0000000..ce71d60 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2rsv8xd3pqgb4/s-gsor8nvd7w-1p482q4-2wp9hwklxlgnv/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/11gte0iv5e4z8m6m.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/11gte0iv5e4z8m6m.o new file mode 100644 index 0000000..c8d6863 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/11gte0iv5e4z8m6m.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/134o7w07bvbbf03t.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/134o7w07bvbbf03t.o new file mode 100644 index 0000000..1ae6435 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/134o7w07bvbbf03t.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/19kam0utf5i6quqv.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/19kam0utf5i6quqv.o new file mode 100644 index 0000000..6f5ef46 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/19kam0utf5i6quqv.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1bxnftd0p43ts3el.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1bxnftd0p43ts3el.o new file mode 100644 index 0000000..562b097 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1bxnftd0p43ts3el.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1fnzzprxdooscpd5.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1fnzzprxdooscpd5.o new file mode 100644 index 0000000..1417789 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1fnzzprxdooscpd5.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1hiommyz5h8l3dfx.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1hiommyz5h8l3dfx.o new file mode 100644 index 0000000..c29519d Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1hiommyz5h8l3dfx.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1j5muv973o2pd7a1.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1j5muv973o2pd7a1.o new file mode 100644 index 0000000..b947ddf Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1j5muv973o2pd7a1.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1t840ymqtacuyacj.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1t840ymqtacuyacj.o new file mode 100644 index 0000000..951b150 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/1t840ymqtacuyacj.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/235a1l1ddj12o18s.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/235a1l1ddj12o18s.o new file mode 100644 index 0000000..6972bb7 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/235a1l1ddj12o18s.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/240029ztm5jgrcdj.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/240029ztm5jgrcdj.o new file mode 100644 index 0000000..b4e549c Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/240029ztm5jgrcdj.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/24085ez8gjs3opl7.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/24085ez8gjs3opl7.o new file mode 100644 index 0000000..34507e8 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/24085ez8gjs3opl7.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/267pewnge3tf9k1v.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/267pewnge3tf9k1v.o new file mode 100644 index 0000000..9b3b54e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/267pewnge3tf9k1v.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/27vdrohnb5rqcdkx.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/27vdrohnb5rqcdkx.o new file mode 100644 index 0000000..30a2b11 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/27vdrohnb5rqcdkx.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2a19hifneoek6kdh.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2a19hifneoek6kdh.o new file mode 100644 index 0000000..be087ad Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2a19hifneoek6kdh.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2cninvxvnahrz4fz.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2cninvxvnahrz4fz.o new file mode 100644 index 0000000..ce2044a Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2cninvxvnahrz4fz.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2gea5anoi6q7liyy.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2gea5anoi6q7liyy.o new file mode 100644 index 0000000..82d889b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2gea5anoi6q7liyy.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2ki3xa9qkawwqsce.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2ki3xa9qkawwqsce.o new file mode 100644 index 0000000..ec26eda Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2ki3xa9qkawwqsce.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2mg85y40pd7lg4jt.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2mg85y40pd7lg4jt.o new file mode 100644 index 0000000..55ba9f6 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2mg85y40pd7lg4jt.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2obyt0rtqx0htme6.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2obyt0rtqx0htme6.o new file mode 100644 index 0000000..3f42a3c Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2obyt0rtqx0htme6.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2skpv6s52tugkwcs.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2skpv6s52tugkwcs.o new file mode 100644 index 0000000..456d7bf Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/2skpv6s52tugkwcs.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/300cigv47oec1wel.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/300cigv47oec1wel.o new file mode 100644 index 0000000..af55172 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/300cigv47oec1wel.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/3fm2idareggq9o79.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/3fm2idareggq9o79.o new file mode 100644 index 0000000..12c1012 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/3fm2idareggq9o79.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/3g61tr4m5u6pw72j.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/3g61tr4m5u6pw72j.o new file mode 100644 index 0000000..04b77d3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/3g61tr4m5u6pw72j.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/44i5adwfp3vedij9.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/44i5adwfp3vedij9.o new file mode 100644 index 0000000..951b340 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/44i5adwfp3vedij9.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/472br0c3gp2rwaj2.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/472br0c3gp2rwaj2.o new file mode 100644 index 0000000..76e0683 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/472br0c3gp2rwaj2.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/47gbxfjitzmdpvyd.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/47gbxfjitzmdpvyd.o new file mode 100644 index 0000000..5dd059a Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/47gbxfjitzmdpvyd.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/49qbxnwqvfumjby1.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/49qbxnwqvfumjby1.o new file mode 100644 index 0000000..3200697 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/49qbxnwqvfumjby1.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4ep58uens277nq39.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4ep58uens277nq39.o new file mode 100644 index 0000000..13da2b3 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4ep58uens277nq39.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4hu09c5sivwee5x5.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4hu09c5sivwee5x5.o new file mode 100644 index 0000000..36bd42e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4hu09c5sivwee5x5.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4q4qsb447g0bc06m.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4q4qsb447g0bc06m.o new file mode 100644 index 0000000..aa8d5cb Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4q4qsb447g0bc06m.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4w1bcg5560r07s6o.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4w1bcg5560r07s6o.o new file mode 100644 index 0000000..849a839 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/4w1bcg5560r07s6o.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/5by4fptvldljw9y.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/5by4fptvldljw9y.o new file mode 100644 index 0000000..c060bad Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/5by4fptvldljw9y.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/9cavfn4u1sdc9tm.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/9cavfn4u1sdc9tm.o new file mode 100644 index 0000000..7fc1474 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/9cavfn4u1sdc9tm.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/9drm4asduuvxia2.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/9drm4asduuvxia2.o new file mode 100644 index 0000000..813a4df Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/9drm4asduuvxia2.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/dep-graph.bin new file mode 100644 index 0000000..2264890 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/ks0ispdl57p7kxk.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/ks0ispdl57p7kxk.o new file mode 100644 index 0000000..2714d51 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/ks0ispdl57p7kxk.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/o0yfi52jfgmml97.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/o0yfi52jfgmml97.o new file mode 100644 index 0000000..c03e3b1 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/o0yfi52jfgmml97.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/qeo72tmrhnd9ihe.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/qeo72tmrhnd9ihe.o new file mode 100644 index 0000000..5b2d55e Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/qeo72tmrhnd9ihe.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/qho42zv5gjff26r.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/qho42zv5gjff26r.o new file mode 100644 index 0000000..284c262 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/qho42zv5gjff26r.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/rpz4p19h0p4b2ym.o b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/rpz4p19h0p4b2ym.o new file mode 100644 index 0000000..b7cf52c Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/rpz4p19h0p4b2ym.o differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/work-products.bin new file mode 100644 index 0000000..543d799 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-2xthspx4ca8uw/s-gr1riwaqnh-1caixp6-68685cow0kjz8p71lfcy0uk7/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-31r8fc05g6o6l/s-gr1suze3tj-cy73w-1tejcnopdzwndvxy79876tcqr/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-31r8fc05g6o6l/s-gr1suze3tj-cy73w-1tejcnopdzwndvxy79876tcqr/dep-graph.bin new file mode 100644 index 0000000..c9b61a0 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-31r8fc05g6o6l/s-gr1suze3tj-cy73w-1tejcnopdzwndvxy79876tcqr/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-31r8fc05g6o6l/s-gr1suze3tj-cy73w-1tejcnopdzwndvxy79876tcqr/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-31r8fc05g6o6l/s-gr1suze3tj-cy73w-1tejcnopdzwndvxy79876tcqr/work-products.bin new file mode 100644 index 0000000..0bb9438 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-31r8fc05g6o6l/s-gr1suze3tj-cy73w-1tejcnopdzwndvxy79876tcqr/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-3hfr4h9balcgj/s-gsorlqz4e0-uu0ig7-36cmuvoaklkjy/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-3hfr4h9balcgj/s-gsorlqz4e0-uu0ig7-36cmuvoaklkjy/dep-graph.bin new file mode 100644 index 0000000..5a94887 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-3hfr4h9balcgj/s-gsorlqz4e0-uu0ig7-36cmuvoaklkjy/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-3hfr4h9balcgj/s-gsorlqz4e0-uu0ig7-36cmuvoaklkjy/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-3hfr4h9balcgj/s-gsorlqz4e0-uu0ig7-36cmuvoaklkjy/work-products.bin new file mode 100644 index 0000000..360a0be Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-3hfr4h9balcgj/s-gsorlqz4e0-uu0ig7-36cmuvoaklkjy/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-aeozat7tx0q/s-gsorlqz4e0-1y9wpbr-12cm7mwu1xbuz/dep-graph.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-aeozat7tx0q/s-gsorlqz4e0-1y9wpbr-12cm7mwu1xbuz/dep-graph.bin new file mode 100644 index 0000000..80ebd30 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-aeozat7tx0q/s-gsorlqz4e0-1y9wpbr-12cm7mwu1xbuz/dep-graph.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-aeozat7tx0q/s-gsorlqz4e0-1y9wpbr-12cm7mwu1xbuz/work-products.bin b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-aeozat7tx0q/s-gsorlqz4e0-1y9wpbr-12cm7mwu1xbuz/work-products.bin new file mode 100644 index 0000000..360a0be Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/incremental/libmerkle_root-aeozat7tx0q/s-gsorlqz4e0-1y9wpbr-12cm7mwu1xbuz/work-products.bin differ diff --git a/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.d b/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.d new file mode 100644 index 0000000..2743383 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.d @@ -0,0 +1 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.rlib: /Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/src/lib.rs diff --git a/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.rlib b/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.rlib new file mode 100644 index 0000000..7c8becb Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/debug/liblibmerkle_root.rlib differ diff --git a/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/dep-lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/dep-lib-libmerkle_root new file mode 100644 index 0000000..fb1fbec Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/dep-lib-libmerkle_root differ diff --git a/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/invoked.timestamp b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/invoked.timestamp new file mode 100644 index 0000000..e00328d --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/invoked.timestamp @@ -0,0 +1 @@ +This file has an mtime of when this was started. \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/lib-libmerkle_root b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/lib-libmerkle_root new file mode 100644 index 0000000..c228ed9 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/lib-libmerkle_root @@ -0,0 +1 @@ +e0f926ecd49f8619 \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/lib-libmerkle_root.json b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/lib-libmerkle_root.json new file mode 100644 index 0000000..4338768 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/lib-libmerkle_root.json @@ -0,0 +1 @@ +{"rustc":17004773524947412777,"features":"[]","target":14212015080961893296,"profile":6269190295429226618,"path":17523903030608720598,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"release/.fingerprint/libmerkle_root-671ba0fe5bfc9244/dep-lib-libmerkle_root"}}],"rustflags":[],"metadata":7797948686568424061,"config":2202906307356721367,"compile_kind":0} \ No newline at end of file diff --git a/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rlib b/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rlib new file mode 100644 index 0000000..492b22b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rlib differ diff --git a/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rmeta b/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rmeta new file mode 100644 index 0000000..6bc0408 Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rmeta differ diff --git a/merkly/accelerator/libmerkle_root/target/release/deps/libmerkle_root-671ba0fe5bfc9244.d b/merkly/accelerator/libmerkle_root/target/release/deps/libmerkle_root-671ba0fe5bfc9244.d new file mode 100644 index 0000000..4abb586 --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/release/deps/libmerkle_root-671ba0fe5bfc9244.d @@ -0,0 +1,7 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/release/deps/libmerkle_root-671ba0fe5bfc9244.rmeta: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/release/deps/liblibmerkle_root-671ba0fe5bfc9244.rlib: src/lib.rs + +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/release/deps/libmerkle_root-671ba0fe5bfc9244.d: src/lib.rs + +src/lib.rs: diff --git a/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.d b/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.d new file mode 100644 index 0000000..7a113ba --- /dev/null +++ b/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.d @@ -0,0 +1 @@ +/Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.rlib: /Users/olivmath/Documents/dev/personal/merkly/merkly/accelerator/libmerkle_root/src/lib.rs diff --git a/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.rlib b/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.rlib new file mode 100644 index 0000000..492b22b Binary files /dev/null and b/merkly/accelerator/libmerkle_root/target/release/liblibmerkle_root.rlib differ diff --git a/merkly/accelerator/mtreers.py b/merkly/accelerator/mtreers.py new file mode 100644 index 0000000..20c9104 --- /dev/null +++ b/merkly/accelerator/mtreers.py @@ -0,0 +1,25 @@ +from Crypto.Hash import keccak as cryptodome_keccak +from typing import List +from ctypes import ( + CDLL, + CFUNCTYPE, + c_ubyte, + c_size_t, + POINTER, + cast, + memmove, +) + + +class MTreers: + def __init__(self) -> None: + ... + + def make_root(self, leaves: List[bytes]) -> bytes: + ... + + def make_proof(self, leaves: List[bytes]) -> bytes: + ... + + def verify(self, proof: List[bytes], raw_leaf: str) -> bytes + ... \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index a87b8bf..f02ebdf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,8 @@ classifiers = [ [tool.poetry.dependencies] pycryptodome = "^3.19.0" pydantic = "^1.10.2" - python = "^3.8" + python = ">=3.9,<4.0" +matplotlib = "^3.8.2" [tool.poetry.dev-dependencies] conventional-pre-commit = "^3.0.0" diff --git a/test/accelerator/test_accelerator.py b/test/accelerator/test_accelerator.py new file mode 100644 index 0000000..3a557dd --- /dev/null +++ b/test/accelerator/test_accelerator.py @@ -0,0 +1,31 @@ +""" +Testing Merkle Tree +""" + +from merkly.accelerator.mtreers import MTreers +from merkly.mtree import MerkleTree +from Crypto.Hash import keccak + + +def hashing(x: bytes, y: bytes = bytes()) -> bytes: + data: bytes = x + y + keccak_256 = keccak.new(digest_bits=256) + keccak_256.update(data) + return keccak_256.digest() + + +def test_merkle_root_rust_and_merkle_root_python(): + """ + Instantiated a simple Merkle Tree + """ + leafs = ["a", "b", "c", "d"] + tree = MerkleTree(leafs) + treers = MTreers() + + bytes_leaves = list(map(lambda x: x.encode(), leafs)) + hash_leaves = list(map(hashing, bytes_leaves)) + + print(tree.human_leaves) + treers.make_root(hash_leaves) + + assert 1 == 2 diff --git a/test/merkletreejs/compare.py b/test/merkletreejs/compare.py new file mode 100644 index 0000000..c4746f8 --- /dev/null +++ b/test/merkletreejs/compare.py @@ -0,0 +1,31 @@ +import hashlib + + +def hash_function(data): + return hashlib.sha256(data).digest() + + +def merkle_tree_root(leaves): + # Converte as folhas para hashed leaves se necessário + hashed_leaves = [hash_function(leaf.encode()) for leaf in leaves] + + # Constrói as camadas da árvore + while len(hashed_leaves) > 1: + # Se o número de nós for ímpar, duplica o último nó + if len(hashed_leaves) % 2 == 1: + hashed_leaves.append(hashed_leaves[-1]) + + # Combina cada par de nós consecutivos + hashed_leaves = [ + hash_function(hashed_leaves[i] + hashed_leaves[i + 1]) + for i in range(0, len(hashed_leaves), 2) + ] + + # Retorna a raiz da Merkle + return hashed_leaves[0] + + +# Exemplo de uso +leaves = ["a", "b", "c", "d", "e", "f", "g"] +root = merkle_tree_root(leaves) +print(root.hex()) # Retorna a raiz da Merkle em formato hexadecimal diff --git a/test/merkletreejs/index.js b/test/merkletreejs/index.js new file mode 100644 index 0000000..95dfb3e --- /dev/null +++ b/test/merkletreejs/index.js @@ -0,0 +1,15 @@ +const { MerkleTree } = require('merkletreejs') +const web3 = require("web3") +const SHA256 = require('crypto-js/sha256') + + +// const keccak = (data) => web3.utils.keccak256(data) + + +const leaves = ['a', 'b', 'c', 'd', 'e', 'f', 'g'].map(SHA256) +const tree = new MerkleTree(leaves, SHA256, {}) +const root = tree.getRoot().toString('hex') + +// console.log(leaves) +console.log(root) + diff --git a/test/merkletreejs/index.py b/test/merkletreejs/index.py new file mode 100644 index 0000000..220ca1d --- /dev/null +++ b/test/merkletreejs/index.py @@ -0,0 +1,45 @@ +from Crypto.Hash import keccak + +import hashlib + + +def hashing(data): + return hashlib.sha256(data.encode()).hexdigest() + + +def hashing2(data: str): + keccak_256 = keccak.new(digest_bits=256) + keccak_256.update(data.encode()) + return keccak_256.hexdigest() + + +class MerkleTree: + def __init__(self, leaves): + self.leaves = [hashing2(leaf) for leaf in leaves] + self.tree = self.build_tree(self.leaves) + + def build_tree(self, leaves): + tree = [leaves] + while len(tree[-1]) > 1: + layer = tree[-1] + next_layer = [] + for i in range(0, len(layer), 2): + left = layer[i] + right = layer[i + 1] if i + 1 < len(layer) else left + next_layer.append(hashing2(left + right)) + tree.append(next_layer) + return tree + + def get_merkle_root(self): + return self.tree[-1][0] if self.tree else None + + +leaves = ["a", "b", "c", "d"] +tree = MerkleTree(leaves) + +root = tree.get_merkle_root() +leafs = tree.leaves + +for i in leafs: + print(i) +print(root) diff --git a/test/merkletreejs/main.js b/test/merkletreejs/main.js new file mode 100644 index 0000000..bcb2d44 --- /dev/null +++ b/test/merkletreejs/main.js @@ -0,0 +1,2825 @@ +import { Buffer } from 'buffer' +import CryptoJS from 'crypto-js' + +export class Base { + /** + * print + * @desc Prints out a visual representation of the merkle tree. + * @example + *```js + *tree.print() + *``` + */ + print (): void { + Base.print(this) + } + + /** + * bufferIndexOf + * @desc Returns the first index of which given buffer is found in array. + * @param {Buffer[]} haystack - Array of buffers. + * @param {Buffer} needle - Buffer to find. + * @return {Number} - Index number + * + * @example + * ```js + *const index = tree.bufferIndexOf(haystack, needle) + *``` + */ + protected bufferIndexOf ( + array: Buffer[], + element: Buffer, + isSorted: boolean = false + ): number { + if (isSorted) { + return this.binarySearch(array, element, Buffer.compare) + } + + const eqChecker = (buffer1, buffer2) => buffer1.equals(buffer2) + return this.linearSearch(array, element, eqChecker) + } + + /** + * binarySearch + * @desc Returns the first index of which given item is found in array using binary search. + * @param {Buffer[]} array - Array of items. + * @param {Buffer} element - Item to find. + * @param {Function} compareFunction + * @return {Number} - Index number + * + * @example + * ```js + *const index = MerkleTree.binarySearch(array, element, Buffer.compare) + *``` + */ + static binarySearch ( + array: Buffer[], + element: Buffer, + compareFunction: (a: unknown, b: unknown) => number + ): number { + let start = 0 + let end = array.length - 1 + + // Iterate while start not meets end + while (start <= end) { + // Find the mid index + const mid = Math.floor((start + end) / 2) + + // Check if the mid value is greater than, equal to, or less than search element. + const ordering = compareFunction(array[mid], element) + + // If element is present at mid, start iterating for searching first appearance. + if (ordering === 0) { + // Linear reverse iteration until the first matching item index is found. + for (let i = mid - 1; i >= 0; i--) { + if (compareFunction(array[i], element) === 0) continue + return i + 1 + } + return 0 + } /* Else look in left or right half accordingly */ else if (ordering < 0) { + start = mid + 1 + } else { + end = mid - 1 + } + } + + return -1 + } + + /** + * binarySearch + * @desc Returns the first index of which given item is found in array using binary search. + * @param {Buffer[]} array - Array of items. + * @param {Buffer} element - Item to find. + * @param {Function} compareFunction + * @return {Number} - Index number + * + * @example + * ```js + *const index = tree.binarySearch(array, element, Buffer.compare) + *``` + */ + binarySearch ( + array: Buffer[], + element: Buffer, + compareFunction: (a: unknown, b: unknown) => number + ): number { + return Base.binarySearch(array, element, compareFunction) + } + + /** + * linearSearch + * @desc Returns the first index of which given item is found in array using linear search. + * @param {Buffer[]} array - Array of items. + * @param {Buffer} element - Item to find. + * @param {Function} eqChecker + * @return {Number} - Index number + * + * @example + * ```js + *const index = MerkleTree.linearSearch(array, element, (a, b) => a === b) + *``` + */ + static linearSearch (array: Buffer[], element: Buffer, eqChecker: (a: unknown, b: unknown) => boolean):number { + for (let i = 0; i < array.length; i++) { + if (eqChecker(array[i], element)) { + return i + } + } + + return -1 + } + + /** + * linearSearch + * @desc Returns the first index of which given item is found in array using linear search. + * @param {Buffer[]} array - Array of items. + * @param {Buffer} element - Item to find. + * @param {Function} eqChecker + * @return {Number} - Index number + * + * @example + * ```js + *const index = tree.linearSearch(array, element, (a, b) => a === b) + *``` + */ + linearSearch (array: Buffer[], element: Buffer, eqChecker: (a: unknown, b: unknown) => boolean):number { + return Base.linearSearch(array, element, eqChecker) + } + + /** + * bufferify + * @desc Returns a buffer type for the given value. + * @param {String|Number|Object|Buffer|ArrayBuffer} value + * @return {Buffer} + * + * @example + * ```js + *const buf = MerkleTree.bufferify('0x1234') + *``` + */ + static bufferify (value: any): Buffer { + if (!Buffer.isBuffer(value)) { + // crypto-js support + if (typeof value === 'object' && value.words) { + return Buffer.from(value.toString(CryptoJS.enc.Hex), 'hex') + } else if (Base.isHexString(value)) { + return Buffer.from(value.replace(/^0x/, ''), 'hex') + } else if (typeof value === 'string') { + return Buffer.from(value) + } else if (typeof value === 'bigint') { + return Buffer.from(value.toString(16), 'hex') + } else if (value instanceof Uint8Array) { + return Buffer.from(value.buffer) + } else if (typeof value === 'number') { + let s = value.toString() + if (s.length % 2) { + s = `0${s}` + } + return Buffer.from(s, 'hex') + } else if (ArrayBuffer.isView(value)) { + return Buffer.from(value.buffer, value.byteOffset, value.byteLength) + } + } + + return value + } + + bigNumberify (value: any): BigInt { + return Base.bigNumberify(value) + } + + static bigNumberify (value: any): BigInt { + if (typeof value === 'bigint') { + return value + } + + if (typeof value === 'string') { + if (value.startsWith('0x') && Base.isHexString(value)) { + return BigInt('0x' + value.replace('0x', '').toString()) + } + return BigInt(value) + } + + if (Buffer.isBuffer(value)) { + return BigInt('0x' + value.toString('hex')) + } + + if (value instanceof Uint8Array) { + return BigInt(value) + } + + if (typeof value === 'number') { + return BigInt(value) + } + + throw new Error('cannot bigNumberify') + } + + /** + * isHexString + * @desc Returns true if value is a hex string. + * @param {String} value + * @return {Boolean} + * + * @example + * ```js + *console.log(MerkleTree.isHexString('0x1234')) + *``` + */ + static isHexString (v: string): boolean { + return typeof v === 'string' && /^(0x)?[0-9A-Fa-f]*$/.test(v) + } + + /** + * print + * @desc Prints out a visual representation of the given merkle tree. + * @param {Object} tree - Merkle tree instance. + * @return {String} + * @example + *```js + *MerkleTree.print(tree) + *``` + */ + static print (tree: any): void { + console.log(tree.toString()) + } + + /** + * bufferToHex + * @desc Returns a hex string with 0x prefix for given buffer. + * @param {Buffer} value + * @return {String} + * @example + *```js + *const hexStr = tree.bufferToHex(Buffer.from('A')) + *``` + */ + bufferToHex (value: Buffer, withPrefix: boolean = true): string { + return Base.bufferToHex(value, withPrefix) + } + + /** + * bufferToHex + * @desc Returns a hex string with 0x prefix for given buffer. + * @param {Buffer} value + * @return {String} + * @example + *```js + *const hexStr = MerkleTree.bufferToHex(Buffer.from('A')) + *``` + */ + static bufferToHex (value: Buffer, withPrefix: boolean = true): string { + return `${withPrefix ? '0x' : ''}${(value || Buffer.alloc(0)).toString( + 'hex' + )}` + } + + /** + * bufferify + * @desc Returns a buffer type for the given value. + * @param {String|Number|Object|Buffer} value + * @return {Buffer} + * + * @example + * ```js + *const buf = tree.bufferify('0x1234') + *``` + */ + bufferify (value: any): Buffer { + return Base.bufferify(value) + } + + /** + * bufferifyFn + * @desc Returns a function that will bufferify the return value. + * @param {Function} + * @return {Function} + * + * @example + * ```js + *const fn = tree.bufferifyFn((value) => sha256(value)) + *``` + */ + bufferifyFn (f: any): any { + return (value: any): Buffer => { + const v = f(value) + if (Buffer.isBuffer(v)) { + return v + } + + if (this.isHexString(v)) { + return Buffer.from(v.replace('0x', ''), 'hex') + } + + if (typeof v === 'string') { + return Buffer.from(v) + } + + if (typeof v === 'bigint') { + return Buffer.from(value.toString(16), 'hex') + } + + if (ArrayBuffer.isView(v)) { + return Buffer.from(v.buffer, v.byteOffset, v.byteLength) + } + + // crypto-js support + return Buffer.from( + f(CryptoJS.enc.Hex.parse(value.toString('hex'))).toString( + CryptoJS.enc.Hex + ), + 'hex' + ) + } + } + + /** + * isHexString + * @desc Returns true if value is a hex string. + * @param {String} value + * @return {Boolean} + * + * @example + * ```js + *console.log(MerkleTree.isHexString('0x1234')) + *``` + */ + protected isHexString (value: string): boolean { + return Base.isHexString(value) + } + + /** + * log2 + * @desc Returns the log2 of number. + * @param {Number} value + * @return {Number} + */ + protected log2 (n: number): number { + return n === 1 ? 0 : 1 + this.log2((n / 2) | 0) + } + + /** + * zip + * @desc Returns true if value is a hex string. + * @param {String[]|Number[]|Buffer[]} a - first array + * @param {String[]|Number[]|Buffer[]} b - second array + * @return {String[][]|Number[][]|Buffer[][]} + * + * @example + * ```js + *const zipped = tree.zip(['a', 'b'],['A', 'B']) + *console.log(zipped) // [ [ 'a', 'A' ], [ 'b', 'B' ] ] + *``` + */ + protected zip (a: any[], b: any[]): any[][] { + return a.map((e, i) => [e, b[i]]) + } + + static hexZeroPad (hexStr: string, length: number) { + return '0x' + hexStr.replace('0x', '').padStart(length, '0') + } +} + + + +import Base from './Base' +import treeify from 'treeify' + +export interface Options { + depth?: number + // how many inputs per node + arity?: number + zeroValue?: any +} + +export class IncrementalMerkleTree extends Base { + private depth?: number + private arity?: number + private zeroes?: any[] + private root?: any + private nodes?: any[] + private hashFn: any + private zeroValue: any + + constructor (hashFn: any, options: Options) { + super() + this.hashFn = hashFn + if (options.depth) { + this.depth = options.depth + } + if (options.arity) { + this.arity = options.arity + } + + if (this.depth < 1) { + throw new Error('depth must be greater than 0') + } + + if (this.arity < 1) { + throw new Error('arity must be greater than 0') + } + + const nodes = [] + let zeroValue = options.zeroValue + this.zeroValue = zeroValue + this.zeroes = [] + if (this.depth) { + for (let i = 0; i < this.depth; i++) { + this.zeroes.push(zeroValue) + nodes[i] = [] + zeroValue = this.hashFn(Array(this.arity).fill(zeroValue)) + } + } + + this.nodes = nodes + this.root = zeroValue + } + + getRoot () { + return this.root + } + + getHexRoot () { + return this.bufferToHex(this.bufferify(this.getRoot())) + } + + insert (leaf: any) { + if (this.depth && this.arity) { + if (this.nodes[0].length >= this.getMaxLeaves()) { + throw new Error('tree is full') + } + } + + let node = leaf + let index = this.nodes[0].length + + for (let level = 0; level < this.depth; level += 1) { + const position = index % this.arity + const levelStartIndex = index - position + const levelEndIndex = levelStartIndex + this.arity + + const children = [] + this.nodes[level][index] = node + + for (let i = levelStartIndex; i < levelEndIndex; i += 1) { + if (i < this.nodes[level].length) { + children.push(this.nodes[level][i]) + } else { + children.push(this.zeroes[level]) + } + } + + node = this.hashFn(children) + index = Math.floor(index / this.arity) + } + + this.root = node + } + + delete (index: number) { + this.update(index, this.zeroValue) + } + + update (index: number, newLeaf: any) { + if (index < 0 || index >= this.nodes[0].length) { + throw new Error('out of bounds') + } + + let node = newLeaf + + for (let level = 0; level < this.depth; level += 1) { + const position = index % this.arity + const levelStartIndex = index - position + const levelEndIndex = levelStartIndex + this.arity + + const children = [] + this.nodes[level][index] = node + + for (let i = levelStartIndex; i < levelEndIndex; i += 1) { + if (i < this.nodes[level].length) { + children.push(this.nodes[level][i]) + } else { + children.push(this.zeroes[level]) + } + } + + node = this.hashFn(children) + index = Math.floor(index / this.arity) + } + + this.root = node + } + + getDepth (): number { + return this.depth + } + + getArity (): number { + return this.arity + } + + getMaxLeaves (): number { + return this.depth ** this.arity + } + + indexOf (leaf: any): number { + return this.nodes[0].indexOf(leaf) + } + + getLeaves () { + const leaves = this.copyList(this.nodes[0]) + const index = this.nodes[0].length + for (let i = index; i < this.getMaxLeaves(); i++) { + leaves[i] = this.zeroValue + } + return leaves + } + + copyList (list: any[]) { + return list.map((x: any) => BigInt(x)) + } + + getLayers ():any[] { + const layers = [] + + for (const list of this.nodes) { + layers.push(this.copyList(list)) + } + + if (layers[0].length < this.getMaxLeaves()) { + let index = layers[0].length + for (let i = index; i < this.getMaxLeaves(); i++) { + layers[0][i] = this.zeroValue + } + for (let level = 0; level < this.depth; level++) { + const position = index % this.arity + const levelStartIndex = index - position + const levelEndIndex = levelStartIndex + this.arity + + for (let i = levelStartIndex; i < levelEndIndex; i++) { + if (i >= layers[level].length) { + layers[level][i] = this.zeroes[level] + } + } + index = Math.floor(index / this.arity) + } + } + + layers.push([this.root]) + return layers + } + + getHexLayers ():string[] { + return this.getLayers().reduce((acc: string[][], item: Buffer[]) => { + if (Array.isArray(item)) { + acc.push(item.map(layer => this.bufferToHex(this.bufferify(layer)))) + } else { + acc.push(item) + } + + return acc + }, []) + } + + getLayersAsObject ():any { + const layers: any[] = this.getLayers().map((layer: any) => layer.map((value: any) => this.bufferToHex(this.bufferify(value), false))) + const objs = [] + for (let i = 0; i < layers.length; i++) { + const arr = [] + for (let j = 0; j < layers[i].length; j++) { + const obj = { [layers[i][j]]: null } + if (objs.length) { + obj[layers[i][j]] = {} + const a = objs.shift() + const akey = Object.keys(a)[0] + obj[layers[i][j]][akey] = a[akey] + if (objs.length) { + const b = objs.shift() + const bkey = Object.keys(b)[0] + obj[layers[i][j]][bkey] = b[bkey] + } + } + + arr.push(obj) + } + + objs.push(...arr) + } + + return objs[0] + } + + computeRoot () { + let node : any + let index = this.nodes[0].length + for (let level = 0; level < this.depth; level += 1) { + const position = index % this.arity + const levelStartIndex = index - position + const levelEndIndex = levelStartIndex + this.arity + + const children = [] + + for (let i = levelStartIndex; i < levelEndIndex; i += 1) { + if (i < this.nodes[level].length) { + children.push(this.nodes[level][i]) + } else { + children.push(this.zeroes[level]) + } + } + + node = this.hashFn(children) + index = Math.floor(index / this.arity) + } + + return node + } + + getProof (index: number): any { + if (index < 0 || index >= this.nodes[0].length) { + throw new Error('The leaf does not exist in this tree') + } + + const siblings: Node[][] = [] + const pathIndices: number[] = [] + const leafIndex = index + + for (let level = 0; level < this.depth; level += 1) { + const position = index % this.arity + const levelStartIndex = index - position + const levelEndIndex = levelStartIndex + this.arity + + pathIndices[level] = position + siblings[level] = [] + + for (let i = levelStartIndex; i < levelEndIndex; i += 1) { + if (i !== index) { + if (i < this.nodes[level].length) { + siblings[level].push(this.nodes[level][i]) + } else { + siblings[level].push(this.zeroes[level]) + } + } + } + + index = Math.floor(index / this.arity) + } + + return { root: this.root, leaf: this.nodes[0][leafIndex], pathIndices, siblings } + } + + verify (proof: any): boolean { + let node = proof.leaf + + for (let i = 0; i < proof.siblings.length; i += 1) { + const children = proof.siblings[i].slice() + + children.splice(proof.pathIndices[i], 0, node) + + node = this.hashFn(children) + } + + return proof.root === node + } + + toString ():string { + return this.toTreeString() + } + + protected toTreeString ():string { + const obj = this.getLayersAsObject() + return treeify.asTree(obj, true) + } +} + +if (typeof window !== 'undefined') { + ;(window as any).IncrementalMerkleTree = IncrementalMerkleTree +} + +import { Buffer } from 'buffer' +import SHA256 from 'crypto-js/sha256' +import Base from './Base' + +// @credit: https://github.com/wanseob/solidity-mmr +/** + * @desc The index of this MMR implementation starts from 1 not 0. + */ +export class MerkleMountainRange extends Base { + root: Buffer = Buffer.alloc(0) + size: number = 0 + width: number = 0 + hashes: any = {} + data: any = {} + hashLeafFn: any + peakBaggingFn: any + hashBranchFn: any + private hashFn: any + + constructor (hashFn = SHA256, leaves: any[] = [], hashLeafFn?: any, peakBaggingFn?: any, hashBranchFn?: any) { + super() + leaves = leaves.map(this.bufferify) + this.hashFn = this.bufferifyFn(hashFn) + this.hashLeafFn = hashLeafFn + this.peakBaggingFn = peakBaggingFn + this.hashBranchFn = hashBranchFn + + for (const leaf of leaves) { + this.append(leaf) + } + } + + /** + * @desc This only stores the hashed value of the leaf. + * If you need to retrieve the detail data later, use a map to store them. + */ + append (data: Buffer | string) { + data = this.bufferify(data) + const dataHash = this.hashFn(data) + const dataHashHex = this.bufferToHex(dataHash) + if (!this.data[dataHashHex] || this.bufferToHex(this.hashFn(this.data[dataHashHex])) !== dataHashHex) { + this.data[dataHashHex] = data + } + + const leaf = this.hashLeaf(this.size + 1, dataHash) + this.hashes[this.size + 1] = leaf + this.width += 1 + + // find peaks for enlarged tree + const peakIndexes = this.getPeakIndexes(this.width) + + // the right most peak's value is the new size of the updated tree + this.size = this.getSize(this.width) + + // starting from the left-most peak, get all peak hashes + const peaks = [] + for (let i = 0; i < peakIndexes.length; i++) { + peaks[i] = this._getOrCreateNode(peakIndexes[i]) + } + + // update the tree root hash + this.root = this.peakBagging(this.width, peaks) + } + + /** + * @desc It returns the hash of a leaf node with hash(M | DATA ) + * M is the index of the node. + */ + hashLeaf (index: number, dataHash: Buffer | string) { + dataHash = this.bufferify(dataHash) + if (this.hashLeafFn) { + return this.bufferify(this.hashLeafFn(index, dataHash)) + } + return this.hashFn(Buffer.concat([this.bufferify(index), dataHash])) + } + + /** + * @desc It returns the hash a parent node with hash(M | Left child | Right child) + * M is the index of the node. + */ + hashBranch (index: number, left: any, right: any): any { + if (this.hashBranchFn) { + return this.bufferify(this.hashBranchFn(index, left, right)) + } + return this.hashFn(Buffer.concat([this.bufferify(index), this.bufferify(left), this.bufferify(right)])) + } + + getPeaks () { + const peakIndexes = this.getPeakIndexes(this.width) + const peaks = [] + for (let i = 0; i < peakIndexes.length; i++) { + peaks[i] = this.hashes[peakIndexes[i]] + } + return peaks + } + + getLeafIndex (width: number) { + if (width % 2 === 1) { + return this.getSize(width) + } + + return this.getSize(width - 1) + 1 + } + + /** + * @desc It returns all peaks of the smallest merkle mountain range tree which includes + * the given index(size). + */ + getPeakIndexes (width: number): number[] { + const numPeaks = this.numOfPeaks(width) + const peakIndexes = [] + let count = 0 + let size = 0 + for (let i = 255; i > 0; i--) { + if ((width & (1 << (i - 1))) !== 0) { + // peak exists + size = size + (1 << i) - 1 + peakIndexes[count++] = size + if (peakIndexes.length >= numPeaks) { + break + } + } + } + + if (count !== peakIndexes.length) { + throw new Error('invalid bit calculation') + } + + return peakIndexes + } + + numOfPeaks (width: number): number { + let bits = width + let num = 0 + while (bits > 0) { + if (bits % 2 === 1) { + num++ + } + bits = bits >> 1 + } + return num + } + + peakBagging (width: number, peaks: any[]): any { + const size = this.getSize(width) + if (this.numOfPeaks(width) !== peaks.length) { + throw new Error('received invalid number of peaks') + } + + if (width === 0 && !peaks.length) { + return Buffer.alloc(0) + } + + if (this.peakBaggingFn) { + return this.bufferify(this.peakBaggingFn(size, peaks)) + } + + return this.hashFn(Buffer.concat([this.bufferify(size), ...peaks.map(this.bufferify)])) + } + + /** + * @desc It returns the size of the tree. + */ + getSize (width: number): number { + return (width << 1) - this.numOfPeaks(width) + } + + /** + * @desc It returns the root value of the tree. + */ + getRoot (): any { + return this.root + } + + getHexRoot (): any { + return this.bufferToHex(this.getRoot()) + } + + /** + * @dev It returns the hash value of a node for the given position. Note that the index starts from 1. + */ + getNode (index: number): any { + return this.hashes[index] + } + + /** + * @desc It returns the height of the highest peak. + */ + mountainHeight (size: number): number { + let height = 1 + while (1 << height <= size + height) { + height++ + } + return height - 1 + } + + /** + * @desc It returns the height of the index. + */ + heightAt (index: number): number { + let reducedIndex = index + let peakIndex = 0 + let height = 0 + + // if an index has a left mountain then subtract the mountain + while (reducedIndex > peakIndex) { + reducedIndex -= (1 << height) - 1 + height = this.mountainHeight(reducedIndex) + peakIndex = (1 << height) - 1 + } + + // index is on the right slope + return height - (peakIndex - reducedIndex) + } + + /** + * @desc It returns whether the index is the leaf node or not + */ + isLeaf (index: number): boolean { + return this.heightAt(index) === 1 + } + + /** + * @desc It returns the children when it is a parent node. + */ + getChildren (index: number) { + const left = index - (1 << (this.heightAt(index) - 1)) + const right = index - 1 + if (left === right) { + throw new Error('not a parent') + } + + return [left, right] + } + + /** + * @desc It returns a merkle proof for a leaf. Note that the index starts from 1. + */ + getMerkleProof (index: number) { + if (index > this.size) { + throw new Error('out of range') + } + if (!this.isLeaf(index)) { + throw new Error('not a leaf') + } + + const root = this.root + const width = this.width + + // find all peaks for bagging + const peaks = this.getPeakIndexes(this.width) + const peakBagging = [] + let cursor = 0 + + for (let i = 0; i < peaks.length; i++) { + // collect the hash of all peaks + peakBagging[i] = this.hashes[peaks[i]] + + // find the peak which includes the target index + if (peaks[i] >= index && cursor === 0) { + cursor = peaks[i] + } + } + + let left = 0 + let right = 0 + + // get hashes of the siblings in the mountain which the index belgons to. + // it moves the cursor from the summit of the mountain down to the target index + let height = this.heightAt(cursor) + const siblings = [] + while (cursor !== index) { + height-- + ([left, right] = this.getChildren(cursor)) + + // move the cursor down to the left size or right size + cursor = index <= left ? left : right + + // remaining node is the sibling + siblings[height - 1] = this.hashes[index <= left ? right : left] + } + + return { + root, + width, + peakBagging, + siblings + } + } + + /** + * @desc It returns true when the given params verifies that the given value exists in the tree or reverts the transaction. + */ + verify (root: any, width: number, index: number, value: Buffer | string, peaks: any[], siblings: any[]) { + value = this.bufferify(value) + const size = this.getSize(width) + if (size < index) { + throw new Error('index is out of range') + } + + // check the root equals the peak bagging hash + if (!root.equals(this.peakBagging(width, peaks))) { + throw new Error('invalid root hash from the peaks') + } + + // find the mountain where the target index belongs to + let cursor = 0 + let targetPeak : number + + const peakIndexes = this.getPeakIndexes(width) + for (let i = 0; i < peakIndexes.length; i++) { + if (peakIndexes[i] >= index) { + targetPeak = peaks[i] + cursor = peakIndexes[i] + break + } + } + + if (!targetPeak) { + throw new Error('target not found') + } + + // find the path climbing down + let height = siblings.length + 1 + const path = new Array(height) + let left = 0 + let right = 0 + + while (height > 0) { + // record the current cursor and climb down + path[--height] = cursor + if (cursor === index) { + // on the leaf node. Stop climbing down + break + } else { + // on the parent node. Go left or right + ([left, right] = this.getChildren(cursor)) + cursor = index > left ? right : left + continue + } + } + + // calculate the summit hash climbing up again + let node : any + while (height < path.length) { + // move cursor + cursor = path[height] + if (height === 0) { + // cusor is on the leaf + node = this.hashLeaf(cursor, this.hashFn(value)) + } else if (cursor - 1 === path[height - 1]) { + // cursor is on a parent and a siblings is on the left + node = this.hashBranch(cursor, siblings[height - 1], node) + } else { + // cursor is on a parent and a siblings is on the right + node = this.hashBranch(cursor, node, siblings[height - 1]) + } + // climb up + height++ + } + + // computed hash value of the summit should equal to the target peak hash + if (!node.equals(targetPeak)) { + throw new Error('hashed peak is invalid') + } + + return true + } + + peaksToPeakMap (width: number, peaks: any[]) { + const peakMap = {} + let bitIndex = 0 + let peakRef = 0 + let count = peaks.length + for (let height = 1; height <= 32; height++) { + // index starts from the right most bit + bitIndex = 32 - height + peakRef = 1 << (height - 1) + if ((width & peakRef) !== 0) { + peakMap[bitIndex] = peaks[--count] + } else { + peakMap[bitIndex] = 0 + } + } + + if (count !== 0) { + throw new Error('invalid number of peaks') + } + + return peakMap + } + + peakMapToPeaks (width: number, peakMap: any) { + const arrLength = this.numOfPeaks(width) + const peaks = new Array(arrLength) + let count = 0 + for (let i = 0; i < 32; i++) { + if (peakMap[i] !== 0) { + peaks[count++] = peakMap[i] + } + } + + if (count !== arrLength) { + throw new Error('invalid number of peaks') + } + + return peaks + } + + peakUpdate (width: number, prevPeakMap: any, itemHash: any) { + const nextPeakMap = {} + const newWidth = width + 1 + let cursorIndex = this.getLeafIndex(newWidth) + let cursorNode = this.hashLeaf(cursorIndex, itemHash) + let bitIndex = 0 + let peakRef = 0 + let prevPeakExist = false + let nextPeakExist = false + let obtained = false + + for (let height = 1; height <= 32; height++) { + // index starts from the right most bit + bitIndex = 32 - height + if (obtained) { + nextPeakMap[bitIndex] = prevPeakMap[bitIndex] + } else { + peakRef = 1 << (height - 1) + prevPeakExist = (width & peakRef) !== 0 + nextPeakExist = (newWidth & peakRef) !== 0 + + // get new cursor node with hashing the peak and the current cursor + cursorIndex++ + if (prevPeakExist) { + cursorNode = this.hashBranch(cursorIndex, prevPeakMap[bitIndex], cursorNode) + } + // if new peak exists for the bit index + if (nextPeakExist) { + // if prev peak exists for the bit index + if (prevPeakExist) { + nextPeakMap[bitIndex] = prevPeakMap[bitIndex] + } else { + nextPeakMap[bitIndex] = cursorNode + } + obtained = true + } else { + nextPeakMap[bitIndex] = 0 + } + } + } + + return nextPeakMap + } + + rollUp (root: any, width: number, peaks: any[], itemHashes: any[]) { + // check the root equals the peak bagging hash + if (!root.equals(this.peakBagging(width, peaks))) { + throw new Error('invalid root hash from the peaks') + } + + let tmpWidth = width + let tmpPeakMap = this.peaksToPeakMap(width, peaks) + for (let i = 0; i < itemHashes.length; i++) { + tmpPeakMap = this.peakUpdate(tmpWidth, tmpPeakMap, itemHashes[i]) + tmpWidth++ + } + + return this.peakBagging(tmpWidth, this.peakMapToPeaks(tmpWidth, tmpPeakMap)) + } + + /** + * @desc It returns the hash value of the node for the index. + * If the hash already exists it simply returns the stored value. On the other hand, + * it computes hashes recursively downward. + * Only appending an item calls this function. + */ + private _getOrCreateNode (index: number) { + if (index > this.size) { + throw new Error('out of range') + } + + if (!this.hashes[index]) { + const [leftIndex, rightIndex] = this.getChildren(index) + const leftHash = this._getOrCreateNode(leftIndex) + const rightHash = this._getOrCreateNode(rightIndex) + this.hashes[index] = this.hashBranch(index, leftHash, rightHash) + } + + return this.hashes[index] + } +} + +if (typeof window !== 'undefined') { + ;(window as any).MerkleMountainRange = MerkleMountainRange +} + + +import { Base } from './Base' + +// @credit: https://github.com/finalitylabs/pymst + +type TValue = Buffer | BigInt | string | number | null | undefined +type THashFn = (value: TValue) => Buffer + +export class Bucket { + size: BigInt + hashed: Buffer + parent: Bucket | null + left: Bucket | null + right: Bucket | null + + constructor (size: BigInt | number, hashed: Buffer) { + this.size = BigInt(size) + this.hashed = hashed + + // each node in the tree can have a parent, and a left or right sibling + this.parent = null + this.left = null + this.right = null + } +} + +export class Leaf { + hashFn: THashFn + rng: BigInt[] + data: Buffer | null + + constructor (hashFn: THashFn, rng: (number | BigInt)[], data: Buffer | null) { + this.hashFn = hashFn + this.rng = rng.map(x => BigInt(x)) + this.data = data + } + + getBucket () { + let hashed : Buffer + if (this.data) { + hashed = this.hashFn(this.data) + } else { + hashed = Buffer.alloc(32) + } + return new Bucket(BigInt(this.rng[1]) - BigInt(this.rng[0]), hashed) + } +} + +export class ProofStep { + bucket: Bucket + right: boolean + + constructor (bucket: Bucket, right: boolean) { + this.bucket = bucket + this.right = right // whether the bucket hash should be appeded on the right side in this step (default is left + } +} + +export class MerkleSumTree extends Base { + hashFn: THashFn + leaves: Leaf[] + buckets: Bucket[] + root: Bucket + + constructor (leaves: Leaf[], hashFn: THashFn) { + super() + this.leaves = leaves + this.hashFn = hashFn + + MerkleSumTree.checkConsecutive(leaves) + + this.buckets = [] + for (const l of leaves) { + this.buckets.push(l.getBucket()) + } + + let buckets = [] + for (const bucket of this.buckets) { + buckets.push(bucket) + } + + while (buckets.length !== 1) { + const newBuckets = [] + while (buckets.length) { + if (buckets.length >= 2) { + const b1 = buckets.shift() + const b2 = buckets.shift() + const size = b1.size + b2.size + const hashed = this.hashFn(Buffer.concat([this.sizeToBuffer(b1.size), this.bufferify(b1.hashed), this.sizeToBuffer(b2.size), this.bufferify(b2.hashed)])) + const b = new Bucket(size, hashed) + b2.parent = b + b1.parent = b2.parent + b1.right = b2 + b2.left = b1 + newBuckets.push(b) + } else { + newBuckets.push(buckets.shift()) + } + } + buckets = newBuckets + } + this.root = buckets[0] + } + + sizeToBuffer (size: BigInt) { + const buf = Buffer.alloc(8) + const view = new DataView(buf.buffer) + view.setBigInt64(0, BigInt(size), false) // true when little endian + return buf + } + + static checkConsecutive (leaves: Leaf[]) { + let curr = BigInt(0) + for (const leaf of leaves) { + if (leaf.rng[0] !== curr) { + throw new Error('leaf ranges are invalid') + } + curr = BigInt(leaf.rng[1]) + } + } + + // gets inclusion/exclusion proof of a bucket in the specified index + getProof (index: number | BigInt) { + let curr = this.buckets[Number(index)] + const proof = [] + while (curr && curr.parent) { + const right = !!curr.right + const bucket = curr.right ? curr.right : curr.left + curr = curr.parent + proof.push(new ProofStep(bucket, right)) + } + return proof + } + + sum (arr: BigInt[]) { + let total = BigInt(0) + for (const value of arr) { + total += BigInt(value) + } + return total + } + + // validates the suppplied proof for a specified leaf according to the root bucket + verifyProof (root: Bucket, leaf: Leaf, proof: ProofStep[]) { + const rng = [this.sum(proof.filter(x => !x.right).map(x => x.bucket.size)), BigInt(root.size) - this.sum(proof.filter(x => x.right).map(x => x.bucket.size))] + if (!(rng[0] === leaf.rng[0] && rng[1] === leaf.rng[1])) { + // supplied steps are not routing to the range specified + return false + } + let curr = leaf.getBucket() + let hashed :Buffer + for (const step of proof) { + if (step.right) { + hashed = this.hashFn(Buffer.concat([this.sizeToBuffer(curr.size), this.bufferify(curr.hashed), this.sizeToBuffer(step.bucket.size), this.bufferify(step.bucket.hashed)])) + } else { + hashed = this.hashFn(Buffer.concat([this.sizeToBuffer(step.bucket.size), this.bufferify(step.bucket.hashed), this.sizeToBuffer(curr.size), this.bufferify(curr.hashed)])) + } + curr = new Bucket(BigInt(curr.size) + BigInt(step.bucket.size), hashed) + } + return curr.size === root.size && curr.hashed.toString('hex') === root.hashed.toString('hex') + } +} + +if (typeof window !== 'undefined') { + ;(window as any).MerkleSumTree = MerkleSumTree +} + + +import { Buffer } from 'buffer' +import reverse from 'buffer-reverse' +import SHA256 from 'crypto-js/sha256' +import treeify from 'treeify' +import Base from './Base' + +// TODO: Clean up and DRY up code +// Disclaimer: The multiproof code is unaudited and may possibly contain serious issues. It's in a hacky state as is and needs to be rewritten. + +type TValue = Buffer | BigInt | string | number | null | undefined +type THashFnResult = Buffer | string +type THashFn = (value: TValue) => Buffer +type TLeaf = Buffer +type TLayer = any +type TFillDefaultHash = (idx?: number, hashFn?: THashFn) => THashFnResult + +export interface Options { + /** If set to `true`, an odd node will be duplicated and combined to make a pair to generate the layer hash. */ + duplicateOdd?: boolean + /** If set to `true`, the leaves will hashed using the set hashing algorithms. */ + hashLeaves?: boolean + /** If set to `true`, constructs the Merkle Tree using the [Bitcoin Merkle Tree implementation](http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html). Enable it when you need to replicate Bitcoin constructed Merkle Trees. In Bitcoin Merkle Trees, single nodes are combined with themselves, and each output hash is hashed again. */ + isBitcoinTree?: boolean + /** If set to `true`, the leaves will be sorted. Recommended for use of multiProofs. */ + sortLeaves?: boolean + /** If set to `true`, the hashing pairs will be sorted. */ + sortPairs?: boolean + /** If set to `true`, the leaves and hashing pairs will be sorted. */ + sort?: boolean + /** If defined, the resulting hash of this function will be used to fill in odd numbered layers. */ + fillDefaultHash?: TFillDefaultHash | Buffer | string + /** If set to `true`, the resulting tree will be a complete tree. Recommended for use of multiProofs. */ + complete?: boolean; + + concatenator?: (inputs: Buffer[]) => Buffer | Buffer[] | BigInt[] +} + +/** + * Class reprensenting a Merkle Tree + * @namespace MerkleTree + */ +export class MerkleTree extends Base { + private duplicateOdd: boolean = false + private hashFn: THashFn + private concatenator: any = Buffer.concat + private hashLeaves: boolean = false + private isBitcoinTree: boolean = false + private leaves: TLeaf[] = [] + private layers: TLayer[] = [] + private sortLeaves: boolean = false + private sortPairs: boolean = false + private sort: boolean = false + private fillDefaultHash: TFillDefaultHash | null = null + private complete: boolean = false + + /** + * @desc Constructs a Merkle Tree. + * All nodes and leaves are stored as Buffers. + * Lonely leaf nodes are promoted to the next level up without being hashed again. + * @param {Buffer[]} leaves - Array of hashed leaves. Each leaf must be a Buffer. + * @param {Function} hashFunction - Hash function to use for hashing leaves and nodes + * @param {Object} options - Additional options + * @example + *```js + *const MerkleTree = require('merkletreejs') + *const crypto = require('crypto') + * + *function sha256(data) { + * // returns Buffer + * return crypto.createHash('sha256').update(data).digest() + *} + * + *const leaves = ['a', 'b', 'c'].map(value => keccak(value)) + * + *const tree = new MerkleTree(leaves, sha256) + *``` + */ + constructor (leaves: any[], hashFn = SHA256, options: Options = {}) { + super() + + if (options.complete) { + if (options.isBitcoinTree) { + throw new Error('option "complete" is incompatible with "isBitcoinTree"') + } + if (options.duplicateOdd) { + throw new Error('option "complete" is incompatible with "duplicateOdd"') + } + } + + this.isBitcoinTree = !!options.isBitcoinTree + this.hashLeaves = !!options.hashLeaves + this.sortLeaves = !!options.sortLeaves + this.sortPairs = !!options.sortPairs + this.complete = !!options.complete + + if (options.fillDefaultHash) { + if (typeof options.fillDefaultHash === 'function') { + this.fillDefaultHash = options.fillDefaultHash + } else if (Buffer.isBuffer(options.fillDefaultHash) || typeof options.fillDefaultHash === 'string') { + this.fillDefaultHash = (idx?: number, hashFn?: THashFn):THashFnResult => options.fillDefaultHash as THashFnResult + } else { + throw new Error('method "fillDefaultHash" must be a function, Buffer, or string') + } + } + + this.sort = !!options.sort + if (this.sort) { + this.sortLeaves = true + this.sortPairs = true + } + + this.duplicateOdd = !!options.duplicateOdd + + if (options.concatenator) { + this.concatenator = options.concatenator + } + + this.hashFn = this.bufferifyFn(hashFn) + this.processLeaves(leaves) + } + + public getOptions () { + return { + complete: this.complete, + isBitcoinTree: this.isBitcoinTree, + hashLeaves: this.hashLeaves, + sortLeaves: this.sortLeaves, + sortPairs: this.sortPairs, + sort: this.sort, + fillDefaultHash: this.fillDefaultHash?.toString() ?? null, + duplicateOdd: this.duplicateOdd + } + } + + private processLeaves (leaves: TLeaf[]) { + if (this.hashLeaves) { + leaves = leaves.map(this.hashFn) + } + + this.leaves = leaves.map(this.bufferify) + if (this.sortLeaves) { + this.leaves = this.leaves.sort(Buffer.compare) + } + + if (this.fillDefaultHash) { + for (let i = this.leaves.length; i < Math.pow(2, Math.ceil(Math.log2(this.leaves.length))); i++) { + this.leaves.push(this.bufferify(this.fillDefaultHash(i, this.hashFn))) + } + } + + this.createHashes(this.leaves) + } + + private createHashes (nodes: any[]) { + this.layers = [nodes] + while (nodes.length > 1) { + const layerIndex = this.layers.length + + this.layers.push([]) + + const layerLimit = this.complete && layerIndex === 1 && !Number.isInteger(Math.log2(nodes.length)) + ? (2 * nodes.length) - (2 ** Math.ceil(Math.log2(nodes.length))) + : nodes.length + + for (let i = 0; i < nodes.length; i += 2) { + if (i >= layerLimit) { + this.layers[layerIndex].push(...nodes.slice(layerLimit)) + break + } else if (i + 1 === nodes.length) { + if (nodes.length % 2 === 1) { + const data = nodes[nodes.length - 1] + let hash = data + + // is bitcoin tree + if (this.isBitcoinTree) { + // Bitcoin method of duplicating the odd ending nodes + hash = this.hashFn(this.concatenator([reverse(data), reverse(data)])) + hash = reverse(this.hashFn(hash)) + + this.layers[layerIndex].push(hash) + continue + } else { + if (this.duplicateOdd) { + // continue with creating layer + } else { + // push copy of hash and continue iteration + this.layers[layerIndex].push(nodes[i]) + continue + } + } + } + } + + const left = nodes[i] + const right = i + 1 === nodes.length ? left : nodes[i + 1] + let combined = null + + if (this.isBitcoinTree) { + combined = [reverse(left), reverse(right)] + } else { + combined = [left, right] + } + + if (this.sortPairs) { + combined.sort(Buffer.compare) + } + + let hash = this.hashFn(this.concatenator(combined)) + + // double hash if bitcoin tree + if (this.isBitcoinTree) { + hash = reverse(this.hashFn(hash)) + } + + this.layers[layerIndex].push(hash) + } + + nodes = this.layers[layerIndex] + } + } + + /** + * addLeaf + * @desc Adds a leaf to the tree and re-calculates layers. + * @param {String|Buffer} - Leaf + * @param {Boolean} - Set to true if the leaf should be hashed before being added to tree. + * @example + *```js + *tree.addLeaf(newLeaf) + *``` + */ + addLeaf (leaf: TLeaf, shouldHash: boolean = false) { + if (shouldHash) { + leaf = this.hashFn(leaf) + } + this.processLeaves(this.leaves.concat(leaf)) + } + + /** + * addLeaves + * @desc Adds multiple leaves to the tree and re-calculates layers. + * @param {String[]|Buffer[]} - Array of leaves + * @param {Boolean} - Set to true if the leaves should be hashed before being added to tree. + * @example + *```js + *tree.addLeaves(newLeaves) + *``` + */ + addLeaves (leaves: TLeaf[], shouldHash: boolean = false) { + if (shouldHash) { + leaves = leaves.map(this.hashFn) + } + this.processLeaves(this.leaves.concat(leaves)) + } + + /** + * getLeaves + * @desc Returns array of leaves of Merkle Tree. + * @return {Buffer[]} + * @example + *```js + *const leaves = tree.getLeaves() + *``` + */ + getLeaves (values?: any[]):Buffer[] { + if (Array.isArray(values)) { + if (this.hashLeaves) { + values = values.map(this.hashFn) + if (this.sortLeaves) { + values = values.sort(Buffer.compare) + } + } + + return this.leaves.filter(leaf => this.bufferIndexOf(values, leaf, this.sortLeaves) !== -1) + } + + return this.leaves + } + + /** + * getLeaf + * @desc Returns the leaf at the given index. + * @param {Number} - Index number + * @return {Buffer} + * @example + *```js + *const leaf = tree.getLeaf(1) + *``` + */ + getLeaf (index: number):Buffer { + if (index < 0 || index > this.leaves.length - 1) { + return Buffer.from([]) + } + + return this.leaves[index] + } + + /** + * getLeafIndex + * @desc Returns the index of the given leaf, or -1 if the leaf is not found. + * @param {String|Buffer} - Target leaf + * @return {number} + * @example + *```js + *const leaf = Buffer.from('abc') + *const index = tree.getLeafIndex(leaf) + *``` + */ + getLeafIndex (target: TLeaf):number { + target = this.bufferify(target) + const leaves = this.getLeaves() + for (let i = 0; i < leaves.length; i++) { + const leaf = leaves[i] + if (leaf.equals(target)) { + return i + } + } + + return -1 + } + + /** + * getLeafCount + * @desc Returns the total number of leaves. + * @return {number} + * @example + *```js + *const count = tree.getLeafCount() + *``` + */ + getLeafCount (): number { + return this.leaves.length + } + + /** + * getHexLeaves + * @desc Returns array of leaves of Merkle Tree as hex strings. + * @return {String[]} + * @example + *```js + *const leaves = tree.getHexLeaves() + *``` + */ + getHexLeaves ():string[] { + return this.leaves.map(leaf => this.bufferToHex(leaf)) + } + + /** + * marshalLeaves + * @desc Returns array of leaves of Merkle Tree as a JSON string. + * @param {String[]|Buffer[]} - Merkle tree leaves + * @return {String} - List of leaves as JSON string + * @example + *```js + *const jsonStr = MerkleTree.marshalLeaves(leaves) + *``` + */ + static marshalLeaves (leaves: any[]):string { + return JSON.stringify(leaves.map(leaf => MerkleTree.bufferToHex(leaf)), null, 2) + } + + /** + * unmarshalLeaves + * @desc Returns array of leaves of Merkle Tree as a Buffers. + * @param {String|Object} - JSON stringified leaves + * @return {Buffer[]} - Unmarshalled list of leaves + * @example + *```js + *const leaves = MerkleTree.unmarshalLeaves(jsonStr) + *``` + */ + static unmarshalLeaves (jsonStr: string | object):Buffer[] { + let parsed :any = null + if (typeof jsonStr === 'string') { + parsed = JSON.parse(jsonStr) + } else if (jsonStr instanceof Object) { + parsed = jsonStr + } else { + throw new Error('Expected type of string or object') + } + + if (!parsed) { + return [] + } + + if (!Array.isArray(parsed)) { + throw new Error('Expected JSON string to be array') + } + + return parsed.map(MerkleTree.bufferify) + } + + /** + * getLayers + * @desc Returns multi-dimensional array of all layers of Merkle Tree, including leaves and root. + * @return {Buffer[][]} + * @example + *```js + *const layers = tree.getLayers() + *``` + */ + getLayers ():Buffer[][] { + return this.layers + } + + /** + * getHexLayers + * @desc Returns multi-dimensional array of all layers of Merkle Tree, including leaves and root as hex strings. + * @return {String[][]} + * @example + *```js + *const layers = tree.getHexLayers() + *``` + */ + getHexLayers ():string[][] { + return this.layers.reduce((acc: string[][], item: Buffer[]) => { + if (Array.isArray(item)) { + acc.push(item.map(layer => this.bufferToHex(layer))) + } else { + acc.push(item) + } + + return acc + }, []) + } + + /** + * getLayersFlat + * @desc Returns single flat array of all layers of Merkle Tree, including leaves and root. + * @return {Buffer[]} + * @example + *```js + *const layers = tree.getLayersFlat() + *``` + */ + getLayersFlat ():Buffer[] { + const layers = this.layers.reduce((acc, item) => { + if (Array.isArray(item)) { + acc.unshift(...item) + } else { + acc.unshift(item) + } + + return acc + }, []) + + layers.unshift(Buffer.from([0])) + + return layers + } + + /** + * getHexLayersFlat + * @desc Returns single flat array of all layers of Merkle Tree, including leaves and root as hex string. + * @return {String[]} + * @example + *```js + *const layers = tree.getHexLayersFlat() + *``` + */ + getHexLayersFlat ():string[] { + return this.getLayersFlat().map(layer => this.bufferToHex(layer)) + } + + /** + * getLayerCount + * @desc Returns the total number of layers. + * @return {number} + * @example + *```js + *const count = tree.getLayerCount() + *``` + */ + getLayerCount ():number { + return this.getLayers().length + } + + /** + * getRoot + * @desc Returns the Merkle root hash as a Buffer. + * @return {Buffer} + * @example + *```js + *const root = tree.getRoot() + *``` + */ + getRoot ():Buffer { + if (this.layers.length === 0) { + return Buffer.from([]) + } + + return this.layers[this.layers.length - 1][0] || Buffer.from([]) + } + + /** + * getHexRoot + * @desc Returns the Merkle root hash as a hex string. + * @return {String} + * @example + *```js + *const root = tree.getHexRoot() + *``` + */ + getHexRoot ():string { + return this.bufferToHex(this.getRoot()) + } + + /** + * getProof + * @desc Returns the proof for a target leaf. + * @param {Buffer} leaf - Target leaf + * @param {Number} [index] - Target leaf index in leaves array. + * Use if there are leaves containing duplicate data in order to distinguish it. + * @return {Object[]} - Array of objects containing a position property of type string + * with values of 'left' or 'right' and a data property of type Buffer. + * @example + * ```js + *const proof = tree.getProof(leaves[2]) + *``` + * + * @example + *```js + *const leaves = ['a', 'b', 'a'].map(value => keccak(value)) + *const tree = new MerkleTree(leaves, keccak) + *const proof = tree.getProof(leaves[2], 2) + *``` + */ + getProof (leaf: Buffer | string, index?: number):{position: 'left' | 'right', data: Buffer}[] { + if (typeof leaf === 'undefined') { + throw new Error('leaf is required') + } + leaf = this.bufferify(leaf) + const proof = [] + + if (!Number.isInteger(index)) { + index = -1 + + for (let i = 0; i < this.leaves.length; i++) { + if (Buffer.compare(leaf, this.leaves[i]) === 0) { + index = i + } + } + } + + if (index <= -1) { + return [] + } + + for (let i = 0; i < this.layers.length; i++) { + const layer = this.layers[i] + const isRightNode = index % 2 + const pairIndex = (isRightNode ? index - 1 + : this.isBitcoinTree && index === layer.length - 1 && i < this.layers.length - 1 + // Proof Generation for Bitcoin Trees + ? index + // Proof Generation for Non-Bitcoin Trees + : index + 1) + + if (pairIndex < layer.length) { + proof.push({ + position: isRightNode ? 'left' : 'right', + data: layer[pairIndex] + }) + } + + // set index to parent index + index = (index / 2) | 0 + } + + return proof + } + + /** + * getHexProof + * @desc Returns the proof for a target leaf as hex strings. + * @param {Buffer} leaf - Target leaf + * @param {Number} [index] - Target leaf index in leaves array. + * Use if there are leaves containing duplicate data in order to distinguish it. + * @return {String[]} - Proof array as hex strings. + * @example + * ```js + *const proof = tree.getHexProof(leaves[2]) + *``` + */ + getHexProof (leaf: Buffer | string, index?: number):string[] { + return this.getProof(leaf, index).map(item => this.bufferToHex(item.data)) + } + + /** + * getProofs + * @desc Returns the proofs for all leaves. + * @return {Object[]} - Array of objects containing a position property of type string + * with values of 'left' or 'right' and a data property of type Buffer for all leaves. + * @example + * ```js + *const proofs = tree.getProofs() + *``` + * + * @example + *```js + *const leaves = ['a', 'b', 'a'].map(value => keccak(value)) + *const tree = new MerkleTree(leaves, keccak) + *const proofs = tree.getProofs() + *``` + */ + getProofs ():any[] { + const proof = []; const proofs = [] + + this.getProofsDFS(this.layers.length - 1, 0, proof, proofs) + + return proofs + } + + /** + * getProofsDFS + * @desc Get all proofs through single traverse + * @param {Number} currentLayer - Current layer index in traverse. + * @param {Number} index - Current tarvese node index in traverse. + * @param {Object[]} proof - Proof chain for single leaf. + * @param {Object[]} proofs - Proofs for all leaves + * @example + * ```js + *const layers = tree.getLayers() + *const index = 0; + *let proof = []; + *let proofs = []; + *const proof = tree.getProofsDFS(layers, index, proof, proofs) + *``` + */ + getProofsDFS (currentLayer, index, proof, proofs):any[] { + const isRightNode = index % 2 + if (currentLayer === -1) { + if (!isRightNode) proofs.push([...proof].reverse()) + return + } + if (index >= this.layers[currentLayer].length) return + + const layer = this.layers[currentLayer] + const pairIndex = isRightNode ? index - 1 : index + 1 + + let pushed = false + if (pairIndex < layer.length) { + pushed = true + proof.push({ + position: isRightNode ? 'left' : 'right', + data: layer[pairIndex] + }) + } + + const leftchildIndex = index * 2 + const rightchildIndex = index * 2 + 1 + + this.getProofsDFS(currentLayer - 1, leftchildIndex, proof, proofs) + this.getProofsDFS(currentLayer - 1, rightchildIndex, proof, proofs) + + if (pushed) proof.splice(proof.length - 1, 1) + } + + /** + * getHexProofs + * @desc Returns the proofs for all leaves as hex strings. + * @return {String[]} - Proofs array as hex strings. + * @example + * ```js + *const proofs = tree.getHexProofs() + *``` + */ + getHexProofs ():string[] { + return this.getProofs().map(item => this.bufferToHex(item.data)) + } + + /** + * getPositionalHexProof + * @desc Returns the proof for a target leaf as hex strings and the position in binary (left == 0). + * @param {Buffer} leaf - Target leaf + * @param {Number} [index] - Target leaf index in leaves array. + * Use if there are leaves containing duplicate data in order to distinguish it. + * @return {(string | number)[][]} - Proof array as hex strings. position at index 0 + * @example + * ```js + *const proof = tree.getPositionalHexProof(leaves[2]) + *``` + */ + getPositionalHexProof (leaf: Buffer | string, index?: number): (string | number)[][] { + return this.getProof(leaf, index).map(item => { + return [ + item.position === 'left' ? 0 : 1, + this.bufferToHex(item.data) + ] + }) + } + + /** + * marshalProof + * @desc Returns proof array as JSON string. + * @param {String[]|Object[]} proof - Merkle tree proof array + * @return {String} - Proof array as JSON string. + * @example + * ```js + *const jsonStr = MerkleTree.marshalProof(proof) + *``` + */ + static marshalProof (proof: any[]):string { + const json = proof.map(item => { + if (typeof item === 'string') { + return item + } + + if (Buffer.isBuffer(item)) { + return MerkleTree.bufferToHex(item) + } + + return { + position: item.position, + data: MerkleTree.bufferToHex(item.data) + } + }) + + return JSON.stringify(json, null, 2) + } + + /** + * unmarshalProof + * @desc Returns the proof for a target leaf as a list of Buffers. + * @param {String|Object} - Merkle tree leaves + * @return {String|Object} - Marshalled proof + * @example + * ```js + *const proof = MerkleTree.unmarshalProof(jsonStr) + *``` + */ + static unmarshalProof (jsonStr: string | object):any[] { + let parsed :any = null + if (typeof jsonStr === 'string') { + parsed = JSON.parse(jsonStr) + } else if (jsonStr instanceof Object) { + parsed = jsonStr + } else { + throw new Error('Expected type of string or object') + } + + if (!parsed) { + return [] + } + + if (!Array.isArray(parsed)) { + throw new Error('Expected JSON string to be array') + } + + return parsed.map(item => { + if (typeof item === 'string') { + return MerkleTree.bufferify(item) + } else if (item instanceof Object) { + return { + position: item.position, + data: MerkleTree.bufferify(item.data) + } + } else { + throw new Error('Expected item to be of type string or object') + } + }) + } + + static marshalTree (tree: MerkleTree):string { + const root = tree.getHexRoot() + const leaves = tree.leaves.map(leaf => MerkleTree.bufferToHex(leaf)) + const layers = tree.getHexLayers() + const options = tree.getOptions() + + return JSON.stringify({ + options, + root, + layers, + leaves + }, null, 2) + } + + static unmarshalTree (jsonStr: string | object, hashFn = SHA256, options: Options = {}):MerkleTree { + let parsed :any = null + if (typeof jsonStr === 'string') { + parsed = JSON.parse(jsonStr) + } else if (jsonStr instanceof Object) { + parsed = jsonStr + } else { + throw new Error('Expected type of string or object') + } + + if (!parsed) { + throw new Error('could not parse json') + } + + options = Object.assign({}, parsed.options || {}, options) + + return new MerkleTree(parsed.leaves, hashFn, options) + } + + /** + * getProofIndices + * @desc Returns the proof indices for given tree indices. + * @param {Number[]} treeIndices - Tree indices + * @param {Number} depth - Tree depth; number of layers. + * @return {Number[]} - Proof indices + * @example + * ```js + *const proofIndices = tree.getProofIndices([2,5,6], 4) + *console.log(proofIndices) // [ 23, 20, 19, 8, 3 ] + *``` + */ + getProofIndices (treeIndices: number[], depth: number):number[] { + const leafCount = 2 ** depth + let maximalIndices :any = new Set() + for (const index of treeIndices) { + let x = leafCount + index + while (x > 1) { + maximalIndices.add(x ^ 1) + x = (x / 2) | 0 + } + } + + const a = treeIndices.map(index => leafCount + index) + const b = Array.from(maximalIndices).sort((a: any, b: any) => a - b).reverse() + maximalIndices = a.concat(b as any) + + const redundantIndices = new Set() + const proof = [] + + for (let index of maximalIndices) { + if (!redundantIndices.has(index)) { + proof.push(index) + while (index > 1) { + redundantIndices.add(index) + if (!redundantIndices.has(index as number ^ 1)) break + index = (index as number / 2) | 0 + } + } + } + + return proof.filter(index => { + return !treeIndices.includes(index - leafCount) + }) + } + + private getProofIndicesForUnevenTree (sortedLeafIndices: number[], leavesCount: number): number[][] { + const depth = Math.ceil(Math.log2(leavesCount)) + const unevenLayers :any[] = [] + for (let index = 0; index < depth; index++) { + const unevenLayer = leavesCount % 2 !== 0 + if (unevenLayer) { + unevenLayers.push({ index, leavesCount }) + } + leavesCount = Math.ceil(leavesCount / 2) + } + + const proofIndices: number[][] = [] + + let layerNodes: any[] = sortedLeafIndices + for (let layerIndex = 0; layerIndex < depth; layerIndex++) { + const siblingIndices = layerNodes.map((index: any) => { + if (index % 2 === 0) { + return index + 1 + } + return index - 1 + }) + let proofNodeIndices = siblingIndices.filter((index: any) => !layerNodes.includes(index)) + const unevenLayer = unevenLayers.find(({ index }) => index === layerIndex) + if (unevenLayer && layerNodes.includes(unevenLayer.leavesCount - 1)) { + proofNodeIndices = proofNodeIndices.slice(0, -1) + } + + proofIndices.push(proofNodeIndices) + layerNodes = [...new Set(layerNodes.map((index: any) => { + if (index % 2 === 0) { + return index / 2 + } + + if (index % 2 === 0) { + return (index + 1) / 2 + } + + return (index - 1) / 2 + }))] + } + + return proofIndices + } + + /** + * getMultiProof + * @desc Returns the multiproof for given tree indices. + * @param {Number[]} indices - Tree indices. + * @return {Buffer[]} - Multiproofs + * @example + * ```js + *const indices = [2, 5, 6] + *const proof = tree.getMultiProof(indices) + *``` + */ + getMultiProof (tree?: any[], indices?: any[]):Buffer[] { + if (!this.complete) { + console.warn('Warning: For correct multiProofs it\'s strongly recommended to set complete: true') + } + + if (!indices) { + indices = tree + tree = this.getLayersFlat() + } + + const isUneven = this.isUnevenTree() + if (isUneven) { + if (indices.every(Number.isInteger)) { + return this.getMultiProofForUnevenTree(indices) + } + } + + if (!indices.every(Number.isInteger)) { + let els = indices + if (this.sortPairs) { + els = els.sort(Buffer.compare) + } + + let ids = els.map((el) => this.bufferIndexOf(this.leaves, el, this.sortLeaves)).sort((a, b) => a === b ? 0 : a > b ? 1 : -1) + if (!ids.every((idx) => idx !== -1)) { + throw new Error('Element does not exist in Merkle tree') + } + + const hashes = [] + const proof = [] + let nextIds = [] + + for (let i = 0; i < this.layers.length; i++) { + const layer = this.layers[i] + for (let j = 0; j < ids.length; j++) { + const idx = ids[j] + const pairElement = this.getPairNode(layer, idx) + + hashes.push(layer[idx]) + if (pairElement) { + proof.push(pairElement) + } + + nextIds.push((idx / 2) | 0) + } + + ids = nextIds.filter((value, i, self) => self.indexOf(value) === i) + nextIds = [] + } + + return proof.filter((value) => !hashes.includes(value)) + } + + return this.getProofIndices(indices, Math.log2((tree.length / 2) | 0)).map(index => tree[index]) + } + + private getMultiProofForUnevenTree (tree?: any[], indices?: any[]):Buffer[] { + if (!indices) { + indices = tree + tree = this.getLayers() + } + + let proofHashes : Buffer[] = [] + let currentLayerIndices: number[] = indices + for (const treeLayer of tree) { + const siblings: Buffer[] = [] + for (const index of currentLayerIndices) { + if (index % 2 === 0) { + const idx = index + 1 + if (!currentLayerIndices.includes(idx)) { + if (treeLayer[idx]) { + siblings.push(treeLayer[idx]) + continue + } + } + } + const idx = index - 1 + if (!currentLayerIndices.includes(idx)) { + if (treeLayer[idx]) { + siblings.push(treeLayer[idx]) + continue + } + } + } + + proofHashes = proofHashes.concat(siblings) + const uniqueIndices = new Set() + + for (const index of currentLayerIndices) { + if (index % 2 === 0) { + uniqueIndices.add(index / 2) + continue + } + + if (index % 2 === 0) { + uniqueIndices.add((index + 1) / 2) + continue + } + + uniqueIndices.add((index - 1) / 2) + } + + currentLayerIndices = Array.from(uniqueIndices) + } + + return proofHashes + } + + /** + * getHexMultiProof + * @desc Returns the multiproof for given tree indices as hex strings. + * @param {Number[]} indices - Tree indices. + * @return {String[]} - Multiproofs as hex strings. + * @example + * ```js + *const indices = [2, 5, 6] + *const proof = tree.getHexMultiProof(indices) + *``` + */ + getHexMultiProof (tree: Buffer[] | string[], indices: number[]):string[] { + return this.getMultiProof(tree, indices).map((x) => this.bufferToHex(x)) + } + + /** + * getProofFlags + * @desc Returns list of booleans where proofs should be used instead of hashing. + * Proof flags are used in the Solidity multiproof verifiers. + * @param {Number[]|Buffer[]} leaves + * @param {Buffer[]} proofs + * @return {Boolean[]} - Boolean flags + * @example + * ```js + *const indices = [2, 5, 6] + *const proof = tree.getMultiProof(indices) + *const proofFlags = tree.getProofFlags(leaves, proof) + *``` + */ + getProofFlags (leaves: any[], proofs: Buffer[] | string[]):boolean[] { + if (!Array.isArray(leaves) || leaves.length <= 0) { + throw new Error('Invalid Inputs!') + } + + let ids : number[] + if (leaves.every(Number.isInteger)) { + ids = [...leaves].sort((a, b) => a === b ? 0 : a > b ? 1 : -1) // Indices where passed + } else { + ids = leaves.map((el) => this.bufferIndexOf(this.leaves, el, this.sortLeaves)).sort((a, b) => a === b ? 0 : a > b ? 1 : -1) + } + + if (!ids.every((idx: number) => idx !== -1)) { + throw new Error('Element does not exist in Merkle tree') + } + + const _proofs: Buffer[] = (proofs as any[]).map(item => this.bufferify(item)) + + const tested = [] + const flags = [] + for (let index = 0; index < this.layers.length; index++) { + const layer = this.layers[index] + ids = ids.reduce((ids, idx) => { + const skipped = tested.includes(layer[idx]) + if (!skipped) { + const pairElement = this.getPairNode(layer, idx) + const proofUsed = _proofs.includes(layer[idx]) || _proofs.includes(pairElement) + pairElement && flags.push(!proofUsed) + tested.push(layer[idx]) + tested.push(pairElement) + } + ids.push((idx / 2) | 0) + return ids + }, []) + } + + return flags + } + + /** + * verify + * @desc Returns true if the proof path (array of hashes) can connect the target node + * to the Merkle root. + * @param {Object[]} proof - Array of proof objects that should connect + * target node to Merkle root. + * @param {Buffer} targetNode - Target node Buffer + * @param {Buffer} root - Merkle root Buffer + * @return {Boolean} + * @example + *```js + *const root = tree.getRoot() + *const proof = tree.getProof(leaves[2]) + *const verified = tree.verify(proof, leaves[2], root) + *``` + */ + verify (proof: any[], targetNode: Buffer | string, root: Buffer | string):boolean { + let hash = this.bufferify(targetNode) + root = this.bufferify(root) + + if ( + !Array.isArray(proof) || + !targetNode || + !root + ) { + return false + } + + for (let i = 0; i < proof.length; i++) { + const node = proof[i] + let data: any = null + let isLeftNode = null + + // case for when proof is hex values only + if (typeof node === 'string') { + data = this.bufferify(node) + isLeftNode = true + } else if (Array.isArray(node)) { + isLeftNode = (node[0] === 0) + data = this.bufferify(node[1]) + } else if (Buffer.isBuffer(node)) { + data = node + isLeftNode = true + } else if (node instanceof Object) { + data = this.bufferify(node.data) + isLeftNode = (node.position === 'left') + } else { + throw new Error('Expected node to be of type string or object') + } + + const buffers: any[] = [] + + if (this.isBitcoinTree) { + buffers.push(reverse(hash)) + + buffers[isLeftNode ? 'unshift' : 'push'](reverse(data)) + + hash = this.hashFn(this.concatenator(buffers)) + hash = reverse(this.hashFn(hash)) + } else { + if (this.sortPairs) { + if (Buffer.compare(hash, data) === -1) { + buffers.push(hash, data) + hash = this.hashFn(this.concatenator(buffers)) + } else { + buffers.push(data, hash) + hash = this.hashFn(this.concatenator(buffers)) + } + } else { + buffers.push(hash) + buffers[isLeftNode ? 'unshift' : 'push'](data) + hash = this.hashFn(this.concatenator(buffers)) + } + } + } + + return Buffer.compare(hash, root) === 0 + } + + /** + * verifyMultiProof + * @desc Returns true if the multiproofs can connect the leaves to the Merkle root. + * @param {Buffer} root - Merkle tree root + * @param {Number[]} proofIndices - Leave indices for proof + * @param {Buffer[]} proofLeaves - Leaf values at indices for proof + * @param {Number} leavesCount - Count of original leaves + * @param {Buffer[]} proof - Multiproofs given indices + * @return {Boolean} + * @example + *```js + *const leaves = tree.getLeaves() + *const root = tree.getRoot() + *const treeFlat = tree.getLayersFlat() + *const leavesCount = leaves.length + *const proofIndices = [2, 5, 6] + *const proofLeaves = proofIndices.map(i => leaves[i]) + *const proof = tree.getMultiProof(treeFlat, indices) + *const verified = tree.verifyMultiProof(root, proofIndices, proofLeaves, leavesCount, proof) + *``` + */ + verifyMultiProof (root: Buffer | string, proofIndices: number[], proofLeaves: Buffer[] | string[], leavesCount: number, proof: Buffer[] | string[]):boolean { + const isUneven = this.isUnevenTree() + if (isUneven) { + // TODO: combine these functions and simplify + return this.verifyMultiProofForUnevenTree(root, proofIndices, proofLeaves, leavesCount, proof) + } + + const depth = Math.ceil(Math.log2(leavesCount)) + root = this.bufferify(root) + proofLeaves = (proofLeaves as any[]).map(leaf => this.bufferify(leaf)) + proof = (proof as any[]).map(leaf => this.bufferify(leaf)) + + const tree = {} + for (const [index, leaf] of this.zip(proofIndices, proofLeaves)) { + tree[(2 ** depth) + index] = leaf + } + for (const [index, proofitem] of this.zip(this.getProofIndices(proofIndices, depth), proof)) { + tree[index] = proofitem + } + let indexqueue = Object.keys(tree).map(value => +value).sort((a, b) => a - b) + indexqueue = indexqueue.slice(0, indexqueue.length - 1) + let i = 0 + while (i < indexqueue.length) { + const index = indexqueue[i] + if (index >= 2 && ({}).hasOwnProperty.call(tree, index ^ 1)) { + let pair = [tree[index - (index % 2)], tree[index - (index % 2) + 1]] + if (this.sortPairs) { + pair = pair.sort(Buffer.compare) + } + + const hash = pair[1] ? this.hashFn(this.concatenator(pair)) : pair[0] + tree[(index / 2) | 0] = hash + indexqueue.push((index / 2) | 0) + } + i += 1 + } + return !proofIndices.length || (({}).hasOwnProperty.call(tree, 1) && tree[1].equals(root)) + } + + verifyMultiProofWithFlags ( + root: Buffer | string, + leaves: TLeaf[], + proofs: Buffer[] | string[], + proofFlag: boolean[] + ) { + root = this.bufferify(root) as Buffer + leaves = leaves.map(this.bufferify) as Buffer[] + proofs = (proofs as any[]).map(this.bufferify) as Buffer[] + const leavesLen = leaves.length + const totalHashes = proofFlag.length + const hashes : Buffer[] = [] + let leafPos = 0 + let hashPos = 0 + let proofPos = 0 + for (let i = 0; i < totalHashes; i++) { + const bufA: Buffer = proofFlag[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proofs[proofPos++] + const bufB : Buffer = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] + const buffers = [bufA, bufB].sort(Buffer.compare) + hashes[i] = this.hashFn(this.concatenator(buffers)) + } + + return Buffer.compare(hashes[totalHashes - 1], root) === 0 + } + + private verifyMultiProofForUnevenTree (root: Buffer | string, indices: number[], leaves: Buffer[] | string[], leavesCount: number, proof: Buffer[] | string[]):boolean { + root = this.bufferify(root) + leaves = (leaves as any[]).map(leaf => this.bufferify(leaf)) + proof = (proof as any[]).map(leaf => this.bufferify(leaf)) + + const computedRoot = this.calculateRootForUnevenTree(indices, leaves, leavesCount, proof) + return root.equals(computedRoot) + } + + /** + * getDepth + * @desc Returns the tree depth (number of layers) + * @return {Number} + * @example + *```js + *const depth = tree.getDepth() + *``` + */ + getDepth ():number { + return this.getLayers().length - 1 + } + + /** + * getLayersAsObject + * @desc Returns the layers as nested objects instead of an array. + * @example + *```js + *const layersObj = tree.getLayersAsObject() + *``` + */ + getLayersAsObject ():any { + const layers: any[] = this.getLayers().map((layer: any) => layer.map((value: any) => this.bufferToHex(value, false))) + const objs = [] + for (let i = 0; i < layers.length; i++) { + const arr = [] + for (let j = 0; j < layers[i].length; j++) { + const obj = { [layers[i][j]]: null } + if (objs.length) { + obj[layers[i][j]] = {} + const a = objs.shift() + const akey = Object.keys(a)[0] + obj[layers[i][j]][akey] = a[akey] + if (objs.length) { + const b = objs.shift() + const bkey = Object.keys(b)[0] + obj[layers[i][j]][bkey] = b[bkey] + } + } + + arr.push(obj) + } + + objs.push(...arr) + } + + return objs[0] + } + + /** + * verify + * @desc Returns true if the proof path (array of hashes) can connect the target node + * to the Merkle root. + * @param {Object[]} proof - Array of proof objects that should connect + * target node to Merkle root. + * @param {Buffer} targetNode - Target node Buffer + * @param {Buffer} root - Merkle root Buffer + * @param {Function} hashFunction - Hash function for hashing leaves and nodes + * @param {Object} options - Additional options + * @return {Boolean} + * @example + *```js + *const verified = MerkleTree.verify(proof, leaf, root, sha256, options) + *``` + */ + static verify (proof: any[], targetNode: Buffer | string, root: Buffer | string, hashFn = SHA256, options: Options = {}):boolean { + const tree = new MerkleTree([], hashFn, options) + return tree.verify(proof, targetNode, root) + } + + /** + * getMultiProof + * @desc Returns the multiproof for given tree indices. + * @param {Buffer[]} tree - Tree as a flat array. + * @param {Number[]} indices - Tree indices. + * @return {Buffer[]} - Multiproofs + * + *@example + * ```js + *const flatTree = tree.getLayersFlat() + *const indices = [2, 5, 6] + *const proof = MerkleTree.getMultiProof(flatTree, indices) + *``` + */ + static getMultiProof (tree: Buffer[] | string[], indices: number[]):Buffer[] { + const t = new MerkleTree([]) + return t.getMultiProof(tree, indices) + } + + /** + * resetTree + * @desc Resets the tree by clearing the leaves and layers. + * @example + *```js + *tree.resetTree() + *``` + */ + resetTree ():void { + this.leaves = [] + this.layers = [] + } + + /** + * getPairNode + * @desc Returns the node at the index for given layer. + * @param {Buffer[]} layer - Tree layer + * @param {Number} index - Index at layer. + * @return {Buffer} - Node + * + *@example + * ```js + *const node = tree.getPairNode(layer, index) + *``` + */ + private getPairNode (layer: Buffer[], idx: number):Buffer { + const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1 + + if (pairIdx < layer.length) { + return layer[pairIdx] + } else { + return null + } + } + + /** + * toTreeString + * @desc Returns a visual representation of the merkle tree as a string. + * @return {String} + * @example + *```js + *console.log(tree.toTreeString()) + *``` + */ + protected toTreeString ():string { + const obj = this.getLayersAsObject() + return treeify.asTree(obj, true) + } + + /** + * toString + * @desc Returns a visual representation of the merkle tree as a string. + * @example + *```js + *console.log(tree.toString()) + *``` + */ + toString ():string { + return this.toTreeString() + } + + isUnevenTree (treeLayers?: any[]) { + const depth = treeLayers?.length || this.getDepth() + return !this.isPowOf2(depth) + } + + private isPowOf2 (v: number) { + return v && !(v & (v - 1)) + } + + private calculateRootForUnevenTree (leafIndices: number[], leafHashes: any[], totalLeavesCount: number, proofHashes: any[]) { + const leafTuples = this.zip(leafIndices, leafHashes).sort(([indexA], [indexB]) => indexA - indexB) + const leafTupleIndices = leafTuples.map(([index]) => index) + const proofIndices = this.getProofIndicesForUnevenTree(leafTupleIndices, totalLeavesCount) + + let nextSliceStart = 0 + const proofTuplesByLayers :any[] = [] + for (let i = 0; i < proofIndices.length; i++) { + const indices = proofIndices[i] + const sliceStart = nextSliceStart + nextSliceStart += indices.length + proofTuplesByLayers[i] = this.zip(indices, proofHashes.slice(sliceStart, nextSliceStart)) + } + + const tree = [leafTuples] + for (let layerIndex = 0; layerIndex < proofTuplesByLayers.length; layerIndex++) { + const currentLayer = proofTuplesByLayers[layerIndex].concat(tree[layerIndex]).sort(([indexA], [indexB]) => indexA - indexB) + .map(([, hash]) => hash) + + const s = tree[layerIndex].map(([layerIndex]) => layerIndex) + const parentIndices = [...new Set(s.map((index: any) => { + if (index % 2 === 0) { + return index / 2 + } + + if (index % 2 === 0) { + return (index + 1) / 2 + } + + return (index - 1) / 2 + }))] + + const parentLayer: any[] = [] + for (let i = 0; i < parentIndices.length; i++) { + const parentNodeTreeIndex = parentIndices[i] + const bufA = currentLayer[i * 2] + const bufB = currentLayer[i * 2 + 1] + const hash = bufB ? this.hashFn(this.concatenator([bufA, bufB])) : bufA + parentLayer.push([parentNodeTreeIndex, hash]) + } + + tree.push(parentLayer) + } + + return tree[tree.length - 1][0][1] + } +} + +if (typeof window !== 'undefined') { + ;(window as any).MerkleTree = MerkleTree +} + + + +export default MerkleTree +export default MerkleSumTree +export default MerkleMountainRange +export default IncrementalMerkleTree +export default Base \ No newline at end of file diff --git a/test/merkletreejs/node_modules/.bin/crc32 b/test/merkletreejs/node_modules/.bin/crc32 new file mode 120000 index 0000000..9f8b79c --- /dev/null +++ b/test/merkletreejs/node_modules/.bin/crc32 @@ -0,0 +1 @@ +../crc-32/bin/crc32.njs \ No newline at end of file diff --git a/test/merkletreejs/node_modules/.bin/rlp b/test/merkletreejs/node_modules/.bin/rlp new file mode 120000 index 0000000..f5e25c6 --- /dev/null +++ b/test/merkletreejs/node_modules/.bin/rlp @@ -0,0 +1 @@ +../@ethereumjs/rlp/bin/rlp \ No newline at end of file diff --git a/test/merkletreejs/node_modules/.yarn-integrity b/test/merkletreejs/node_modules/.yarn-integrity new file mode 100644 index 0000000..cdff833 --- /dev/null +++ b/test/merkletreejs/node_modules/.yarn-integrity @@ -0,0 +1,110 @@ +{ + "systemParams": "darwin-arm64-108", + "modulesFolders": [ + "node_modules" + ], + "flags": [], + "linkedModules": [], + "topLevelPatterns": [ + "merkletreejs@^0.3.11", + "web3@^4.3.0" + ], + "lockfileEntries": { + "@adraffy/ens-normalize@^1.8.8": "https://registry.yarnpkg.com/@adraffy/ens-normalize/-/ens-normalize-1.10.0.tgz#d2a39395c587e092d77cbbc80acf956a54f38bf7", + "@ethereumjs/rlp@^4.0.1": "https://registry.yarnpkg.com/@ethereumjs/rlp/-/rlp-4.0.1.tgz#626fabfd9081baab3d0a3074b0c7ecaf674aaa41", + "@ethereumjs/util@^8.1.0": "https://registry.yarnpkg.com/@ethereumjs/util/-/util-8.1.0.tgz#299df97fb6b034e0577ce9f94c7d9d1004409ed4", + "@noble/curves@1.1.0": "https://registry.yarnpkg.com/@noble/curves/-/curves-1.1.0.tgz#f13fc667c89184bc04cccb9b11e8e7bae27d8c3d", + "@noble/curves@~1.1.0": "https://registry.yarnpkg.com/@noble/curves/-/curves-1.1.0.tgz#f13fc667c89184bc04cccb9b11e8e7bae27d8c3d", + "@noble/hashes@1.3.1": "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.1.tgz#8831ef002114670c603c458ab8b11328406953a9", + "@noble/hashes@~1.3.0": "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.2.tgz#6f26dbc8fbc7205873ce3cee2f690eba0d421b39", + "@noble/hashes@~1.3.1": "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.2.tgz#6f26dbc8fbc7205873ce3cee2f690eba0d421b39", + "@scure/base@~1.1.0": "https://registry.yarnpkg.com/@scure/base/-/base-1.1.3.tgz#8584115565228290a6c6c4961973e0903bb3df2f", + "@scure/bip32@1.3.1": "https://registry.yarnpkg.com/@scure/bip32/-/bip32-1.3.1.tgz#7248aea723667f98160f593d621c47e208ccbb10", + "@scure/bip39@1.2.1": "https://registry.yarnpkg.com/@scure/bip39/-/bip39-1.2.1.tgz#5cee8978656b272a917b7871c981e0541ad6ac2a", + "@types/node@*": "https://registry.yarnpkg.com/@types/node/-/node-20.10.3.tgz#4900adcc7fc189d5af5bb41da8f543cea6962030", + "@types/ws@8.5.3": "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.3.tgz#7d25a1ffbecd3c4f2d35068d0b283c037003274d", + "abitype@0.7.1": "https://registry.yarnpkg.com/abitype/-/abitype-0.7.1.tgz#16db20abe67de80f6183cf75f3de1ff86453b745", + "available-typed-arrays@^1.0.5": "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz#92f95616501069d07d10edb2fc37d3e1c65123b7", + "bignumber.js@^9.0.1": "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-9.1.2.tgz#b7c4242259c008903b13707983b5f4bbd31eda0c", + "bn.js@4.11.6": "https://registry.yarnpkg.com/bn.js/-/bn.js-4.11.6.tgz#53344adb14617a13f6e8dd2ce28905d1c0ba3215", + "bn.js@^5.2.1": "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.1.tgz#0bc527a6a0d18d0aa8d5b0538ce4a77dccfa7b70", + "buffer-reverse@^1.0.1": "https://registry.yarnpkg.com/buffer-reverse/-/buffer-reverse-1.0.1.tgz#49283c8efa6f901bc01fa3304d06027971ae2f60", + "call-bind@^1.0.2": "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.5.tgz#6fa2b7845ce0ea49bf4d8b9ef64727a2c2e2e513", + "call-bind@^1.0.4": "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.5.tgz#6fa2b7845ce0ea49bf4d8b9ef64727a2c2e2e513", + "crc-32@^1.2.2": "https://registry.yarnpkg.com/crc-32/-/crc-32-1.2.2.tgz#3cad35a934b8bf71f25ca524b6da51fb7eace2ff", + "cross-fetch@^4.0.0": "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-4.0.0.tgz#f037aef1580bb3a1a35164ea2a848ba81b445983", + "crypto-js@^4.2.0": "https://registry.yarnpkg.com/crypto-js/-/crypto-js-4.2.0.tgz#4d931639ecdfd12ff80e8186dba6af2c2e856631", + "define-data-property@^1.1.1": "https://registry.yarnpkg.com/define-data-property/-/define-data-property-1.1.1.tgz#c35f7cd0ab09883480d12ac5cb213715587800b3", + "ethereum-bloom-filters@^1.0.6": "https://registry.yarnpkg.com/ethereum-bloom-filters/-/ethereum-bloom-filters-1.0.10.tgz#3ca07f4aed698e75bd134584850260246a5fed8a", + "ethereum-cryptography@^2.0.0": "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-2.1.2.tgz#18fa7108622e56481157a5cb7c01c0c6a672eb67", + "ethereum-cryptography@^2.1.2": "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-2.1.2.tgz#18fa7108622e56481157a5cb7c01c0c6a672eb67", + "ethjs-unit@0.1.6": "https://registry.yarnpkg.com/ethjs-unit/-/ethjs-unit-0.1.6.tgz#c665921e476e87bce2a9d588a6fe0405b2c41699", + "for-each@^0.3.3": "https://registry.yarnpkg.com/for-each/-/for-each-0.3.3.tgz#69b447e88a0a5d32c3e7084f3f1710034b21376e", + "function-bind@^1.1.2": "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c", + "get-intrinsic@^1.1.3": "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.2.tgz#281b7622971123e1ef4b3c90fd7539306da93f3b", + "get-intrinsic@^1.2.1": "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.2.tgz#281b7622971123e1ef4b3c90fd7539306da93f3b", + "get-intrinsic@^1.2.2": "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.2.tgz#281b7622971123e1ef4b3c90fd7539306da93f3b", + "gopd@^1.0.1": "https://registry.yarnpkg.com/gopd/-/gopd-1.0.1.tgz#29ff76de69dac7489b7c0918a5788e56477c332c", + "has-property-descriptors@^1.0.0": "https://registry.yarnpkg.com/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz#52ba30b6c5ec87fd89fa574bc1c39125c6f65340", + "has-proto@^1.0.1": "https://registry.yarnpkg.com/has-proto/-/has-proto-1.0.1.tgz#1885c1305538958aff469fef37937c22795408e0", + "has-symbols@^1.0.2": "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8", + "has-symbols@^1.0.3": "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8", + "has-tostringtag@^1.0.0": "https://registry.yarnpkg.com/has-tostringtag/-/has-tostringtag-1.0.0.tgz#7e133818a7d394734f941e73c3d3f9291e658b25", + "hasown@^2.0.0": "https://registry.yarnpkg.com/hasown/-/hasown-2.0.0.tgz#f4c513d454a57b7c7e1650778de226b11700546c", + "inherits@^2.0.3": "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c", + "is-arguments@^1.0.4": "https://registry.yarnpkg.com/is-arguments/-/is-arguments-1.1.1.tgz#15b3f88fda01f2a97fec84ca761a560f123efa9b", + "is-callable@^1.1.3": "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.7.tgz#3bc2a85ea742d9e36205dcacdd72ca1fdc51b055", + "is-generator-function@^1.0.7": "https://registry.yarnpkg.com/is-generator-function/-/is-generator-function-1.0.10.tgz#f1558baf1ac17e0deea7c0415c438351ff2b3c72", + "is-hex-prefixed@1.0.0": "https://registry.yarnpkg.com/is-hex-prefixed/-/is-hex-prefixed-1.0.0.tgz#7d8d37e6ad77e5d127148913c573e082d777f554", + "is-typed-array@^1.1.3": "https://registry.yarnpkg.com/is-typed-array/-/is-typed-array-1.1.12.tgz#d0bab5686ef4a76f7a73097b95470ab199c57d4a", + "isomorphic-ws@^5.0.0": "https://registry.yarnpkg.com/isomorphic-ws/-/isomorphic-ws-5.0.0.tgz#e5529148912ecb9b451b46ed44d53dae1ce04bbf", + "js-sha3@^0.8.0": "https://registry.yarnpkg.com/js-sha3/-/js-sha3-0.8.0.tgz#b9b7a5da73afad7dedd0f8c463954cbde6818840", + "merkletreejs@^0.3.11": "https://registry.yarnpkg.com/merkletreejs/-/merkletreejs-0.3.11.tgz#e0de05c3ca1fd368de05a12cb8efb954ef6fc04f", + "micro-ftch@^0.3.1": "https://registry.yarnpkg.com/micro-ftch/-/micro-ftch-0.3.1.tgz#6cb83388de4c1f279a034fb0cf96dfc050853c5f", + "node-fetch@^2.6.12": "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d", + "number-to-bn@1.7.0": "https://registry.yarnpkg.com/number-to-bn/-/number-to-bn-1.7.0.tgz#bb3623592f7e5f9e0030b1977bd41a0c53fe1ea0", + "randombytes@^2.1.0": "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a", + "safe-buffer@^5.1.0": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6", + "set-function-length@^1.1.1": "https://registry.yarnpkg.com/set-function-length/-/set-function-length-1.1.1.tgz#4bc39fafb0307224a33e106a7d35ca1218d659ed", + "setimmediate@^1.0.5": "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285", + "strip-hex-prefix@1.0.0": "https://registry.yarnpkg.com/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz#0c5f155fef1151373377de9dbb588da05500e36f", + "tr46@~0.0.3": "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a", + "treeify@^1.1.0": "https://registry.yarnpkg.com/treeify/-/treeify-1.1.0.tgz#4e31c6a463accd0943879f30667c4fdaff411bb8", + "undici-types@~5.26.4": "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617", + "utf8@3.0.0": "https://registry.yarnpkg.com/utf8/-/utf8-3.0.0.tgz#f052eed1364d696e769ef058b183df88c87f69d1", + "util@^0.12.5": "https://registry.yarnpkg.com/util/-/util-0.12.5.tgz#5f17a6059b73db61a875668781a1c2b136bd6fbc", + "web3-core@^4.3.0": "https://registry.yarnpkg.com/web3-core/-/web3-core-4.3.2.tgz#f24b11d6a57dee527de8d42c89de2a439f0c4bed", + "web3-core@^4.3.2": "https://registry.yarnpkg.com/web3-core/-/web3-core-4.3.2.tgz#f24b11d6a57dee527de8d42c89de2a439f0c4bed", + "web3-errors@^1.1.3": "https://registry.yarnpkg.com/web3-errors/-/web3-errors-1.1.4.tgz#5667a0a5f66fc936e101ef32032ccc1e8ca4d5a1", + "web3-errors@^1.1.4": "https://registry.yarnpkg.com/web3-errors/-/web3-errors-1.1.4.tgz#5667a0a5f66fc936e101ef32032ccc1e8ca4d5a1", + "web3-eth-abi@^4.1.4": "https://registry.yarnpkg.com/web3-eth-abi/-/web3-eth-abi-4.1.4.tgz#56ae7ebb1385db1a948e69fb35f4057bff6743af", + "web3-eth-accounts@^4.1.0": "https://registry.yarnpkg.com/web3-eth-accounts/-/web3-eth-accounts-4.1.0.tgz#5b5e6c60d457e7b829ec590021fc87ada8585920", + "web3-eth-contract@^4.1.2": "https://registry.yarnpkg.com/web3-eth-contract/-/web3-eth-contract-4.1.4.tgz#513720fc674e42180ec1b88384dc2ce31715488e", + "web3-eth-contract@^4.1.4": "https://registry.yarnpkg.com/web3-eth-contract/-/web3-eth-contract-4.1.4.tgz#513720fc674e42180ec1b88384dc2ce31715488e", + "web3-eth-ens@^4.0.8": "https://registry.yarnpkg.com/web3-eth-ens/-/web3-eth-ens-4.0.8.tgz#f4e0a018ce6cc69e37007ee92063867feb5994f0", + "web3-eth-iban@^4.0.7": "https://registry.yarnpkg.com/web3-eth-iban/-/web3-eth-iban-4.0.7.tgz#ee504f845d7b6315f0be78fcf070ccd5d38e4aaf", + "web3-eth-personal@^4.0.8": "https://registry.yarnpkg.com/web3-eth-personal/-/web3-eth-personal-4.0.8.tgz#b51628c560de550ca8b354fa784f9556aae6065c", + "web3-eth@^4.3.1": "https://registry.yarnpkg.com/web3-eth/-/web3-eth-4.3.1.tgz#cb4224356716da71e694091aa3fbf10bcb813fb5", + "web3-net@^4.0.7": "https://registry.yarnpkg.com/web3-net/-/web3-net-4.0.7.tgz#ed2c1bd700cf94be93a6dbd8bd8aa413d8681942", + "web3-providers-http@^4.1.0": "https://registry.yarnpkg.com/web3-providers-http/-/web3-providers-http-4.1.0.tgz#8d7afda67d1d8542ca85b30f60a3d1fe1993b561", + "web3-providers-ipc@^4.0.7": "https://registry.yarnpkg.com/web3-providers-ipc/-/web3-providers-ipc-4.0.7.tgz#9ec4c8565053af005a5170ba80cddeb40ff3e3d3", + "web3-providers-ws@^4.0.7": "https://registry.yarnpkg.com/web3-providers-ws/-/web3-providers-ws-4.0.7.tgz#7a78a0dcf077e0e802da524fbb37d080b356c14b", + "web3-rpc-methods@^1.1.3": "https://registry.yarnpkg.com/web3-rpc-methods/-/web3-rpc-methods-1.1.4.tgz#0b478e38231d3f3260ac504307c6dc4059af6fda", + "web3-rpc-methods@^1.1.4": "https://registry.yarnpkg.com/web3-rpc-methods/-/web3-rpc-methods-1.1.4.tgz#0b478e38231d3f3260ac504307c6dc4059af6fda", + "web3-types@^1.3.0": "https://registry.yarnpkg.com/web3-types/-/web3-types-1.3.1.tgz#cf6148ad46b68c5c89714613380b270d31e297be", + "web3-types@^1.3.1": "https://registry.yarnpkg.com/web3-types/-/web3-types-1.3.1.tgz#cf6148ad46b68c5c89714613380b270d31e297be", + "web3-utils@^1.3.4": "https://registry.yarnpkg.com/web3-utils/-/web3-utils-1.10.3.tgz#f1db99c82549c7d9f8348f04ffe4e0188b449714", + "web3-utils@^4.0.7": "https://registry.yarnpkg.com/web3-utils/-/web3-utils-4.1.0.tgz#3fcb77261fe1e4d02c46564fdee26f690f58a76a", + "web3-utils@^4.1.0": "https://registry.yarnpkg.com/web3-utils/-/web3-utils-4.1.0.tgz#3fcb77261fe1e4d02c46564fdee26f690f58a76a", + "web3-validator@^2.0.3": "https://registry.yarnpkg.com/web3-validator/-/web3-validator-2.0.3.tgz#e5dcd4b4902612cff21b7f8817dd233393999d97", + "web3@^4.3.0": "https://registry.yarnpkg.com/web3/-/web3-4.3.0.tgz#3f1d5e878295ef8bc7d2195f0f42aa2f7b8224cf", + "webidl-conversions@^3.0.0": "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871", + "whatwg-url@^5.0.0": "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d", + "which-typed-array@^1.1.11": "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.13.tgz#870cd5be06ddb616f504e7b039c4c24898184d36", + "which-typed-array@^1.1.2": "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.13.tgz#870cd5be06ddb616f504e7b039c4c24898184d36", + "ws@^8.8.1": "https://registry.yarnpkg.com/ws/-/ws-8.14.2.tgz#6c249a806eb2db7a20d26d51e7709eab7b2e6c7f", + "zod@^3.21.4": "https://registry.yarnpkg.com/zod/-/zod-3.22.4.tgz#f31c3a9386f61b1f228af56faa9255e845cf3fff" + }, + "files": [], + "artifacts": {} +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@adraffy/ens-normalize/LICENSE b/test/merkletreejs/node_modules/@adraffy/ens-normalize/LICENSE new file mode 100644 index 0000000..c8a213d --- /dev/null +++ b/test/merkletreejs/node_modules/@adraffy/ens-normalize/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Andrew Raffensperger + +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. diff --git a/test/merkletreejs/node_modules/@adraffy/ens-normalize/README.md b/test/merkletreejs/node_modules/@adraffy/ens-normalize/README.md new file mode 100644 index 0000000..b9a0d2c --- /dev/null +++ b/test/merkletreejs/node_modules/@adraffy/ens-normalize/README.md @@ -0,0 +1,195 @@ +# ens-normalize.js +0-dependancy [Ethereum Name Service](https://ens.domains/) (ENS) Name Normalizer. + +* 🏛️ Follows [ENSIP-15: ENS Name Normalization Standard](https://docs.ens.domains/ens-improvement-proposals/ensip-15-normalization-standard) + * Other implementations: + * Python — [namehash/ens-normalize-python](https://github.com/namehash/ens-normalize-python) + * C# — [adraffy/ENSNormalize.cs](https://github.com/adraffy/ENSNormalize.cs) + * Java — [adraffy/ENSNormalize.java](https://github.com/adraffy/ENSNormalize.java) + * Javascript — [ensdomains/eth-ens-namehash](https://github.com/ensdomains/eth-ens-namehash) + * [Breakdown Reports from ENSIP-1](https://adraffy.github.io/ens-norm-tests/test-breakdown/output/) +* ✅️ Passes **100%** [ENSIP-15 Validation Tests](https://adraffy.github.io/ens-normalize.js/test/validate.html) +* ✅️ Passes **100%** [Unicode Normalization Tests](https://adraffy.github.io/ens-normalize.js/test/report-nf.html) +* Minified File Sizes: + * [`28KB`](./dist/index-xnf.min.js) — native `NFC` via [nf-native.js](./src/nf-native.js) using `String.normalize()` ⚠️ + * [`37KB` **Default**](./dist/index.min.js) — custom `NFC` via [nf.js](./src/nf.js) + * [`43KB`](./dist/all.min.js) *Everything!* — custom `NFC` + sub-libraries: [parts.js](./src/parts.js), [utils.js](./src/utils.js) +* Included Apps: + * [**Resolver Demo**](https://adraffy.github.io/ens-normalize.js/test/resolver.html) ⭐ + * [Supported Emoji](https://adraffy.github.io/ens-normalize.js/test/emoji.html) + * [Character Viewer](https://adraffy.github.io/ens-normalize.js/test/chars.html) + * [Confused Explainer](https://adraffy.github.io/ens-normalize.js/test/confused.html) +* Related Projects: + * [Recent Registrations](https://raffy.antistupid.com/eth/ens-regs.html) + * [Emoji Frequency Explorer](https://raffy.antistupid.com/eth/ens-emoji-freq.html) + * [ENS+NFT Matcher](https://raffy.antistupid.com/eth/ens-nft-matcher.html) + * [Batch Resolver](https://raffy.antistupid.com/eth/ens-batch-resolver.html) + * [Punycode Coder](https://adraffy.github.io/punycode.js/test/demo.html) + * [Label Database](https://github.com/adraffy/ens-labels/) + +```Javascript +import {ens_normalize} from '@adraffy/ens-normalize'; // or require() +// npm i @adraffy/ens-normalize +// browser: https://cdn.jsdelivr.net/npm/@adraffy/ens-normalize@latest/dist/index.min.mjs (or .cjs) + +// *** ALL errors thrown by this library are safe to print *** +// - characters are shown as {HEX} if should_escape() +// - potentially different bidi directions inside "quotes" +// - 200E is used near "quotes" to prevent spillover +// - an "error type" can be extracted by slicing up to the first (:) + +// string -> string +// throws on invalid names +// output ready for namehash +let normalized = ens_normalize('RaFFY🚴‍♂️.eTh'); +// => "raffy🚴‍♂.eth" + +// note: does not enforce .eth registrar 3-character minimum +``` + +Format names with fully-qualified emoji: +```Javascript +// works like ens_normalize() +// output ready for display +let pretty = ens_beautify('1⃣2⃣.eth'); +// => "1️⃣2️⃣.eth" + +// note: normalization is unchanged: +// ens_normalize(ens_beautify(x)) == ens_normalize(x) +``` + +Normalize name fragments for [substring search](./test/fragment.js): +```Javascript +// these fragments fail ens_normalize() +// but will normalize fine as fragments +let frag1 = ens_normalize_fragment('AB--'); // expected error: label ext +let frag2 = ens_normalize_fragment('\u{303}'); // expected error: leading cm +let frag3 = ens_normalize_fragment('οо'); // expected error: mixture +``` + +Input-based tokenization: +```Javascript +// string -> Token[] +// never throws +let tokens = ens_tokenize('_R💩\u{FE0F}a\u{FE0F}\u{304}\u{AD}./'); +// [ +// { type: 'valid', cp: [ 95 ] }, // valid (as-is) +// { +// type: 'mapped', +// cp: 82, // input +// cps: [ 114 ] // output +// }, +// { +// type: 'emoji', +// input: Emoji(2) [ 128169, 65039 ], // input +// emoji: [ 128169, 65039 ], // fully-qualified +// cps: Emoji(1) [ 128169 ] // output (normalized) +// }, +// { +// type: 'nfc', +// input: [ 97, 772 ], // input (before nfc) +// tokens0: [ // tokens (before nfc) +// { type: 'valid', cps: [ 97 ] }, +// { type: 'ignored', cp: 65039 }, +// { type: 'valid', cps: [ 772 ] } +// ], +// cps: [ 257 ], // output (after nfc) +// tokens: [ // tokens (after nfc) +// { type: 'valid', cps: [ 257 ] } +// ] +// }, +// { type: 'ignored', cp: 173 }, +// { type: 'stop', cp: 46 }, +// { type: 'disallowed', cp: 47 } +// ] + +// note: if name is normalizable, then: +// ens_normalize(ens_tokenize(name).map(token => { +// ** convert valid/mapped/nfc/stop to string ** +// }).join('')) == ens_normalize(name) +``` + +Output-based tokenization: +```Javascript +// string -> Label[] +// never throws +let labels = ens_split('💩Raffy.eth_'); +// [ +// { +// input: [ 128169, 82, 97, 102, 102, 121 ], +// offset: 0, // index of codepoint, not substring index! +// // (corresponding length can be inferred from input) +// tokens: [ +// Emoji(2) [ 128169, 65039 ], // emoji +// [ 114, 97, 102, 102, 121 ] // nfc-text +// ], +// output: [ 128169, 114, 97, 102, 102, 121 ], +// emoji: true, +// type: 'Latin' +// }, +// { +// input: [ 101, 116, 104, 95 ], +// offset: 7, +// tokens: [ [ 101, 116, 104, 95 ] ], +// output: [ 101, 116, 104, 95 ], +// error: Error('underscore allowed only at start') +// } +// ] +``` + +Generate a sorted array of supported emoji codepoints: +```Javascript +// () -> number[][] +let emojis = ens_emoji(); +// [ +// [ 2764 ], +// [ 128169, 65039 ], +// [ 128105, 127997, 8205, 9877, 65039 ], +// ... +// ] +``` + +Determine if a character shouldn't be printed directly: +```Javascript +// number -> bool +should_escape(0x202E); // eg. RIGHT-TO-LEFT OVERRIDE => true +``` + +Determine if a character is a combining mark: +```Javascript +// number -> bool +is_combining_mark(0x20E3); // eg. COMBINING ENCLOSING KEYCAP => true +``` + +## Build + +* `git clone` this repo, then `npm install` +* Follow instructions in [/derive/](./derive/) to generate data files + * `npm run derive` + * [spec.json](./derive/output/spec.json) + * [nf.json](./derive/output/nf.json) + * [nf-tests.json](./derive/output/nf-tests.json) +* `npm run make` — compress data files from [/derive/output/](./derive/output/) + * [include-ens.js](./src/include-ens.js) + * [include-nf.js](./src/include-nf.js) + * [include-versions.js](./src/include-versions.js) +* Follow instructions in [/validate/](./validate/) to generate validation tests + * `npm run validate` + * [tests.json](./validate/tests.json) +* `npm run test` — perform validation tests +* `npm run build` — create [/dist/](./dist/) +* `npm run rebuild` — run all the commands above +* `npm run order` — create optimal group ordering and rebuild again + +### Publishing to NPM + +This project uses `.js` instead of `.mjs` so [package.json](./package.json) uses `type: module`. To avoid bundling issues, `type` is [dropped during packing](./src/prepost.js). `pre/post` hooks aren't used because they're buggy. +* `npm run pack` instead of `npm pack` +* `npm run pub` instead of `npm publish` + +## Security + +* [Build](#build) and compare against [include-versions.js](./src/include-versions.js) + * `spec_hash` — SHA-256 of [spec.json](./derive/output/spec.json) bytes + * `base64_ens_hash` — SHA-256 of [include-ens.js](./src/include-ens.js) base64 literal + * `base64_nf_hash` — SHA-256 of [include-nf.js](./src/include-nf.js) base64 literal diff --git a/test/merkletreejs/node_modules/@adraffy/ens-normalize/package.json b/test/merkletreejs/node_modules/@adraffy/ens-normalize/package.json new file mode 100755 index 0000000..ec24d95 --- /dev/null +++ b/test/merkletreejs/node_modules/@adraffy/ens-normalize/package.json @@ -0,0 +1,76 @@ +{ + "name": "@adraffy/ens-normalize", + "version": "1.10.0", + "description": "Ethereum Name Service (ENS) Name Normalizer", + "keywords": [ + "ENS", + "ENSIP-1", + "ENSIP-15", + "Ethereum", + "UTS-46", + "UTS-51", + "IDNA", + "Name", + "Normalize", + "Normalization", + "NFC", + "NFD" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "default": "./dist/index.cjs" + }, + "./xnf": { + "types": "./dist/index.d.ts", + "import": "./dist/index-xnf.mjs", + "default": "./dist/index-xnf.cjs" + } + }, + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "./dist/index.d.ts" + ] + } + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "files": [ + "./dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/adraffy/ens-normalize.js.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/adraffy/ens-normalize.js/issues" + }, + "homepage": "https://github.com/adraffy/ens-normalize.js#readme", + "author": { + "name": "raffy.eth", + "email": "raffy@me.com", + "url": "http://raffy.antistupid.com" + }, + "scripts": { + "unicode": "node derive/download.js", + "labels": "node validate/download-labels.js", + "derive": "node derive/make.js", + "make": "node src/make.js", + "validate": "node validate/make.js", + "test": "node test/coder.js && node test/nf.js && node test/validate.js && node test/init.js", + "build": "rollup -c", + "rebuild": "npm run derive && npm run make && npm run validate && npm run test && npm run build", + "order": "node validate/dump-group-order.js save && npm run rebuild", + "pack": "node ./src/prepost.js pack", + "pub": "node ./src/prepost.js publish" + }, + "devDependencies": { + "@rollup/plugin-alias": "^5.0.0", + "@rollup/plugin-terser": "^0.4.0", + "rollup": "^3.24.1" + } +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@ethereumjs/rlp/LICENSE b/test/merkletreejs/node_modules/@ethereumjs/rlp/LICENSE new file mode 100644 index 0000000..14e2f77 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/rlp/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/test/merkletreejs/node_modules/@ethereumjs/rlp/README.md b/test/merkletreejs/node_modules/@ethereumjs/rlp/README.md new file mode 100644 index 0000000..87b9dfa --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/rlp/README.md @@ -0,0 +1,107 @@ +# @ethereumjs/rlp + +[![NPM Package][rlp-npm-badge]][rlp-npm-link] +[![GitHub Issues][rlp-issues-badge]][rlp-issues-link] +[![Actions Status][rlp-actions-badge]][rlp-actions-link] +[![Code Coverage][rlp-coverage-badge]][rlp-coverage-link] +[![Discord][discord-badge]][discord-link] + +[Recursive Length Prefix](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp) encoding for Node.js and the browser. + +## Installation + +To obtain the latest version, simply require the project using `npm`: + +```shell +npm install @ethereumjs/rlp +``` + +Install with `-g` if you want to use the CLI. + +## Usage + +```typescript +import assert from 'assert' +import { RLP } from '@ethereumjs/rlp' + +const nestedList = [[], [[]], [[], [[]]]] +const encoded = RLP.encode(nestedList) +const decoded = RLP.decode(encoded) +assert.deepEqual(nestedList, decoded) +``` + +## API + +`RLP.encode(plain)` - RLP encodes an `Array`, `Uint8Array` or `String` and returns a `Uint8Array`. + +`RLP.decode(encoded, [stream=false])` - Decodes an RLP encoded `Uint8Array`, `Array` or `String` and returns a `Uint8Array` or `NestedUint8Array`. If `stream` is enabled, it will just decode the first rlp sequence in the Uint8Array. By default, it would throw an error if there are more bytes in Uint8Array than used by the rlp sequence. + +### Buffer compatibility + +If you would like to continue using Buffers like in rlp v2, you can use: + +```typescript +import assert from 'assert' +import { arrToBufArr, bufArrToArr } from '@ethereumjs/util' +import { RLP } from '@ethereumjs/rlp' + +const bufferList = [Buffer.from('123', 'hex'), Buffer.from('456', 'hex')] +const encoded = RLP.encode(bufArrToArr(bufferList)) +const encodedAsBuffer = Buffer.from(encoded) +const decoded = RLP.decode(Uint8Array.from(encodedAsBuffer)) // or RLP.decode(encoded) +const decodedAsBuffers = arrToBufArr(decoded) +assert.deepEqual(bufferList, decodedAsBuffers) +``` + +### BigInt Support + +Starting with v4 the usage of [BN.js](https://github.com/indutny/bn.js/) for big numbers has been removed from the library and replaced with the usage of the native JS [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) data type (introduced in `ES2020`). + +Please note that number-related API signatures have changed along with this version update and the minimal build target has been updated to `ES2020`. + +## CLI + +`rlp encode `\ +`rlp decode <0x-prefixed hex string>` + +### Examples + +- `rlp encode '5'` -> `0x05` +- `rlp encode '[5]'` -> `0xc105` +- `rlp encode '["cat", "dog"]'` -> `0xc88363617483646f67` +- `rlp decode 0xc88363617483646f67` -> `["cat","dog"]` + +## Tests + +Tests use mocha. + +To run tests and linting: `npm test` + +To auto-fix linting problems run: `npm run lint:fix` + +## Code Coverage + +Install dev dependencies: `npm install` + +Run coverage: `npm run coverage` + +The results will be at: `coverage/lcov-report/index.html` + +## EthereumJS + +See our organizational [documentation](https://ethereumjs.readthedocs.io) for an introduction to `EthereumJS` as well as information on current standards and best practices. If you want to join for work or carry out improvements on the libraries, please review our [contribution guidelines](https://ethereumjs.readthedocs.io/en/latest/contributing.html) first. + +## License + +[MPL-2.0]() + +[discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue +[discord-link]: https://discord.gg/TNwARpR +[rlp-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/rlp.svg +[rlp-npm-link]: https://www.npmjs.com/package/@ethereumjs/rlp +[rlp-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20rlp?label=issues +[rlp-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+rlp" +[rlp-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/rlp/badge.svg +[rlp-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22rlp%22 +[rlp-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=rlp +[rlp-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/rlp diff --git a/test/merkletreejs/node_modules/@ethereumjs/rlp/bin/rlp b/test/merkletreejs/node_modules/@ethereumjs/rlp/bin/rlp new file mode 100755 index 0000000..42aee26 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/rlp/bin/rlp @@ -0,0 +1,58 @@ +#!/usr/bin/env node + +const RLP = require('../dist/index.js') +const method = process.argv[2] +const strInput = process.argv[3] + +const { bytesToHex } = RLP.utils + +if (typeof strInput !== 'string') { + return console.error(`Expected JSON string input, received type: ${typeof strInput}`) +} + +if (method === 'encode') { + // Parse JSON + let json + try { + json = JSON.parse(strInput) + } catch (error) { + const errorMsg = error.message ? error.message : error + return console.error(`Error could not parse JSON: ${errorMsg}`) + } + + // Encode RLP + try { + const encoded = RLP.encode(json) + console.log('0x' + bytesToHex(encoded)) + } catch (error) { + const errorMsg = error.message ? error.message : error + console.error(`Error encoding RLP: ${errorMsg}`) + } +} else if (method === 'decode') { + // Decode + try { + const decoded = RLP.decode(strInput) + const json = JSON.stringify(arrToJSON(decoded)) + console.log(json) + } catch (error) { + const errorMsg = error.message ? error.message : error + console.error(`Error decoding RLP: ${errorMsg}`) + } +} else { + console.error('Unsupported method') +} + +/** + * Uint8Array or Array to JSON + */ +function arrToJSON(ba) { + if (ba instanceof Uint8Array) { + return bytesToHex(ba) + } else if (ba instanceof Array) { + const arr = [] + for (let i = 0; i < ba.length; i++) { + arr.push(arrToJSON(ba[i])) + } + return arr + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/rlp/package.json b/test/merkletreejs/node_modules/@ethereumjs/rlp/package.json new file mode 100644 index 0000000..6302d6b --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/rlp/package.json @@ -0,0 +1,54 @@ +{ + "name": "@ethereumjs/rlp", + "version": "4.0.1", + "description": "Recursive Length Prefix Encoding Module", + "keywords": [ + "rlp", + "ethereum" + ], + "homepage": "https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/rlp#readme", + "bugs": { + "url": "https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aissue+label%3A%22package%3A+rlp%22" + }, + "repository": { + "type": "git", + "url": "https://github.com/ethereumjs/ethereumjs-monorepo.git" + }, + "license": "MPL-2.0", + "author": { + "name": "martin becze", + "email": "mjbecze@gmail.com" + }, + "contributors": [ + "Alex Beregszaszi ", + "Holger Drewes ", + "Paul Miller " + ], + "main": "dist/index.js", + "types": "dist/index.d.ts", + "bin": { + "rlp": "bin/rlp" + }, + "files": [ + "dist", + "bin", + "src" + ], + "scripts": { + "build": "../../config/cli/ts-build.sh node", + "clean": "../../config/cli/clean-package.sh", + "coverage": "../../config/cli/coverage.sh", + "lint": "../../config/cli/lint.sh", + "lint:diff": "../../config/cli/lint-diff.sh", + "lint:fix": "../../config/cli/lint-fix.sh", + "prepublishOnly": "../../config/cli/prepublish.sh", + "tape": "tape -r ts-node/register", + "test": "npm run test:node && npm run test:browser", + "test:browser": "karma start karma.conf.js", + "test:node": "npm run tape -- test/*.spec.ts", + "tsc": "../../config/cli/ts-compile.sh" + }, + "engines": { + "node": ">=14" + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/rlp/src/index.ts b/test/merkletreejs/node_modules/@ethereumjs/rlp/src/index.ts new file mode 100644 index 0000000..9fda5d6 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/rlp/src/index.ts @@ -0,0 +1,295 @@ +export type Input = string | number | bigint | Uint8Array | Array | null | undefined + +export type NestedUint8Array = Array + +export interface Decoded { + data: Uint8Array | NestedUint8Array + remainder: Uint8Array +} + +/** + * RLP Encoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/ + * This function takes in data, converts it to Uint8Array if not, + * and adds a length for recursion. + * @param input Will be converted to Uint8Array + * @returns Uint8Array of encoded data + **/ +export function encode(input: Input): Uint8Array { + if (Array.isArray(input)) { + const output: Uint8Array[] = [] + let outputLength = 0 + for (let i = 0; i < input.length; i++) { + const encoded = encode(input[i]) + output.push(encoded) + outputLength += encoded.length + } + return concatBytes(encodeLength(outputLength, 192), ...output) + } + const inputBuf = toBytes(input) + if (inputBuf.length === 1 && inputBuf[0] < 128) { + return inputBuf + } + return concatBytes(encodeLength(inputBuf.length, 128), inputBuf) +} + +/** + * Slices a Uint8Array, throws if the slice goes out-of-bounds of the Uint8Array. + * E.g. `safeSlice(hexToBytes('aa'), 1, 2)` will throw. + * @param input + * @param start + * @param end + */ +function safeSlice(input: Uint8Array, start: number, end: number) { + if (end > input.length) { + throw new Error('invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds') + } + return input.slice(start, end) +} + +/** + * Parse integers. Check if there is no leading zeros + * @param v The value to parse + */ +function decodeLength(v: Uint8Array): number { + if (v[0] === 0) { + throw new Error('invalid RLP: extra zeros') + } + return parseHexByte(bytesToHex(v)) +} + +function encodeLength(len: number, offset: number): Uint8Array { + if (len < 56) { + return Uint8Array.from([len + offset]) + } + const hexLength = numberToHex(len) + const lLength = hexLength.length / 2 + const firstByte = numberToHex(offset + 55 + lLength) + return Uint8Array.from(hexToBytes(firstByte + hexLength)) +} + +/** + * RLP Decoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/ + * @param input Will be converted to Uint8Array + * @param stream Is the input a stream (false by default) + * @returns decoded Array of Uint8Arrays containing the original message + **/ +export function decode(input: Input, stream?: false): Uint8Array | NestedUint8Array +export function decode(input: Input, stream?: true): Decoded +export function decode(input: Input, stream = false): Uint8Array | NestedUint8Array | Decoded { + if (typeof input === 'undefined' || input === null || (input as any).length === 0) { + return Uint8Array.from([]) + } + + const inputBytes = toBytes(input) + const decoded = _decode(inputBytes) + + if (stream) { + return decoded + } + if (decoded.remainder.length !== 0) { + throw new Error('invalid RLP: remainder must be zero') + } + + return decoded.data +} + +/** Decode an input with RLP */ +function _decode(input: Uint8Array): Decoded { + let length: number, llength: number, data: Uint8Array, innerRemainder: Uint8Array, d: Decoded + const decoded = [] + const firstByte = input[0] + + if (firstByte <= 0x7f) { + // a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. + return { + data: input.slice(0, 1), + remainder: input.slice(1), + } + } else if (firstByte <= 0xb7) { + // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string + // The range of the first byte is [0x80, 0xb7] + length = firstByte - 0x7f + + // set 0x80 null to 0 + if (firstByte === 0x80) { + data = Uint8Array.from([]) + } else { + data = safeSlice(input, 1, length) + } + + if (length === 2 && data[0] < 0x80) { + throw new Error('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed') + } + + return { + data, + remainder: input.slice(length), + } + } else if (firstByte <= 0xbf) { + // string is greater than 55 bytes long. A single byte with the value (0xb7 plus the length of the length), + // followed by the length, followed by the string + llength = firstByte - 0xb6 + if (input.length - 1 < llength) { + throw new Error('invalid RLP: not enough bytes for string length') + } + length = decodeLength(safeSlice(input, 1, llength)) + if (length <= 55) { + throw new Error('invalid RLP: expected string length to be greater than 55') + } + data = safeSlice(input, llength, length + llength) + + return { + data, + remainder: input.slice(length + llength), + } + } else if (firstByte <= 0xf7) { + // a list between 0-55 bytes long + length = firstByte - 0xbf + innerRemainder = safeSlice(input, 1, length) + while (innerRemainder.length) { + d = _decode(innerRemainder) + decoded.push(d.data) + innerRemainder = d.remainder + } + + return { + data: decoded, + remainder: input.slice(length), + } + } else { + // a list over 55 bytes long + llength = firstByte - 0xf6 + length = decodeLength(safeSlice(input, 1, llength)) + if (length < 56) { + throw new Error('invalid RLP: encoded list too short') + } + const totalLength = llength + length + if (totalLength > input.length) { + throw new Error('invalid RLP: total length is larger than the data') + } + + innerRemainder = safeSlice(input, llength, totalLength) + + while (innerRemainder.length) { + d = _decode(innerRemainder) + decoded.push(d.data) + innerRemainder = d.remainder + } + + return { + data: decoded, + remainder: input.slice(totalLength), + } + } +} + +const cachedHexes = Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0')) +function bytesToHex(uint8a: Uint8Array): string { + // Pre-caching chars with `cachedHexes` speeds this up 6x + let hex = '' + for (let i = 0; i < uint8a.length; i++) { + hex += cachedHexes[uint8a[i]] + } + return hex +} + +function parseHexByte(hexByte: string): number { + const byte = Number.parseInt(hexByte, 16) + if (Number.isNaN(byte)) throw new Error('Invalid byte sequence') + return byte +} + +// Caching slows it down 2-3x +function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + typeof hex) + } + if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex') + const array = new Uint8Array(hex.length / 2) + for (let i = 0; i < array.length; i++) { + const j = i * 2 + array[i] = parseHexByte(hex.slice(j, j + 2)) + } + return array +} + +/** Concatenates two Uint8Arrays into one. */ +function concatBytes(...arrays: Uint8Array[]): Uint8Array { + if (arrays.length === 1) return arrays[0] + const length = arrays.reduce((a, arr) => a + arr.length, 0) + const result = new Uint8Array(length) + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i] + result.set(arr, pad) + pad += arr.length + } + return result +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any +declare const TextDecoder: any + +function utf8ToBytes(utf: string): Uint8Array { + return new TextEncoder().encode(utf) +} + +/** Transform an integer into its hexadecimal value */ +function numberToHex(integer: number | bigint): string { + if (integer < 0) { + throw new Error('Invalid integer as argument, must be unsigned!') + } + const hex = integer.toString(16) + return hex.length % 2 ? `0${hex}` : hex +} + +/** Pad a string to be even */ +function padToEven(a: string): string { + return a.length % 2 ? `0${a}` : a +} + +/** Check if a string is prefixed by 0x */ +function isHexPrefixed(str: string): boolean { + return str.length >= 2 && str[0] === '0' && str[1] === 'x' +} + +/** Removes 0x from a given String */ +function stripHexPrefix(str: string): string { + if (typeof str !== 'string') { + return str + } + return isHexPrefixed(str) ? str.slice(2) : str +} + +/** Transform anything into a Uint8Array */ +function toBytes(v: Input): Uint8Array { + if (v instanceof Uint8Array) { + return v + } + if (typeof v === 'string') { + if (isHexPrefixed(v)) { + return hexToBytes(padToEven(stripHexPrefix(v))) + } + return utf8ToBytes(v) + } + if (typeof v === 'number' || typeof v === 'bigint') { + if (!v) { + return Uint8Array.from([]) + } + return hexToBytes(numberToHex(v)) + } + if (v === null || v === undefined) { + return Uint8Array.from([]) + } + throw new Error('toBytes: received unsupported type ' + typeof v) +} + +export const utils = { + bytesToHex, + concatBytes, + hexToBytes, + utf8ToBytes, +} + +export const RLP = { encode, decode } diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/LICENSE b/test/merkletreejs/node_modules/@ethereumjs/util/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/README.md b/test/merkletreejs/node_modules/@ethereumjs/util/README.md new file mode 100644 index 0000000..0a2b90d --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/README.md @@ -0,0 +1,104 @@ +# @ethereumjs/util + +[![NPM Package][util-npm-badge]][util-npm-link] +[![GitHub Issues][util-issues-badge]][util-issues-link] +[![Actions Status][util-actions-badge]][util-actions-link] +[![Code Coverage][util-coverage-badge]][util-coverage-link] +[![Discord][discord-badge]][discord-link] + +A collection of utility functions for Ethereum. It can be used in Node.js and in the browser with [browserify](http://browserify.org/). + +## Installation + +To obtain the latest version, simply require the project using `npm`: + +```shell +npm install @ethereumjs/util +``` + +## Usage + +```js +import assert from 'assert' +import { isValidChecksumAddress, unpadBuffer } from '@ethereumjs/util' + +assert.ok(isValidChecksumAddress('0x2F015C60E0be116B1f0CD534704Db9c92118FB6A')) + +assert.ok(unpadBuffer(Buffer.from('000000006600', 'hex')).equals(Buffer.from('6600', 'hex'))) +``` + +## API + +### Documentation + +Read the [API docs](docs/). + +### Modules + +- [account](src/account.ts) + - Account class + - Private/public key and address-related functionality (creation, validation, conversion) +- [address](src/address.ts) + - Address class and type +- [bytes](src/bytes.ts) + - Byte-related helper and conversion functions +- [constants](src/constants.ts) + - Exposed constants + - e.g. `KECCAK256_NULL_S` for string representation of Keccak-256 hash of null +- hash + - This module has been removed with `v8`, please use [ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) directly instead +- [signature](src/signature.ts) + - Signing, signature validation, conversion, recovery +- [types](src/types.ts) + - Helpful TypeScript types +- [internal](src/internal.ts) + - Internalized helper methods +- [withdrawal](src/withdrawal.ts) + - Withdrawal class (EIP-4895) + +### BigInt Support + +Starting with v8 the usage of [BN.js](https://github.com/indutny/bn.js/) for big numbers has been removed from the library and replaced with the usage of the native JS [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) data type (introduced in `ES2020`). + +Please note that number-related API signatures have changed along with this version update and the minimal build target has been updated to `ES2020`. + +### ethjs-util methods + +The following methods are available by an internalized version of the [ethjs-util](https://github.com/ethjs/ethjs-util) package (`MIT` license), see [internal.ts](src/internal.ts). The original package is not maintained any more and the original functionality will be replaced by own implementations over time (starting with the `v7.1.3` release, October 2021). + +- arrayContainsArray +- getBinarySize +- stripHexPrefix +- isHexPrefixed +- isHexString +- padToEven +- fromAscii +- fromUtf8 +- toUtf8 +- toAscii +- getKeys + +They can be imported by name: + +```typescript +import { stripHexPrefix } from '@ethereumjs/util' +``` + +## EthereumJS + +See our organizational [documentation](https://ethereumjs.readthedocs.io) for an introduction to `EthereumJS` as well as information on current standards and best practices. If you want to join for work or carry out improvements on the libraries, please review our [contribution guidelines](https://ethereumjs.readthedocs.io/en/latest/contributing.html) first. + +## License + +[MPL-2.0]() + +[util-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/util.svg +[util-npm-link]: https://www.npmjs.org/package/@ethereumjs/util +[util-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20util?label=issues +[util-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+util" +[util-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/Util/badge.svg +[util-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22Util%22 +[util-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=util +[util-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/util +[discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue +[discord-link]: https://discord.gg/TNwARpR diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/node_modules/.bin/rlp b/test/merkletreejs/node_modules/@ethereumjs/util/node_modules/.bin/rlp new file mode 120000 index 0000000..ee958a3 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/node_modules/.bin/rlp @@ -0,0 +1 @@ +../../../rlp/bin/rlp \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/package.json b/test/merkletreejs/node_modules/@ethereumjs/util/package.json new file mode 100644 index 0000000..1b9959b --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/package.json @@ -0,0 +1,97 @@ +{ + "name": "@ethereumjs/util", + "version": "8.1.0", + "description": "A collection of utility functions for Ethereum", + "keywords": [ + "ethereum", + "utilities", + "utils" + ], + "homepage": "https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/util#readme", + "bugs": { + "url": "https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aissue+label%3A%22package%3A+util%22" + }, + "repository": { + "type": "git", + "url": "https://github.com/ethereumjs/ethereumjs-monorepo.git" + }, + "license": "MPL-2.0", + "author": "EthereumJS Team", + "contributors": [ + { + "name": "Tim Coulter", + "email": "tim@timothyjcoulter.com", + "url": "https://github.com/tcoulter" + }, + { + "name": "Nick Dodson", + "url": "https://github.com/SilentCicero" + }, + { + "name": "Mr. Chico", + "url": "https://github.com/MrChico" + }, + { + "name": "Dũng Trần", + "email": "tad88.dev@gmail.com", + "url": "https://github.com/tad88dev" + }, + { + "name": "Alex Beregszaszi", + "email": "alex@rtfs.hu", + "url": "https://github.com/axic" + }, + { + "name": "Taylor Gerring", + "url": "https://github.com/tgerring" + }, + { + "name": "Kirill Fomichev", + "email": "fanatid@ya.ru", + "url": "https://github.com/fanatid" + }, + { + "name": "kumavis", + "email": "aaron@kumavis.me", + "url": "https://github.com/kumavis" + }, + { + "name": "Alexander Sinyagin", + "email": "sinyagin.alexander@gmail.com", + "url": "https://github.com/asinyagin" + } + ], + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist", + "src" + ], + "scripts": { + "build": "../../config/cli/ts-build.sh", + "clean": "../../config/cli/clean-package.sh", + "coverage": "../../config/cli/coverage.sh", + "docs:build": "npx typedoc --options typedoc.js", + "lint": "../../config/cli/lint.sh", + "lint:diff": "../../config/cli/lint-diff.sh", + "lint:fix": "../../config/cli/lint-fix.sh", + "prepublishOnly": "../../config/cli/prepublish.sh", + "tape": "tape -r ts-node/register", + "test": "npm run test:node && npm run test:browser", + "test:browser": "karma start karma.conf.js", + "test:node": "npm run tape -- test/*.spec.ts", + "tsc": "../../config/cli/ts-compile.sh" + }, + "dependencies": { + "@ethereumjs/rlp": "^4.0.1", + "ethereum-cryptography": "^2.0.0", + "micro-ftch": "^0.3.1" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/secp256k1": "^4.0.1" + }, + "engines": { + "node": ">=14" + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/account.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/account.ts new file mode 100644 index 0000000..261d6d8 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/account.ts @@ -0,0 +1,378 @@ +import { RLP } from '@ethereumjs/rlp' +import { keccak256 } from 'ethereum-cryptography/keccak' +import { secp256k1 } from 'ethereum-cryptography/secp256k1' +import { bytesToHex } from 'ethereum-cryptography/utils' + +import { + arrToBufArr, + bigIntToUnpaddedBuffer, + bufArrToArr, + bufferToBigInt, + bufferToHex, + toBuffer, + zeros, +} from './bytes' +import { KECCAK256_NULL, KECCAK256_RLP } from './constants' +import { assertIsBuffer, assertIsHexString, assertIsString } from './helpers' +import { stripHexPrefix } from './internal' + +import type { BigIntLike, BufferLike } from './types' + +const _0n = BigInt(0) + +export interface AccountData { + nonce?: BigIntLike + balance?: BigIntLike + storageRoot?: BufferLike + codeHash?: BufferLike +} + +export type AccountBodyBuffer = [Buffer, Buffer, Buffer | Uint8Array, Buffer | Uint8Array] + +export class Account { + nonce: bigint + balance: bigint + storageRoot: Buffer + codeHash: Buffer + + static fromAccountData(accountData: AccountData) { + const { nonce, balance, storageRoot, codeHash } = accountData + + return new Account( + nonce !== undefined ? bufferToBigInt(toBuffer(nonce)) : undefined, + balance !== undefined ? bufferToBigInt(toBuffer(balance)) : undefined, + storageRoot !== undefined ? toBuffer(storageRoot) : undefined, + codeHash !== undefined ? toBuffer(codeHash) : undefined + ) + } + + public static fromRlpSerializedAccount(serialized: Buffer) { + const values = arrToBufArr(RLP.decode(Uint8Array.from(serialized)) as Uint8Array[]) as Buffer[] + + if (!Array.isArray(values)) { + throw new Error('Invalid serialized account input. Must be array') + } + + return this.fromValuesArray(values) + } + + public static fromValuesArray(values: Buffer[]) { + const [nonce, balance, storageRoot, codeHash] = values + + return new Account(bufferToBigInt(nonce), bufferToBigInt(balance), storageRoot, codeHash) + } + + /** + * This constructor assigns and validates the values. + * Use the static factory methods to assist in creating an Account from varying data types. + */ + constructor(nonce = _0n, balance = _0n, storageRoot = KECCAK256_RLP, codeHash = KECCAK256_NULL) { + this.nonce = nonce + this.balance = balance + this.storageRoot = storageRoot + this.codeHash = codeHash + + this._validate() + } + + private _validate() { + if (this.nonce < _0n) { + throw new Error('nonce must be greater than zero') + } + if (this.balance < _0n) { + throw new Error('balance must be greater than zero') + } + if (this.storageRoot.length !== 32) { + throw new Error('storageRoot must have a length of 32') + } + if (this.codeHash.length !== 32) { + throw new Error('codeHash must have a length of 32') + } + } + + /** + * Returns a Buffer Array of the raw Buffers for the account, in order. + */ + raw(): Buffer[] { + return [ + bigIntToUnpaddedBuffer(this.nonce), + bigIntToUnpaddedBuffer(this.balance), + this.storageRoot, + this.codeHash, + ] + } + + /** + * Returns the RLP serialization of the account as a `Buffer`. + */ + serialize(): Buffer { + return Buffer.from(RLP.encode(bufArrToArr(this.raw()))) + } + + /** + * Returns a `Boolean` determining if the account is a contract. + */ + isContract(): boolean { + return !this.codeHash.equals(KECCAK256_NULL) + } + + /** + * Returns a `Boolean` determining if the account is empty complying to the definition of + * account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): + * "An account is considered empty when it has no code and zero nonce and zero balance." + */ + isEmpty(): boolean { + return this.balance === _0n && this.nonce === _0n && this.codeHash.equals(KECCAK256_NULL) + } +} + +/** + * Checks if the address is a valid. Accepts checksummed addresses too. + */ +export const isValidAddress = function (hexAddress: string): boolean { + try { + assertIsString(hexAddress) + } catch (e: any) { + return false + } + + return /^0x[0-9a-fA-F]{40}$/.test(hexAddress) +} + +/** + * Returns a checksummed address. + * + * If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This + * has the effect of checksummed addresses for one chain having invalid checksums for others. + * For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191). + * + * WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not + * backwards compatible to the original widely adopted checksum format standard introduced in + * [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications. + * Usage of this EIP is therefore discouraged unless you have a very targeted use case. + */ +export const toChecksumAddress = function ( + hexAddress: string, + eip1191ChainId?: BigIntLike +): string { + assertIsHexString(hexAddress) + const address = stripHexPrefix(hexAddress).toLowerCase() + + let prefix = '' + if (eip1191ChainId !== undefined) { + const chainId = bufferToBigInt(toBuffer(eip1191ChainId)) + prefix = chainId.toString() + '0x' + } + + const buf = Buffer.from(prefix + address, 'utf8') + const hash = bytesToHex(keccak256(buf)) + let ret = '0x' + + for (let i = 0; i < address.length; i++) { + if (parseInt(hash[i], 16) >= 8) { + ret += address[i].toUpperCase() + } else { + ret += address[i] + } + } + + return ret +} + +/** + * Checks if the address is a valid checksummed address. + * + * See toChecksumAddress' documentation for details about the eip1191ChainId parameter. + */ +export const isValidChecksumAddress = function ( + hexAddress: string, + eip1191ChainId?: BigIntLike +): boolean { + return isValidAddress(hexAddress) && toChecksumAddress(hexAddress, eip1191ChainId) === hexAddress +} + +/** + * Generates an address of a newly created contract. + * @param from The address which is creating this new address + * @param nonce The nonce of the from account + */ +export const generateAddress = function (from: Buffer, nonce: Buffer): Buffer { + assertIsBuffer(from) + assertIsBuffer(nonce) + + if (bufferToBigInt(nonce) === BigInt(0)) { + // in RLP we want to encode null in the case of zero nonce + // read the RLP documentation for an answer if you dare + return Buffer.from(keccak256(RLP.encode(bufArrToArr([from, null] as any)))).slice(-20) + } + + // Only take the lower 160bits of the hash + return Buffer.from(keccak256(RLP.encode(bufArrToArr([from, nonce])))).slice(-20) +} + +/** + * Generates an address for a contract created using CREATE2. + * @param from The address which is creating this new address + * @param salt A salt + * @param initCode The init code of the contract being created + */ +export const generateAddress2 = function (from: Buffer, salt: Buffer, initCode: Buffer): Buffer { + assertIsBuffer(from) + assertIsBuffer(salt) + assertIsBuffer(initCode) + + if (from.length !== 20) { + throw new Error('Expected from to be of length 20') + } + if (salt.length !== 32) { + throw new Error('Expected salt to be of length 32') + } + + const address = keccak256( + Buffer.concat([Buffer.from('ff', 'hex'), from, salt, keccak256(initCode)]) + ) + + return toBuffer(address).slice(-20) +} + +/** + * Checks if the private key satisfies the rules of the curve secp256k1. + */ +export const isValidPrivate = function (privateKey: Buffer): boolean { + return secp256k1.utils.isValidPrivateKey(privateKey) +} + +/** + * Checks if the public key satisfies the rules of the curve secp256k1 + * and the requirements of Ethereum. + * @param publicKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ +export const isValidPublic = function (publicKey: Buffer, sanitize: boolean = false): boolean { + assertIsBuffer(publicKey) + if (publicKey.length === 64) { + // Convert to SEC1 for secp256k1 + // Automatically checks whether point is on curve + try { + secp256k1.ProjectivePoint.fromHex(Buffer.concat([Buffer.from([4]), publicKey])) + return true + } catch (e) { + return false + } + } + + if (!sanitize) { + return false + } + + try { + secp256k1.ProjectivePoint.fromHex(publicKey) + return true + } catch (e) { + return false + } +} + +/** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ +export const pubToAddress = function (pubKey: Buffer, sanitize: boolean = false): Buffer { + assertIsBuffer(pubKey) + if (sanitize && pubKey.length !== 64) { + pubKey = Buffer.from(secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1)) + } + if (pubKey.length !== 64) { + throw new Error('Expected pubKey to be of length 64') + } + // Only take the lower 160bits of the hash + return Buffer.from(keccak256(pubKey)).slice(-20) +} +export const publicToAddress = pubToAddress + +/** + * Returns the ethereum public key of a given private key. + * @param privateKey A private key must be 256 bits wide + */ +export const privateToPublic = function (privateKey: Buffer): Buffer { + assertIsBuffer(privateKey) + // skip the type flag and use the X, Y points + return Buffer.from( + secp256k1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(false).slice(1) + ) +} + +/** + * Returns the ethereum address of a given private key. + * @param privateKey A private key must be 256 bits wide + */ +export const privateToAddress = function (privateKey: Buffer): Buffer { + return publicToAddress(privateToPublic(privateKey)) +} + +/** + * Converts a public key to the Ethereum format. + */ +export const importPublic = function (publicKey: Buffer): Buffer { + assertIsBuffer(publicKey) + if (publicKey.length !== 64) { + publicKey = Buffer.from(secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes(false).slice(1)) + } + return publicKey +} + +/** + * Returns the zero address. + */ +export const zeroAddress = function (): string { + const addressLength = 20 + const addr = zeros(addressLength) + return bufferToHex(addr) +} + +/** + * Checks if a given address is the zero address. + */ +export const isZeroAddress = function (hexAddress: string): boolean { + try { + assertIsString(hexAddress) + } catch (e: any) { + return false + } + + const zeroAddr = zeroAddress() + return zeroAddr === hexAddress +} + +export function accountBodyFromSlim(body: AccountBodyBuffer) { + const [nonce, balance, storageRoot, codeHash] = body + return [ + nonce, + balance, + arrToBufArr(storageRoot).length === 0 ? KECCAK256_RLP : storageRoot, + arrToBufArr(codeHash).length === 0 ? KECCAK256_NULL : codeHash, + ] +} + +const emptyUint8Arr = new Uint8Array(0) +export function accountBodyToSlim(body: AccountBodyBuffer) { + const [nonce, balance, storageRoot, codeHash] = body + return [ + nonce, + balance, + arrToBufArr(storageRoot).equals(KECCAK256_RLP) ? emptyUint8Arr : storageRoot, + arrToBufArr(codeHash).equals(KECCAK256_NULL) ? emptyUint8Arr : codeHash, + ] +} + +/** + * Converts a slim account (per snap protocol spec) to the RLP encoded version of the account + * @param body Array of 4 Buffer-like items to represent the account + * @returns RLP encoded version of the account + */ +export function accountBodyToRLP(body: AccountBodyBuffer, couldBeSlim = true) { + const accountBody = couldBeSlim ? accountBodyFromSlim(body) : body + return arrToBufArr(RLP.encode(accountBody)) +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/address.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/address.ts new file mode 100644 index 0000000..eaa26c4 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/address.ts @@ -0,0 +1,131 @@ +import { + generateAddress, + generateAddress2, + isValidAddress, + privateToAddress, + pubToAddress, +} from './account' +import { bigIntToBuffer, bufferToBigInt, toBuffer, zeros } from './bytes' + +/** + * Handling and generating Ethereum addresses + */ +export class Address { + public readonly buf: Buffer + + constructor(buf: Buffer) { + if (buf.length !== 20) { + throw new Error('Invalid address length') + } + this.buf = buf + } + + /** + * Returns the zero address. + */ + static zero(): Address { + return new Address(zeros(20)) + } + + /** + * Returns an Address object from a hex-encoded string. + * @param str - Hex-encoded address + */ + static fromString(str: string): Address { + if (!isValidAddress(str)) { + throw new Error('Invalid address') + } + return new Address(toBuffer(str)) + } + + /** + * Returns an address for a given public key. + * @param pubKey The two points of an uncompressed key + */ + static fromPublicKey(pubKey: Buffer): Address { + if (!Buffer.isBuffer(pubKey)) { + throw new Error('Public key should be Buffer') + } + const buf = pubToAddress(pubKey) + return new Address(buf) + } + + /** + * Returns an address for a given private key. + * @param privateKey A private key must be 256 bits wide + */ + static fromPrivateKey(privateKey: Buffer): Address { + if (!Buffer.isBuffer(privateKey)) { + throw new Error('Private key should be Buffer') + } + const buf = privateToAddress(privateKey) + return new Address(buf) + } + + /** + * Generates an address for a newly created contract. + * @param from The address which is creating this new address + * @param nonce The nonce of the from account + */ + static generate(from: Address, nonce: bigint): Address { + if (typeof nonce !== 'bigint') { + throw new Error('Expected nonce to be a bigint') + } + return new Address(generateAddress(from.buf, bigIntToBuffer(nonce))) + } + + /** + * Generates an address for a contract created using CREATE2. + * @param from The address which is creating this new address + * @param salt A salt + * @param initCode The init code of the contract being created + */ + static generate2(from: Address, salt: Buffer, initCode: Buffer): Address { + if (!Buffer.isBuffer(salt)) { + throw new Error('Expected salt to be a Buffer') + } + if (!Buffer.isBuffer(initCode)) { + throw new Error('Expected initCode to be a Buffer') + } + return new Address(generateAddress2(from.buf, salt, initCode)) + } + + /** + * Is address equal to another. + */ + equals(address: Address): boolean { + return this.buf.equals(address.buf) + } + + /** + * Is address zero. + */ + isZero(): boolean { + return this.equals(Address.zero()) + } + + /** + * True if address is in the address range defined + * by EIP-1352 + */ + isPrecompileOrSystemAddress(): boolean { + const address = bufferToBigInt(this.buf) + const rangeMin = BigInt(0) + const rangeMax = BigInt('0xffff') + return address >= rangeMin && address <= rangeMax + } + + /** + * Returns hex encoding of address. + */ + toString(): string { + return '0x' + this.buf.toString('hex') + } + + /** + * Returns Buffer representation of address. + */ + toBuffer(): Buffer { + return Buffer.from(this.buf) + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/asyncEventEmitter.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/asyncEventEmitter.ts new file mode 100644 index 0000000..7085b0a --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/asyncEventEmitter.ts @@ -0,0 +1,212 @@ +/** + * Ported to Typescript from original implementation below: + * https://github.com/ahultgren/async-eventemitter -- MIT licensed + * + * Type Definitions based on work by: patarapolw -- MIT licensed + * that was contributed to Definitely Typed below: + * https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/async-eventemitter + */ + +import { EventEmitter } from 'events' +type AsyncListener = + | ((data: T, callback?: (result?: R) => void) => Promise) + | ((data: T, callback?: (result?: R) => void) => void) +export interface EventMap { + [event: string]: AsyncListener +} + +async function runInSeries( + context: any, + tasks: Array<(data: unknown, callback?: (error?: Error) => void) => void>, + data: unknown +): Promise { + let error: Error | undefined + for await (const task of tasks) { + try { + if (task.length < 2) { + //sync + task.call(context, data) + } else { + await new Promise((resolve, reject) => { + task.call(context, data, (error) => { + if (error) { + reject(error) + } else { + resolve() + } + }) + }) + } + } catch (e: unknown) { + error = e as Error + } + } + if (error) { + throw error + } +} + +export class AsyncEventEmitter extends EventEmitter { + emit(event: E & string, ...args: Parameters) { + let [data, callback] = args + const self = this + + let listeners = (self as any)._events[event] ?? [] + + // Optional data argument + if (callback === undefined && typeof data === 'function') { + callback = data + data = undefined + } + + // Special treatment of internal newListener and removeListener events + if (event === 'newListener' || event === 'removeListener') { + data = { + event: data, + fn: callback, + } + + callback = undefined + } + + // A single listener is just a function not an array... + listeners = Array.isArray(listeners) ? listeners : [listeners] + runInSeries(self, listeners.slice(), data).then(callback).catch(callback) + + return self.listenerCount(event) > 0 + } + + once(event: E & string, listener: T[E]): this { + const self = this + let g: (...args: any[]) => void + + if (typeof listener !== 'function') { + throw new TypeError('listener must be a function') + } + + // Hack to support set arity + if (listener.length >= 2) { + g = function (e: E, next: any) { + self.removeListener(event, g as T[E]) + void listener(e, next) + } + } else { + g = function (e: E) { + self.removeListener(event, g as T[E]) + void listener(e, g) + } + } + + self.on(event, g as T[E]) + + return self + } + + first(event: E & string, listener: T[E]): this { + let listeners = (this as any)._events[event] ?? [] + + // Contract + if (typeof listener !== 'function') { + throw new TypeError('listener must be a function') + } + + // Listeners are not always an array + if (!Array.isArray(listeners)) { + ;(this as any)._events[event] = listeners = [listeners] + } + + listeners.unshift(listener) + + return this + } + + before(event: E & string, target: T[E], listener: T[E]): this { + return this.beforeOrAfter(event, target, listener) + } + + after(event: E & string, target: T[E], listener: T[E]): this { + return this.beforeOrAfter(event, target, listener, 'after') + } + + private beforeOrAfter( + event: E & string, + target: T[E], + listener: T[E], + beforeOrAfter?: string + ) { + let listeners = (this as any)._events[event] ?? [] + let i + let index + const add = beforeOrAfter === 'after' ? 1 : 0 + + // Contract + if (typeof listener !== 'function') { + throw new TypeError('listener must be a function') + } + if (typeof target !== 'function') { + throw new TypeError('target must be a function') + } + + // Listeners are not always an array + if (!Array.isArray(listeners)) { + ;(this as any)._events[event] = listeners = [listeners] + } + + index = listeners.length + + for (i = listeners.length; i--; ) { + if (listeners[i] === target) { + index = i + add + break + } + } + + listeners.splice(index, 0, listener) + + return this + } + + on(event: E & string, listener: T[E]): this { + return super.on(event, listener) + } + + addListener(event: E & string, listener: T[E]): this { + return super.addListener(event, listener) + } + + prependListener(event: E & string, listener: T[E]): this { + return super.prependListener(event, listener) + } + + prependOnceListener(event: E & string, listener: T[E]): this { + return super.prependOnceListener(event, listener) + } + + removeAllListeners(event?: keyof T & string): this { + return super.removeAllListeners(event) + } + + removeListener(event: E & string, listener: T[E]): this { + return super.removeListener(event, listener) + } + + eventNames(): Array { + return super.eventNames() as keyof T & string[] + } + + listeners(event: E & string): Array { + return super.listeners(event) as T[E][] + } + + listenerCount(event: keyof T & string): number { + return super.listenerCount(event) + } + + getMaxListeners(): number { + return super.getMaxListeners() + } + + setMaxListeners(maxListeners: number): this { + return super.setMaxListeners(maxListeners) + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/bytes.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/bytes.ts new file mode 100644 index 0000000..086295f --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/bytes.ts @@ -0,0 +1,392 @@ +import { assertIsArray, assertIsBuffer, assertIsHexString } from './helpers' +import { isHexPrefixed, isHexString, padToEven, stripHexPrefix } from './internal' + +import type { + NestedBufferArray, + NestedUint8Array, + PrefixedHexString, + TransformableToArray, + TransformableToBuffer, +} from './types' + +/** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ +export const intToHex = function (i: number) { + if (!Number.isSafeInteger(i) || i < 0) { + throw new Error(`Received an invalid integer type: ${i}`) + } + return `0x${i.toString(16)}` +} + +/** + * Converts an `Number` to a `Buffer` + * @param {Number} i + * @return {Buffer} + */ +export const intToBuffer = function (i: number) { + const hex = intToHex(i) + return Buffer.from(padToEven(hex.slice(2)), 'hex') +} + +/** + * Returns a buffer filled with 0s. + * @param bytes the number of bytes the buffer should be + */ +export const zeros = function (bytes: number): Buffer { + return Buffer.allocUnsafe(bytes).fill(0) +} + +/** + * Pads a `Buffer` with zeros till it has `length` bytes. + * Truncates the beginning or end of input if its length exceeds `length`. + * @param msg the value to pad (Buffer) + * @param length the number of bytes the output should be + * @param right whether to start padding form the left or right + * @return (Buffer) + */ +const setLength = function (msg: Buffer, length: number, right: boolean) { + const buf = zeros(length) + if (right) { + if (msg.length < length) { + msg.copy(buf) + return buf + } + return msg.slice(0, length) + } else { + if (msg.length < length) { + msg.copy(buf, length - msg.length) + return buf + } + return msg.slice(-length) + } +} + +/** + * Left Pads a `Buffer` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Buffer) + * @param length the number of bytes the output should be + * @return (Buffer) + */ +export const setLengthLeft = function (msg: Buffer, length: number) { + assertIsBuffer(msg) + return setLength(msg, length, false) +} + +/** + * Right Pads a `Buffer` with trailing zeros till it has `length` bytes. + * it truncates the end if it exceeds. + * @param msg the value to pad (Buffer) + * @param length the number of bytes the output should be + * @return (Buffer) + */ +export const setLengthRight = function (msg: Buffer, length: number) { + assertIsBuffer(msg) + return setLength(msg, length, true) +} + +/** + * Trims leading zeros from a `Buffer`, `String` or `Number[]`. + * @param a (Buffer|Array|String) + * @return (Buffer|Array|String) + */ +const stripZeros = function (a: any): Buffer | number[] | string { + let first = a[0] + while (a.length > 0 && first.toString() === '0') { + a = a.slice(1) + first = a[0] + } + return a +} + +/** + * Trims leading zeros from a `Buffer`. + * @param a (Buffer) + * @return (Buffer) + */ +export const unpadBuffer = function (a: Buffer): Buffer { + assertIsBuffer(a) + return stripZeros(a) as Buffer +} + +/** + * Trims leading zeros from an `Array` (of numbers). + * @param a (number[]) + * @return (number[]) + */ +export const unpadArray = function (a: number[]): number[] { + assertIsArray(a) + return stripZeros(a) as number[] +} + +/** + * Trims leading zeros from a hex-prefixed `String`. + * @param a (String) + * @return (String) + */ +export const unpadHexString = function (a: string): string { + assertIsHexString(a) + a = stripHexPrefix(a) + return ('0x' + stripZeros(a)) as string +} + +export type ToBufferInputTypes = + | PrefixedHexString + | number + | bigint + | Buffer + | Uint8Array + | number[] + | TransformableToArray + | TransformableToBuffer + | null + | undefined + +/** + * Attempts to turn a value into a `Buffer`. + * Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toBuffer()` method. + * @param v the value + */ +export const toBuffer = function (v: ToBufferInputTypes): Buffer { + if (v === null || v === undefined) { + return Buffer.allocUnsafe(0) + } + + if (Buffer.isBuffer(v)) { + return Buffer.from(v) + } + + if (Array.isArray(v) || v instanceof Uint8Array) { + return Buffer.from(v as Uint8Array) + } + + if (typeof v === 'string') { + if (!isHexString(v)) { + throw new Error( + `Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: ${v}` + ) + } + return Buffer.from(padToEven(stripHexPrefix(v)), 'hex') + } + + if (typeof v === 'number') { + return intToBuffer(v) + } + + if (typeof v === 'bigint') { + if (v < BigInt(0)) { + throw new Error(`Cannot convert negative bigint to buffer. Given: ${v}`) + } + let n = v.toString(16) + if (n.length % 2) n = '0' + n + return Buffer.from(n, 'hex') + } + + if (v.toArray) { + // converts a BN to a Buffer + return Buffer.from(v.toArray()) + } + + if (v.toBuffer) { + return Buffer.from(v.toBuffer()) + } + + throw new Error('invalid type') +} + +/** + * Converts a `Buffer` into a `0x`-prefixed hex `String`. + * @param buf `Buffer` object to convert + */ +export const bufferToHex = function (buf: Buffer): string { + buf = toBuffer(buf) + return '0x' + buf.toString('hex') +} + +/** + * Converts a {@link Buffer} to a {@link bigint} + */ +export function bufferToBigInt(buf: Buffer) { + const hex = bufferToHex(buf) + if (hex === '0x') { + return BigInt(0) + } + return BigInt(hex) +} + +/** + * Converts a {@link bigint} to a {@link Buffer} + */ +export function bigIntToBuffer(num: bigint) { + return toBuffer('0x' + num.toString(16)) +} + +/** + * Converts a `Buffer` to a `Number`. + * @param buf `Buffer` object to convert + * @throws If the input number exceeds 53 bits. + */ +export const bufferToInt = function (buf: Buffer): number { + const res = Number(bufferToBigInt(buf)) + if (!Number.isSafeInteger(res)) throw new Error('Number exceeds 53 bits') + return res +} + +/** + * Interprets a `Buffer` as a signed integer and returns a `BigInt`. Assumes 256-bit numbers. + * @param num Signed integer value + */ +export const fromSigned = function (num: Buffer): bigint { + return BigInt.asIntN(256, bufferToBigInt(num)) +} + +/** + * Converts a `BigInt` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. + * @param num + */ +export const toUnsigned = function (num: bigint): Buffer { + return bigIntToBuffer(BigInt.asUintN(256, num)) +} + +/** + * Adds "0x" to a given `String` if it does not already start with "0x". + */ +export const addHexPrefix = function (str: string): string { + if (typeof str !== 'string') { + return str + } + + return isHexPrefixed(str) ? str : '0x' + str +} + +/** + * Shortens a string or buffer's hex string representation to maxLength (default 50). + * + * Examples: + * + * Input: '657468657265756d000000000000000000000000000000000000000000000000' + * Output: '657468657265756d0000000000000000000000000000000000…' + */ +export function short(buffer: Buffer | string, maxLength: number = 50): string { + const bufferStr = Buffer.isBuffer(buffer) ? buffer.toString('hex') : buffer + if (bufferStr.length <= maxLength) { + return bufferStr + } + return bufferStr.slice(0, maxLength) + '…' +} + +/** + * Returns the utf8 string representation from a hex string. + * + * Examples: + * + * Input 1: '657468657265756d000000000000000000000000000000000000000000000000' + * Input 2: '657468657265756d' + * Input 3: '000000000000000000000000000000000000000000000000657468657265756d' + * + * Output (all 3 input variants): 'ethereum' + * + * Note that this method is not intended to be used with hex strings + * representing quantities in both big endian or little endian notation. + * + * @param string Hex string, should be `0x` prefixed + * @return Utf8 string + */ +export const toUtf8 = function (hex: string): string { + const zerosRegexp = /^(00)+|(00)+$/g + hex = stripHexPrefix(hex) + if (hex.length % 2 !== 0) { + throw new Error('Invalid non-even hex string input for toUtf8() provided') + } + const bufferVal = Buffer.from(hex.replace(zerosRegexp, ''), 'hex') + + return bufferVal.toString('utf8') +} + +/** + * Converts a `Buffer` or `Array` to JSON. + * @param ba (Buffer|Array) + * @return (Array|String|null) + */ +export const baToJSON = function (ba: any): any { + if (Buffer.isBuffer(ba)) { + return `0x${ba.toString('hex')}` + } else if (ba instanceof Array) { + const array = [] + for (let i = 0; i < ba.length; i++) { + array.push(baToJSON(ba[i])) + } + return array + } +} + +/** + * Checks provided Buffers for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Buffer values + * @throws if any provided value is found to have leading zero bytes + */ +export const validateNoLeadingZeroes = function (values: { [key: string]: Buffer | undefined }) { + for (const [k, v] of Object.entries(values)) { + if (v !== undefined && v.length > 0 && v[0] === 0) { + throw new Error(`${k} cannot have leading zeroes, received: ${v.toString('hex')}`) + } + } +} + +/** + * Converts a {@link Uint8Array} or {@link NestedUint8Array} to {@link Buffer} or {@link NestedBufferArray} + */ +export function arrToBufArr(arr: Uint8Array): Buffer +export function arrToBufArr(arr: NestedUint8Array): NestedBufferArray +export function arrToBufArr(arr: Uint8Array | NestedUint8Array): Buffer | NestedBufferArray +export function arrToBufArr(arr: Uint8Array | NestedUint8Array): Buffer | NestedBufferArray { + if (!Array.isArray(arr)) { + return Buffer.from(arr) + } + return arr.map((a) => arrToBufArr(a)) +} + +/** + * Converts a {@link Buffer} or {@link NestedBufferArray} to {@link Uint8Array} or {@link NestedUint8Array} + */ +export function bufArrToArr(arr: Buffer): Uint8Array +export function bufArrToArr(arr: NestedBufferArray): NestedUint8Array +export function bufArrToArr(arr: Buffer | NestedBufferArray): Uint8Array | NestedUint8Array +export function bufArrToArr(arr: Buffer | NestedBufferArray): Uint8Array | NestedUint8Array { + if (!Array.isArray(arr)) { + return Uint8Array.from(arr ?? []) + } + return arr.map((a) => bufArrToArr(a)) +} + +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +export const bigIntToHex = (num: bigint) => { + return '0x' + num.toString(16) +} + +/** + * Convert value from bigint to an unpadded Buffer + * (useful for RLP transport) + * @param value value to convert + */ +export function bigIntToUnpaddedBuffer(value: bigint): Buffer { + return unpadBuffer(bigIntToBuffer(value)) +} + +export function intToUnpaddedBuffer(value: number): Buffer { + return unpadBuffer(intToBuffer(value)) +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/constants.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/constants.ts new file mode 100644 index 0000000..606b303 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/constants.ts @@ -0,0 +1,71 @@ +import { Buffer } from 'buffer' +import { secp256k1 } from 'ethereum-cryptography/secp256k1' + +/** + * 2^64-1 + */ +export const MAX_UINT64 = BigInt('0xffffffffffffffff') + +/** + * The max integer that the evm can handle (2^256-1) + */ +export const MAX_INTEGER = BigInt( + '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' +) + +/** + * The max integer that the evm can handle (2^256-1) as a bigint + * 2^256-1 equals to 340282366920938463463374607431768211455 + * We use literal value instead of calculated value for compatibility issue. + */ +export const MAX_INTEGER_BIGINT = BigInt( + '115792089237316195423570985008687907853269984665640564039457584007913129639935' +) + +export const SECP256K1_ORDER = secp256k1.CURVE.n +export const SECP256K1_ORDER_DIV_2 = secp256k1.CURVE.n / BigInt(2) + +/** + * 2^256 + */ +export const TWO_POW256 = BigInt( + '0x10000000000000000000000000000000000000000000000000000000000000000' +) + +/** + * Keccak-256 hash of null + */ +export const KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + +/** + * Keccak-256 hash of null + */ +export const KECCAK256_NULL = Buffer.from(KECCAK256_NULL_S, 'hex') + +/** + * Keccak-256 of an RLP of an empty array + */ +export const KECCAK256_RLP_ARRAY_S = + '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347' + +/** + * Keccak-256 of an RLP of an empty array + */ +export const KECCAK256_RLP_ARRAY = Buffer.from(KECCAK256_RLP_ARRAY_S, 'hex') + +/** + * Keccak-256 hash of the RLP of null + */ +export const KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421' + +/** + * Keccak-256 hash of the RLP of null + */ +export const KECCAK256_RLP = Buffer.from(KECCAK256_RLP_S, 'hex') + +/** + * RLP encoded empty string + */ +export const RLP_EMPTY_STRING = Buffer.from([0x80]) + +export const MAX_WITHDRAWALS_PER_PAYLOAD = 16 diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/encoding.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/encoding.ts new file mode 100644 index 0000000..da4f736 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/encoding.ts @@ -0,0 +1,85 @@ +// Reference: https://ethereum.org/en/developers/docs/data-structures-and-encoding/patricia-merkle-trie/ +/** + * + * @param s byte sequence + * @returns boolean indicating if input hex nibble sequence has terminator indicating leaf-node + * terminator is represented with 16 because a nibble ranges from 0 - 15(f) + */ +export const hasTerminator = (nibbles: Uint8Array) => { + return nibbles.length > 0 && nibbles[nibbles.length - 1] === 16 +} + +export const nibblesToBytes = (nibbles: Uint8Array, bytes: Uint8Array) => { + for (let bi = 0, ni = 0; ni < nibbles.length; bi += 1, ni += 2) { + bytes[bi] = (nibbles[ni] << 4) | nibbles[ni + 1] + } +} + +export const nibblesToCompactBytes = (nibbles: Uint8Array) => { + let terminator = 0 + if (hasTerminator(nibbles)) { + terminator = 1 + // Remove the terminator from the sequence + nibbles = nibbles.subarray(0, nibbles.length - 1) + } + const buf = new Uint8Array(nibbles.length / 2 + 1) + // Shift the terminator info into the first nibble of buf[0] + buf[0] = terminator << 5 + // If odd length, then add that flag into the first nibble and put the odd nibble to + // second part of buf[0] which otherwise will be left padded with a 0 + if ((nibbles.length & 1) === 1) { + buf[0] |= 1 << 4 + buf[0] |= nibbles[0] + nibbles = nibbles.subarray(1) + } + // create bytes out of the rest even nibbles + nibblesToBytes(nibbles, buf.subarray(1)) + return buf +} + +export const bytesToNibbles = (str: Uint8Array) => { + const l = str.length * 2 + 1 + const nibbles = new Uint8Array(l) + for (let i = 0; i < str.length; i++) { + const b = str[i] + nibbles[i * 2] = b / 16 + nibbles[i * 2 + 1] = b % 16 + } + // This will get removed from calling function if the first nibble + // indicates that terminator is not present + nibbles[l - 1] = 16 + return nibbles +} + +export const compactBytesToNibbles = (compact: Uint8Array) => { + if (compact.length === 0) { + return compact + } + let base = bytesToNibbles(compact) + // delete terminator flag if terminator flag was not in first nibble + if (base[0] < 2) { + base = base.subarray(0, base.length - 1) + } + // chop the terminator nibble and the even padding (if there is one) + // i.e. chop 2 left nibbles when even else 1 when odd + const chop = 2 - (base[0] & 1) + return base.subarray(chop) +} + +/** + * A test helper to generates compact path for a subset of key bytes + * + * TODO: Commenting the code for now as this seems to be helper function + * (from geth codebase ) + * + */ +// +// +// export const getPathTo = (tillBytes: number, key: Buffer) => { +// const hexNibbles = bytesToNibbles(key).subarray(0, tillBytes) +// // Remove the terminator if its there, although it would be there only if tillBytes >= key.length +// // This seems to be a test helper to generate paths so correctness of this isn't necessary +// hexNibbles[hexNibbles.length - 1] = 0 +// const compactBytes = nibblesToCompactBytes(hexNibbles) +// return [Buffer.from(compactBytes)] +// } diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/helpers.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/helpers.ts new file mode 100644 index 0000000..297dbb0 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/helpers.ts @@ -0,0 +1,45 @@ +import { isHexString } from './internal' + +/** + * Throws if a string is not hex prefixed + * @param {string} input string to check hex prefix of + */ +export const assertIsHexString = function (input: string): void { + if (!isHexString(input)) { + const msg = `This method only supports 0x-prefixed hex strings but input was: ${input}` + throw new Error(msg) + } +} + +/** + * Throws if input is not a buffer + * @param {Buffer} input value to check + */ +export const assertIsBuffer = function (input: Buffer): void { + if (!Buffer.isBuffer(input)) { + const msg = `This method only supports Buffer but input was: ${input}` + throw new Error(msg) + } +} + +/** + * Throws if input is not an array + * @param {number[]} input value to check + */ +export const assertIsArray = function (input: number[]): void { + if (!Array.isArray(input)) { + const msg = `This method only supports number arrays but input was: ${input}` + throw new Error(msg) + } +} + +/** + * Throws if input is not a string + * @param {string} input value to check + */ +export const assertIsString = function (input: string): void { + if (typeof input !== 'string') { + const msg = `This method only supports strings but input was: ${input}` + throw new Error(msg) + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/index.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/index.ts new file mode 100644 index 0000000..9109fba --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/index.ts @@ -0,0 +1,63 @@ +/** + * Constants + */ +export * from './constants' + +/** + * Units helpers + */ +export * from './units' + +/** + * Account class and helper functions + */ +export * from './account' + +/** + * Address type + */ +export * from './address' + +/** + * Withdrawal type + */ +export * from './withdrawal' + +/** + * ECDSA signature + */ +export * from './signature' + +/** + * Utilities for manipulating Buffers, byte arrays, etc. + */ +export * from './bytes' + +/** + * Helpful TypeScript types + */ +export * from './types' + +/** + * Helper function for working with compact encoding + */ +export * from './encoding' + +/** + * Export ethjs-util methods + */ +export * from './asyncEventEmitter' +export { + arrayContainsArray, + fromAscii, + fromUtf8, + getBinarySize, + getKeys, + isHexPrefixed, + isHexString, + padToEven, + stripHexPrefix, + toAscii, +} from './internal' +export * from './lock' +export * from './provider' diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/internal.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/internal.ts new file mode 100644 index 0000000..9a9d04a --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/internal.ts @@ -0,0 +1,209 @@ +/* +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +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 + */ + +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +export function isHexPrefixed(str: string): boolean { + if (typeof str !== 'string') { + throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`) + } + + return str[0] === '0' && str[1] === 'x' +} + +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +export const stripHexPrefix = (str: string): string => { + if (typeof str !== 'string') + throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`) + + return isHexPrefixed(str) ? str.slice(2) : str +} + +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +export function padToEven(value: string): string { + let a = value + + if (typeof a !== 'string') { + throw new Error(`[padToEven] value must be type 'string', received ${typeof a}`) + } + + if (a.length % 2) a = `0${a}` + + return a +} + +/** + * Get the binary size of a string + * @param str + * @returns the number of bytes contained within the string + */ +export function getBinarySize(str: string) { + if (typeof str !== 'string') { + throw new Error(`[getBinarySize] method requires input type 'string', received ${typeof str}`) + } + + return Buffer.byteLength(str, 'utf8') +} + +/** + * Returns TRUE if the first specified array contains all elements + * from the second one. FALSE otherwise. + * + * @param superset + * @param subset + * + */ +export function arrayContainsArray( + superset: unknown[], + subset: unknown[], + some?: boolean +): boolean { + if (Array.isArray(superset) !== true) { + throw new Error( + `[arrayContainsArray] method requires input 'superset' to be an array, got type '${typeof superset}'` + ) + } + if (Array.isArray(subset) !== true) { + throw new Error( + `[arrayContainsArray] method requires input 'subset' to be an array, got type '${typeof subset}'` + ) + } + + return subset[some === true ? 'some' : 'every']((value) => superset.indexOf(value) >= 0) +} + +/** + * Should be called to get ascii from its hex representation + * + * @param string in hex + * @returns ascii string representation of hex value + */ +export function toAscii(hex: string): string { + let str = '' + let i = 0 + const l = hex.length + + if (hex.substring(0, 2) === '0x') i = 2 + + for (; i < l; i += 2) { + const code = parseInt(hex.substr(i, 2), 16) + str += String.fromCharCode(code) + } + + return str +} + +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * + * @param string + * @param optional padding + * @returns hex representation of input string + */ +export function fromUtf8(stringValue: string) { + const str = Buffer.from(stringValue, 'utf8') + + return `0x${padToEven(str.toString('hex')).replace(/^0+|0+$/g, '')}` +} + +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * + * @param string + * @param optional padding + * @returns hex representation of input string + */ +export function fromAscii(stringValue: string) { + let hex = '' + for (let i = 0; i < stringValue.length; i++) { + const code = stringValue.charCodeAt(i) + const n = code.toString(16) + hex += n.length < 2 ? `0${n}` : n + } + + return `0x${hex}` +} + +/** + * Returns the keys from an array of objects. + * @example + * ```js + * getKeys([{a: '1', b: '2'}, {a: '3', b: '4'}], 'a') => ['1', '3'] + *```` + * @param params + * @param key + * @param allowEmpty + * @returns output just a simple array of output keys + */ +export function getKeys(params: Record[], key: string, allowEmpty?: boolean) { + if (!Array.isArray(params)) { + throw new Error(`[getKeys] method expects input 'params' to be an array, got ${typeof params}`) + } + if (typeof key !== 'string') { + throw new Error( + `[getKeys] method expects input 'key' to be type 'string', got ${typeof params}` + ) + } + + const result = [] + + for (let i = 0; i < params.length; i++) { + let value = params[i][key] + if (allowEmpty === true && !value) { + value = '' + } else if (typeof value !== 'string') { + throw new Error(`invalid abi - expected type 'string', received ${typeof value}`) + } + result.push(value) + } + + return result +} + +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +export function isHexString(value: string, length?: number): boolean { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) return false + + if (typeof length !== 'undefined' && length > 0 && value.length !== 2 + 2 * length) return false + + return true +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/lock.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/lock.ts new file mode 100644 index 0000000..d0f0a91 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/lock.ts @@ -0,0 +1,42 @@ +// Based on https://github.com/jsoendermann/semaphore-async-await/blob/master/src/Semaphore.ts +export class Lock { + private permits: number = 1 + private promiseResolverQueue: Array<(v: boolean) => void> = [] + + /** + * Returns a promise used to wait for a permit to become available. This method should be awaited on. + * @returns A promise that gets resolved when execution is allowed to proceed. + */ + public async acquire(): Promise { + if (this.permits > 0) { + this.permits -= 1 + return Promise.resolve(true) + } + + // If there is no permit available, we return a promise that resolves once the semaphore gets + // signaled enough times that permits is equal to one. + return new Promise((resolver) => this.promiseResolverQueue.push(resolver)) + } + + /** + * Increases the number of permits by one. If there are other functions waiting, one of them will + * continue to execute in a future iteration of the event loop. + */ + public release(): void { + this.permits += 1 + + if (this.permits > 1 && this.promiseResolverQueue.length > 0) { + // eslint-disable-next-line no-console + console.warn('Lock.permits should never be > 0 when there is someone waiting.') + } else if (this.permits === 1 && this.promiseResolverQueue.length > 0) { + // If there is someone else waiting, immediately consume the permit that was released + // at the beginning of this function and let the waiting function resume. + this.permits -= 1 + + const nextResolver = this.promiseResolverQueue.shift() + if (nextResolver) { + nextResolver(true) + } + } + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/provider.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/provider.ts new file mode 100644 index 0000000..da87962 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/provider.ts @@ -0,0 +1,32 @@ +import fetch from 'micro-ftch' + +type rpcParams = { + method: string + params: (string | boolean | number)[] +} +export const fetchFromProvider = async (url: string, params: rpcParams) => { + const res = await fetch(url, { + headers: { + 'content-type': 'application/json', + }, + type: 'json', + data: { + method: params.method, + params: params.params, + jsonrpc: '2.0', + id: 1, + }, + }) + + return res.result +} + +export const getProvider = (provider: string | any) => { + if (typeof provider === 'string') { + return provider + } else if (provider?.connection?.url !== undefined) { + return provider.connection.url + } else { + throw new Error('Must provide valid provider URL or Web3Provider') + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/signature.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/signature.ts new file mode 100644 index 0000000..35aaad4 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/signature.ts @@ -0,0 +1,194 @@ +import { keccak256 } from 'ethereum-cryptography/keccak' +import { secp256k1 } from 'ethereum-cryptography/secp256k1' + +import { bufferToBigInt, bufferToHex, bufferToInt, setLengthLeft, toBuffer } from './bytes' +import { SECP256K1_ORDER, SECP256K1_ORDER_DIV_2 } from './constants' +import { assertIsBuffer } from './helpers' + +export interface ECDSASignature { + v: bigint + r: Buffer + s: Buffer +} + +/** + * Returns the ECDSA signature of a message hash. + * + * If `chainId` is provided assume an EIP-155-style signature and calculate the `v` value + * accordingly, otherwise return a "static" `v` just derived from the `recovery` bit + */ +export function ecsign(msgHash: Buffer, privateKey: Buffer, chainId?: bigint): ECDSASignature { + const sig = secp256k1.sign(msgHash, privateKey) + const buf = sig.toCompactRawBytes() + const r = Buffer.from(buf.slice(0, 32)) + const s = Buffer.from(buf.slice(32, 64)) + + const v = + chainId === undefined + ? BigInt(sig.recovery! + 27) + : BigInt(sig.recovery! + 35) + BigInt(chainId) * BigInt(2) + + return { r, s, v } +} + +function calculateSigRecovery(v: bigint, chainId?: bigint): bigint { + if (v === BigInt(0) || v === BigInt(1)) return v + + if (chainId === undefined) { + return v - BigInt(27) + } + return v - (chainId * BigInt(2) + BigInt(35)) +} + +function isValidSigRecovery(recovery: bigint): boolean { + return recovery === BigInt(0) || recovery === BigInt(1) +} + +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +export const ecrecover = function ( + msgHash: Buffer, + v: bigint, + r: Buffer, + s: Buffer, + chainId?: bigint +): Buffer { + const signature = Buffer.concat([setLengthLeft(r, 32), setLengthLeft(s, 32)], 64) + const recovery = calculateSigRecovery(v, chainId) + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value') + } + + const sig = secp256k1.Signature.fromCompact(signature).addRecoveryBit(Number(recovery)) + const senderPubKey = sig.recoverPublicKey(msgHash) + return Buffer.from(senderPubKey.toRawBytes(false).slice(1)) +} + +/** + * Convert signature parameters into the format of `eth_sign` RPC method. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Signature + */ +export const toRpcSig = function (v: bigint, r: Buffer, s: Buffer, chainId?: bigint): string { + const recovery = calculateSigRecovery(v, chainId) + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value') + } + + // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin + return bufferToHex(Buffer.concat([setLengthLeft(r, 32), setLengthLeft(s, 32), toBuffer(v)])) +} + +/** + * Convert signature parameters into the format of Compact Signature Representation (EIP-2098). + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Signature + */ +export const toCompactSig = function (v: bigint, r: Buffer, s: Buffer, chainId?: bigint): string { + const recovery = calculateSigRecovery(v, chainId) + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value') + } + + let ss = s + if ((v > BigInt(28) && v % BigInt(2) === BigInt(1)) || v === BigInt(1) || v === BigInt(28)) { + ss = Buffer.from(s) + ss[0] |= 0x80 + } + + return bufferToHex(Buffer.concat([setLengthLeft(r, 32), setLengthLeft(ss, 32)])) +} + +/** + * Convert signature format of the `eth_sign` RPC method to signature parameters + * + * NOTE: For an extracted `v` value < 27 (see Geth bug https://github.com/ethereum/go-ethereum/issues/2053) + * `v + 27` is returned for the `v` value + * NOTE: After EIP1559, `v` could be `0` or `1` but this function assumes + * it's a signed message (EIP-191 or EIP-712) adding `27` at the end. Remove if needed. + */ +export const fromRpcSig = function (sig: string): ECDSASignature { + const buf: Buffer = toBuffer(sig) + + let r: Buffer + let s: Buffer + let v: bigint + if (buf.length >= 65) { + r = buf.slice(0, 32) + s = buf.slice(32, 64) + v = bufferToBigInt(buf.slice(64)) + } else if (buf.length === 64) { + // Compact Signature Representation (https://eips.ethereum.org/EIPS/eip-2098) + r = buf.slice(0, 32) + s = buf.slice(32, 64) + v = BigInt(bufferToInt(buf.slice(32, 33)) >> 7) + s[0] &= 0x7f + } else { + throw new Error('Invalid signature length') + } + + // support both versions of `eth_sign` responses + if (v < 27) { + v = v + BigInt(27) + } + + return { + v, + r, + s, + } +} + +/** + * Validate a ECDSA signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @param homesteadOrLater Indicates whether this is being used on either the homestead hardfork or a later one + */ +export const isValidSignature = function ( + v: bigint, + r: Buffer, + s: Buffer, + homesteadOrLater: boolean = true, + chainId?: bigint +): boolean { + if (r.length !== 32 || s.length !== 32) { + return false + } + + if (!isValidSigRecovery(calculateSigRecovery(v, chainId))) { + return false + } + + const rBigInt = bufferToBigInt(r) + const sBigInt = bufferToBigInt(s) + + if ( + rBigInt === BigInt(0) || + rBigInt >= SECP256K1_ORDER || + sBigInt === BigInt(0) || + sBigInt >= SECP256K1_ORDER + ) { + return false + } + + if (homesteadOrLater && sBigInt >= SECP256K1_ORDER_DIV_2) { + return false + } + + return true +} + +/** + * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. + * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` + * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key + * used to produce the signature. + */ +export const hashPersonalMessage = function (message: Buffer): Buffer { + assertIsBuffer(message) + const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${message.length}`, 'utf-8') + return Buffer.from(keccak256(Buffer.concat([prefix, message]))) +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/types.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/types.ts new file mode 100644 index 0000000..6c007c0 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/types.ts @@ -0,0 +1,122 @@ +import { bufferToBigInt, bufferToHex, toBuffer } from './bytes' +import { isHexString } from './internal' + +import type { Address } from './address' +import type { ToBufferInputTypes } from './bytes' + +/* + * A type that represents an input that can be converted to a BigInt. + */ +export type BigIntLike = bigint | PrefixedHexString | number | Buffer + +/* + * A type that represents an input that can be converted to a Buffer. + */ +export type BufferLike = + | Buffer + | Uint8Array + | number[] + | number + | bigint + | TransformableToBuffer + | PrefixedHexString + +/* + * A type that represents a `0x`-prefixed hex string. + */ +export type PrefixedHexString = string + +/** + * A type that represents an input that can be converted to an Address. + */ +export type AddressLike = Address | Buffer | PrefixedHexString + +/* + * A type that represents an object that has a `toArray()` method. + */ +export interface TransformableToArray { + toArray(): Uint8Array + toBuffer?(): Buffer +} + +/* + * A type that represents an object that has a `toBuffer()` method. + */ +export interface TransformableToBuffer { + toBuffer(): Buffer + toArray?(): Uint8Array +} + +export type NestedUint8Array = Array +export type NestedBufferArray = Array + +/** + * Type output options + */ +export enum TypeOutput { + Number, + BigInt, + Buffer, + PrefixedHexString, +} + +export type TypeOutputReturnType = { + [TypeOutput.Number]: number + [TypeOutput.BigInt]: bigint + [TypeOutput.Buffer]: Buffer + [TypeOutput.PrefixedHexString]: PrefixedHexString +} + +/** + * Convert an input to a specified type. + * Input of null/undefined returns null/undefined regardless of the output type. + * @param input value to convert + * @param outputType type to output + */ +export function toType(input: null, outputType: T): null +export function toType(input: undefined, outputType: T): undefined +export function toType( + input: ToBufferInputTypes, + outputType: T +): TypeOutputReturnType[T] +export function toType( + input: ToBufferInputTypes, + outputType: T +): TypeOutputReturnType[T] | undefined | null { + if (input === null) { + return null + } + if (input === undefined) { + return undefined + } + + if (typeof input === 'string' && !isHexString(input)) { + throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`) + } else if (typeof input === 'number' && !Number.isSafeInteger(input)) { + throw new Error( + 'The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)' + ) + } + + const output = toBuffer(input) + + switch (outputType) { + case TypeOutput.Buffer: + return output as TypeOutputReturnType[T] + case TypeOutput.BigInt: + return bufferToBigInt(output) as TypeOutputReturnType[T] + case TypeOutput.Number: { + const bigInt = bufferToBigInt(output) + if (bigInt > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error( + 'The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)' + ) + } + return Number(bigInt) as TypeOutputReturnType[T] + } + case TypeOutput.PrefixedHexString: + return bufferToHex(output) as TypeOutputReturnType[T] + default: + throw new Error('unknown outputType') + } +} diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/units.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/units.ts new file mode 100644 index 0000000..4ed6f1a --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/units.ts @@ -0,0 +1,2 @@ +/** Easy conversion from Gwei to wei */ +export const GWEI_TO_WEI = BigInt(1000000000) diff --git a/test/merkletreejs/node_modules/@ethereumjs/util/src/withdrawal.ts b/test/merkletreejs/node_modules/@ethereumjs/util/src/withdrawal.ts new file mode 100644 index 0000000..88a9ef5 --- /dev/null +++ b/test/merkletreejs/node_modules/@ethereumjs/util/src/withdrawal.ts @@ -0,0 +1,123 @@ +import { Address } from './address' +import { bigIntToHex } from './bytes' +import { TypeOutput, toType } from './types' + +import type { AddressLike, BigIntLike } from './types' + +/** + * Flexible input data type for EIP-4895 withdrawal data with amount in Gwei to + * match CL representation and for eventual ssz withdrawalsRoot + */ +export type WithdrawalData = { + index: BigIntLike + validatorIndex: BigIntLike + address: AddressLike + amount: BigIntLike +} + +/** + * JSON RPC interface for EIP-4895 withdrawal data with amount in Gwei to + * match CL representation and for eventual ssz withdrawalsRoot + */ +export interface JsonRpcWithdrawal { + index: string // QUANTITY - bigint 8 bytes + validatorIndex: string // QUANTITY - bigint 8 bytes + address: string // DATA, 20 Bytes address to withdraw to + amount: string // QUANTITY - bigint amount in Gwei 8 bytes +} + +export type WithdrawalBuffer = [Buffer, Buffer, Buffer, Buffer] + +/** + * Representation of EIP-4895 withdrawal data + */ +export class Withdrawal { + /** + * This constructor assigns and validates the values. + * Use the static factory methods to assist in creating a Withdrawal object from varying data types. + * Its amount is in Gwei to match CL representation and for eventual ssz withdrawalsRoot + */ + constructor( + public readonly index: bigint, + public readonly validatorIndex: bigint, + public readonly address: Address, + /** + * withdrawal amount in Gwei to match the CL repesentation and eventually ssz withdrawalsRoot + */ + public readonly amount: bigint + ) {} + + public static fromWithdrawalData(withdrawalData: WithdrawalData) { + const { + index: indexData, + validatorIndex: validatorIndexData, + address: addressData, + amount: amountData, + } = withdrawalData + const index = toType(indexData, TypeOutput.BigInt) + const validatorIndex = toType(validatorIndexData, TypeOutput.BigInt) + const address = new Address(toType(addressData, TypeOutput.Buffer)) + const amount = toType(amountData, TypeOutput.BigInt) + + return new Withdrawal(index, validatorIndex, address, amount) + } + + public static fromValuesArray(withdrawalArray: WithdrawalBuffer) { + if (withdrawalArray.length !== 4) { + throw Error(`Invalid withdrawalArray length expected=4 actual=${withdrawalArray.length}`) + } + const [index, validatorIndex, address, amount] = withdrawalArray + return Withdrawal.fromWithdrawalData({ index, validatorIndex, address, amount }) + } + + /** + * Convert a withdrawal to a buffer array + * @param withdrawal the withdrawal to convert + * @returns buffer array of the withdrawal + */ + public static toBufferArray(withdrawal: Withdrawal | WithdrawalData): WithdrawalBuffer { + const { index, validatorIndex, address, amount } = withdrawal + const indexBuffer = + toType(index, TypeOutput.BigInt) === BigInt(0) + ? Buffer.alloc(0) + : toType(index, TypeOutput.Buffer) + const validatorIndexBuffer = + toType(validatorIndex, TypeOutput.BigInt) === BigInt(0) + ? Buffer.alloc(0) + : toType(validatorIndex, TypeOutput.Buffer) + let addressBuffer + if (address instanceof Address) { + addressBuffer = (
address).buf + } else { + addressBuffer = toType(address, TypeOutput.Buffer) + } + const amountBuffer = + toType(amount, TypeOutput.BigInt) === BigInt(0) + ? Buffer.alloc(0) + : toType(amount, TypeOutput.Buffer) + + return [indexBuffer, validatorIndexBuffer, addressBuffer, amountBuffer] + } + + raw() { + return Withdrawal.toBufferArray(this) + } + + toValue() { + return { + index: this.index, + validatorIndex: this.validatorIndex, + address: this.address.buf, + amount: this.amount, + } + } + + toJSON() { + return { + index: bigIntToHex(this.index), + validatorIndex: bigIntToHex(this.validatorIndex), + address: '0x' + this.address.buf.toString('hex'), + amount: bigIntToHex(this.amount), + } + } +} diff --git a/test/merkletreejs/node_modules/@noble/curves/LICENSE b/test/merkletreejs/node_modules/@noble/curves/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/README.md b/test/merkletreejs/node_modules/@noble/curves/README.md new file mode 100644 index 0000000..a5d14f4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/README.md @@ -0,0 +1,971 @@ +# noble-curves + +Audited & minimal JS implementation of elliptic curve cryptography. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: property-based, cross-library and Wycheproof vectors, fuzzing +- ➰ Short Weierstrass, Edwards, Montgomery curves +- ✍️ ECDSA, EdDSA, Schnorr, BLS signature schemes, ECDH key agreement +- 🔖 SUF-CMA and SBS (non-repudiation) for ed25519, ed448 and others +- #️⃣ Hash-to-curve + for encoding or hashing an arbitrary string to an elliptic curve point +- 🧜‍♂️ Poseidon ZK-friendly hash + +Check out [Upgrading](#upgrading) if you've previously used single-feature noble +packages. See [Resources](#resources) for articles and real-world software that uses curves. + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported in all major browsers and stable node.js versions +- All releases are signed with PGP keys +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [curves](https://github.com/paulmillr/noble-curves) + (4kb versions [secp256k1](https://github.com/paulmillr/noble-secp256k1), + [ed25519](https://github.com/paulmillr/noble-ed25519)), + [hashes](https://github.com/paulmillr/noble-hashes) + +## Usage + +> npm install @noble/curves + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for crypto.getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available. + +The library is tree-shaking-friendly and does not expose root entry point as +`@noble/curves`. Instead, you need to import specific primitives. +This is done to ensure small size of your apps. + +The package consists of two parts: + +* [Implementations](#implementations), utilizing one dependency [noble-hashes](https://github.com/paulmillr/noble-hashes), + providing ready-to-use: + - NIST curves secp256r1 / p256, secp384r1 / p384, secp521r1 / p521 + - SECG curve secp256k1 + - ed25519 / curve25519 / x25519 / ristretto255, edwards448 / curve448 / x448 + - pairing-friendly curves bls12-381, bn254 + - [pasta](https://electriccoin.co/blog/the-pasta-curves-for-halo-2-and-beyond/) curves +2. [Abstract](#abstract-api), zero-dependency elliptic curve algorithms + +### Implementations + +#### Generic example for all curves, secp256k1 + +```ts +// Each curve has similar methods +import { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js +// import { secp256k1 } from 'npm:@noble/curves@1.2.0/secp256k1'; // Deno +const priv = secp256k1.utils.randomPrivateKey(); +const pub = secp256k1.getPublicKey(priv); +const msg = new Uint8Array(32).fill(1); +const sig = secp256k1.sign(msg, priv); +const isValid = secp256k1.verify(sig, msg, pub) === true; + +// hex strings are also supported besides Uint8Arrays: +const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236'; +const pub2 = secp256k1.getPublicKey(privHex); +``` + +#### All imports + +```typescript +import { secp256k1, schnorr } from '@noble/curves/secp256k1'; +import { ed25519, ed25519ph, ed25519ctx, x25519, RistrettoPoint } from '@noble/curves/ed25519'; +import { ed448, ed448ph, ed448ctx, x448 } from '@noble/curves/ed448'; +import { p256 } from '@noble/curves/p256'; +import { p384 } from '@noble/curves/p384'; +import { p521 } from '@noble/curves/p521'; +import { pallas, vesta } from '@noble/curves/pasta'; +import { bls12_381 } from '@noble/curves/bls12-381'; +import { bn254 } from '@noble/curves/bn254'; +import { jubjub } from '@noble/curves/jubjub'; +``` + +#### ECDSA public key recovery & ECDH + +```ts +// extraEntropy https://moderncrypto.org/mail-archive/curves/2017/000925.html +const sigImprovedSecurity = secp256k1.sign(msg, priv, { extraEntropy: true }); +sig.recoverPublicKey(msg) === pub; // public key recovery +const someonesPub = secp256k1.getPublicKey(secp256k1.utils.randomPrivateKey()); +const shared = secp256k1.getSharedSecret(priv, someonesPub); // ECDH +``` + +#### Schnorr signatures over secp256k1 (BIP340) + +```ts +import { schnorr } from '@noble/curves/secp256k1'; +const priv = schnorr.utils.randomPrivateKey(); +const pub = schnorr.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = schnorr.sign(msg, priv); +const isValid = schnorr.verify(sig, msg, pub); +``` + +#### ed25519, X25519, ristretto255 + +```ts +import { ed25519 } from '@noble/curves/ed25519'; +const priv = ed25519.utils.randomPrivateKey(); +const pub = ed25519.getPublicKey(priv); +const msg = new TextEncoder().encode('hello'); +const sig = ed25519.sign(msg, priv); +ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215 +ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5 +``` + +Default `verify` behavior follows [ZIP215](https://zips.z.cash/zip-0215) and +[can be used in consensus-critical applications](https://hdevalence.ca/blog/2020-10-04-its-25519am). +It has SUF-CMA (strong unforgeability under chosen message attacks). +`zip215: false` option switches verification criteria to strict +[RFC8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final) +and additionally provides non-repudiation with SBS [(Strongly Binding Signatures)](https://eprint.iacr.org/2020/1244). + +X25519 follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748). +ristretto255 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448). + +```ts +// Variants from RFC8032: with context, prehashed +import { ed25519ctx, ed25519ph } from '@noble/curves/ed25519'; + +// ECDH using curve25519 aka x25519 +import { x25519 } from '@noble/curves/ed25519'; +const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4'; +const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c'; +x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases +x25519.getPublicKey(priv) === x25519.scalarMultBase(priv); +x25519.getPublicKey(x25519.utils.randomPrivateKey()); + +// ed25519 => x25519 conversion +import { edwardsToMontgomeryPub, edwardsToMontgomeryPriv } from '@noble/curves/ed25519'; +edwardsToMontgomeryPub(ed25519.getPublicKey(ed25519.utils.randomPrivateKey())); +edwardsToMontgomeryPriv(ed25519.utils.randomPrivateKey()); + +// hash-to-curve, ristretto255 +import { hashToCurve, encodeToCurve, RistrettoPoint } from '@noble/curves/ed25519'; +const rp = RistrettoPoint.fromHex( + '6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919' +); +RistrettoPoint.hashToCurve('Ristretto is traditionally a short shot of espresso coffee'); +// also has add(), equals(), multiply(), toRawBytes() methods +``` + +#### ed448, X448 + +```ts +import { ed448 } from '@noble/curves/ed448'; +const priv = ed448.utils.randomPrivateKey(); +const pub = ed448.getPublicKey(priv); +const msg = new TextEncoder().encode('whatsup'); +const sig = ed448.sign(msg, priv); +ed448.verify(sig, msg, pub); + +import { ed448ph, ed448ctx, x448, hashToCurve, encodeToCurve } from '@noble/curves/ed448'; +x448.getSharedSecret(priv, pub) === x448.scalarMult(priv, pub); // aliases +x448.getPublicKey(priv) === x448.scalarMultBase(priv); +``` + +Same RFC7748 / RFC8032 are followed. + +#### bls12-381 + +See [abstract/bls](#abstractbls-barreto-lynn-scott-curves). + +#### Accessing a curve's variables + +```ts +import { secp256k1 } from '@noble/curves/secp256k1'; +// Every curve has `CURVE` object that contains its parameters, field, and others +console.log(secp256k1.CURVE.p); // field modulus +console.log(secp256k1.CURVE.n); // curve order +console.log(secp256k1.CURVE.a, secp256k1.CURVE.b); // equation params +console.log(secp256k1.CURVE.Gx, secp256k1.CURVE.Gy); // base point coordinates +``` + +## Abstract API + +Abstract API allows to define custom curves. All arithmetics is done with JS +bigints over finite fields, which is defined from `modular` sub-module. For +scalar multiplication, we use +[precomputed tables with w-ary non-adjacent form (wNAF)](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/). +Precomputes are enabled for weierstrass and edwards BASE points of a curve. You +could precompute any other point (e.g. for ECDH) using `utils.precompute()` +method: check out examples. + +There are following zero-dependency algorithms: + +- [abstract/weierstrass: Short Weierstrass curve](#abstractweierstrass-short-weierstrass-curve) +- [abstract/edwards: Twisted Edwards curve](#abstractedwards-twisted-edwards-curve) +- [abstract/montgomery: Montgomery curve](#abstractmontgomery-montgomery-curve) +- [abstract/bls: Barreto-Lynn-Scott curves](#abstractbls-barreto-lynn-scott-curves) +- [abstract/hash-to-curve: Hashing strings to curve points](#abstracthash-to-curve-hashing-strings-to-curve-points) +- [abstract/poseidon: Poseidon hash](#abstractposeidon-poseidon-hash) +- [abstract/modular: Modular arithmetics utilities](#abstractmodular-modular-arithmetics-utilities) +- [abstract/utils: General utilities](#abstractutils-general-utilities) + +### abstract/weierstrass: Short Weierstrass curve + +```ts +import { weierstrass } from '@noble/curves/abstract/weierstrass'; +import { Field } from '@noble/curves/abstract/modular'; // finite field for mod arithmetics +import { sha256 } from '@noble/hashes/sha256'; // 3rd-party sha256() of type utils.CHash +import { hmac } from '@noble/hashes/hmac'; // 3rd-party hmac() that will accept sha256() +import { concatBytes, randomBytes } from '@noble/hashes/utils'; // 3rd-party utilities +const secq256k1 = weierstrass({ + // secq256k1: cycle of secp256k1 with Fp/N flipped. + // https://personaelabs.org/posts/spartan-ecdsa + // https://zcash.github.io/halo2/background/curves.html#cycles-of-curves + a: 0n, + b: 7n, + Fp: Field(2n ** 256n - 432420386565659656852420866394968145599n), + n: 2n ** 256n - 2n ** 32n - 2n ** 9n - 2n ** 8n - 2n ** 7n - 2n ** 6n - 2n ** 4n - 1n, + Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n, + Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n, + hash: sha256, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(sha256, key, concatBytes(...msgs)), + randomBytes, +}); + +// Replace weierstrass with weierstrassPoints if you don't need ECDSA, hash, hmac, randomBytes +``` + +Short Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass` +expects arguments `a`, `b`, field `Fp`, curve order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +**`k` generation** is done deterministically, following +[RFC6979](https://www.rfc-editor.org/rfc/rfc6979). For this you will need +`hmac` & `hash`, which in our implementations is provided by noble-hashes. If +you're using different hashing library, make sure to wrap it in the following interface: + +```ts +type CHash = { + (message: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create(): any; +}; +``` + +**Weierstrass points:** + +1. Exported as `ProjectivePoint` +2. Represented in projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using + `ProjectivePoint.fromHex` and `ProjectivePoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates + +```ts +// `weierstrassPoints()` returns `CURVE` and `ProjectivePoint` +// `weierstrass()` returns `CurveFn` +type SignOpts = { lowS?: boolean; prehash?: boolean; extraEntropy: boolean | Uint8Array }; +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => SignatureType; + verify: ( + signature: Hex | SignatureType, + msgHash: Hex, + publicKey: Hex, + opts?: { lowS?: boolean; prehash?: boolean } + ) => boolean; + ProjectivePoint: ProjectivePointConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(key: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +// T is usually bigint, but can be something else like complex numbers in BLS curves +interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): bigint; + get y(): bigint; + multiply(scalar: bigint): ProjPointType; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods for 3d XYZ points +interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; +} +``` + +**ECDSA signatures** are represented by `Signature` instances and can be +described by the interface: + +```ts +interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): SignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(): Uint8Array; + toDERHex(): string; +} +type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +``` + +More examples: + +```typescript +// All curves expose same generic interface. +const priv = secq256k1.utils.randomPrivateKey(); +secq256k1.getPublicKey(priv); // Convert private key to public. +const sig = secq256k1.sign(msg, priv); // Sign msg with private key. +secq256k1.verify(sig, msg, priv); // Verify if sig is correct. + +const Point = secq256k1.ProjectivePoint; +const point = Point.BASE; // Elliptic curve Point class and BASE point static var. +point.add(point).equals(point.double()); // add(), equals(), double() methods +point.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var +point.negate(); // Flips point over x/y coordinate. +point.multiply(31415n); // Multiplication of Point by scalar. + +point.assertValidity(); // Checks for being on-curve +point.toAffine(); // Converts to 2d affine xy coordinates + +secq256k1.CURVE.n; +secq256k1.CURVE.p; +secq256k1.CURVE.Fp.mod(); +secq256k1.CURVE.hash(); + +// precomputes +const fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey)); +fast.multiply(privKey); // much faster ECDH now +``` + +### abstract/edwards: Twisted Edwards curve + +```ts +import { twistedEdwards } from '@noble/curves/abstract/edwards'; +import { Field } from '@noble/curves/abstract/modular'; +import { sha512 } from '@noble/hashes/sha512'; +import { randomBytes } from '@noble/hashes/utils'; + +const Fp = Field(2n ** 255n - 19n); +const ed25519 = twistedEdwards({ + a: Fp.create(-1n), + d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p + Fp: Fp, + n: 2n ** 252n + 27742317777372353535851937790883648493n, + h: 8n, + Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n, + Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n, + hash: sha512, + randomBytes, + adjustScalarBytes(bytes) { + // optional; but mandatory in ed25519 + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +} as const); +``` + +Twisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`. You must specify `a`, `d`, field `Fp`, order `n`, cofactor `h` +and coordinates `Gx`, `Gy` of generator point. + +For EdDSA signatures, `hash` param required. `adjustScalarBytes` which instructs how to change private scalars could be specified. + +**Edwards points:** + +1. Exported as `ExtendedPoint` +2. Represented in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z) +3. Use complete exception-free formulas for addition and doubling +4. Can be decoded/encoded from/to Uint8Array / hex strings using `ExtendedPoint.fromHex` and `ExtendedPoint#toRawBytes()` +5. Have `assertValidity()` which checks for being on-curve +6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates +7. Have `isTorsionFree()`, `clearCofactor()` and `isSmallOrder()` utilities to handle torsions + +```ts +// `twistedEdwards()` returns `CurveFn` of following type: +type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, context?: Hex) => Uint8Array; + verify: (sig: SigType, message: Hex, publicKey: Hex, context?: Hex) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: PrivKey) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: PointType; + pointBytes: Uint8Array; + }; + }; +}; + +interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} +``` + +### abstract/montgomery: Montgomery curve + +```typescript +import { montgomery } from '@noble/curves/abstract/montgomery'; +import { Field } from '@noble/curves/abstract/modular'; + +const x25519 = montgomery({ + a: 486662n, + Gu: 9n, + Fp: Field(2n ** 255n - 19n), + montgomeryBits: 255, + nByteLength: 32, + // Optional param + adjustScalarBytes(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + }, +}); +``` + +The module contains methods for x-only ECDH on Curve25519 / Curve448 from RFC7748. +Proper Elliptic Curve Points are not implemented yet. + +You must specify curve params `Fp`, `a`, `Gu` coordinate of u, `montgomeryBits` and `nByteLength`. + +### abstract/bls: Barreto-Lynn-Scott curves + +The module abstracts BLS (Barreto-Lynn-Scott) pairing-friendly elliptic curve construction. +They allow to construct [zk-SNARKs](https://z.cash/technology/zksnarks/) and +use aggregated, batch-verifiable +[threshold signatures](https://medium.com/snigirev.stepan/bls-signatures-better-than-schnorr-5a7fe30ea716), +using Boneh-Lynn-Shacham signature scheme. + +Main methods and properties are: + +- `getPublicKey(privateKey)` +- `sign(message, privateKey)` +- `verify(signature, message, publicKey)` +- `aggregatePublicKeys(publicKeys)` +- `aggregateSignatures(signatures)` +- `G1` and `G2` curves containing `CURVE` and `ProjectivePoint` +- `Signature` property with `fromHex`, `toHex` methods +- `fields` containing `Fp`, `Fp2`, `Fp6`, `Fp12`, `Fr` + +Right now we only implement BLS12-381 (compatible with ETH and others), +but in theory defining BLS12-377, BLS24 should be straightforward. An example: + +```ts +import { bls12_381 as bls } from '@noble/curves/bls12-381'; +const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c'; +const message = '64726e3da8'; +const publicKey = bls.getPublicKey(privateKey); +const signature = bls.sign(message, privateKey); +const isValid = bls.verify(signature, message, publicKey); +console.log({ publicKey, signature, isValid }); + +// Sign 1 msg with 3 keys +const privateKeys = [ + '18f020b98eb798752a50ed0563b079c125b0db5dd0b1060d1c1b47d4a193e1e4', + 'ed69a8c50cf8c9836be3b67c7eeff416612d45ba39a5c099d48fa668bf558c9c', + '16ae669f3be7a2121e17d0c68c05a8f3d6bef21ec0f2315f1d7aec12484e4cf5', +]; +const messages = ['d2', '0d98', '05caf3']; +const publicKeys = privateKeys.map(bls.getPublicKey); +const signatures2 = privateKeys.map((p) => bls.sign(message, p)); +const aggPubKey2 = bls.aggregatePublicKeys(publicKeys); +const aggSignature2 = bls.aggregateSignatures(signatures2); +const isValid2 = bls.verify(aggSignature2, message, aggPubKey2); +console.log({ signatures2, aggSignature2, isValid2 }); + +// Sign 3 msgs with 3 keys +const signatures3 = privateKeys.map((p, i) => bls.sign(messages[i], p)); +const aggSignature3 = bls.aggregateSignatures(signatures3); +const isValid3 = bls.verifyBatch(aggSignature3, messages, publicKeys); +console.log({ publicKeys, signatures3, aggSignature3, isValid3 }); + +// bls.pairing(PointG1, PointG2) // pairings +// bls.G1.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE +// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr + +// hash-to-curve examples can be seen below +``` + +Full types: + +```ts +getPublicKey: (privateKey: PrivKey) => Uint8Array; +sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; +}; +verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType +) => boolean; +verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[] +) => boolean; +aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; +}; +aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; +}; +millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; +pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; +G1: CurvePointsRes & ReturnType>; +G2: CurvePointsRes & ReturnType>; +Signature: SignatureCoder; +params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; +}; +fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; +}; +utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; +}; +``` + +### abstract/hash-to-curve: Hashing strings to curve points + +The module allows to hash arbitrary strings to elliptic curve points. Implements [hash-to-curve v16](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16). + +Every curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security: + +```ts +import { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1'; +import { randomBytes } from '@noble/hashes/utils'; +hashToCurve('0102abcd'); +console.log(hashToCurve(randomBytes())); +console.log(encodeToCurve(randomBytes())); + +import { bls12_381 } from '@noble/curves/bls12-381'; +bls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' }); +bls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' }); +``` + +If you need low-level methods from spec: + +`expand_message_xmd` [(spec)](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1) produces a uniformly random byte string using a cryptographic hash function H that outputs b bits. + +Hash must conform to `CHash` interface (see [weierstrass section](#abstractweierstrass-short-weierstrass-curve)). + +```ts +function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash +): Uint8Array; +function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array; +``` + +`hash_to_field(msg, count, options)` +[(spec)](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3) +hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + +```ts +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand?: 'xmd' | 'xof'; + hash: CHash; +}; + +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +``` + +### abstract/poseidon: Poseidon hash + +Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + +There are many poseidon variants with different constants. +We don't provide them: you should construct them manually. +Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + +```ts +import { poseidon } from '@noble/curves/abstract/poseidon'; + +type PoseidonOpts = { + Fp: Field; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +const instance = poseidon(opts: PoseidonOpts); +``` + +### abstract/modular: Modular arithmetics utilities + +```ts +import * as mod from '@noble/curves/abstract/modular'; +const fp = mod.Field(2n ** 255n - 19n); // Finite field over 2^255-19 +fp.mul(591n, 932n); // multiplication +fp.pow(481n, 11024858120n); // exponentiation +fp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17) +fp.sqrt(21n); // square root + +// Generic non-FP utils are also available +mod.mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10 +mod.invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse +mod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion +``` + +#### Creating private keys from hashes + +Suppose you have `sha256(something)` (e.g. from HMAC) and you want to make a private key from it. +Even though p256 or secp256k1 may have 32-byte private keys, +and sha256 output is also 32-byte, you can't just use it and reduce it modulo `CURVE.n`. + +Doing so will make the result key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/). + +To avoid the bias, we implement FIPS 186 B.4.1, which allows to take arbitrary +byte array and produce valid scalars / private keys with bias being neglible. + +Use [hash-to-curve](#abstracthash-to-curve-hashing-strings-to-curve-points) if you need +hashing to **public keys**; the function in the module instead operates on **private keys**. + +```ts +import { p256 } from '@noble/curves/p256'; +import { sha256 } from '@noble/hashes/sha256'; +import { hkdf } from '@noble/hashes/hkdf'; +const someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2) +const derived = hkdf(sha256, someKey, undefined, 'application', 40); // 40 bytes +const validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n); +``` + +### abstract/utils: General utilities + +```ts +import * as utils from '@noble/curves/abstract/utils'; + +utils.bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.hexToBytes('deadbeef'); +utils.numberToHexUnpadded(123n); +utils.hexToNumber(); + +utils.bytesToNumberBE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])); +utils.numberToBytesBE(123n, 32); +utils.numberToBytesLE(123n, 64); + +utils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef])); +utils.nLength(255n); +utils.equalBytes(Uint8Array.from([0xde]), Uint8Array.from([0xde])); +``` + +## Security + +1. The library has been audited in Feb 2023 by an independent security firm [Trail of Bits](https://www.trailofbits.com): +[PDF](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf). +The audit has been funded by [Ryan Shea](https://www.shea.io). Audit scope was abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass`, and top-level modules `_shortw_utils` and `secp256k1`. See [changes since audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. Even statically typed Rust, a language without GC, [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. + +We consider infrastructure attacks like rogue NPM modules very important; that's why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. If your app uses 500 dependencies, any dep could get hacked and you'll be downloading malware with every `npm install`. Our goal is to minimize this attack vector. As for devDependencies used by the library: + +- `@scure` base, bip32, bip39 (used in tests), micro-bmark (benchmark), micro-should (testing) are developed by us + and follow the same practices such as: minimal library size, auditability, signed releases +- prettier (linter), fast-check (property-based testing), + typescript versions are locked and rarely updated. Every update is checked with `npm-diff`. + The packages are big, which makes it hard to audit their source code thoroughly and fully. +- They are only used if you clone the git repo and want to add some feature to it. End-users won't use them. + +As for key generation, we're deferring to built-in +[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) +which is considered cryptographically secure (CSPRNG). + +## Speed + +Benchmark results on Apple M2 with node v20: + +``` +secp256k1 +init x 68 ops/sec @ 14ms/op +getPublicKey x 6,750 ops/sec @ 148μs/op +sign x 5,206 ops/sec @ 192μs/op +verify x 880 ops/sec @ 1ms/op +getSharedSecret x 536 ops/sec @ 1ms/op +recoverPublicKey x 852 ops/sec @ 1ms/op +schnorr.sign x 685 ops/sec @ 1ms/op +schnorr.verify x 908 ops/sec @ 1ms/op + +p256 +init x 38 ops/sec @ 26ms/op +getPublicKey x 6,530 ops/sec @ 153μs/op +sign x 5,074 ops/sec @ 197μs/op +verify x 626 ops/sec @ 1ms/op + +p384 +init x 17 ops/sec @ 57ms/op +getPublicKey x 2,883 ops/sec @ 346μs/op +sign x 2,358 ops/sec @ 424μs/op +verify x 245 ops/sec @ 4ms/op + +p521 +init x 9 ops/sec @ 109ms/op +getPublicKey x 1,516 ops/sec @ 659μs/op +sign x 1,271 ops/sec @ 786μs/op +verify x 123 ops/sec @ 8ms/op + +ed25519 +init x 54 ops/sec @ 18ms/op +getPublicKey x 10,269 ops/sec @ 97μs/op +sign x 5,110 ops/sec @ 195μs/op +verify x 1,049 ops/sec @ 952μs/op + +ed448 +init x 19 ops/sec @ 51ms/op +getPublicKey x 3,775 ops/sec @ 264μs/op +sign x 1,771 ops/sec @ 564μs/op +verify x 351 ops/sec @ 2ms/op + +ecdh +├─x25519 x 1,466 ops/sec @ 682μs/op +├─secp256k1 x 539 ops/sec @ 1ms/op +├─p256 x 511 ops/sec @ 1ms/op +├─p384 x 199 ops/sec @ 5ms/op +├─p521 x 103 ops/sec @ 9ms/op +└─x448 x 548 ops/sec @ 1ms/op + +bls12-381 +init x 36 ops/sec @ 27ms/op +getPublicKey 1-bit x 973 ops/sec @ 1ms/op +getPublicKey x 970 ops/sec @ 1ms/op +sign x 55 ops/sec @ 17ms/op +verify x 39 ops/sec @ 25ms/op +pairing x 106 ops/sec @ 9ms/op +aggregatePublicKeys/8 x 129 ops/sec @ 7ms/op +aggregatePublicKeys/32 x 34 ops/sec @ 28ms/op +aggregatePublicKeys/128 x 8 ops/sec @ 112ms/op +aggregatePublicKeys/512 x 2 ops/sec @ 446ms/op +aggregatePublicKeys/2048 x 0 ops/sec @ 1778ms/op +aggregateSignatures/8 x 50 ops/sec @ 19ms/op +aggregateSignatures/32 x 13 ops/sec @ 74ms/op +aggregateSignatures/128 x 3 ops/sec @ 296ms/op +aggregateSignatures/512 x 0 ops/sec @ 1180ms/op +aggregateSignatures/2048 x 0 ops/sec @ 4715ms/op + +hash-to-curve +hash_to_field x 91,600 ops/sec @ 10μs/op +secp256k1 x 2,373 ops/sec @ 421μs/op +p256 x 4,310 ops/sec @ 231μs/op +p384 x 1,664 ops/sec @ 600μs/op +p521 x 807 ops/sec @ 1ms/op +ed25519 x 3,088 ops/sec @ 323μs/op +ed448 x 1,247 ops/sec @ 801μs/op +``` + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests + +## Upgrading + +Previously, the library was split into single-feature packages +noble-secp256k1, noble-ed25519 and noble-bls12-381. + +Curves continue their original work. The single-feature packages changed their +direction towards providing minimal 4kb implementations of cryptography, +which means they have less features. + +Upgrading from @noble/secp256k1 2.0 or @noble/ed25519 2.0: no changes, libraries are compatible. + +Upgrading from [@noble/secp256k1](https://github.com/paulmillr/noble-secp256k1) 1.7: + +- `getPublicKey` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getPublicKey(priv, false)` +- `sign` + - is now sync; use `signAsync` for async version + - now returns `Signature` instance with `{ r, s, recovery }` properties + - `canonical` option was renamed to `lowS` + - `recovered` option has been removed because recovery bit is always returned now + - `der` option has been removed. There are 2 options: + 1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`. + Compact encoding is simply a concatenation of 32-byte r and 32-byte s. + 2. If you must use DER encoding, switch to noble-curves (see above). +- `verify` + - `strict` option was renamed to `lowS` +- `getSharedSecret` + - now produce 33-byte compressed signatures by default + - to use old behavior, which produced 65-byte uncompressed keys, set + argument `isCompressed` to `false`: `getSharedSecret(a, b, false)` +- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)` +- `number` type for private keys have been removed: use `bigint` instead +- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz) +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`hmacSha256Sync` and others) + +Upgrading from [@noble/ed25519](https://github.com/paulmillr/noble-ed25519) 1.7: + +- Methods are now sync by default +- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs +- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt) +- `Signature` was removed: just use raw bytes or hex now +- `utils` were split into `utils` (same api as in noble-curves) and + `etc` (`sha512Sync` and others) +- `getSharedSecret` was moved to `x25519` module +- `toX25519` has been moved to `edwardsToMontgomeryPub` and `edwardsToMontgomeryPriv` methods + +Upgrading from [@noble/bls12-381](https://github.com/paulmillr/noble-bls12-381): + +- Methods and classes were renamed: + - PointG1 -> G1.Point, PointG2 -> G2.Point + - PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode +- Fp2 ORDER was corrected + +## Resources + +Useful documentation and articles about the library or its primitives: + +- [Learning fast elliptic-curve cryptography](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/) +- [Taming the many EdDSAs](https://csrc.nist.gov/csrc/media/Presentations/2023/crclub-2023-03-08/images-media/20230308-crypto-club-slides--taming-the-many-EdDSAs.pdf) + that describes concepts of Strong UnForgeability under Chosen Message Attacks and Strongly Binding Signatures +- Pairings and BLS + - [BLS signatures for busy people](https://gist.github.com/paulmillr/18b802ad219b1aee34d773d08ec26ca2) + - [BLS12-381 for the rest of us](https://hackmd.io/@benjaminion/bls12-381) + - [Key concepts of pairings](https://medium.com/@alonmuroch_65570/bls-signatures-part-2-key-concepts-of-pairings-27a8a9533d0c) + - Pairing over bls12-381: + [part 1](https://research.nccgroup.com/2020/07/06/pairing-over-bls12-381-part-1-fields/), + [part 2](https://research.nccgroup.com/2020/07/13/pairing-over-bls12-381-part-2-curves/), + [part 3](https://research.nccgroup.com/2020/08/13/pairing-over-bls12-381-part-3-pairing/) + - [Estimating the bit security of pairing-friendly curves](https://research.nccgroup.com/2022/02/03/estimating-the-bit-security-of-pairing-friendly-curves/) + +Online demos: + +- [Elliptic Curve Calculator](https://paulmillr.com/noble): add / multiply points, sign messages +- [BLS threshold signatures](https://genthresh.com) + +Projects using noble-curves: + +- [scure-bip32](https://github.com/paulmillr/scure-bip32) and separate [bip32](https://github.com/bitcoinjs/bip32) HDkey libraries +- Ethereum libraries: + - [ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) + - [@ethereumjs](https://github.com/ethereumjs/ethereumjs-monorepo) + - [micro-eth-signer](https://github.com/paulmillr/micro-eth-signer) + - [ethers](https://github.com/ethers-io/ethers.js) (old noble-secp256k1 for now) + - [viem.sh](https://viem.sh) + - [metamask's eth-sig-util](https://github.com/MetaMask/eth-sig-util) + - [gridplus lattice sdk](https://github.com/GridPlus/lattice-eth2-utils) +- Bitcoin libraries: [scure-btc-signer](https://github.com/paulmillr/scure-btc-signer) +- Solana libraries: [micro-sol-signer](https://github.com/paulmillr/micro-sol-signer), [solana-web3.js](https://github.com/solana-labs/solana-web3.js) +- [polkadot.js](https://github.com/polkadot-js/common), [micro-starknet](https://github.com/paulmillr/micro-starknet) +- [protonmail](https://github.com/ProtonMail/WebClients) (old noble-ed25519 for now) +- [did-jwt](https://github.com/decentralized-identity/did-jwt), [hpke-js](https://github.com/dajiaji/hpke-js), [nostr-tools](https://github.com/nbd-wtf/nostr-tools) +- [ed25519-keygen](https://github.com/paulmillr/ed25519-keygen) SSH, PGP, TOR key generation +- [secp256k1 compatibility layer](https://github.com/ethereum/js-ethereum-cryptography/blob/2.0.0/src/secp256k1-compat.ts) +for users who want to switch from secp256k1-node or tiny-secp256k1. Allows to see which methods map to corresponding noble code. +- [BLS BBS signatures](https://github.com/Wind4Greg/BBS-Draft-Checks) following [draft-irtf-cfrg-bbs-signatures-latest](https://identity.foundation/bbs-signature/draft-irtf-cfrg-bbs-signatures.html) +- [KZG trusted setup ceremony](https://github.com/dsrvlabs/czg-keremony) + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.d.ts b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.d.ts new file mode 100644 index 0000000..3eb43a8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.d.ts @@ -0,0 +1,62 @@ +import { randomBytes } from '@noble/hashes/utils'; +import { CurveType } from './abstract/weierstrass.js'; +import { CHash } from './abstract/utils.js'; +export declare function getHash(hash: CHash): { + hash: CHash; + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array; + randomBytes: typeof randomBytes; +}; +type CurveDef = Readonly>; +export declare function createCurve(curveDef: CurveDef, defHash: CHash): Readonly<{ + create: (hash: CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export {}; +//# sourceMappingURL=_shortw_utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.d.ts.map new file mode 100644 index 0000000..974f8da --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAe,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAG5C,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK;;gBAGnB,UAAU,WAAW,UAAU,EAAE;;EAGhD;AAED,KAAK,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAC3E,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK;mBACtC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE5B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.js b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.js new file mode 100644 index 0000000..555de44 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCurve = exports.getHash = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const hmac_1 = require("@noble/hashes/hmac"); +const utils_1 = require("@noble/hashes/utils"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)), + randomBytes: utils_1.randomBytes, + }; +} +exports.getHash = getHash; +function createCurve(curveDef, defHash) { + const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +exports.createCurve = createCurve; +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.js.map b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.js.map new file mode 100644 index 0000000..318dfda --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAA0C;AAC1C,+CAA+D;AAC/D,8DAAmE;AAGnE,wCAAwC;AACxC,SAAgB,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAA,WAAI,EAAC,IAAI,EAAE,GAAG,EAAE,IAAA,mBAAW,EAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW,EAAX,mBAAW;KACZ,CAAC;AACJ,CAAC;AAND,0BAMC;AAGD,SAAgB,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,IAAA,4BAAW,EAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC;AAHD,kCAGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/bls.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.d.ts new file mode 100644 index 0000000..f6f14ac --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.d.ts @@ -0,0 +1,103 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. + * Implements BLS (Boneh-Lynn-Shacham) signatures. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer). + * Some projects may prefer to swap this relation, it is not supported for now. + */ +import { AffinePoint } from './curve.js'; +import { IField } from './modular.js'; +import { Hex, PrivKey, CHash } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { CurvePointsType, ProjPointType as ProjPointType, CurvePointsRes } from './weierstrass.js'; +type Fp = bigint; +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; +export type CurveType = { + G1: Omit, 'n'> & { + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: IField & { + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: IField; + Fp12: IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + }; + }; + params: { + x: bigint; + r: bigint; + }; + htfDefaults: htf.Opts; + hash: CHash; + randomBytes: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; + }; + verify: (signature: Hex | ProjPointType, message: Hex | ProjPointType, publicKey: Hex | ProjPointType) => boolean; + verifyBatch: (signature: Hex | ProjPointType, messages: (Hex | ProjPointType)[], publicKeys: (Hex | ProjPointType)[]) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; + }; +}; +export declare function bls(CURVE: CurveType): CurveFn; +export {}; +//# sourceMappingURL=bls.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/bls.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.d.ts.map new file mode 100644 index 0000000..75b6d26 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.d.ts","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,MAAM,EAAuB,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAA+B,MAAM,YAAY,CAAC;AAC9E,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,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c,CAAC,GAAG,CAAC,CAAC;IAC/B,MAAM,EAAE;QACN,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,GAAG,CAAC;KACV,CAAC;IACF,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;QACf,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QACjB,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QACjB,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;QACnB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;KACpB,CAAC;IACF,KAAK,EAAE;QACL,gBAAgB,EAAE,MAAM,UAAU,CAAC;QACnC,sBAAsB,EAAE,CAAC,CAAC,EAAE,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC;KACpE,CAAC;CACH,CAAC;AAEF,wBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAChC,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GACnC,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAqR7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/bls.js b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.js new file mode 100644 index 0000000..1c0e956 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls = void 0; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const htf = require("./hash-to-curve.js"); +const weierstrass_js_1 = require("./weierstrass.js"); +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); +function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = (0, utils_js_1.bitLen)(CURVE.params.x); + const groupLen = 32; // TODO: calculate; hardcoded for now + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), + Fp2.mul(Fp2.sqr(Rx), _3n), + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if ((0, utils_js_1.bitGet)(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), + Fp2.neg(t0), + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + function millerLoop(ell, g1) { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if ((0, utils_js_1.bitGet)(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) + f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + const utils = { + randomPrivateKey: () => { + return Fr.toBytes((0, modular_js_1.hashToPrivateScalar)(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + }, + calcPairingPrecomputes, + }; + // Point on G1 curve: (x, y) + const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + function pairingPrecomputes(point) { + const p = point; + if (p._PPRECOMPUTES) + return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + const { Signature } = CURVE.G2; + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve((0, utils_js_1.ensureBytes)('point', point), htfOpts); + } + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, messages, publicKeys, htfOpts) { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +exports.bls = bls; +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/bls.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.js.map new file mode 100644 index 0000000..1ce9b31 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":";;;AAcA,6CAA2D;AAC3D,yCAA8E;AAC9E,0CAA0C;AAC1C,qDAK0B;AAI1B,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AA2FvC,SAAgB,GAAG,CACjB,KAAoC;IAEpC,8EAA8E;IAC9E,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC;IAChD,MAAM,SAAS,GAAG,IAAA,iBAAM,EAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACzC,MAAM,QAAQ,GAAG,EAAE,CAAC,CAAC,qCAAqC;IAE1D,qDAAqD;IACrD,0EAA0E;IAC1E,SAAS,sBAAsB,CAAC,CAAmB;QACjD,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;QACnB,kBAAkB;QAClB,MAAM,EAAE,G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AAC,OAAO,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;SAChC;QAAC,MAAM;YACN,OAAO,KAAK,CAAC;SACd;IACH,CAAC;IAED,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;IAE1C,OAAO;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,WAAW;QACX,mBAAmB;QACnB,mBAAmB;QACnB,UAAU;QACV,OAAO;QACP,EAAE;QACF,EAAE;QACF,SAAS;QACT,MAAM,EAAE;YACN,EAAE;YACF,EAAE;YACF,GAAG;YACH,GAAG;YACH,IAAI;SACL;QACD,MAAM,EAAE;YACN,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC;AAvRD,kBAuRC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/curve.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.d.ts new file mode 100644 index 0000000..9caf29c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.d.ts @@ -0,0 +1,70 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type AffinePoint = { + x: T; + y: T; +} & { + z?: never; + t?: never; +}; +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; +export declare function wNAF>(c: GroupConstructor, bits: number): { + constTimeNegate: (condition: boolean, item: T) => T; + unsafeLadder(elm: T, n: bigint): T; + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[]; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { + p: T; + f: T; + }; + wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { + p: T; + f: T; + }; +}; +export type BasicCurve = { + Fp: IField; + n: bigint; + nBitLength?: number; + nByteLength?: number; + h: bigint; + hEff?: bigint; + Gx: T; + Gy: T; + allowInfinityPoint?: boolean; +}; +export declare function validateBasic(curve: BasicCurve & T): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; +} & BasicCurve & T & { + p: bigint; +}>; +//# sourceMappingURL=curve.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/curve.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.d.ts.map new file mode 100644 index 0000000..fc52e87 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.d.ts","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAA0B,MAAM,cAAc,CAAC;AAK9D,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,GAAG;IAAE,CAAC,CAAC,EAAE,KAAK,CAAC;I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CAAC;IACd,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,CAAC,CAAC;IACN,EAAE,EAAE,CAAC,CAAC;IACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,wBAAgB,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC;;;;;GAqB7D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/curve.js b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.js new file mode 100644 index 0000000..5a005bc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateBasic = exports.wNAF = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +exports.wNAF = wNAF; +function validateBasic(curve) { + (0, modular_js_1.validateField)(curve.Fp); + (0, utils_js_1.validateObject)(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +exports.validateBasic = validateBasic; +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/curve.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.js.map new file mode 100644 index 0000000..dd6ca4b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACt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AAE,CAAS,EAAE,SAAoB;YAC3E,aAAa;YACb,MAAM,CAAC,GAAW,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC;YACtC,yDAAyD;YACzD,IAAI,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YACjC,IAAI,CAAC,IAAI,EAAE;gBACT,IAAI,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAQ,CAAC;gBAC1C,IAAI,CAAC,KAAK,CAAC,EAAE;oBACX,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;iBACxC;aACF;YACD,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC;AA/HD,oBA+HC;AAgBD,SAAgB,aAAa,CAAQ,KAAyB;IAC5D,IAAA,0BAAa,EAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACxB,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,EAAE,EAAE,OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,IAAA,oBAAO,EAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC;AArBD,sCAqBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.d.ts new file mode 100644 index 0000000..9c43c66 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.d.ts @@ -0,0 +1,89 @@ +import * as ut from './utils.js'; +import { FHash, Hex } from './utils.js'; +import { Group, GroupConstructor, BasicCurve, AffinePoint } from './curve.js'; +export type CurveType = BasicCurve & { + a: bigint; + d: bigint; + hash: FHash; + randomBytes: (bytesLength?: number) => Uint8Array; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + uvRatio?: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; + prehash?: FHash; + mapToCurve?: (scalar: bigint[]) => AffinePoint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly d: bigint; + readonly hash: ut.FHash; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + readonly adjustScalarBytes?: ((bytes: Uint8Array) => Uint8Array) | undefined; + readonly domain?: ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array) | undefined; + readonly uvRatio?: ((u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }) | undefined; + readonly prehash?: ut.FHash | undefined; + readonly mapToCurve?: ((scalar: bigint[]) => AffinePoint) | undefined; + readonly p: bigint; +}>; +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { + context?: Hex; + }) => Uint8Array; + verify: (sig: Hex, message: Hex, publicKey: Hex, options?: { + context?: Hex; + zip215: boolean; + }) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; +export declare function twistedEdwards(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=edwards.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.d.ts.map new file mode 100644 index 0000000..a32123f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.d.ts","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAe,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAQ,UAAU,EAAiB,WAAW,EAAE,MAAM,YAAY,CAAC;AAOnG,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,GAAG;IAC3C,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,EAAE,KAAK,CAAC;IACZ,WAAW,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;IAClD,iBAAiB,C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F,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA8Z3D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.js b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.js new file mode 100644 index 0000000..6dd4151 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.js @@ -0,0 +1,429 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.twistedEdwards = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +const modular_js_1 = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +const curve_js_1 = require("./curve.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n, max) { + // n in [1..max-1] + if (inRange(n, max)) + return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + if (!in0MaskRange(ex)) + throw new Error('x required'); + if (!in0MaskRange(ey)) + throw new Error('y required'); + if (!in0MaskRange(ez)) + throw new Error('z required'); + if (!in0MaskRange(et)) + throw new Error('t required'); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) + throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + const { a, d } = CURVE; + if (this.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = (0, utils_js_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } + else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) + assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else + assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = (0, curve_js_1.wNAF)(Point, nByteLength * 8); + function modN(a) { + return (0, modular_js_1.mod)(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = (0, utils_js_1.ensureBytes)('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = (0, utils_js_1.ensureBytes)('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, (0, utils_js_1.ensureBytes)('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return (0, utils_js_1.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = (0, utils_js_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked. + msg = (0, utils_js_1.ensureBytes)('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +exports.twistedEdwards = twistedEdwards; +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.js.map new file mode 100644 index 0000000..73ac6d5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,6CAAmC;AACnC,iCAAiC;AACjC,yCAAqD;AACrD,yCAAmG;AAEnG,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAExC,SAAS,YAAY,CAAC,KAAgB;IACpC,MAAM,IAAI,GAAG,IAAA,wBAAa,EAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,KAAK,EACL;QACE,IAAI,EAAE,UAAU;QAChB,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,WAAW,EAAE,UAAU;KACxB,EACD;QACE,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,UAAU;QACnB,UAAU,EAAE,UAAU;KACvB,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAW,CAAC,CAAC;AAC7C,CAAC;AAmDD,oFAAoF;AACpF,SAAgB,cAAc,CAAC,QAAmB;IAChD,MAAM,KAAK,GAAG,YAAY,CAAC,QAAQ,CAAoC,CAAC;IACxE,MAAM,EACJ,EAAE,EACF,CAAC,EAAE,WAAW,EACd,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,KAAK,EACX,WAAW,EACX,WAAW,EACX,CAAC,EAAE,QAAQ,GACZ,GAAG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;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC;AA9ZD,wCA8ZC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.d.ts new file mode 100644 index 0000000..7f09950 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.d.ts @@ -0,0 +1,57 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { Group, GroupConstructor, AffinePoint } from './curve.js'; +import { IField } from './modular.js'; +import { CHash } from './utils.js'; +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; +export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array; +export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][]; +export declare function isogenyMap>(field: F, map: [T[], T[], T[], T[]]): (x: T, y: T) => { + x: T; + y: T; +}; +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} +export type MapToCurve = (scalar: bigint[]) => AffinePoint; +export type htfBasicOpts = { + DST: UnicodeOrBytes; +}; +export declare function createHasher(Point: H2CPointConstructor, mapToCurve: MapToCurve, def: Opts & { + encodeDST?: UnicodeOrBytes; +}): { + hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint; +}; +export {}; +//# sourceMappingURL=hash-to-curve.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map new file mode 100644 index 0000000..e89ad84 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,KAAK,EAAE,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAO,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAmB,KAAK,EAA4C,MAAM,YAAY,CAAC;AAE9F;;;;;;;GAOG;AACH,KAAK,cAAc,GAAG,MAAM,GAAG,UAAU,CAAC;AAC1C,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,cAAc,CAAC;IACpB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,MAAM,EAAE,KAAK,GAAG,KAAK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AC,CAAC,CAAC,CAAC;CAC7C;AAED,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC;AAIjE,MAAM,MAAM,YAAY,GAAG;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,CAAC;AAEnD,wBAAgB,YAAY,CAAC,CAAC,EAC5B,KAAK,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC7B,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,EACzB,GAAG,EAAE,IAAI,GAAG;IAAE,SAAS,CAAC,EAAE,cAAc,CAAA;CAAE;qBAMvB,UAAU,YAAY,YAAY;uBAUhC,UAAU,YAAY,YAAY;EAOxD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.js b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.js new file mode 100644 index 0000000..418a80c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.js @@ -0,0 +1,175 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0; +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === 'string') + return (0, utils_js_1.utf8ToBytes)(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = utils_js_1.bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1 +function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + if (DST.length > 255) + DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H((0, utils_js_1.concatBytes)(...args)); + } + const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +exports.expand_message_xmd = expand_message_xmd; +function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +exports.expand_message_xof = expand_message_xof; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +function hash_to_field(msg, count, options) { + (0, utils_js_1.validateObject)(options, { + DST: 'string', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = (0, modular_js_1.mod)(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +exports.hash_to_field = hash_to_field; +function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +exports.isogenyMap = isogenyMap; +function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +exports.createHasher = createHasher; +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..c2fa8bd --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":";;;AAEA,6CAA2C;AAC3C,yCAA8F;AAoB9F,SAAS,WAAW,CAAC,GAAmB;IACtC,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,IAAI,OAAO,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AAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC9C,MAAM,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC9C,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,aAAa,EAAE,CAAC;YACrC,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;QAED,mFAAmF;QACnF,aAAa,CAAC,GAAe,EAAE,OAAsB;YACnD,MAAM,CAAC,GAAG,aAAa,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,SAAS,EAAE,GAAG,OAAO,EAAU,CAAC,CAAC;YACpF,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAC7D,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC;AA1BD,oCA0BC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/modular.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.d.ts new file mode 100644 index 0000000..3acaa1e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.d.ts @@ -0,0 +1,83 @@ +export declare function mod(a: bigint, b: bigint): bigint; +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +export declare function pow(num: bigint, power: bigint, modulo: bigint): bigint; +export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint; +export declare function invert(number: bigint, modulo: bigint): bigint; +export declare function tonelliShanks(P: bigint): (Fp: IField, n: T) => T; +export declare function FpSqrt(P: bigint): (Fp: IField, n: T) => T; +export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean; +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + isOdd?(num: T): boolean; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + cmov(a: T, b: T, c: boolean): T; +} +export declare function validateField(field: IField): IField; +export declare function FpPow(f: IField, num: T, power: bigint): T; +export declare function FpInvertBatch(f: IField, nums: T[]): T[]; +export declare function FpDiv(f: IField, lhs: T, rhs: T | bigint): T; +export declare function FpIsSquare(f: IField): (x: T) => boolean; +export declare function nLength(n: bigint, nBitLength?: number): { + nBitLength: number; + nByteLength: number; +}; +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export declare function Field(ORDER: bigint, bitLen?: number, isLE?: boolean, redef?: Partial>): Readonly; +export declare function FpSqrtOdd(Fp: IField, elm: T): T; +export declare function FpSqrtEven(Fp: IField, elm: T): T; +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export declare function hashToPrivateScalar(hash: string | Uint8Array, groupOrder: bigint, isLE?: boolean): bigint; +export {}; +//# sourceMappingURL=modular.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/modular.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.d.ts.map new file mode 100644 index 0000000..49b9d75 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"AAmBA,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAGhD;AACD;;;;;GAKG;AAEH,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAUtE;AAGD,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAOrE;AAGD,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAsB7D;AAKD,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,iCAsDtC;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,MAAM,iCA2D/B;AAGD,eAAO,MAAM,YAAY,QAAS,MAAM,UAAU,MAAM,YAAqC,CAAC;AAG9F,MAAM,W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,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM;;;EAKrD;AAED,KAAK,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACxE;;;;;;;;;;;GAWG;AACH,wBAAgB,KAAK,CACnB,KAAK,EAAE,MAAM,EACb,MAAM,CAAC,EAAE,MAAM,EACf,IAAI,UAAQ,EACZ,KAAK,GAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAM,GAClC,QAAQ,CAAC,OAAO,CAAC,CAkDnB;AAED,wBAAgB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIjD;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAIlD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,UAAQ,GACX,MAAM,CAQR"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/modular.js b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.js new file mode 100644 index 0000000..2f338e5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.js @@ -0,0 +1,381 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +const utils_js_1 = require("./utils.js"); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +exports.mod = mod; +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +exports.pow = pow; +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +exports.pow2 = pow2; +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +exports.invert = invert; +// Tonelli-Shanks algorithm +// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12) +// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +exports.tonelliShanks = tonelliShanks; +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +exports.FpSqrt = FpSqrt; +// Little-endian check for first LE bit (last BE bit); +const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +exports.isNegativeLE = isNegativeLE; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return (0, utils_js_1.validateObject)(field, opts); +} +exports.validateField = validateField; +// Generic field functions +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +exports.FpPow = FpPow; +// 0 is non-invertible: non-batched version will throw on 0 +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +exports.FpInvertBatch = FpInvertBatch; +function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +exports.FpDiv = FpDiv; +// This function returns True whenever the value x is a square in the field F. +function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +exports.FpIsSquare = FpIsSquare; +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +exports.nLength = nLength; +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: (0, utils_js_1.bitMask)(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes); + }, + }); + return Object.freeze(f); +} +exports.Field = Field; +function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +exports.FpSqrtOdd = FpSqrtOdd; +function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +exports.FpSqrtEven = FpSqrtEven; +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = (0, utils_js_1.ensureBytes)('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash); + return mod(num, groupOrder - _1n) + _1n; +} +exports.hashToPrivateScalar = hashToPrivateScalar; +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/modular.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.js.map new file mode 100644 index 0000000..9938a17 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,sDAAsD;AACtD,yCAQoB;AACpB,kBAAkB;AAClB,MAAM,GAAG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AAI,CAAC,GAAG,CAAC,CAAC;IAC1B,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC;AAJD,gCAIC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,mBAAmB,CACjC,IAAyB,EACzB,UAAkB,EAClB,IAAI,GAAG,KAAK;IAEZ,IAAI,GAAG,IAAA,sBAAW,EAAC,aAAa,EAAE,IAAI,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC;IACnD,IAAI,MAAM,GAAG,EAAE,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,GAAG,IAAI;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,MAAM,6BAA6B,OAAO,EAAE,CAAC,CAAC;IACjG,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAA,0BAAe,EAAC,IAAI,CAAC,CAAC;IACjE,OAAO,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAC1C,CAAC;AAZD,kDAYC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.d.ts new file mode 100644 index 0000000..69e2bc4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.d.ts @@ -0,0 +1,26 @@ +type Hex = string | Uint8Array; +export type CurveType = { + P: bigint; + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { + randomPrivateKey: () => Uint8Array; + }; + GuBytes: Uint8Array; +}; +export declare function montgomery(curveDef: CurveType): CurveFn; +export {}; +//# sourceMappingURL=montgomery.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.d.ts.map new file mode 100644 index 0000000..a0d1c0b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAMA,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/B,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,KAAK,UAAU,CAAC;IAC5E,CAAC,EAAE,MAAM,CAAC;IACV,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD,CAAC;AACF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,UAAU,CAAC;IAChD,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,UAAU,CAAC;IAC5C,eAAe,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IACnE,YAAY,EAAE,CAAC,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,KAAK,EAAE;QAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;KAAE,CAAC;IAC9C,OAAO,EAAE,UAAU,CAAC;CACrB,CAAC;AAuBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CA0IvD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.js b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.js new file mode 100644 index 0000000..b43e43b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.montgomery = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const modular_js_1 = require("./modular.js"); +const utils_js_1 = require("./utils.js"); +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + (0, utils_js_1.validateObject)(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => (0, modular_js_1.mod)(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => (0, modular_js_1.pow)(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // Accepts 0 as well + function assertFieldElement(n) { + if (typeof n === 'bigint' && _0n <= n && n < P) + return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU, scalar) { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return (0, utils_js_1.numberToBytesLE)(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = (0, utils_js_1.ensureBytes)('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) + u[fieldLen - 1] &= 127; // 0b0111_1111 + return (0, utils_js_1.bytesToNumberLE)(u); + } + function decodeScalar(n) { + const bytes = (0, utils_js_1.ensureBytes)('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return (0, utils_js_1.bytesToNumberLE)(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +exports.montgomery = montgomery; +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.js.map new file mode 100644 index 0000000..1aa0c9e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAAwC;AACxC,yCAA2F;AAE3F,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAwBtB,SAAS,YAAY,CAAC,KAAgB;IACpC,IAAA,yBAAc,EACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;KACZ,EACD;QACE,cAAc,EAAE,eAAe;QAC/B,WAAW,EAAE,eAAe;QAC5B,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,UAAU,EAAE,UAAU;QACtB,EAAE,EAAE,QAAQ;KACb,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,EAAW,CAAC,CAAC;AAC9C,CAAC;AAED,4IAA4I;AAC5I,0CAA0C;AAC1C,SAAgB,UAAU,CAAC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AAE,OAAO,CAAC,CAAC;QAC7C,kCAAkC;QAClC,sCAAsC;QACtC,IAAI,EAAE,KAAK,GAAG;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAC1E,OAAO,iBAAiB,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;IACD,kFAAkF;IAClF,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,SAAS,cAAc,CAAC,MAAW;QACjC,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,OAAO;QACL,UAAU;QACV,cAAc;QACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC;AA1ID,gCA0IC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.d.ts new file mode 100644 index 0000000..2f9ab81 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.d.ts @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { IField } from './modular.js'; +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + mds: bigint[][]; + roundConstants: bigint[][]; +}; +export declare function validateOpts(opts: PoseidonOpts): Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number | undefined; + reversePartialPowIdx?: boolean | undefined; +}>; +export declare function splitConstants(rc: bigint[], t: number): bigint[][]; +export declare function poseidon(opts: PoseidonOpts): { + (values: bigint[]): bigint[]; + roundConstants: bigint[][]; +}; +//# sourceMappingURL=poseidon.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.d.ts.map new file mode 100644 index 0000000..7107b83 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,MAAM,EAAwB,MAAM,cAAc,CAAC;AAG5D,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY;;gBAgB5B,MAAM;;;;;;;;;GAgCxB;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,cAarD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY;aAeU,MAAM,EAAE;;EAsB5D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.js b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.js new file mode 100644 index 0000000..fc66916 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.poseidon = exports.splitConstants = exports.validateOpts = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +const modular_js_1 = require("./modular.js"); +function validateOpts(opts) { + const { Fp } = opts; + (0, modular_js_1.validateField)(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`); + // Default is 5, but by some reasons stark uses 3 + let sboxPower = opts.sboxPower; + if (sboxPower === undefined) + sboxPower = 5; + if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => (0, modular_js_1.FpPow)(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + if (opts.roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`); + const rounds = opts.roundsFull + opts.roundsPartial; + if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = opts.roundConstants.map((rc) => { + if (!Array.isArray(rc) || rc.length !== opts.t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + // MDS is TxT matrix + if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t) + throw new Error('Poseidon: wrong MDS matrix'); + const mds = opts.mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds }); +} +exports.validateOpts = validateOpts; +function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +exports.splitConstants = splitConstants; +function poseidon(opts) { + const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts); + const halfRoundsFull = Math.floor(opts.roundsFull / 2); + const partialIdx = reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = opts.mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < opts.roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = opts.roundConstants; + return poseidonHash; +} +exports.poseidon = poseidon; +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.js.map new file mode 100644 index 0000000..422866d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,sFAAsF;AACtF,6CAA4D;AAc5D,SAAgB,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACpB,IAAA,0BAAa,EAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE;QAC7D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClF;IACD,IAAI,IAAI,CAAC,oBAAoB,KAAK,SAAS,IAAI,OAAO,IAAI,CAAC,oBAAoB,KAAK,SAAS;QAC3F,MAAM,IAAI,KAAK,CAAC,gDAAgD,IAAI,CAAC,oBAAo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,CAAC;QACtB,CAAC,CAAC,CAAC;QACH,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,4BAA4B;QAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5F,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IAClD,OAAO,YAAY,CAAC;AACtB,CAAC;AArCD,4BAqCC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/utils.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.d.ts new file mode 100644 index 0000000..2842612 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.d.ts @@ -0,0 +1,91 @@ +export type Hex = Uint8Array | string; +export type PrivKey = Hex | bigint; +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { + dkLen?: number; + }): any; +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function numberToHexUnpadded(num: number | bigint): string; +export declare function hexToNumber(hex: string): bigint; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare function bytesToNumberBE(bytes: Uint8Array): bigint; +export declare function bytesToNumberLE(bytes: Uint8Array): bigint; +export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array; +export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array; +export declare function numberToVarBytesBE(n: number | bigint): Uint8Array; +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare function equalBytes(b1: Uint8Array, b2: Uint8Array): boolean; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export declare function bitLen(n: bigint): number; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export declare function bitGet(n: bigint, pos: number): bigint; +/** + * Sets single bit at position. + */ +export declare const bitSet: (n: bigint, pos: number, value: boolean) => bigint; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export declare const bitMask: (n: number) => bigint; +type Pred = (v: Uint8Array) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export declare function createHmacDrbg(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred) => T; +declare const validatorFns: { + readonly bigint: (val: any) => boolean; + readonly function: (val: any) => boolean; + readonly boolean: (val: any) => boolean; + readonly string: (val: any) => boolean; + readonly isSafeInteger: (val: any) => boolean; + readonly array: (val: any) => boolean; + readonly field: (val: any, object: any) => any; + readonly hash: (val: any) => boolean; +}; +type Validator = keyof typeof validatorFns; +type ValMap> = { + [K in keyof T]?: Validator; +}; +export declare function validateObject>(object: T, validators: ValMap, optValidators?: ValMap): T; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/utils.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.d.ts.map new file mode 100644 index 0000000..706d651 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,GAAG,GAAG,UAAU,GAAG,MAAM,CAAC;AACtC,MAAM,MAAM,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC;AACnC,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,GAAG,CAAC;CACxC,CAAC;AACF,MAAM,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,KAAK,UAAU,CAAC;AAGjE;;GAEG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,MAAM,MAAO,MAAM,OAAO,MAAM,SAAS,OAAO,WAE5D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,OAAO,MAAO,MAAM,WAAiC,CAAC;AAMnE,KAAK,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,KAAK,CAAC,GAAG,SAAS,CAAC;AAChD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAC9B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,GACjE,CAAC,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CA4C7C;AAID,QAAA,MAAM,YAAY;2BACF,GAAG;6BACD,GAAG;4BACJ,GAAG;2BACJ,GAAG;kCACI,GAAG;0BACX,GAAG;0BACH,GAAG,UAAU,GAAG;yBACjB,GAAG;CACP,CAAC;AACX,KAAK,SAAS,GAAG,MAAM,OAAO,YAAY,CAAC;AAC3C,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS;CAAE,CAAC;AAG5E,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1D,MAAM,EAAE,CAAC,EACT,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,EACrB,aAAa,GAAE,MAAM,CAAC,CAAC,CAAM,KAkB9B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/utils.js b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.js new file mode 100644 index 0000000..60774c4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.js @@ -0,0 +1,287 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +exports.numberToHexUnpadded = numberToHexUnpadded; +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +exports.hexToNumber = hexToNumber; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +exports.bytesToNumberBE = bytesToNumberBE; +function bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +exports.bytesToNumberLE = bytesToNumberLE; +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +exports.numberToBytesBE = numberToBytesBE; +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +exports.numberToBytesLE = numberToBytesLE; +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +exports.numberToVarBytesBE = numberToVarBytesBE; +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +exports.ensureBytes = ensureBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +exports.equalBytes = equalBytes; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +exports.bitLen = bitLen; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +exports.bitGet = bitGet; +/** + * Sets single bit at position. + */ +const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +exports.bitSet = bitSet; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +exports.bitMask = bitMask; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +exports.createHmacDrbg = createHmacDrbg; +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +exports.validateObject = validateObject; +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/utils.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.js.map new file mode 100644 index 0000000..c60d8a8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/abstract/utils.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AAWjE,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EA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AC,CAAC;IAClG,OAAO,MAAM,CAAC;AAChB,CAAC;AArBD,wCAqBC;AACD,sBAAsB;AACtB,uEAAuE;AACvE,gFAAgF;AAChF,4BAA4B;AAC5B,2DAA2D;AAC3D,qEAAqE;AACrE,+DAA+D;AAC/D,4DAA4D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.d.ts b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.d.ts new file mode 100644 index 0000000..53449c5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.d.ts @@ -0,0 +1,240 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey } from './utils.js'; +import { Group, GroupConstructor, BasicCurve, AffinePoint } from './curve.js'; +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; +}; +export type BasicWCurve = BasicCurve & { + a: T; + b: T; + allowedPrivateKeyLengths?: readonly number[]; + wrapPrivateKey?: boolean; + endo?: EndomorphismOpts; + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; +type Entropy = Hex | true; +export type SignOpts = { + lowS?: boolean; + extraEntropy?: Entropy; + prehash?: boolean; +}; +export type VerOpts = { + lowS?: boolean; + prehash?: boolean; +}; +/** + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + */ +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; +} +export type CurvePointsType = BasicWCurve & { + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; +export type CurvePointsRes = { + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +export declare const DER: { + Err: { + new (m?: string): { + name: string; + message: string; + stack?: string | undefined; + }; + }; + _parseInt(data: Uint8Array): { + d: bigint; + l: Uint8Array; + }; + toSig(hex: string | Uint8Array): { + r: bigint; + s: bigint; + }; + hexFromSig(sig: { + r: bigint; + s: bigint; + }): string; +}; +export declare function weierstrassPoints(opts: CurvePointsType): { + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: T; + readonly Gy: T; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: T; + readonly b: T; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: EndomorphismOpts | undefined; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly fromBytes?: ((bytes: Uint8Array) => AffinePoint) | undefined; + readonly toBytes?: ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array) | undefined; + readonly p: bigint; + }>; + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { + r: bigint; + s: bigint; +}; +export type PubKey = Hex | ProjPointType; +export type CurveType = BasicWCurve & { + hash: CHash; + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; +declare function validateOpts(curve: CurveType): Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: mod.IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: EndomorphismOpts | undefined; + readonly isTorsionFree?: ((c: ProjConstructor, point: ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: ProjConstructor, point: ProjPointType) => ProjPointType) | undefined; + readonly hash: ut.CHash; + readonly hmac: HmacFnSync; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; +}>; +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; +export declare function weierstrass(curveDef: CurveType): CurveFn; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export declare function SWUFpSqrtRatio(Fp: mod.IField, Z: T): (u: T, v: T) => { + isValid: boolean; + value: T; +}; +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +export declare function mapToCurveSimpleSWU(Fp: mod.IField, opts: { + A: T; + B: T; + Z: T; +}): (u: T) => { + x: T; + y: T; +}; +//# sourceMappingURL=weierstrass.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.d.ts.map new file mode 100644 index 0000000..ef26890 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.d.ts","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAe,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAQ,UAAU,EAAiB,WAAW,EAAE,MAAM,YAAY,CAAC;AAEnG,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,KAAK,UAAU,CAAC;AAC7E,KAAK,gBAAgB,GAAG;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;CACxF,CAAC;AACF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,GAAG;IAE3C,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE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,EAAE,CAAC,CAAA;CAAE,CAmD7D;AACD;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EACnC,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EACjB,IAAI,EAAE;IACJ,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,CAAC;CACN,OASU,CAAC;OAAQ,CAAC;OAAK,CAAC;EA8B5B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.js b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.js new file mode 100644 index 0000000..b24bfbf --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.js @@ -0,0 +1,1061 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = exports.DER = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +const mod = require("./modular.js"); +const ut = require("./utils.js"); +const utils_js_1 = require("./utils.js"); +const curve_js_1 = require("./curve.js"); +function validatePointOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +exports.DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = exports.DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = exports.DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = exports.DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = exports.DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((c, point, isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + // Zero is valid point too! + if (this.is0()) { + if (CURVE.allowInfinityPoint) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +exports.weierstrassPoints = weierstrassPoints; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return exports.DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: () => { + const rand = CURVE.randomBytes(Fp.BYTES + 8); + const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); + return ut.numberToBytesBE(num, CURVE.nByteLength); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + if (prehash) + msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof exports.DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +exports.weierstrass = weierstrass; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +exports.SWUFpSqrtRatio = SWUFpSqrtRatio; +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.js.map b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.js.map new file mode 100644 index 0000000..56663a3 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,4DAA4D;AAC5D,oCAAoC;AACpC,iCAAiC;AACjC,yCAA8D;AAC9D,yCAAmG;AAqFnG,SAAS,iBAAiB,CAAI,KAAyB;IACrD,MAAM,IAAI,GAAG,IAAA,wBAAa,EAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,IAAI,EACJ;QACE,CAAC,EAAE,OAAO;QACV,CAAC,EAAE,OAAO;KACX,EACD;QACE,wBAAwB,EAAE,OAAO;QACjC,cAAc,EAAE,SAAS;QACzB,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,UAAU;QACzB,kBAAkB,EAAE,SAAS;QAC7B,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;IAC7B,IAAI,IAAI,EAA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AC5C,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,iDAAiD;QACjG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,qCAAqC;QACzD,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,mBAAmB;QACzC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,wCAAwC;QACtE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,uCAAuC;QACvE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;QACzE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AA7CD,kDA6CC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bls12-381.d.ts b/test/merkletreejs/node_modules/@noble/curves/bls12-381.d.ts new file mode 100644 index 0000000..0e71114 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bls12-381.d.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +declare const Fp: Readonly & Required, "isOdd">>>; +type Fp = bigint; +type BigintTuple = [bigint, bigint]; +type Fp2 = { + c0: bigint; + c1: bigint; +}; +type Fp2Utils = { + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { + re: bigint; + im: bigint; + }; + mulByNonresidue: (num: Fp2) => Fp2; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; +}; +declare const Fp2: mod.IField & Fp2Utils; +type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +type Fp6 = { + c0: Fp2; + c1: Fp2; + c2: Fp2; +}; +type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + multiplyBy1(num: Fp6, b1: Fp2): Fp6; + multiplyBy01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + multiplyByFp2(lhs: Fp6, rhs: Fp2): Fp6; +}; +declare const Fp6: mod.IField & Fp6Utils; +type Fp12 = { + c0: Fp6; + c1: Fp6; +}; +type BigintTwelve = [ + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint +]; +type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + multiplyByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; +declare const Fp12: mod.IField & Fp12Utils; +export declare const bls12_381: CurveFn; +export {}; +//# sourceMappingURL=bls12-381.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bls12-381.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/bls12-381.d.ts.map new file mode 100644 index 0000000..b724df1 --- /dev/null +++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AAI,CAAC;IACzC,SAAS,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IAC3B,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C,CAAC;AAEF,QAAA,MAAM,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,SA6I9B,CAAC;AAmWF,eAAO,MAAM,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CA2ShD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bls12-381.js b/test/merkletreejs/node_modules/@noble/curves/bls12-381.js new file mode 100644 index 0000000..c825e0e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bls12-381.js @@ -0,0 +1,1176 @@ +"use strict"; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bls12_381 = void 0; +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const bls_js_1 = require("./abstract/bls.js"); +const mod = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +// Types +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'); +const Fp = mod.Field(Fp_raw); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; +const Fp2 = { + ORDER: FP2_ORDER, + BITS: (0, utils_js_1.bitLen)(FP2_ORDER), + BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8), + MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) + return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) + throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) + throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_fp2 in draft-irtf-cfrg-hash-to-curve-16 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), +].map((item) => Fp.create(item)); +// For Fp2 roots of unity. +const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +const Fp6 = { + ORDER: Fp2.ORDER, + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = (0, utils_js_1.bitLen)(BLS_X); +const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +const Fp12 = { + ORDER: Fp2.ORDER, + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if ((0, utils_js_1.bitGet)(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], + [ + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3 +const isogenyMapG2 = (0, hash_to_curve_js_1.isogenyMap)(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x, y) { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c, P) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'); +function psi2(x, y) { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c, P) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256_1.sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes((0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(exports.bls12_381.G2.ProjectivePoint.ZERO)) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = (0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(z1, len), (0, utils_js_1.numberToBytesBE)(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +exports.bls12_381 = (0, bls_js_1.bls)({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(exports.bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(exports.bls12_381.params.x); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(exports.bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = (0, utils_js_1.bytesToNumberBE)(bytes); + const bflag = (0, utils_js_1.bitGet)(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) + return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(exports.bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = (0, utils_js_1.bitGet)(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) + return exports.bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = (0, utils_js_1.bytesToNumberBE)(bytes.subarray(0, Fp.BYTES)); + const y = (0, utils_js_1.bytesToNumberBE)(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = (0, utils_js_1.bitSet)(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = (0, utils_js_1.bitSet)(num, S_BIT_POS, true); + return (0, utils_js_1.numberToBytesBE)(num, Fp.BYTES); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(exports.bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = exports.bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b, from, to) => (0, utils_js_1.bytesToNumberBE)(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = exports.bls12_381.params.G2b; + const P = Fp.ORDER; + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = (0, utils_js_1.bitSet)(x.c1, C_BIT_POS, flag); + x_1 = (0, utils_js_1.bitSet)(x_1, S_BIT_POS, true); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x_1, len), (0, utils_js_1.numberToBytesBE)(x.c0, len)); + } + else { + if (isZero) + return (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x1, len), (0, utils_js_1.numberToBytesBE)(x0, len), (0, utils_js_1.numberToBytesBE)(y1, len), (0, utils_js_1.numberToBytesBE)(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = (0, utils_js_1.bytesToNumberBE)(hex.slice(0, half)); + const z2 = (0, utils_js_1.bytesToNumberBE)(hex.slice(half)); + // Indicates the infinity point + const bflag1 = (0, utils_js_1.bitGet)(z1, I_BIT_POS); + if (bflag1 === _1n) + return exports.bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), exports.bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = (0, utils_js_1.bitGet)(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = exports.bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return (0, utils_js_1.bytesToHex)(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256_1.sha256, + randomBytes: utils_1.randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bls12-381.js.map b/test/merkletreejs/node_modules/@noble/curves/bls12-381.js.map new file mode 100644 index 0000000..55ecfb5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,uFAAuF;AACvF,gDAAgD;AAChD,kGAAkG;AAClG,+EAA+E;AAC/E,EAAE;AACF,mGAAmG;AACnG,+EAA+E;AAC/E,+FAA+F;AAC/F,+EAA+E;AAC/E,oFAAoF;AACpF,EAAE;AACF,cAAc;AACd,gDAAgD;AAChD,4BAA4B;AAC5B,2FAA2F;AAC3F,mHAAmH;AACnH,0FAA0F;AAC1F,2HAA2H;AAC3H,6CAA6C;AAC7C,EAAE;AACF,eAAe;AACf,+BAA+B;AAC/B,8BAA8B;AAC9B,0DAA0D;AAC1D,4EAA4E;AAC5E,6DAA6D;AAC7D,6DAA6D;AAC7D,iDAA8C;AAC9C,+CAAkD;AAClD,8CAAiD;AACjD,6CAA6C;AAC7C,kDAW6B;AAC7B,QAAQ;AACR,8DAKmC;AACnC,kEAAyD;AAEzD,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAC1F,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAA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;QACR,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,gDAAgD;KAC9D;IACD,WAAW;IACX,IAAI,EAAE,eAAM;IACZ,WAAW,EAAX,mBAAW;CACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bn254.d.ts b/test/merkletreejs/node_modules/@noble/curves/bn254.d.ts new file mode 100644 index 0000000..fd7064a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bn254.d.ts @@ -0,0 +1,8 @@ +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export declare const bn254: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=bn254.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bn254.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/bn254.d.ts.map new file mode 100644 index 0000000..572db18 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bn254.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.d.ts","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bn254.js b/test/merkletreejs/node_modules/@noble/curves/bn254.js new file mode 100644 index 0000000..8b1c4b7 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bn254.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bn254 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +exports.bn254 = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(3), + Fp: (0, modular_js_1.Field)(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/bn254.js.map b/test/merkletreejs/node_modules/@noble/curves/bn254.js.map new file mode 100644 index 0000000..a54fb58 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,8DAAwD;AACxD,yDAA6C;AAC7C,sDAA8C;AAC9C;;;;;GAKG;AACU,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed25519.d.ts b/test/merkletreejs/node_modules/@noble/curves/ed25519.d.ts new file mode 100644 index 0000000..b996bf4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed25519.d.ts @@ -0,0 +1,75 @@ +import { ExtPointType } from './abstract/edwards.js'; +import { Hex } from './abstract/utils.js'; +import { htfBasicOpts } from './abstract/hash-to-curve.js'; +import { AffinePoint } from './abstract/curve.js'; +export declare const ED25519_TORSION_SUBGROUP: string[]; +export declare const ed25519: import("./abstract/edwards.js").CurveFn; +export declare const ed25519ctx: import("./abstract/edwards.js").CurveFn; +export declare const ed25519ph: import("./abstract/edwards.js").CurveFn; +export declare const x25519: import("./abstract/montgomery.js").CurveFn; +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export declare function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array; +export declare const hashToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +type ExtendedPoint = ExtPointType; +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +declare class RistPoint { + private readonly ep; + static BASE: RistPoint; + static ZERO: RistPoint; + constructor(ep: ExtendedPoint); + static fromAffine(ap: AffinePoint): RistPoint; + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint; + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint; + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array; + toHex(): string; + toString(): string; + equals(other: RistPoint): boolean; + add(other: RistPoint): RistPoint; + subtract(other: RistPoint): RistPoint; + multiply(scalar: bigint): RistPoint; + multiplyUnsafe(scalar: bigint): RistPoint; +} +export declare const RistrettoPoint: typeof RistPoint; +export declare const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint; +export {}; +//# sourceMappingURL=ed25519.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed25519.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/ed25519.d.ts.map new file mode 100644 index 0000000..13be7bc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed25519.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAkB,MAAM,uBAAuB,CAAC;AAGrE,OAAO,EAKL,GAAG,EAEJ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAgB,YAAY,E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S,GAAG,SAAS;IAKrC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IAInC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;CAG1C;AACD,eAAO,MAAM,cAAc,kBAIvB,CAAC;AAIL,eAAO,MAAM,oBAAoB,QAAS,UAAU,WAAW,YAAY,cAM1E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed25519.js b/test/merkletreejs/node_modules/@noble/curves/ed25519.js new file mode 100644 index 0000000..c750251 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed25519.js @@ -0,0 +1,436 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hash_to_ristretto255 = exports.RistrettoPoint = exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomeryPriv = exports.edwardsToMontgomery = exports.edwardsToMontgomeryPub = exports.x25519 = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = exports.ED25519_TORSION_SUBGROUP = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const modular_js_1 = require("./abstract/modular.js"); +const utils_js_1 = require("./abstract/utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); +function ed25519_pow_2_252_3(x) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = ((0, modular_js_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = ((0, modular_js_1.pow2)(b4, _1n, P) * x) % P; // x^31 + const b10 = ((0, modular_js_1.pow2)(b5, _5n, P) * b5) % P; + const b20 = ((0, modular_js_1.pow2)(b10, _10n, P) * b10) % P; + const b40 = ((0, modular_js_1.pow2)(b20, _20n, P) * b20) % P; + const b80 = ((0, modular_js_1.pow2)(b40, _40n, P) * b40) % P; + const b160 = ((0, modular_js_1.pow2)(b80, _80n, P) * b80) % P; + const b240 = ((0, modular_js_1.pow2)(b160, _80n, P) * b80) % P; + const b250 = ((0, modular_js_1.pow2)(b240, _10n, P) * b10) % P; + const pow_p_5_8 = ((0, modular_js_1.pow2)(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = (0, modular_js_1.mod)(v * v * v, P); // v³ + const v7 = (0, modular_js_1.mod)(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = (0, modular_js_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = (0, modular_js_1.mod)(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = (0, modular_js_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === (0, modular_js_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === (0, modular_js_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = (0, modular_js_1.mod)(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +exports.ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = (0, modular_js_1.Field)(ED25519_P, undefined, true); +const ed25519Defaults = { + // Param: a + a: BigInt(-1), + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}; +exports.ed25519 = (0, edwards_js_1.twistedEdwards)(ed25519Defaults); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +exports.ed25519ctx = (0, edwards_js_1.twistedEdwards)({ ...ed25519Defaults, domain: ed25519_domain }); +exports.ed25519ph = (0, edwards_js_1.twistedEdwards)({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512_1.sha512, +}); +exports.x25519 = (() => (0, montgomery_js_1.montgomery)({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return (0, modular_js_1.mod)((0, modular_js_1.pow2)(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +exports.edwardsToMontgomeryPriv = edwardsToMontgomeryPriv; +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = (0, modular_js_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => exports.ed25519.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!(0, modular_js_1.isNegativeLE)(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new exports.ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(exports.ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = (0, utils_js_1.ensureBytes)('ristrettoHex', hex, 32); + const { a, d } = exports.ed25519.CURVE; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 32), hex) || (0, modular_js_1.isNegativeLE)(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if ((0, modular_js_1.isNegativeLE)(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || (0, modular_js_1.isNegativeLE)(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new exports.ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = exports.ed25519.CURVE.Fp.ORDER; + const mod = exports.ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if ((0, modular_js_1.isNegativeLE)(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if ((0, modular_js_1.isNegativeLE)(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if ((0, modular_js_1.isNegativeLE)(s, P)) + s = mod(-s); + return (0, utils_js_1.numberToBytesLE)(s, 32); // 11 + } + toHex() { + return (0, utils_js_1.bytesToHex)(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = exports.ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +exports.RistrettoPoint = (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(exports.ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(exports.ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/ +// Appendix B. Hashing to ristretto255 +const hash_to_ristretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? (0, utils_1.utf8ToBytes)(d) : d; + const uniform_bytes = (0, hash_to_curve_js_1.expand_message_xmd)(msg, DST, 64, sha512_1.sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +exports.hash_to_ristretto255 = hash_to_ristretto255; +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed25519.js.map b/test/merkletreejs/node_modules/@noble/curves/ed25519.js.map new file mode 100644 index 0000000..fb5b523 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAA4E;AAC5E,sDAAqE;AACrE,4DAAsD;AACtD,sDAAmF;AACnF,kDAO6B;AAC7B,kEAA6F;AAG7F;;;;;GAKG;AAEH,MAAM,SAAS,GAAG,MAAM,CACtB,+EAA+E,CAChF,CAAC;AACF,iCAAiC;AACjC,MAAM,eAAe,GAAG,MAAM,CAC5B,+EAA+E,CAChF,CAAC;AAEF,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACzE,kBAAkB;AAClB,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEjF,SAAS,mBAAmB,CAAC,CAAS;IACpC,MAAM,CAAC,GAAG,SAAS,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACvB,MAAM,EAAE,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.d.ts b/test/merkletreejs/node_modules/@noble/curves/ed448.d.ts new file mode 100644 index 0000000..c6e8068 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed448.d.ts @@ -0,0 +1,16 @@ +export declare const ed448: import("./abstract/edwards.js").CurveFn; +export declare const ed448ph: import("./abstract/edwards.js").CurveFn; +export declare const x448: import("./abstract/montgomery.js").CurveFn; +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export declare function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array; +export declare const edwardsToMontgomery: typeof edwardsToMontgomeryPub; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=ed448.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed448.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/ed448.d.ts.map new file mode 100644 index 0000000..93b9d92 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed448.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAwHA,eAAO,MAAM,KAAK,yCAA4B,CAAC;AAE/C,eAAO,MAAM,OAAO,yCAAyD,CAAC;AAE9E,eAAO,MAAM,IAAI,4CAeV,CAAC;AAER;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,CAIlF;AACD,eAAO,MAAM,mBAAmB,+BAAyB,CAAC;AA2F1D,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed448.js b/test/merkletreejs/node_modules/@noble/curves/ed448.js new file mode 100644 index 0000000..5d08fc3 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed448.js @@ -0,0 +1,219 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.edwardsToMontgomery = exports.edwardsToMontgomeryPub = exports.x448 = exports.ed448ph = exports.ed448 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha3_1 = require("@noble/hashes/sha3"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const modular_js_1 = require("./abstract/modular.js"); +const montgomery_js_1 = require("./abstract/montgomery.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * * X448 ECDH + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 114 })); +const shake256_64 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + // prettier-ignore + const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b222 = ((0, modular_js_1.pow2)(b220, _2n, P) * b2) % P; + const b223 = ((0, modular_js_1.pow2)(b222, _1n, P) * x) % P; + return ((0, modular_js_1.pow2)(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +const Fp = (0, modular_js_1.Field)(ed448P, 456, true); +const _4n = BigInt(4); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes: utils_1.randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + uvRatio: (u, v) => { + const P = ed448P; + // https://datatracker.ietf.org/doc/html/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = (0, modular_js_1.mod)(u * u * v, P); // u²v + const u3v = (0, modular_js_1.mod)(u2v * u, P); // u³v + const u5v3 = (0, modular_js_1.mod)(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = (0, modular_js_1.mod)(u3v * root, P); + // Verify that root is exists + const x2 = (0, modular_js_1.mod)(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: (0, modular_js_1.mod)(x2 * v, P) === u, value: x }; + }, +}; +exports.ed448 = (0, edwards_js_1.twistedEdwards)(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +exports.ed448ph = (0, edwards_js_1.twistedEdwards)({ ...ED448_DEF, prehash: shake256_64 }); +exports.x448 = (() => (0, montgomery_js_1.montgomery)({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = (0, modular_js_1.pow2)(Pminus3div4, BigInt(2), P); + return (0, modular_js_1.mod)(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes: utils_1.randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +function edwardsToMontgomeryPub(edwardsPub) { + const { y } = exports.ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub; +exports.edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: sha3_1.shake256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/ed448.js.map b/test/merkletreejs/node_modules/@noble/curves/ed448.js.map new file mode 100644 index 0000000..b3956e2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,6CAA8C;AAC9C,+CAA6F;AAC7F,sDAAuD;AACvD,sDAAyD;AACzD,4DAAsD;AACtD,kEAA2D;AAE3D;;;;GAIG;AAEH,MAAM,YAAY,GAAG,IAAA,uBA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iB;IACzD,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,kCAAkC;AAC/F,CAAC;AAED,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EACV,aAAK,CAAC,aAAa,EACnB,CAAC,OAAiB,EAAE,EAAE,CAAC,kCAAkC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EACrE;IACE,GAAG,EAAE,kCAAkC;IACvC,SAAS,EAAE,kCAAkC;IAC7C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAQ;CACf,CACF,CAAC,EAAE,CAAC;AACM,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/_shortw_utils.js b/test/merkletreejs/node_modules/@noble/curves/esm/_shortw_utils.js new file mode 100644 index 0000000..cc93e45 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/_shortw_utils.js @@ -0,0 +1,17 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass } from './abstract/weierstrass.js'; +// connects noble-curves to noble-hashes +export function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +export function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +//# sourceMappingURL=_shortw_utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/_shortw_utils.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/_shortw_utils.js.map new file mode 100644 index 0000000..656ee45 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/_shortw_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["../src/_shortw_utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAa,MAAM,2BAA2B,CAAC;AAGnE,wCAAwC;AACxC,MAAM,UAAU,OAAO,CAAC,IAAW;IACjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW;KACZ,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/bls.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/bls.js new file mode 100644 index 0000000..cbb3721 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/bls.js @@ -0,0 +1,235 @@ +import { hashToPrivateScalar } from './modular.js'; +import { bitLen, bitGet, ensureBytes } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { weierstrassPoints, } from './weierstrass.js'; +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); +export function bls(CURVE) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = bitLen(CURVE.params.x); + const groupLen = 32; // TODO: calculate; hardcoded for now + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), + Fp2.mul(Fp2.sqr(Rx), _3n), + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if (bitGet(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), + Fp2.neg(t0), + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + function millerLoop(ell, g1) { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if (bitGet(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) + f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + const utils = { + randomPrivateKey: () => { + return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + }, + calcPairingPrecomputes, + }; + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + })); + function pairingPrecomputes(point) { + const p = point; + if (p._PPRECOMPUTES) + return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + })); + const { Signature } = CURVE.G2; + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + function normP1(point) { + return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + } + function normP2(point) { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point, htfOpts) { + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve(ensureBytes('point', point), htfOpts); + } + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey) { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + function sign(message, privateKey, htfOpts) { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) + return sigPoint; + return Signature.toRawBytes(sigPoint); + } + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify(signature, message, publicKey, htfOpts) { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + function aggregatePublicKeys(publicKeys) { + if (!publicKeys.length) + throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + function aggregateSignatures(signatures) { + if (!signatures.length) + throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch(signature, messages, publicKeys, htfOpts) { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + if (!messages.length) + throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + } + G1.ProjectivePoint.BASE._setWindowSize(4); + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/bls.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/bls.js.map new file mode 100644 index 0000000..84a65d7 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/bls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.js","sourceRoot":"","sources":["../../src/abstract/bls.ts"],"names":[],"mappings":"AAcA,OAAO,EAAU,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAuB,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9E,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAIL,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAI1B,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AA2FvC,MAAM,UAAU,GAAG,CACjB,KAAoC;IAEpC,8EAA8E;IAC9E,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,M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AE,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;YACnE,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;YAClE,MAAM,GAAG,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;SAChC;QAAC,MAAM;YACN,OAAO,KAAK,CAAC;SACd;IACH,CAAC;IAED,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;IAE1C,OAAO;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,WAAW;QACX,mBAAmB;QACnB,mBAAmB;QACnB,UAAU;QACV,OAAO;QACP,EAAE;QACF,EAAE;QACF,SAAS;QACT,MAAM,EAAE;YACN,EAAE;YACF,EAAE;YACF,GAAG;YACH,GAAG;YACH,IAAI;SACL;QACD,MAAM,EAAE;YACN,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAChB;QACD,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/curve.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/curve.js new file mode 100644 index 0000000..3454763 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/curve.js @@ -0,0 +1,156 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { validateField, nLength } from './modular.js'; +import { validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +export function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +export function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/curve.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/curve.js.map new file mode 100644 index 0000000..f0fbc7d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../../src/abstract/curve.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0BAA0B;AAC1B,OAAO,EAAU,aAAa,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBtB,6DAA6D;AAC7D,mGAAmG;AACnG,yDAAyD;AACzD,4DAA4D;AAC5D,+EAA+E;AAC/E,oGAAoG;AACpG,oGAAoG;AACpG,qCAAqC;AACrC,kGAAkG;AAClG,gGAAgG;AAChG,8CAA8C;AAC9C,MAAM,UAAU,IAAI,CAAqB,CAAsB,EAAE,IAAY;IAC3E,MAAM,eAAe,GAAG,CAAC,SAAkB,EAAE,IAAO,EAAK,EAAE;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IAChC,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE;QACzB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC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OAAO;QACX,EAAE,EAAE,OAAO;KACZ,EACD;QACE,UAAU,EAAE,eAAe;QAC3B,WAAW,EAAE,eAAe;KAC7B,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC;QACrC,GAAG,KAAK;QACR,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE;KAChB,CAAC,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/edwards.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/edwards.js new file mode 100644 index 0000000..de5123a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/edwards.js @@ -0,0 +1,425 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { mod } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes } from './utils.js'; +import { wNAF, validateBasic } from './curve.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +export function twistedEdwards(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n, max) { + // n in [1..max-1] + if (inRange(n, max)) + return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + if (!in0MaskRange(ex)) + throw new Error('x required'); + if (!in0MaskRange(ey)) + throw new Error('y required'); + if (!in0MaskRange(ez)) + throw new Error('z required'); + if (!in0MaskRange(et)) + throw new Error('t required'); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) + throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + const { a, d } = CURVE; + if (this.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) + return I; + if (this.equals(I) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } + else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) + assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else + assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(ut.bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/edwards.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/edwards.js.map new file mode 100644 index 0000000..dda68a8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,8DAA8D;AAC9D,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACnC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,WAAW,EAAc,MAAM,YAAY,CAAC;AACrD,OAAO,EAA2B,IAAI,EAAc,aAAa,EAAe,MAAM,YAAY,CAAC;AAEnG,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAezE,8EAA8E;AAC9E,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAExC,SAAS,YAAY,CAAC,KAAgB;IACpC,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAClC,EAAE,CAAC,cAAc,CACf,KAAK,EACL;QACE,IAAI,EAAE,UAAU;QAChB,CAAC,EAAE,QAAQ;QACX,CAAC,EAAE,QAAQ;QACX,WAAW,EAAE,UAAU;KACxB,EACD;QACE,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,UAAU;QACnB,UAAU,EAAE,UAAU;KACvB,CACF,CAAC;IACF,eAAe;IACf,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAW,CAAC,CAAC;AAC7C,CAAC;AAmDD,oFAAoF;AACpF,MAAM,UAAU,cAAc,CAAC,QAAmB;IAChD,MA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AAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IAEF,OAAO;QACL,KAAK;QACL,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,KAAK;KACN,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/hash-to-curve.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/hash-to-curve.js new file mode 100644 index 0000000..a6419f9 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/hash-to-curve.js @@ -0,0 +1,167 @@ +import { mod } from './modular.js'; +import { bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js'; +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === 'string') + return utf8ToBytes(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1 +export function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + if (DST.length > 255) + DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +export function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export function hash_to_field(msg, count, options) { + validateObject(options, { + DST: 'string', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +export function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +export function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..02c9e79 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAS,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAoB9F,SAAS,WAAW,CAAC,GAAmB;IACtC,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC;IACrD,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;AACtD,CAAC;AAED,6FAA6F;AAC7F,MAAM,KAAK,GAAG,eAAe,CAAC;AAE9B,4CAA4C;AAC5C,SAAS,KAAK,CAAC,KAAa,EAAE,MAAc;IAC1C,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,EAAE;QAC3C,MAAM,IAAI,KAAK,CAAC,yBAAyB,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;KACpE;IACD,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,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AAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAC7D,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/modular.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/modular.js new file mode 100644 index 0000000..e26772a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/modular.js @@ -0,0 +1,361 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +export function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +export function pow(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +export function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +// Tonelli-Shanks algorithm +// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12) +// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks +export function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +export function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +export function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +export function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +// 0 is non-invertible: non-batched version will throw on 0 +export function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +export function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +// CURVE.n lengths +export function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +export function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +export function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return mod(num, groupOrder - _1n) + _1n; +} +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/modular.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/modular.js.map new file mode 100644 index 0000000..607c1f2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../../src/abstract/modular.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sDAAsD;AACtD,OAAO,EACL,OAAO,EACP,e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I,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,mBAAmB,CACjC,IAAyB,EACzB,UAAkB,EAClB,IAAI,GAAG,KAAK;IAEZ,IAAI,GAAG,WAAW,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC;IACnD,IAAI,MAAM,GAAG,EAAE,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,GAAG,IAAI;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,MAAM,6BAA6B,OAAO,EAAE,CAAC,CAAC;IACjG,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IACjE,OAAO,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/montgomery.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/montgomery.js new file mode 100644 index 0000000..19a8b6e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/montgomery.js @@ -0,0 +1,157 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // Accepts 0 as well + function assertFieldElement(n) { + if (typeof n === 'bigint' && _0n <= n && n < P) + return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU, scalar) { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) + u[fieldLen - 1] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/montgomery.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/montgomery.js.map new file mode 100644 index 0000000..6bc1a06 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE3F,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAwBtB,SAAS,YAAY,CAAC,KAAgB;IACpC,cAAc,CACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;KACZ,EACD;QACE,cAAc,EAAE,eAAe;QAC/B,WAAW,EAAE,eAAe;QAC5B,iBAAiB,EAAE,UAAU;QAC7B,MAAM,EAAE,UAAU;QAClB,UAAU,EAAE,UAAU;QACtB,EAAE,EAAE,QAAQ;KACb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AC,CAAC,CAAC;QACpC,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,EAAE,GAAG,gBAAgB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC7C,kCAAkC;QAClC,sCAAsC;QACtC,IAAI,EAAE,KAAK,GAAG;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAC1E,OAAO,iBAAiB,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;IACD,kFAAkF;IAClF,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,SAAS,cAAc,CAAC,MAAW;QACjC,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,OAAO;QACL,UAAU;QACV,cAAc;QACd,eAAe,EAAE,CAAC,UAAe,EAAE,SAAc,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC;QACvF,YAAY,EAAE,CAAC,UAAe,EAAc,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC;QACzE,KAAK,EAAE,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,WAAY,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;QACxE,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/poseidon.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/poseidon.js new file mode 100644 index 0000000..7ea744b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/poseidon.js @@ -0,0 +1,110 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { FpPow, validateField } from './modular.js'; +export function validateOpts(opts) { + const { Fp } = opts; + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial']) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`); + // Default is 5, but by some reasons stark uses 3 + let sboxPower = opts.sboxPower; + if (sboxPower === undefined) + sboxPower = 5; + if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + if (opts.roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`); + const rounds = opts.roundsFull + opts.roundsPartial; + if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = opts.roundConstants.map((rc) => { + if (!Array.isArray(rc) || rc.length !== opts.t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + // MDS is TxT matrix + if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t) + throw new Error('Poseidon: wrong MDS matrix'); + const mds = opts.mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds }); +} +export function splitConstants(rc, t) { + if (typeof t !== 'number') + throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +export function poseidon(opts) { + const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts); + const halfRoundsFull = Math.floor(opts.roundsFull / 2); + const partialIdx = reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = opts.mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') + throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < opts.roundsPartial; i++) + values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, round++); + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = opts.roundConstants; + return poseidonHash; +} +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/poseidon.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/poseidon.js.map new file mode 100644 index 0000000..8863ad2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,sFAAsF;AACtF,OAAO,EAAU,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAc5D,MAAM,UAAU,YAAY,CAAC,IAAkB;IAC7C,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACpB,aAAa,CAAC,EAAE,CAAC,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,eAAe,CAAU,EAAE;QAC7D,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClF;IACD,IAAI,IAAI,CAAC,oBAAoB,KAAK,SAAS,IAAI,OAAO,IAAI,CAAC,oBAAoB,KAAK,SAAS;QAC3F,MAAM,IAAI,KAAK,CAAC,gDAAgD,IAAI,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAC/F,iDAAiD;IACjD,IAAI,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IAC/B,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,GAAG,CAAC,CAAC;IAC3C,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC;QACnE,MAAM,IAAI,KAAK,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAE3D,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;IACrC,IAAI,MAAM,G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,KAAK,EAAE,CAAC,CAAC;QAC5F,2BAA2B;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEvF,IAAI,KAAK,KAAK,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,KAAK,WAAW,MAAM,EAAE,CAAC,CAAC;QAC5F,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,4BAA4B;IAC5B,YAAY,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IAClD,OAAO,YAAY,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/utils.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/utils.js new file mode 100644 index 0000000..7839e25 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/utils.js @@ -0,0 +1,265 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +export function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +export function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +export function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +export function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +/** + * Sets single bit at position. + */ +export const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +export function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/utils.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/utils.js.map new file mode 100644 index 0000000..289afb8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/abstract/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,8DAA8D;AAC9D,+EAA+E;AAC/E,uCAAuC;AACvC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AAWjE,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAA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ff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/weierstrass.js b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/weierstrass.js new file mode 100644 index 0000000..3d79ba0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/weierstrass.js @@ -0,0 +1,1054 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes } from './utils.js'; +import { wNAF, validateBasic } from './curve.js'; +function validatePointOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +export const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +export function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((c, point, isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + // Zero is valid point too! + if (this.is0()) { + if (CURVE.allowInfinityPoint) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +export function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: () => { + const rand = CURVE.randomBytes(Fp.BYTES + 8); + const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); + return ut.numberToBytesBE(num, CURVE.nByteLength); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +export function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/abstract/weierstrass.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/weierstrass.js.map new file mode 100644 index 0000000..7d2bc4b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,4DAA4D;AAC5D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CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,4BAA4B;QAC3D,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,oBAAoB;QACxC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/bls12-381.js b/test/merkletreejs/node_modules/@noble/curves/esm/bls12-381.js new file mode 100644 index 0000000..4173044 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/bls12-381.js @@ -0,0 +1,1173 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { concatBytes as concatB, ensureBytes, numberToBytesBE, bytesToNumberBE, bitLen, bitSet, bitGet, bitMask, bytesToHex, } from './abstract/utils.js'; +// Types +import { mapToCurveSimpleSWU, } from './abstract/weierstrass.js'; +import { isogenyMap } from './abstract/hash-to-curve.js'; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'); +const Fp = mod.Field(Fp_raw); +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); +const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; +const Fp2 = { + ORDER: FP2_ORDER, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) + return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) + throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) + throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + }, + // Same as sgn0_fp2 in draft-irtf-cfrg-hash-to-curve-16 + isOdd: (x) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b) { + if (b.length !== Fp2.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple) => { + if (tuple.length !== 2) + throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)); + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power) => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), +].map((item) => Fp.create(item)); +// For Fp2 roots of unity. +const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }, rhs) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +const Fp6 = { + ORDER: Fp2.ORDER, + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp6.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }) => concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t) => { + if (!Array.isArray(t) || t.length !== 6) + throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1) => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0, b1) { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); +const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }, rhs) => { + if (typeof rhs === 'bigint') + return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a, b) { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +const Fp12 = { + ORDER: Fp2.ORDER, + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + // Bytes utils + fromBytes: (b) => { + if (b.length !== Fp12.BYTES) + throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t) => ({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0, o1, o4) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs) => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }), + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }) => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) + z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'), + BigInt('0x0'), + ], + [ + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + ], + [ + BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'), + BigInt('0x0'), + ], + [ + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + ], + [ + BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'), + BigInt('0x0'), + ], + [ + BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'), + BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'), + BigInt('0x0'), + ], + [ + BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'), + BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'), + ], + [ + BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'), + BigInt('0x0'), + ], + [ + BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'), + BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS +// HashToCurve +// 3-isogeny map from E' to E +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3 +const isogenyMapG2 = isogenyMap(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), +}); +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x, y) { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c, P) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'); +function psi2(x, y) { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c, P) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +}); +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits +function signatureG2ToRawBytes(point) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return concatB(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); +} +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381 = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + // todo: unroll + const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P + return u2P.equals(phi); + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(bytes); + const bflag = bitGet(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) + return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) + throw new Error('Invalid compressed G1 point'); + const aflag = bitGet(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) + y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) + return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = bytesToNumberBE(bytes.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } + else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = bitSet(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = bitSet(num, S_BIT_POS, true); + return numberToBytesBE(num, Fp.BYTES); + } + else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } + else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes) => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } + else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } + else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = bitSet(x.c1, C_BIT_POS, flag); + x_1 = bitSet(x_1, S_BIT_POS, true); + return concatB(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + } + else { + if (isZero) + return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len)); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex) { + hex = ensureBytes('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(hex.slice(0, half)); + const z2 = bytesToNumberBE(hex.slice(half)); + // Indicates the infinity point + const bflag1 = bitGet(z1, I_BIT_POS); + if (bflag1 === _1n) + return bls12_381.G2.ProjectivePoint.ZERO; + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) + throw new Error('Failed to find a square root'); + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = bitGet(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) + y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point) { + return signatureG2ToRawBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256, + randomBytes, +}); +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/bls12-381.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/bls12-381.js.map new file mode 100644 index 0000000..09f0c12 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["../src/bls12-381.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,uFAAuF;AACvF,gDAAgD;AAChD,kGAAkG;AAClG,+EAA+E;AAC/E,EAAE;AACF,mGAAmG;AACnG,+EAA+E;AAC/E,+FAA+F;AAC/F,+EAA+E;AAC/E,oFAAoF;AACpF,EAAE;AACF,cAAc;AACd,gDAAgD;AAChD,4BAA4B;AAC5B,2FAA2F;AAC3F,mHAAmH;AACnH,0FAA0F;AAC1F,2HAA2H;AAC3H,6CAA6C;AAC7C,EAAE;AACF,eAAe;AACf,+BAA+B;AAC/B,8BAA8B;AAC9B,0DAA0D;AAC1D,4EAA4E;AAC5E,6DAA6D;AAC7D,6DAA6D;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,GAAG,EAAW,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EACL,WAAW,IAAI,OAAO,EACtB,WAAW,EACX,eAAe,EACf,eAAe,EACf,MAAM,EACN,MAAM,EACN,MAAM,EAEN,OAAO,EACP,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AAqB,CAAC,KAAK,CAAC,CAAC,CAAC;YAClD,CAAC;SACF;KACF;IACD,MAAM,EAAE;QACN,CAAC,EAAE,KAAK;QACR,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,gDAAgD;KAC9D;IACD,WAAW;IACX,IAAI,EAAE,MAAM;IACZ,WAAW;CACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/bn254.js b/test/merkletreejs/node_modules/@noble/curves/esm/bn254.js new file mode 100644 index 0000000..6b4f7c6 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/bn254.js @@ -0,0 +1,22 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import { Field } from './abstract/modular.js'; +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export const bn254 = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp: Field(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/bn254.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/bn254.js.map new file mode 100644 index 0000000..e0ec023 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/bn254.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.js","sourceRoot":"","sources":["../src/bn254.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/ed25519.js b/test/merkletreejs/node_modules/@noble/curves/esm/ed25519.js new file mode 100644 index 0000000..01ee630 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/ed25519.js @@ -0,0 +1,430 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { montgomery } from './abstract/montgomery.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js'; +import { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js'; +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ +const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); +function ed25519_pow_2_252_3(x) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// sqrt(u/v) +function uvRatio(u, v) { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) + x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; +const Fp = Field(ED25519_P, undefined, true); +const ed25519Defaults = { + // Param: a + a: BigInt(-1), + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +}; +export const ed25519 = twistedEdwards(ed25519Defaults); +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +export const ed25519ctx = twistedEdwards({ ...ed25519Defaults, domain: ed25519_domain }); +export const ed25519ph = twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512, +}); +export const x25519 = /* @__PURE__ */ (() => montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv) { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); +// prettier-ignore +function map_to_curve_elligator2_curve25519(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function assertRstPoint(other) { + if (!(other instanceof RistPoint)) + throw new Error('RistrettoPoint expected'); +} +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// Calculates 1/√(number) +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0) { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(ep) { + this.ep = ep; + } + static fromAffine(ap) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex) { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) + throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes() { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) + y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) + s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + // Compare one point to another. + equals(other) { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) + RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) + RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); +// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/ +// Appendix B. Hashing to ristretto255 +export const hash_to_ristretto255 = (msg, options) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/ed25519.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/ed25519.js.map new file mode 100644 index 0000000..5a84c43 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["../src/ed25519.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OA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CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,SAAS,CAAC,IAAI;QAAE,SAAS,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC;AAEL,qEAAqE;AACrE,uCAAuC;AACvC,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAe,EAAE,OAAqB,EAAE,EAAE;IAC7E,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IACtB,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;IAC/C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/ed448.js b/test/merkletreejs/node_modules/@noble/curves/esm/ed448.js new file mode 100644 index 0000000..76b4633 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/ed448.js @@ -0,0 +1,215 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { mod, pow2, Field } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * * X448 ECDH + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + // prettier-ignore + const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +const Fp = Field(ed448P, 456, true); +const _4n = BigInt(4); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + uvRatio: (u, v) => { + const P = ed448P; + // https://datatracker.ietf.org/doc/html/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; + }, +}; +export const ed448 = twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +export const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub) { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +const htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/ed448.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/ed448.js.map new file mode 100644 index 0000000..e877407 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["../src/ed448.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAo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G,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,4BAA4B;IAE3D,MAAM,GAAG,GAAG,EAAE,CAAC,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;IACzD,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,kCAAkC;AAC/F,CAAC;AAED,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,YAAY,CACV,KAAK,CAAC,aAAa,EACnB,CAAC,OAAiB,EAAE,EAAE,CAAC,kCAAkC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EACrE;IACE,GAAG,EAAE,kCAAkC;IACvC,SAAS,EAAE,kCAAkC;IAC7C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,QAAQ;CACf,CACF,CAAC,EAAE,CAAC;AACP,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/index.js b/test/merkletreejs/node_modules/@noble/curves/esm/index.js new file mode 100644 index 0000000..ac4f223 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('Incorrect usage. Import submodules instead'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/index.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/index.js.map new file mode 100644 index 0000000..b5117dc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/jubjub.js b/test/merkletreejs/node_modules/@noble/curves/esm/jubjub.js new file mode 100644 index 0000000..2b1f575 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/jubjub.js @@ -0,0 +1,54 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { blake2s } from '@noble/hashes/blake2s'; +import { Field } from './abstract/modular.js'; +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export const jubjub = twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +}); +const GH_FIRST_BLOCK = utf8ToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag, personalization) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +export function findGroupHash(m, personalization) { + const tag = concatBytes(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } + catch (e) { } + } + throw new Error('findGroupHash tag overflow'); +} +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/jubjub.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/jubjub.js.map new file mode 100644 index 0000000..41ad6bb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["../src/jubjub.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9C;;;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CAAC,CAAa,EAAE,eAA2B;IACtE,MAAM,GAAG,GAAG,WAAW,CAAC,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI;YACF,OAAO,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;SACxC;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/p256.js b/test/merkletreejs/node_modules/@noble/curves/esm/p256.js new file mode 100644 index 0000000..5e2e89e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/p256.js @@ -0,0 +1,42 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha256 } from '@noble/hashes/sha256'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); +export const secp256r1 = p256; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/p256.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/p256.js.map new file mode 100644 index 0000000..1efec39 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["../src/p256.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC/F,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,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WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/p384.js b/test/merkletreejs/node_modules/@noble/curves/esm/p384.js new file mode 100644 index 0000000..21d9308 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/p384.js @@ -0,0 +1,46 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha384 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); +export const secp384r1 = p384; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/p384.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/p384.js.map new file mode 100644 index 0000000..bf8b8ed --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,kBAAkB;AAClB,MAAM,OAAO,GAAG,MAAM,CAAC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,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/p521.js b/test/merkletreejs/node_modules/@noble/curves/esm/p521.js new file mode 100644 index 0000000..0131155 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/p521.js @@ -0,0 +1,53 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha512 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, + b: CURVE.b, + Fp, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); +export const secp521r1 = p521; +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/p521.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/p521.js.map new file mode 100644 index 0000000..cd24eb5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/p521.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.js","sourceRoot":"","sources":["../src/p521.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,0BAA0B;AAC1B,mEAAmE;AACnE,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,uIAAuI,CAAC,CAAC;AAC1J,MAAM,EAAE,GAA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AM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/package.json b/test/merkletreejs/node_modules/@noble/curves/esm/package.json new file mode 100644 index 0000000..267769c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/package.json @@ -0,0 +1,7 @@ +{ + "type": "module", + "browser": { + "crypto": false, + "./crypto": "./esm/crypto.js" + } +} diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/pasta.js b/test/merkletreejs/node_modules/@noble/curves/esm/pasta.js new file mode 100644 index 0000000..fa5ca52 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/pasta.js @@ -0,0 +1,30 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import * as mod from './abstract/modular.js'; +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(p), + n: q, + Gx: mod.mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(q), + n: p, + Gx: mod.mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/pasta.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/pasta.js.map new file mode 100644 index 0000000..4942dd2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["../src/pasta.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAE7C,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAC9F,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,WAAW,CAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAChB,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AACzC,MAAM,CAAC,MAAM,KAAK,GAAG,WAAW,CAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAChB,CAAC,EAAE,CAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,OAAO,CAAC,MAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/secp256k1.js b/test/merkletreejs/node_modules/@noble/curves/esm/secp256k1.js new file mode 100644 index 0000000..eb36ebc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/secp256k1.js @@ -0,0 +1,254 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { createCurve } from './_shortw_utils.js'; +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +export const secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => numberToBytesBE(n, 32); +const modP = (x) => mod(x, secp256k1P); +const modN = (x) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/esm/secp256k1.js.map b/test/merkletreejs/node_modules/@noble/curves/esm/secp256k1.js.map new file mode 100644 index 0000000..692678a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/esm/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["../src/secp256k1.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAA8B,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAE5F,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACjG,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AAE/D;;;GAGG;AACH,SAAS,OAAO,CAAC,CAAS;IACxB,MAAM,CA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,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,MAAM;CACb,CACF,CAAC,EAAE,CAAC;AACP,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/index.d.ts b/test/merkletreejs/node_modules/@noble/curves/index.d.ts new file mode 100644 index 0000000..f36479a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/index.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/index.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/index.js b/test/merkletreejs/node_modules/@noble/curves/index.js new file mode 100644 index 0000000..ac4f223 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('Incorrect usage. Import submodules instead'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/index.js.map b/test/merkletreejs/node_modules/@noble/curves/index.js.map new file mode 100644 index 0000000..292b53a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/jubjub.d.ts b/test/merkletreejs/node_modules/@noble/curves/jubjub.d.ts new file mode 100644 index 0000000..7d2c398 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/jubjub.d.ts @@ -0,0 +1,9 @@ +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +export declare const jubjub: import("./abstract/edwards.js").CurveFn; +export declare function groupHash(tag: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +export declare function findGroupHash(m: Uint8Array, personalization: Uint8Array): import("./abstract/edwards.js").ExtPointType; +//# sourceMappingURL=jubjub.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/jubjub.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/jubjub.d.ts.map new file mode 100644 index 0000000..e79099d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/jubjub.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.d.ts","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":"AAOA;;;;GAIG;AAEH,eAAO,MAAM,MAAM,yCAgBR,CAAC;AAOZ,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDAUrE;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,UAAU,gDASvE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/jubjub.js b/test/merkletreejs/node_modules/@noble/curves/jubjub.js new file mode 100644 index 0000000..60c8329 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/jubjub.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.findGroupHash = exports.groupHash = exports.jubjub = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const edwards_js_1 = require("./abstract/edwards.js"); +const blake2s_1 = require("@noble/hashes/blake2s"); +const modular_js_1 = require("./abstract/modular.js"); +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ +exports.jubjub = (0, edwards_js_1.twistedEdwards)({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: (0, modular_js_1.Field)(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512_1.sha512, + randomBytes: utils_1.randomBytes, +}); +const GH_FIRST_BLOCK = (0, utils_1.utf8ToBytes)('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +// Returns point at JubJub curve which is prime order and not zero +function groupHash(tag, personalization) { + const h = blake2s_1.blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = exports.jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(exports.jubjub.CURVE.h); + if (p.equals(exports.jubjub.ExtendedPoint.ZERO)) + throw new Error('Point has small order'); + return p; +} +exports.groupHash = groupHash; +function findGroupHash(m, personalization) { + const tag = (0, utils_1.concatBytes)(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } + catch (e) { } + } + throw new Error('findGroupHash tag overflow'); +} +exports.findGroupHash = findGroupHash; +//# sourceMappingURL=jubjub.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/jubjub.js.map b/test/merkletreejs/node_modules/@noble/curves/jubjub.js.map new file mode 100644 index 0000000..08b1694 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/jubjub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jubjub.js","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAA4E;AAC5E,sDAAuD;AACvD,mDAAgD;AAChD,sDAA8C;AAE9C;;;;GAIG;AAEU,QAAA,MAAM,GAAG,IAAA,2BAAc,EAAC;IACnC,eAAe;IACf,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,oDAAoD;IACpD,sCAAsC;IACtC,EAAE,EAAE,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC;IACvF,4CAA4C;IAC5C,CAAC,EAAE,MAAM,CAAC,mEAAmE,CAAC;IAC9E,WAAW;IACX,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,wCAAwC;IACxC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,IAAI,EAAE,eAAM;IACZ,WAAW,EAAX,mBAAW;CACH,CAAC,CAAC;AAEZ,MAAM,cAAc,GAAG,IAAA,mBAAW,EAChC,kEAAkE,CACnE,CAAC;AAEF,kEAAkE;AAClE,SAAgB,SAAS,CAAC,GAAe,EAAE,eAA2B;IACpE,MAAM,CAAC,GAAG,iBAAO,CAAC,MAAM,CAAC,EAAE,eAAe,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;IACzD,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IACzB,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACd,mEAAmE;IACnE,IAAI,CAAC,GAAG,cAAM,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;IACjD,0DAA0D;IAC1D,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,cAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC/B,IAAI,CAAC,CAAC,MAAM,CAAC,cAAM,CAAC,aAAa,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAClF,OAAO,CAAC,CAAC;AACX,CAAC;AAVD,8BAUC;AAED,SAAgB,aAAa,CAAC,CAAa,EAAE,eAA2B;IACtE,MAAM,GAAG,GAAG,IAAA,mBAAW,EAAC,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI;YACF,OAAO,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;SACxC;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC;AATD,sCASC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p256.d.ts b/test/merkletreejs/node_modules/@noble/curves/p256.d.ts new file mode 100644 index 0000000..cf8c0d6 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p256.d.ts @@ -0,0 +1,105 @@ +export declare const p256: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp256r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p256.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p256.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/p256.d.ts.map new file mode 100644 index 0000000..d16f812 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.d.ts","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p256.js b/test/merkletreejs/node_modules/@noble/curves/p256.js new file mode 100644 index 0000000..1e7e809 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p256.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp256r1 = exports.p256 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha256_1 = require("@noble/hashes/sha256"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp = (0, modular_js_1.Field)(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +exports.p256 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256_1.sha256); +exports.secp256r1 = exports.p256; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p256.js.map b/test/merkletreejs/node_modules/@noble/curves/p256.js.map new file mode 100644 index 0000000..0459df9 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p256.js","sourceRoot":"","sources":["src/p256.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,MAAM,CAAC,oEAAoE,CAAC,CAAC,CAAC;AAC/F,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE7F,kBAAkB;AACL,QAAA,IAAI,GAAG,IAAA,8BAAW,EAAC;IAC9B,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,EAAE;IACF,wDAAwD;IACxD,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,IAAI,EAAE,KAAK;CACH,EAAE,eAAM,CAAC,CAAC;AACP,QAAA,SAAS,GAAG,YAAI,CAAC;AAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,OAAO;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p384.d.ts b/test/merkletreejs/node_modules/@noble/curves/p384.d.ts new file mode 100644 index 0000000..0be4254 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p384.d.ts @@ -0,0 +1,105 @@ +export declare const p384: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp384r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p384.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p384.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/p384.d.ts.map new file mode 100644 index 0000000..547746d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p384.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.d.ts","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p384.js b/test/merkletreejs/node_modules/@noble/curves/p384.js new file mode 100644 index 0000000..d3a472b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p384.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp384r1 = exports.p384 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha512_1 = require("@noble/hashes/sha512"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +exports.p384 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE_A, + b: CURVE_B, + Fp, + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha512_1.sha384); +exports.secp384r1 = exports.p384; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha512_1.sha384, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p384.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p384.js.map b/test/merkletreejs/node_modules/@noble/curves/p384.js.map new file mode 100644 index 0000000..6816f0d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p384.js.map @@ -0,0 +1 @@ +{"version":3,"file":"p384.js","sourceRoot":"","sources":["src/p384.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,yDAAiD;AACjD,iDAA8C;AAC9C,sDAA8C;AAC9C,8DAAgE;AAChE,kEAA2D;AAE3D,0BAA0B;AAC1B,0EAA0E;AAE1E,0CAA0C;AAC1C,kBAAkB;AAClB,MAAM,CAAC,GAAG,MAAM,CAAC,oGAAoG,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,IAAA,kBAAK,EAAC,CAAC,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAA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B,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p521.d.ts b/test/merkletreejs/node_modules/@noble/curves/p521.d.ts new file mode 100644 index 0000000..47cca46 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p521.d.ts @@ -0,0 +1,105 @@ +export declare const p521: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const secp521r1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: import("./abstract/weierstrass.js").ProjPointType) => import("./abstract/weierstrass.js").ProjPointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("./abstract/utils.js").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("./abstract/utils.js").PrivKey, publicB: import("./abstract/utils.js").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("./abstract/utils.js").Hex, privKey: import("./abstract/utils.js").PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: import("./abstract/utils.js").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("./abstract/utils.js").Hex, publicKey: import("./abstract/utils.js").Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("./abstract/weierstrass.js").ProjPointType | undefined) => import("./abstract/weierstrass.js").ProjPointType; + }; +}>; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +//# sourceMappingURL=p521.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p521.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/p521.d.ts.map new file mode 100644 index 0000000..1c3cdaa --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p521.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"p521.d.ts","sourceRoot":"","sources":["src/p521.ts"],"names":[],"mappings":"AAmCA,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWE,CAAC;AACpB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAO,CAAC;AAmB9B,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p521.js b/test/merkletreejs/node_modules/@noble/curves/p521.js new file mode 100644 index 0000000..c1c0e22 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/p521.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.secp521r1 = exports.p521 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const sha512_1 = require("@noble/hashes/sha512"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = (0, modular_js_1.Field)(P); +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +exports.p521 = (0, _shortw_utils_js_1.createCurve)({ + a: CURVE.a, + b: CURVE.b, + Fp, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512_1.sha512); +exports.secp521r1 = exports.p521; +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512_1.sha512, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=p521.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/p521.js.map b/test/merkletreejs/node_modules/@noble/curves/p521.js.map new file mode 100644 index 0000000..f79e5f0 --- /dev/null +++ b/test/merkletreejs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CACnC,IAAA,oCAAmB,EAAC,EAAE,EAAE;IACtB,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC3B,CAAC,CAAC,EAAE,CAAC;AAER,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EAAC,iBAAS,CAAC,eAAe,EAAE,CAAC,OAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;IACjF,GAAG,EAAE,2BAA2B;IAChC,SAAS,EAAE,2BAA2B;IACtC,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CAAC,CAAC,EAAE,CAAC;AACK,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/package.json b/test/merkletreejs/node_modules/@noble/curves/package.json new file mode 100644 index 0000000..8d59a95 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/package.json @@ -0,0 +1,180 @@ +{ + "name": "@noble/curves", + "version": "1.1.0", + "description": "Audited & minimal JS implementation of elliptic curve cryptography", + "files": [ + "abstract", + "esm", + "src", + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map" + ], + "scripts": { + "bench": "cd benchmark; node secp256k1.js; node curves.js; node ecdh.js; node hash-to-curve.js; node modular.js; node bls.js", + "build": "tsc && tsc -p tsconfig.esm.json", + "build:release": "rollup -c rollup.config.js", + "build:clean": "rm *.{js,d.ts,d.ts.map,js.map} esm/*.{js,d.ts,d.ts.map,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/*.js'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/*.js'", + "test": "node test/index.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-curves.git" + }, + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.1" + }, + "devDependencies": { + "fast-check": "3.0.0", + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "main": "index.js", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./abstract/edwards": { + "types": "./abstract/edwards.d.ts", + "import": "./esm/abstract/edwards.js", + "default": "./abstract/edwards.js" + }, + "./abstract/modular": { + "types": "./abstract/modular.d.ts", + "import": "./esm/abstract/modular.js", + "default": "./abstract/modular.js" + }, + "./abstract/montgomery": { + "types": "./abstract/montgomery.d.ts", + "import": "./esm/abstract/montgomery.js", + "default": "./abstract/montgomery.js" + }, + "./abstract/weierstrass": { + "types": "./abstract/weierstrass.d.ts", + "import": "./esm/abstract/weierstrass.js", + "default": "./abstract/weierstrass.js" + }, + "./abstract/bls": { + "types": "./abstract/bls.d.ts", + "import": "./esm/abstract/bls.js", + "default": "./abstract/bls.js" + }, + "./abstract/hash-to-curve": { + "types": "./abstract/hash-to-curve.d.ts", + "import": "./esm/abstract/hash-to-curve.js", + "default": "./abstract/hash-to-curve.js" + }, + "./abstract/curve": { + "types": "./abstract/curve.d.ts", + "import": "./esm/abstract/curve.js", + "default": "./abstract/curve.js" + }, + "./abstract/utils": { + "types": "./abstract/utils.d.ts", + "import": "./esm/abstract/utils.js", + "default": "./abstract/utils.js" + }, + "./abstract/poseidon": { + "types": "./abstract/poseidon.d.ts", + "import": "./esm/abstract/poseidon.js", + "default": "./abstract/poseidon.js" + }, + "./_shortw_utils": { + "types": "./_shortw_utils.d.ts", + "import": "./esm/_shortw_utils.js", + "default": "./_shortw_utils.js" + }, + "./bls12-381": { + "types": "./bls12-381.d.ts", + "import": "./esm/bls12-381.js", + "default": "./bls12-381.js" + }, + "./bn254": { + "types": "./bn254.d.ts", + "import": "./esm/bn254.js", + "default": "./bn254.js" + }, + "./ed25519": { + "types": "./ed25519.d.ts", + "import": "./esm/ed25519.js", + "default": "./ed25519.js" + }, + "./ed448": { + "types": "./ed448.d.ts", + "import": "./esm/ed448.js", + "default": "./ed448.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./jubjub": { + "types": "./jubjub.d.ts", + "import": "./esm/jubjub.js", + "default": "./jubjub.js" + }, + "./p256": { + "types": "./p256.d.ts", + "import": "./esm/p256.js", + "default": "./p256.js" + }, + "./p384": { + "types": "./p384.d.ts", + "import": "./esm/p384.js", + "default": "./p384.js" + }, + "./p521": { + "types": "./p521.d.ts", + "import": "./esm/p521.js", + "default": "./p521.js" + }, + "./pasta": { + "types": "./pasta.d.ts", + "import": "./esm/pasta.js", + "default": "./pasta.js" + }, + "./secp256k1": { + "types": "./secp256k1.d.ts", + "import": "./esm/secp256k1.js", + "default": "./secp256k1.js" + } + }, + "keywords": [ + "elliptic", + "curve", + "cryptography", + "weierstrass", + "montgomery", + "edwards", + "p256", + "p384", + "p521", + "secp256r1", + "secp256k1", + "ed25519", + "ed448", + "x25519", + "ed25519", + "bls12-381", + "bn254", + "pasta", + "bls", + "noble", + "ecc", + "ecdsa", + "eddsa", + "schnorr" + ], + "funding": "https://paulmillr.com/funding/" +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/pasta.d.ts b/test/merkletreejs/node_modules/@noble/curves/pasta.d.ts new file mode 100644 index 0000000..9e1f4ed --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/pasta.d.ts @@ -0,0 +1,5 @@ +export declare const p: bigint; +export declare const q: bigint; +export declare const pallas: import("./abstract/weierstrass.js").CurveFn; +export declare const vesta: import("./abstract/weierstrass.js").CurveFn; +//# sourceMappingURL=pasta.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/pasta.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/pasta.d.ts.map new file mode 100644 index 0000000..d4e6dd5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/pasta.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.d.ts","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,CAAC,QAA+E,CAAC;AAC9F,eAAO,MAAM,CAAC,QAA+E,CAAC;AAG9F,eAAO,MAAM,MAAM,6CASjB,CAAC;AAEH,eAAO,MAAM,KAAK,6CAShB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/pasta.js b/test/merkletreejs/node_modules/@noble/curves/pasta.js new file mode 100644 index 0000000..c3bee21 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/pasta.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.vesta = exports.pallas = exports.q = exports.p = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const mod = require("./abstract/modular.js"); +exports.p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +exports.q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); +// https://neuromancer.sk/std/other/Pallas +exports.pallas = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(exports.p), + n: exports.q, + Gx: mod.mod(BigInt(-1), exports.p), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +// https://neuromancer.sk/std/other/Vesta +exports.vesta = (0, weierstrass_js_1.weierstrass)({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(exports.q), + n: exports.p, + Gx: mod.mod(BigInt(-1), exports.q), + Gy: BigInt(2), + h: BigInt(1), + ...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256), +}); +//# sourceMappingURL=pasta.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/pasta.js.map b/test/merkletreejs/node_modules/@noble/curves/pasta.js.map new file mode 100644 index 0000000..5ea530c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/pasta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pasta.js","sourceRoot":"","sources":["src/pasta.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,8DAAwD;AACxD,yDAA6C;AAC7C,6CAA6C;AAEhC,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AACjF,QAAA,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE9F,0CAA0C;AAC7B,QAAA,MAAM,GAAG,IAAA,4BAAW,EAAC;IAChC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAC,CAAC;IAChB,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC;AACH,yCAAyC;AAC5B,QAAA,KAAK,GAAG,IAAA,4BAAW,EAAC;IAC/B,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAC,CAAC;IAChB,CAAC,EAAE,SAAC;IACJ,EAAE,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,SAAC,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACb,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,GAAG,IAAA,0BAAO,EAAC,eAAM,CAAC;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/secp256k1.d.ts b/test/merkletreejs/node_modules/@noble/curves/secp256k1.d.ts new file mode 100644 index 0000000..b94df77 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/secp256k1.d.ts @@ -0,0 +1,93 @@ +import { mod } from './abstract/modular.js'; +import { ProjPointType as PointType } from './abstract/weierstrass.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, numberToBytesBE } from './abstract/utils.js'; +export declare const secp256k1: Readonly<{ + create: (hash: import("./abstract/utils.js").CHash) => import("./abstract/weierstrass.js").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("./abstract/modular.js").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor, point: PointType) => PointType) | undefined; + readonly hash: import("./abstract/utils.js").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: import("./abstract/weierstrass.js").SignOpts | undefined) => import("./abstract/weierstrass.js").RecoveredSignatureType; + verify: (signature: Hex | { + r: bigint; + s: bigint; + }, msgHash: Hex, publicKey: Hex, opts?: import("./abstract/weierstrass.js").VerOpts | undefined) => boolean; + ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor; + Signature: import("./abstract/weierstrass.js").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: PointType | undefined) => PointType; + }; +}>; +declare function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array; +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +declare function lift_x(x: bigint): PointType; +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +declare function schnorrGetPublicKey(privateKey: Hex): Uint8Array; +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +declare function schnorrSign(message: Hex, privateKey: PrivKey, auxRand?: Hex): Uint8Array; +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +declare function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean; +export declare const schnorr: { + getPublicKey: typeof schnorrGetPublicKey; + sign: typeof schnorrSign; + verify: typeof schnorrVerify; + utils: { + randomPrivateKey: () => Uint8Array; + lift_x: typeof lift_x; + pointToBytes: (point: PointType) => Uint8Array; + numberToBytesBE: typeof numberToBytesBE; + bytesToNumberBE: typeof bytesToNumberBE; + taggedHash: typeof taggedHash; + mod: typeof mod; + }; +}; +export declare const hashToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export declare const encodeToCurve: (msg: Uint8Array, options?: import("./abstract/hash-to-curve.js").htfBasicOpts | undefined) => import("./abstract/hash-to-curve.js").H2CPoint; +export {}; +//# sourceMappingURL=secp256k1.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/secp256k1.d.ts.map b/test/merkletreejs/node_modules/@noble/curves/secp256k1.d.ts.map new file mode 100644 index 0000000..c6ddafc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/secp256k1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":"AAGA,OAAO,EAAS,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,IAAI,SAAS,EAAuB,MAAM,2BAA2B,CAAC;AAC5F,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,eAAe,EAA4B,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAwCjG,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2CrB,CAAC;AASF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAkBD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAS5C;AAQD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAExD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAClB,OAAO,EAAE,GAAG,EACZ,UAAU,EAAE,OAAO,EACnB,OAAO,GAAE,GAAqB,GAC7B,UAAU,CAgBZ;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAiB5E;AAED,eAAO,MAAM,OAAO;;;;;;;8BA5FS,UAAU,MAAM,CAAC;;;;;;CAyGzC,CAAC;AA0DN,eAAO,MAAM,WAAW,uJAA4C,CAAC;AACrE,eAAO,MAAM,aAAa,uJAA8C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/secp256k1.js b/test/merkletreejs/node_modules/@noble/curves/secp256k1.js new file mode 100644 index 0000000..463edcc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/secp256k1.js @@ -0,0 +1,257 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = require("@noble/hashes/sha256"); +const utils_1 = require("@noble/hashes/utils"); +const modular_js_1 = require("./abstract/modular.js"); +const weierstrass_js_1 = require("./abstract/weierstrass.js"); +const utils_js_1 = require("./abstract/utils.js"); +const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js"); +const _shortw_utils_js_1 = require("./_shortw_utils.js"); +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P; + const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P; + const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P; + const root = (0, modular_js_1.pow2)(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = (0, modular_js_1.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n); + let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256_1.sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = (0, utils_js_1.concatBytes)(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32); +const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P); +const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N); +const Point = exports.secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = (0, utils_1.randomBytes)(32)) { + const m = (0, utils_js_1.ensureBytes)('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ (0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN((0, utils_js_1.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = (0, utils_js_1.ensureBytes)('signature', signature, 64); + const m = (0, utils_js_1.ensureBytes)('message', message); + const pub = (0, utils_js_1.ensureBytes)('publicKey', publicKey, 32); + try { + const P = lift_x((0, utils_js_1.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails + const r = (0, utils_js_1.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = (0, utils_js_1.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +exports.schnorr = (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: exports.secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE: utils_js_1.numberToBytesBE, + bytesToNumberBE: utils_js_1.bytesToNumberBE, + taggedHash, + mod: modular_js_1.mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/secp256k1.js.map b/test/merkletreejs/node_modules/@noble/curves/secp256k1.js.map new file mode 100644 index 0000000..4d76de2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,iDAA8C;AAC9C,+CAAkD;AAClD,sDAAyD;AACzD,8DAA4F;AAE5F,kDAAiG;AACjG,kEAAuE;AACvE,yDAAiD;AAEjD,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAChG,MAAM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AC/E,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC;IACjB,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC,CAAC,EAAE,CAAC;AACR,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAChC,IAAA,+BAAY,EACV,iBAAS,CAAC,eAAe,EACzB,CAAC,OAAiB,EAAE,EAAE;IACpB,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACtB,CAAC,EACD;IACE,GAAG,EAAE,gCAAgC;IACrC,SAAS,EAAE,gCAAgC;IAC3C,CAAC,EAAE,EAAE,CAAC,KAAK;IACX,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,GAAG;IACN,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,eAAM;CACb,CACF,CAAC,EAAE,CAAC;AACM,QAAA,WAAW,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;AACxD,QAAA,aAAa,GAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/curves/src/_shortw_utils.ts b/test/merkletreejs/node_modules/@noble/curves/src/_shortw_utils.ts new file mode 100644 index 0000000..3ae5ca4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/_shortw_utils.ts @@ -0,0 +1,20 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { concatBytes, randomBytes } from '@noble/hashes/utils'; +import { weierstrass, CurveType } from './abstract/weierstrass.js'; +import { CHash } from './abstract/utils.js'; + +// connects noble-curves to noble-hashes +export function getHash(hash: CHash) { + return { + hash, + hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)), + randomBytes, + }; +} +// Same API as @noble/hashes, with ability to create curve with custom hash +type CurveDef = Readonly>; +export function createCurve(curveDef: CurveDef, defHash: CHash) { + const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/bls.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/bls.ts new file mode 100644 index 0000000..7e965b2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/bls.ts @@ -0,0 +1,398 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves. + * Implements BLS (Boneh-Lynn-Shacham) signatures. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer). + * Some projects may prefer to swap this relation, it is not supported for now. + */ +import { AffinePoint } from './curve.js'; +import { IField, hashToPrivateScalar } from './modular.js'; +import { Hex, PrivKey, CHash, bitLen, bitGet, ensureBytes } from './utils.js'; +import * as htf from './hash-to-curve.js'; +import { + CurvePointsType, + ProjPointType as ProjPointType, + CurvePointsRes, + weierstrassPoints, +} from './weierstrass.js'; + +type Fp = bigint; // Can be different field? + +// prettier-ignore +const _2n = BigInt(2), _3n = BigInt(3); + +export type SignatureCoder = { + fromHex(hex: Hex): ProjPointType; + toRawBytes(point: ProjPointType): Uint8Array; + toHex(point: ProjPointType): string; +}; + +export type CurveType = { + G1: Omit, 'n'> & { + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + G2: Omit, 'n'> & { + Signature: SignatureCoder; + mapToCurve: htf.MapToCurve; + htfDefaults: htf.Opts; + }; + fields: { + Fp: IField; + Fr: IField; + Fp2: IField & { + reim: (num: Fp2) => { re: bigint; im: bigint }; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; + }; + Fp6: IField; + Fp12: IField & { + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + }; + }; + params: { + x: bigint; + r: bigint; + }; + htfDefaults: htf.Opts; + hash: CHash; // Because we need outputLen for DRBG + randomBytes: (bytesLength?: number) => Uint8Array; +}; + +export type CurveFn = { + getPublicKey: (privateKey: PrivKey) => Uint8Array; + sign: { + (message: Hex, privateKey: PrivKey): Uint8Array; + (message: ProjPointType, privateKey: PrivKey): ProjPointType; + }; + verify: ( + signature: Hex | ProjPointType, + message: Hex | ProjPointType, + publicKey: Hex | ProjPointType + ) => boolean; + verifyBatch: ( + signature: Hex | ProjPointType, + messages: (Hex | ProjPointType)[], + publicKeys: (Hex | ProjPointType)[] + ) => boolean; + aggregatePublicKeys: { + (publicKeys: Hex[]): Uint8Array; + (publicKeys: ProjPointType[]): ProjPointType; + }; + aggregateSignatures: { + (signatures: Hex[]): Uint8Array; + (signatures: ProjPointType[]): ProjPointType; + }; + millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12; + pairing: (P: ProjPointType, Q: ProjPointType, withFinalExponent?: boolean) => Fp12; + G1: CurvePointsRes & ReturnType>; + G2: CurvePointsRes & ReturnType>; + Signature: SignatureCoder; + params: { + x: bigint; + r: bigint; + G1b: bigint; + G2b: Fp2; + }; + fields: { + Fp: IField; + Fp2: IField; + Fp6: IField; + Fp12: IField; + Fr: IField; + }; + utils: { + randomPrivateKey: () => Uint8Array; + calcPairingPrecomputes: (p: AffinePoint) => [Fp2, Fp2, Fp2][]; + }; +}; + +export function bls( + CURVE: CurveType +): CurveFn { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; + const BLS_X_LEN = bitLen(CURVE.params.x); + const groupLen = 32; // TODO: calculate; hardcoded for now + + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + function calcPairingPrecomputes(p: AffinePoint) { + const { x, y } = p; + // prettier-ignore + const Qx = x, Qy = y, Qz = Fp2.ONE; + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Qz; + let ell_coeff: [Fp2, Fp2, Fp2][] = []; + for (let i = BLS_X_LEN - 2; i >= 0; i--) { + // Double + let t0 = Fp2.sqr(Ry); // Ry² + let t1 = Fp2.sqr(Rz); // Rz² + let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + let t3 = Fp2.mul(t2, _3n); // 3 * T2 + let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + ell_coeff.push([ + Fp2.sub(t2, t0), // T2 - T0 + Fp2.mul(Fp2.sqr(Rx), _3n), // 3 * Rx² + Fp2.neg(t4), // -T4 + ]); + Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2 + Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2² + Rz = Fp2.mul(t0, t4); // T0 * T4 + if (bitGet(CURVE.params.x, i)) { + // Addition + let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + ell_coeff.push([ + Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), // T0 * Qx - T1 * Qy + Fp2.neg(t0), // -T0 + t1, // T1 + ]); + let t2 = Fp2.sqr(t1); // T1² + let t3 = Fp2.mul(t2, t1); // T2 * T1 + let t4 = Fp2.mul(t2, Rx); // T2 * Rx + let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + } + } + return ell_coeff; + } + + function millerLoop(ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]): Fp12 { + const { x } = CURVE.params; + const Px = g1[0]; + const Py = g1[1]; + let f12 = Fp12.ONE; + for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) { + const E = ell[j]; + f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py)); + if (bitGet(x, i)) { + j += 1; + const F = ell[j]; + f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py)); + } + if (i !== 0) f12 = Fp12.sqr(f12); + } + return Fp12.conjugate(f12); + } + + const utils = { + randomPrivateKey: (): Uint8Array => { + return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + }, + calcPairingPrecomputes, + }; + + // Point on G1 curve: (x, y) + const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); + const G1 = Object.assign( + G1_, + htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G1.htfDefaults, + }) + ); + + // Sparse multiplication against precomputed coefficients + // TODO: replace with weakmap? + type withPairingPrecomputes = { _PPRECOMPUTES: [Fp2, Fp2, Fp2][] | undefined }; + function pairingPrecomputes(point: G2): [Fp2, Fp2, Fp2][] { + const p = point as G2 & withPairingPrecomputes; + if (p._PPRECOMPUTES) return p._PPRECOMPUTES; + p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); + return p._PPRECOMPUTES; + } + + // TODO: export + // function clearPairingPrecomputes(point: G2) { + // const p = point as G2 & withPairingPrecomputes; + // p._PPRECOMPUTES = undefined; + // } + + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); + const G2 = Object.assign( + G2_, + htf.createHasher(G2_.ProjectivePoint as htf.H2CPointConstructor, CURVE.G2.mapToCurve, { + ...CURVE.htfDefaults, + ...CURVE.G2.htfDefaults, + }) + ); + + const { Signature } = CURVE.G2; + + // Calculates bilinear pairing + function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 { + if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO)) + throw new Error('pairing is not available for ZERO point'); + Q.assertValidity(); + P.assertValidity(); + // Performance: 9ms for millerLoop and ~14ms for exp. + const Qa = Q.toAffine(); + const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]); + return withFinalExponent ? Fp12.finalExponentiate(looped) : looped; + } + type G1 = typeof G1.ProjectivePoint.BASE; + type G2 = typeof G2.ProjectivePoint.BASE; + + type G1Hex = Hex | G1; + type G2Hex = Hex | G2; + function normP1(point: G1Hex): G1 { + return point instanceof G1.ProjectivePoint ? (point as G1) : G1.ProjectivePoint.fromHex(point); + } + function normP2(point: G2Hex): G2 { + return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + } + function normP2Hash(point: G2Hex, htfOpts?: htf.htfBasicOpts): G2 { + return point instanceof G2.ProjectivePoint + ? point + : (G2.hashToCurve(ensureBytes('point', point), htfOpts) as G2); + } + + // Multiplies generator by private key. + // P = pk x G + function getPublicKey(privateKey: PrivKey): Uint8Array { + return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); + } + + // Executes `hashToCurve` on the message and then multiplies the result by private key. + // S = pk x H(m) + function sign(message: Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array; + function sign(message: G2, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): G2; + function sign(message: G2Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array | G2 { + const msgPoint = normP2Hash(message, htfOpts); + msgPoint.assertValidity(); + const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); + if (message instanceof G2.ProjectivePoint) return sigPoint; + return Signature.toRawBytes(sigPoint); + } + + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + function verify( + signature: G2Hex, + message: G2Hex, + publicKey: G1Hex, + htfOpts?: htf.htfBasicOpts + ): boolean { + const P = normP1(publicKey); + const Hm = normP2Hash(message, htfOpts); + const G = G1.ProjectivePoint.BASE; + const S = normP2(signature); + // Instead of doing 2 exponentiations, we use property of billinear maps + // and do one exp after multiplying 2 points. + const ePHm = pairing(P.negate(), Hm, false); + const eGS = pairing(G, S, false); + const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm)); + return Fp12.eql(exp, Fp12.ONE); + } + + // Adds a bunch of public key points together. + // pk1 + pk2 + pk3 = pkA + function aggregatePublicKeys(publicKeys: Hex[]): Uint8Array; + function aggregatePublicKeys(publicKeys: G1[]): G1; + function aggregatePublicKeys(publicKeys: G1Hex[]): Uint8Array | G1 { + if (!publicKeys.length) throw new Error('Expected non-empty array'); + const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (publicKeys[0] instanceof G1.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + // toRawBytes ensures point validity + return aggAffine.toRawBytes(true); + } + + // Adds a bunch of signature points together. + function aggregateSignatures(signatures: Hex[]): Uint8Array; + function aggregateSignatures(signatures: G2[]): G2; + function aggregateSignatures(signatures: G2Hex[]): Uint8Array | G2 { + if (!signatures.length) throw new Error('Expected non-empty array'); + const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + const aggAffine = agg; //.toAffine(); + if (signatures[0] instanceof G2.ProjectivePoint) { + aggAffine.assertValidity(); + return aggAffine; + } + return Signature.toRawBytes(aggAffine); + } + + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + function verifyBatch( + signature: G2Hex, + messages: G2Hex[], + publicKeys: G1Hex[], + htfOpts?: htf.htfBasicOpts + ): boolean { + // @ts-ignore + // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex)); + + if (!messages.length) throw new Error('Expected non-empty messages array'); + if (publicKeys.length !== messages.length) + throw new Error('Pubkey count should equal msg count'); + const sig = normP2(signature); + const nMessages = messages.map((i) => normP2Hash(i, htfOpts)); + const nPublicKeys = publicKeys.map(normP1); + try { + const paired = []; + for (const message of new Set(nMessages)) { + const groupPublicKey = nMessages.reduce( + (groupPublicKey, subMessage, i) => + subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, + G1.ProjectivePoint.ZERO + ); + // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message); + // Possible to batch pairing for same msg with different groupPublicKey here + paired.push(pairing(groupPublicKey, message, false)); + } + paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); + const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE); + const exp = Fp12.finalExponentiate(product); + return Fp12.eql(exp, Fp12.ONE); + } catch { + return false; + } + } + + G1.ProjectivePoint.BASE._setWindowSize(4); + + return { + getPublicKey, + sign, + verify, + verifyBatch, + aggregatePublicKeys, + aggregateSignatures, + millerLoop, + pairing, + G1, + G2, + Signature, + fields: { + Fr, + Fp, + Fp2, + Fp6, + Fp12, + }, + params: { + x: CURVE.params.x, + r: CURVE.params.r, + G1b: CURVE.G1.b, + G2b: CURVE.G2.b, + }, + utils, + }; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/curve.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/curve.ts new file mode 100644 index 0000000..2876377 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/curve.ts @@ -0,0 +1,203 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +import { IField, validateField, nLength } from './modular.js'; +import { validateObject } from './utils.js'; +const _0n = BigInt(0); +const _1n = BigInt(1); + +export type AffinePoint = { + x: T; + y: T; +} & { z?: never; t?: never }; + +export interface Group> { + double(): T; + negate(): T; + add(other: T): T; + subtract(other: T): T; + equals(other: T): boolean; + multiply(scalar: bigint): T; +} + +export type GroupConstructor = { + BASE: T; + ZERO: T; +}; +export type Mapper = (i: T[]) => T[]; + +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +export function wNAF>(c: GroupConstructor, bits: number) { + const constTimeNegate = (condition: boolean, item: T): T => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W: number) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm: T, n: bigint) { + let p = c.ZERO; + let d: T = elm; + while (n > _0n) { + if (n & _1n) p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm: T, W: number): Group[] { + const { windows, windowSize } = opts(W); + const points: T[] = []; + let p: T = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + + let p = c.ZERO; + let f = c.BASE; + + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + + // Shift number by W bits. + n >>= shiftBy; + + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + + wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { p: T; f: T } { + // @ts-ignore + const W: number = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W) as T[]; + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} + +// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok. +// Though generator can be different (Fp2 / Fp6 for BLS). +export type BasicCurve = { + Fp: IField; // Field over which we'll do calculations (Fp) + n: bigint; // Curve order, total count of valid points in the field + nBitLength?: number; // bit length of curve order + nByteLength?: number; // byte length of curve order + h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation + hEff?: bigint; // Number to multiply to clear cofactor + Gx: T; // base point X coordinate + Gy: T; // base point Y coordinate + allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey +}; + +export function validateBasic(curve: BasicCurve & T) { + validateField(curve.Fp); + validateObject( + curve, + { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, + { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + } + ); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + } as const); +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/edwards.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/edwards.ts new file mode 100644 index 0000000..9124f66 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/edwards.ts @@ -0,0 +1,513 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +import { mod } from './modular.js'; +import * as ut from './utils.js'; +import { ensureBytes, FHash, Hex } from './utils.js'; +import { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8); + +// Edwards curves must declare params a & d. +export type CurveType = BasicCurve & { + a: bigint; // curve param a + d: bigint; // curve param d + hash: FHash; // Hashing + randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing + uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v) + prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify() + mapToCurve?: (scalar: bigint[]) => AffinePoint; // for hash-to-curve standard +}; + +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + curve, + { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, + { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + } + ); + // Set defaults + return Object.freeze({ ...opts } as const); +} + +// Instance of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointType extends Group { + readonly ex: bigint; + readonly ey: bigint; + readonly ez: bigint; + readonly et: bigint; + get x(): bigint; + get y(): bigint; + assertValidity(): void; + multiply(scalar: bigint): ExtPointType; + multiplyUnsafe(scalar: bigint): ExtPointType; + isSmallOrder(): boolean; + isTorsionFree(): boolean; + clearCofactor(): ExtPointType; + toAffine(iz?: bigint): AffinePoint; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; +} +// Static methods of Extended Point with coordinates in X, Y, Z, T +export interface ExtPointConstructor extends GroupConstructor { + new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType; + fromAffine(p: AffinePoint): ExtPointType; + fromHex(hex: Hex): ExtPointType; + fromPrivateKey(privateKey: Hex): ExtPointType; +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: Hex) => Uint8Array; + sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array; + verify: ( + sig: Hex, + message: Hex, + publicKey: Hex, + options?: { context?: Hex; zip215: boolean } + ) => boolean; + ExtendedPoint: ExtPointConstructor; + utils: { + randomPrivateKey: () => Uint8Array; + getExtendedPublicKey: (key: Hex) => { + head: Uint8Array; + prefix: Uint8Array; + scalar: bigint; + point: ExtPointType; + pointBytes: Uint8Array; + }; + }; +}; + +// It is not generic twisted curve for now, but ed25519/ed448 generic implementation +export function twistedEdwards(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { + Fp, + n: CURVE_ORDER, + prehash: prehash, + hash: cHash, + randomBytes, + nByteLength, + h: cofactor, + } = CURVE; + const MASK = _2n << (BigInt(nByteLength * 8) - _1n); + const modP = Fp.create; // Function overrides + + // sqrt(u/v) + const uvRatio = + CURVE.uvRatio || + ((u: bigint, v: bigint) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } catch (e) { + return { isValid: false, value: _0n }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP + const domain = + CURVE.domain || + ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..] + const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1] + const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1] + function assertInRange(n: bigint, max: bigint) { + // n in [1..max-1] + if (inRange(n, max)) return n; + throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); + } + function assertGE0(n: bigint) { + // n in [0..CURVE_ORDER-1] + return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group + } + const pointPrecomputes = new Map(); + function isPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ExtendedPoint expected'); + } + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point implements ExtPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + + constructor( + readonly ex: bigint, + readonly ey: bigint, + readonly ez: bigint, + readonly et: bigint + ) { + if (!in0MaskRange(ex)) throw new Error('x required'); + if (!in0MaskRange(ey)) throw new Error('y required'); + if (!in0MaskRange(ez)) throw new Error('z required'); + if (!in0MaskRange(et)) throw new Error('t required'); + } + + get x(): bigint { + return this.toAffine().x; + } + get y(): bigint { + return this.toAffine().y; + } + + static fromAffine(p: AffinePoint): Point { + if (p instanceof Point) throw new Error('extended point not allowed'); + const { x, y } = p || {}; + if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point'); + return new Point(x, y, _1n, modP(x * y)); + } + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + _WINDOW_SIZE?: number; + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity(): void { + const { a, d } = CURVE; + if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = this; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) throw new Error('bad point: equation left != right (2)'); + } + + // Compare one point to another. + equals(other: Point): boolean { + isPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + + protected is0(): boolean { + return this.equals(Point.ZERO); + } + + negate(): Point { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double(): Point { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other: Point) { + isPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n * T2); + const D = modP(T1 * _2n * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + + return new Point(X3, Y3, Z3, T3); + } + + subtract(other: Point): Point { + return this.add(other.negate()); + } + + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ); + } + + // Constant-time multiplication. + multiply(scalar: bigint): Point { + const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER)); + return Point.normalizeZ([p, f])[0]; + } + + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar: bigint): Point { + let n = assertGE0(scalar); // 0 <= scalar < CURVE.n + if (n === _0n) return I; + if (this.equals(I) || n === _1n) return this; + if (this.equals(G)) return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder(): boolean { + return this.multiplyUnsafe(cofactor).is0(); + } + + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree(): boolean { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz?: bigint): AffinePoint { + const { ex: x, ey: y, ez: z } = this; + const is0 = this.is0(); + if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) return { x: _0n, y: _1n }; + if (zz !== _1n) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + + clearCofactor(): Point { + const { h: cofactor } = CURVE; + if (cofactor === _1n) return this; + return this.multiplyUnsafe(cofactor); + } + + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex: Hex, zip215 = false): Point { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = ut.bytesToNumberLE(normed); + if (y === _0n) { + // y=0 is allowed + } else { + // RFC8032 prohibits >= p, but ZIP215 doesn't + if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519) + else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519) + } + + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey: Hex) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes(): Uint8Array { + const { x, y } = this.toAffine(); + const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex(): string { + return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + + function modN(a: bigint) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash: Uint8Array): bigint { + return modN(ut.bytesToNumberLE(hash)); + } + + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key: Hex) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey: Hex): Uint8Array { + return getExtendedPublicKey(privKey).pointBytes; + } + + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) { + const msg = ut.concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array { + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + assertGE0(s); // 0 <= s < l + const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + + const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT; + function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (prehash) msg = prehash(msg); // for ed25519ph, etc + + const s = ut.bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) return false; + + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES), + + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/hash-to-curve.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/hash-to-curve.ts new file mode 100644 index 0000000..38d31d4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/hash-to-curve.ts @@ -0,0 +1,223 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { Group, GroupConstructor, AffinePoint } from './curve.js'; +import { mod, IField } from './modular.js'; +import { bytesToNumberBE, CHash, concatBytes, utf8ToBytes, validateObject } from './utils.js'; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +type UnicodeOrBytes = string | Uint8Array; +export type Opts = { + DST: UnicodeOrBytes; + p: bigint; + m: number; + k: number; + expand: 'xmd' | 'xof'; + hash: CHash; +}; + +function validateDST(dst: UnicodeOrBytes): Uint8Array { + if (dst instanceof Uint8Array) return dst; + if (typeof dst === 'string') return utf8ToBytes(dst); + throw new Error('DST must be Uint8Array or string'); +} + +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; + +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value: number, length: number): Uint8Array { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0) as number[]; + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} + +function strxor(a: Uint8Array, b: Uint8Array): Uint8Array { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function isBytes(item: unknown): void { + if (!(item instanceof Uint8Array)) throw new Error('Uint8Array expected'); +} +function isNum(item: unknown): void { + if (!Number.isSafeInteger(item)) throw new Error('number expected'); +} + +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1 +export function expand_message_xmd( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + H: CHash +): Uint8Array { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) throw new Error('Invalid xmd length'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} + +export function expand_message_xof( + msg: Uint8Array, + DST: Uint8Array, + lenInBytes: number, + k: number, + H: CHash +): Uint8Array { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return ( + H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest() + ); +} + +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +export function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] { + validateObject(options, { + DST: 'string', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} + +export function isogenyMap>(field: F, map: [T[], T[], T[], T[]]) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x: T, y: T) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => + val.reduce((acc, i) => field.add(field.mul(acc, x), i)) + ); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} + +export interface H2CPoint extends Group> { + add(rhs: H2CPoint): H2CPoint; + toAffine(iz?: bigint): AffinePoint; + clearCofactor(): H2CPoint; + assertValidity(): void; +} + +export interface H2CPointConstructor extends GroupConstructor> { + fromAffine(ap: AffinePoint): H2CPoint; +} + +export type MapToCurve = (scalar: bigint[]) => AffinePoint; + +// Separated from initialization opts, so users won't accidentally change per-curve parameters +// (changing DST is ok!) +export type htfBasicOpts = { DST: UnicodeOrBytes }; + +export function createHasher( + Point: H2CPointConstructor, + mapToCurve: MapToCurve, + def: Opts & { encodeDST?: UnicodeOrBytes } +) { + if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/modular.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/modular.ts new file mode 100644 index 0000000..bb1061b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/modular.ts @@ -0,0 +1,425 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +import { + bitMask, + numberToBytesBE, + numberToBytesLE, + bytesToNumberBE, + bytesToNumberLE, + ensureBytes, + validateObject, +} from './utils.js'; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); + +// Calculates a modulo b +export function mod(a: bigint, b: bigint): bigint { + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +export function pow(num: bigint, power: bigint, modulo: bigint): bigint { + if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} + +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +export function pow2(x: bigint, power: bigint, modulo: bigint): bigint { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} + +// Inverses number over modulo +export function invert(number: bigint, modulo: bigint): bigint { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) throw new Error('invert: does not exist'); + return mod(x, modulo); +} + +// Tonelli-Shanks algorithm +// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12) +// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks +export function tonelliShanks(P: bigint) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n) / _2n; + + let Q: bigint, S: number, Z: bigint; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++); + + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++); + + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + return function tonelliFast(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Slow-path + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp: IField, n: T): T { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} + +export function FpSqrt(P: bigint) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + return function sqrt3mod4(Fp: IField, n: T) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp: IField, n: T) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); + return root; + }; + } + + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} + +// Little-endian check for first LE bit (last BE bit); +export const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n; + +// Field is not always over prime, Fp2 for example has ORDER(q)=p^m +export interface IField { + ORDER: bigint; + BYTES: number; + BITS: number; + MASK: bigint; + ZERO: T; + ONE: T; + // 1-arg + create: (num: T) => T; + isValid: (num: T) => boolean; + is0: (num: T) => boolean; + neg(num: T): T; + inv(num: T): T; + sqrt(num: T): T; + sqr(num: T): T; + // 2-args + eql(lhs: T, rhs: T): boolean; + add(lhs: T, rhs: T): T; + sub(lhs: T, rhs: T): T; + mul(lhs: T, rhs: T | bigint): T; + pow(lhs: T, power: bigint): T; + div(lhs: T, rhs: T | bigint): T; + // N for NonNormalized (for now) + addN(lhs: T, rhs: T): T; + subN(lhs: T, rhs: T): T; + mulN(lhs: T, rhs: T | bigint): T; + sqrN(num: T): T; + + // Optional + // Should be same as sgn0 function in https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/ + // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway. + isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2 + // legendre?(num: T): T; + pow(lhs: T, power: bigint): T; + invertBatch: (lst: T[]) => T[]; + toBytes(num: T): Uint8Array; + fromBytes(bytes: Uint8Array): T; + // If c is False, CMOV returns a, otherwise it returns b. + cmov(a: T, b: T, c: boolean): T; +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +] as const; +export function validateField(field: IField) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + } as Record; + const opts = FIELD_FIELDS.reduce((map, val: string) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} + +// Generic field functions +export function FpPow(f: IField, num: T, power: bigint): T { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) throw new Error('Expected power > 0'); + if (power === _0n) return f.ONE; + if (power === _1n) return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} + +// 0 is non-invertible: non-batched version will throw on 0 +export function FpInvertBatch(f: IField, nums: T[]): T[] { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} + +export function FpDiv(f: IField, lhs: T, rhs: T | bigint): T { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} + +// This function returns True whenever the value x is a square in the field F. +export function FpIsSquare(f: IField) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x: T): boolean => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} + +// CURVE.n lengths +export function nLength(n: bigint, nBitLength?: number) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} + +type FpField = IField & Required, 'isOdd'>>; +/** + * Initializes a galois field over prime. Non-primes are not supported for now. + * Do not init in loop: slow. Very fragile: always run a benchmark on change. + * Major performance gains: + * a) non-normalized operations like mulN instead of mul + * b) `Object.freeze` + * c) Same object shape: never add or remove keys + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +export function Field( + ORDER: bigint, + bitLen?: number, + isLE = false, + redef: Partial> = {} +): Readonly { + if (ORDER <= _0n) throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f: Readonly = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + } as FpField); + return Object.freeze(f); +} + +export function FpSqrtOdd(Fp: IField, elm: T) { + if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} + +export function FpSqrtEven(Fp: IField, elm: T) { + if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} + +/** + * FIPS 186 B.4.1-compliant "constant-time" private key generation utility. + * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 40 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. curveFn.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +export function hashToPrivateScalar( + hash: string | Uint8Array, + groupOrder: bigint, + isLE = false +): bigint { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return mod(num, groupOrder - _1n) + _1n; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/montgomery.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/montgomery.ts new file mode 100644 index 0000000..64d1b53 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/montgomery.ts @@ -0,0 +1,189 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { mod, pow } from './modular.js'; +import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js'; + +const _0n = BigInt(0); +const _1n = BigInt(1); +type Hex = string | Uint8Array; + +export type CurveType = { + P: bigint; // finite field prime + nByteLength: number; + adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; + domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; + a: bigint; + montgomeryBits: number; + powPminus2?: (x: bigint) => bigint; + xyToU?: (x: bigint, y: bigint) => bigint; + Gu: bigint; + randomBytes?: (bytesLength?: number) => Uint8Array; +}; +export type CurveFn = { + scalarMult: (scalar: Hex, u: Hex) => Uint8Array; + scalarMultBase: (scalar: Hex) => Uint8Array; + getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; + getPublicKey: (privateKey: Hex) => Uint8Array; + utils: { randomPrivateKey: () => Uint8Array }; + GuBytes: Uint8Array; +}; + +function validateOpts(curve: CurveType) { + validateObject( + curve, + { + a: 'bigint', + }, + { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + } + ); + // Set defaults + return Object.freeze({ ...curve } as const); +} + +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +export function montgomery(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n: bigint) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P)); + + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + + // Accepts 0 as well + function assertFieldElement(n: bigint): bigint { + if (typeof n === 'bigint' && _0n <= n && n < P) return n; + throw new Error('Expected valid scalar 0 < scalar < CURVE.P'); + } + + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(pointU: bigint, scalar: bigint): bigint { + const u = assertFieldElement(pointU); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = assertFieldElement(scalar); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw: [bigint, bigint]; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + + function encodeUCoordinate(u: bigint): Uint8Array { + return numberToBytesLE(modP(u), montgomeryBytes); + } + + function decodeUCoordinate(uEnc: Hex): bigint { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP + // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519 + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index) + if (fieldLen === montgomeryBytes) u[fieldLen - 1] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n: Hex): bigint { + const bytes = ensureBytes('scalar', n); + if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar: Hex, u: Hex): Uint8Array { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar: Hex): Uint8Array { + return scalarMult(scalar, GuBytes); + } + + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/poseidon.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/poseidon.ts new file mode 100644 index 0000000..38ab17d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/poseidon.ts @@ -0,0 +1,119 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info +import { IField, FpPow, validateField } from './modular.js'; +// We don't provide any constants, since different implementations use different constants. +// For reference constants see './test/poseidon.test.js'. +export type PoseidonOpts = { + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; // Hack for stark + mds: bigint[][]; + roundConstants: bigint[][]; +}; + +export function validateOpts(opts: PoseidonOpts) { + const { Fp } = opts; + validateField(Fp); + for (const i of ['t', 'roundsFull', 'roundsPartial'] as const) { + if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i])) + throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`); + } + if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean') + throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`); + // Default is 5, but by some reasons stark uses 3 + let sboxPower = opts.sboxPower; + if (sboxPower === undefined) sboxPower = 5; + if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower)) + throw new Error(`Poseidon wrong sboxPower=${sboxPower}`); + + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + + if (opts.roundsFull % 2 !== 0) + throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`); + const rounds = opts.roundsFull + opts.roundsPartial; + + if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds) + throw new Error('Poseidon: wrong round constants'); + const roundConstants = opts.roundConstants.map((rc) => { + if (!Array.isArray(rc) || rc.length !== opts.t) + throw new Error(`Poseidon wrong round constants: ${rc}`); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error(`Poseidon wrong round constant=${i}`); + return Fp.create(i); + }); + }); + // MDS is TxT matrix + if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t) + throw new Error('Poseidon: wrong MDS matrix'); + const mds = opts.mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t) + throw new Error(`Poseidon MDS matrix row: ${mdsRow}`); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon MDS matrix value=${i}`); + return Fp.create(i); + }); + }); + return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds }); +} + +export function splitConstants(rc: bigint[], t: number) { + if (typeof t !== 'number') throw new Error('poseidonSplitConstants: wrong t'); + if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: wrong rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + tmp.push(rc[i]); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} + +export function poseidon(opts: PoseidonOpts) { + const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts); + const halfRoundsFull = Math.floor(opts.roundsFull / 2); + const partialIdx = reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => { + values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j])); + + if (isFull) values = values.map((i) => sboxFn(i)); + else values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = opts.mds.map((i) => + i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO) + ); + return values; + }; + const poseidonHash = function poseidonHash(values: bigint[]) { + if (!Array.isArray(values) || values.length !== t) + throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`); + values = values.map((i) => { + if (typeof i !== 'bigint') throw new Error(`Poseidon: wrong value=${i} (${typeof i})`); + return Fp.create(i); + }); + let round = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + // Apply r_p partial rounds. + for (let i = 0; i < opts.roundsPartial; i++) values = poseidonRound(values, false, round++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++); + + if (round !== rounds) + throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`); + return values; + }; + // For verification in tests + poseidonHash.roundConstants = opts.roundConstants; + return poseidonHash; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/utils.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/utils.ts new file mode 100644 index 0000000..00fc18f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/utils.ts @@ -0,0 +1,287 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +export type Hex = Uint8Array | string; // hex strings are accepted for simplicity +export type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve +export type CHash = { + (message: Uint8Array | string): Uint8Array; + blockLen: number; + outputLen: number; + create(opts?: { dkLen?: number }): any; // For shake +}; +export type FHash = (message: Uint8Array | string) => Uint8Array; + +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +export function numberToHexUnpadded(num: number | bigint): string { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} + +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// BE: Big Endian, LE: Little Endian +export function bytesToNumberBE(bytes: Uint8Array): bigint { + return hexToNumber(bytesToHex(bytes)); +} +export function bytesToNumberLE(bytes: Uint8Array): bigint { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} + +export function numberToBytesBE(n: number | bigint, len: number): Uint8Array { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +export function numberToBytesLE(n: number | bigint, len: number): Uint8Array { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +export function numberToVarBytesBE(n: number | bigint): Uint8Array { + return hexToBytes(numberToHexUnpadded(n)); +} + +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array { + let res: Uint8Array; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } else if (u8a(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +export function equalBytes(b1: Uint8Array, b2: Uint8Array) { + // We don't care about timing attacks here + if (b1.length !== b2.length) return false; + for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false; + return true; +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +// Bit operations + +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +export function bitLen(n: bigint) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1); + return len; +} + +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +export function bitGet(n: bigint, pos: number) { + return (n >> BigInt(pos)) & _1n; +} + +/** + * Sets single bit at position. + */ +export const bitSet = (n: bigint, pos: number, value: boolean) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; + +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +export const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n; + +// DRBG + +const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut +type Pred = (v: Uint8Array) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +export function createHmacDrbg( + hashLen: number, + qByteLen: number, + hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array +): (seed: Uint8Array, predicate: Pred) => T { + if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) throw new Error('drbg: tried 1000 values'); + let len = 0; + const out: Uint8Array[] = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed: Uint8Array, pred: Pred): T => { + reset(); + reseed(seed); // Steps D-G + let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) reseed(); + reset(); + return res; + }; + return genUntil; +} + +// Validating curves and fields + +const validatorFns = { + bigint: (val: any) => typeof val === 'bigint', + function: (val: any) => typeof val === 'function', + boolean: (val: any) => typeof val === 'boolean', + string: (val: any) => typeof val === 'string', + isSafeInteger: (val: any) => Number.isSafeInteger(val), + array: (val: any) => Array.isArray(val), + field: (val: any, object: any) => (object as any).Fp.isValid(val), + hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +} as const; +type Validator = keyof typeof validatorFns; +type ValMap> = { [K in keyof T]?: Validator }; +// type Record = { [P in K]: T; } + +export function validateObject>( + object: T, + validators: ValMap, + optValidators: ValMap = {} +) { + const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + + const val = object[fieldName as keyof typeof object]; + if (isOptional && val === undefined) return; + if (!checkVal(val, object)) { + throw new Error( + `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}` + ); + } + }; + for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false); + for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/abstract/weierstrass.ts b/test/merkletreejs/node_modules/@noble/curves/src/abstract/weierstrass.ts new file mode 100644 index 0000000..5981ca4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/abstract/weierstrass.ts @@ -0,0 +1,1220 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +import * as mod from './modular.js'; +import * as ut from './utils.js'; +import { CHash, Hex, PrivKey, ensureBytes } from './utils.js'; +import { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js'; + +export type { AffinePoint }; +type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; +type EndomorphismOpts = { + beta: bigint; + splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint }; +}; +export type BasicWCurve = BasicCurve & { + // Params: a, b + a: T; + b: T; + + // Optional params + allowedPrivateKeyLengths?: readonly number[]; // for P521 + wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n + endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves + // When a cofactor != 1, there can be an effective methods to: + // 1. Determine whether a point is torsion-free + isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean; + // 2. Clear torsion component + clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType; +}; + +type Entropy = Hex | true; +export type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean }; +export type VerOpts = { lowS?: boolean; prehash?: boolean }; + +/** + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + */ + +// Instance for 3d XYZ points +export interface ProjPointType extends Group> { + readonly px: T; + readonly py: T; + readonly pz: T; + get x(): T; + get y(): T; + multiply(scalar: bigint): ProjPointType; + toAffine(iz?: T): AffinePoint; + isTorsionFree(): boolean; + clearCofactor(): ProjPointType; + assertValidity(): void; + hasEvenY(): boolean; + toRawBytes(isCompressed?: boolean): Uint8Array; + toHex(isCompressed?: boolean): string; + + multiplyUnsafe(scalar: bigint): ProjPointType; + multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined; + _setWindowSize(windowSize: number): void; +} +// Static methods for 3d XYZ points +export interface ProjConstructor extends GroupConstructor> { + new (x: T, y: T, z: T): ProjPointType; + fromAffine(p: AffinePoint): ProjPointType; + fromHex(hex: Hex): ProjPointType; + fromPrivateKey(privateKey: PrivKey): ProjPointType; + normalizeZ(points: ProjPointType[]): ProjPointType[]; +} + +export type CurvePointsType = BasicWCurve & { + // Bytes + fromBytes?: (bytes: Uint8Array) => AffinePoint; + toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array; +}; + +function validatePointOpts(curve: CurvePointsType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + a: 'field', + b: 'field', + }, + { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + } + ); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if ( + typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function' + ) { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts } as const); +} + +export type CurvePointsRes = { + ProjectivePoint: ProjConstructor; + normPrivateKeyToScalar: (key: PrivKey) => bigint; + weierstrassEquation: (x: T) => T; + isWithinCurveOrder: (num: bigint) => boolean; +}; + +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +export const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex: string | Uint8Array): { r: bigint; s: bigint } { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag'); + if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig: { r: bigint; s: bigint }): string { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num: number | bigint) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); + +export function weierstrassPoints(opts: CurvePointsType) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + + const toBytes = + CURVE.toBytes || + ((c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = + CURVE.fromBytes || + ((bytes: Uint8Array) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x: T): T { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num: bigint): boolean { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num: bigint) { + if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key: PrivKey): bigint { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num: bigint; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + + const pointPrecomputes = new Map(); + function assertPrjPoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point implements ProjPointType { + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + + constructor(readonly px: T, readonly py: T, readonly pz: T) { + if (px == null || !Fp.isValid(px)) throw new Error('x required'); + if (py == null || !Fp.isValid(py)) throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) throw new Error('z required'); + } + + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p: AffinePoint): Point { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point'); + if (p instanceof Point) throw new Error('projective point not allowed'); + const is0 = (i: T) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + + get x(): T { + return this.toAffine().x; + } + get y(): T { + return this.toAffine().y; + } + + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points: Point[]): Point[] { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex: Hex): Point { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey: PrivKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + _WINDOW_SIZE?: number; + + // "Private method", don't use it directly + _setWindowSize(windowSize: number) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + + // A point on curve is valid if it conforms to equation. + assertValidity(): void { + // Zero is valid point too! + if (this.is0()) { + if (CURVE.allowInfinityPoint) return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY(): boolean { + const { y } = this.toAffine(); + if (Fp.isOdd) return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + + /** + * Compare one point to another. + */ + equals(other: Point): boolean { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate(): Point { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other: Point): Point { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + + subtract(other: Point) { + return this.add(other.negate()); + } + + private is0() { + return this.equals(Point.ZERO); + } + private wNAF(n: bigint): { p: Point; f: Point } { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n: bigint): Point { + const I = Point.ZERO; + if (n === _0n) return I; + assertGE(n); // Will throw on 0 + if (n === _1n) return this; + const { endo } = CURVE; + if (!endo) return wnaf.unsafeLadder(this, n); + + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d: Point = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) k1p = k1p.add(d); + if (k2 & _1n) k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar: bigint): Point { + assertGE(scalar); + let n = scalar; + let point: Point, fake: Point; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = ( + P: Point, + a: bigint // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz?: T): AffinePoint { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree(): boolean { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) return true; // No subgroups, always torsion-free + if (isTorsionFree) return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor(): Point { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) return this; // Fast-path + if (clearCofactor) return clearCofactor(Point, this) as Point; + return this.multiplyUnsafe(CURVE.h); + } + + toRawBytes(isCompressed = true): Uint8Array { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + + toHex(isCompressed = true): string { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point as ProjConstructor, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} + +// Instance +export interface SignatureType { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + assertValidity(): void; + addRecoveryBit(recovery: number): RecoveredSignatureType; + hasHighS(): boolean; + normalizeS(): SignatureType; + recoverPublicKey(msgHash: Hex): ProjPointType; + toCompactRawBytes(): Uint8Array; + toCompactHex(): string; + // DER-encoded + toDERRawBytes(isCompressed?: boolean): Uint8Array; + toDERHex(isCompressed?: boolean): string; +} +export type RecoveredSignatureType = SignatureType & { + readonly recovery: number; +}; +// Static methods +export type SignatureConstructor = { + new (r: bigint, s: bigint): SignatureType; + fromCompact(hex: Hex): SignatureType; + fromDER(hex: Hex): SignatureType; +}; +type SignatureLike = { r: bigint; s: bigint }; + +export type PubKey = Hex | ProjPointType; + +export type CurveType = BasicWCurve & { + hash: CHash; // CHash not FHash because we need outputLen for DRBG + hmac: HmacFnSync; + randomBytes: (bytesLength?: number) => Uint8Array; + lowS?: boolean; + bits2int?: (bytes: Uint8Array) => bigint; + bits2int_modN?: (bytes: Uint8Array) => bigint; +}; + +function validateOpts(curve: CurveType) { + const opts = validateBasic(curve); + ut.validateObject( + opts, + { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, + { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + } + ); + return Object.freeze({ lowS: true, ...opts } as const); +} + +export type CurveFn = { + CURVE: ReturnType; + getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array; + getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array; + sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType; + verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean; + ProjectivePoint: ProjConstructor; + Signature: SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: PrivKey) => bigint; + isValidPrivateKey(privateKey: PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType; + }; +}; + +export function weierstrass(curveDef: CurveType): CurveFn { + const CURVE = validateOpts(curveDef) as ReturnType; + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + + function isValidFieldElement(num: bigint): boolean { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a: bigint) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a: bigint) { + return mod.invert(a, CURVE_ORDER); + } + + const { + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed: boolean): Uint8Array { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes: Uint8Array) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) y = Fp.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } else { + throw new Error( + `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes` + ); + } + }, + }); + const numToNByteStr = (num: bigint): string => + ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + + function isBiggerThanHalfOrder(number: bigint) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + + function normalizeS(s: bigint) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to)); + + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature implements SignatureType { + constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) { + this.assertValidity(); + } + + // pair (bytes of r, bytes of s) + static fromCompact(hex: Hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex: Hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + + assertValidity(): void { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n'); + } + + addRecoveryBit(recovery: number): RecoveredSignature { + return new Signature(this.r, this.s, recovery) as RecoveredSignature; + } + + recoverPublicKey(msgHash: Hex): typeof Point.BASE { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + + // Signatures should be low-s, to prevent malleability. + hasHighS(): boolean { + return isBiggerThanHalfOrder(this.s); + } + + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + type RecoveredSignature = Signature & { recovery: number }; + + const utils = { + isValidPrivateKey(privateKey: PrivKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: (): Uint8Array => { + const rand = CURVE.randomBytes(Fp.BYTES + 8); + const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); + return ut.numberToBytesBE(num, CURVE.nByteLength); + }, + + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item: PrivKey | PubKey): boolean { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && (item as Hex).length; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) return true; + return false; + } + + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array { + if (isProbPub(privateA)) throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = + CURVE.bits2int || + function (bytes: Uint8Array): bigint { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = + CURVE.bits2int_modN || + function (bytes: Uint8Array): bigint { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num: bigint): Uint8Array { + if (typeof num !== 'bigint') throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false }; + + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify( + signature: Hex | SignatureLike, + msgHash: Hex, + publicKey: Hex, + opts = defaultVerOpts + ): boolean { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + + let _sig: Signature | undefined = undefined; + let P: ProjPointType; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } catch (error) { + if ((error as Error).message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} + +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +export function SWUFpSqrtRatio(Fp: mod.IField, Z: T) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u: T, v: T) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * From draft-irtf-cfrg-hash-to-curve-16 + */ +export function mapToCurveSimpleSWU( + Fp: mod.IField, + opts: { + A: T; + B: T; + Z: T; + } +) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u: T): { x: T; y: T } => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/bls12-381.ts b/test/merkletreejs/node_modules/@noble/curves/src/bls12-381.ts new file mode 100644 index 0000000..5f6fdc2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/bls12-381.ts @@ -0,0 +1,1351 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to: +// - Construct zk-SNARKs at the 128-bit security +// - Use threshold signatures, which allows a user to sign lots of messages with one signature and +// verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme. +// +// The library uses G1 for public keys and G2 for signatures. Support for G1 signatures is planned. +// Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs +// [pairing-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11), +// [bls-sigs-04](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04), +// [hash-to-curve-12](https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-12). +// +// ### Summary +// 1. BLS Relies on Bilinear Pairing (expensive) +// 2. Private Keys: 32 bytes +// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes. +// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays. +// - The signature is a point on the G2 subgroup, which is defined over a finite field +// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers). +// 5. The 12 stands for the Embedding degree. +// +// ### Formulas +// - `P = pk x G` - public keys +// - `S = pk x H(m)` - signing +// - `e(P, H(m)) == e(G, S)` - verification using pairings +// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation +// Filecoin uses little endian byte arrays for private keys - +// so ensure to reverse byte order if you'll use it with FIL. +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { bls, CurveFn } from './abstract/bls.js'; +import * as mod from './abstract/modular.js'; +import { + concatBytes as concatB, + ensureBytes, + numberToBytesBE, + bytesToNumberBE, + bitLen, + bitSet, + bitGet, + Hex, + bitMask, + bytesToHex, +} from './abstract/utils.js'; +// Types +import { + ProjPointType, + ProjConstructor, + mapToCurveSimpleSWU, + AffinePoint, +} from './abstract/weierstrass.js'; +import { isogenyMap } from './abstract/hash-to-curve.js'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// prettier-ignore +const _8n = BigInt(8), _16n = BigInt(16); + +// CURVE FIELDS +// Finite field over p. +const Fp_raw = BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab' +); +const Fp = mod.Field(Fp_raw); +type Fp = bigint; +// Finite field over r. +// This particular field is not used anywhere in bls12-381, but it is still useful. +const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')); + +// Fp₂ over complex plane +type BigintTuple = [bigint, bigint]; +type Fp2 = { c0: bigint; c1: bigint }; +const Fp2Add = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), +}); +const Fp2Subtract = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), +}); +const Fp2Multiply = ({ c0, c1 }: Fp2, rhs: Fp2) => { + if (typeof rhs === 'bigint') return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }; + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return { c0: o0, c1: o1 }; +}; +const Fp2Square = ({ c0, c1 }: Fp2) => { + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }; +}; +type Fp2Utils = { + fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2; + reim: (num: Fp2) => { re: bigint; im: bigint }; + mulByNonresidue: (num: Fp2) => Fp2; + multiplyByB: (num: Fp2) => Fp2; + frobeniusMap(num: Fp2, power: number): Fp2; +}; +// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), +// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where +// G² - 1 +// h2q +// NOTE: ORDER was wrong! +const FP2_ORDER = Fp_raw * Fp_raw; + +const Fp2: mod.IField & Fp2Utils = { + ORDER: FP2_ORDER, + BITS: bitLen(FP2_ORDER), + BYTES: Math.ceil(bitLen(FP2_ORDER) / 8), + MASK: bitMask(bitLen(FP2_ORDER)), + ZERO: { c0: Fp.ZERO, c1: Fp.ZERO }, + ONE: { c0: Fp.ONE, c1: Fp.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint', + is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1), + eql: ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => Fp.eql(c0, r0) && Fp.eql(c1, r1), + neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }), + pow: (num, power) => mod.FpPow(Fp2, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums), + // Normalized + add: Fp2Add, + sub: Fp2Subtract, + mul: Fp2Multiply, + sqr: Fp2Square, + // NonNormalized stuff + addN: Fp2Add, + subN: Fp2Subtract, + mulN: Fp2Multiply, + sqrN: Fp2Square, + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)), + inv: ({ c0: a, c1: b }) => { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const factor = Fp.inv(Fp.create(a * a + b * b)); + return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }; + }, + sqrt: (num) => { + if (Fp2.eql(num, Fp2.ZERO)) return Fp2.ZERO; // Algo doesn't handles this case + // TODO: Optimize this line. It's extremely slow. + // Speeding this up would boost aggregateSignatures. + // https://eprint.iacr.org/2012/685.pdf applicable? + // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250 + // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1 + // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99 + const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n); + const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this); + const R = FP2_ROOTS_OF_UNITY; + const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check)); + if (!divisor) throw new Error('No root'); + const index = R.indexOf(divisor); + const root = R[index / 2]; + if (!root) throw new Error('Invalid root'); + const x1 = Fp2.div(candidateSqrt, root); + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1; + return x2; + }, + // Same as sgn0_fp2 in draft-irtf-cfrg-hash-to-curve-16 + isOdd: (x: Fp2) => { + const { re: x0, im: x1 } = Fp2.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + }, + // Bytes util + fromBytes(b: Uint8Array): Fp2 { + if (b.length !== Fp2.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) }; + }, + toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }), + // Specific utils + // toString() { + // return `Fp2(${this.c0} + ${this.c1}×i)`; + // } + reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), + // multiply by u + 1 + mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }), + multiplyByB: ({ c0, c1 }) => { + let t0 = Fp.mul(c0, _4n); // 4 * c0 + let t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + fromBigTuple: (tuple: BigintTuple | bigint[]) => { + if (tuple.length !== 2) throw new Error('Invalid tuple'); + const fps = tuple.map((n) => Fp.create(n)) as [Fp, Fp]; + return { c0: fps[0], c1: fps[1] }; + }, + frobeniusMap: ({ c0, c1 }, power: number): Fp2 => ({ + c0, + c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), +}; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +const FP2_FROBENIUS_COEFFICIENTS = [ + BigInt('0x1'), + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), +].map((item) => Fp.create(item)); + +// For Fp2 roots of unity. +const rv1 = BigInt( + '0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' +); +// const ev1 = +// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90'); +// const ev2 = +// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5'); +// const ev3 = +// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17'); +// const ev4 = +// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1'); + +// Eighth roots of unity, used for computing square roots in Fp2. +// To verify or re-calculate: +// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n)) +const FP2_ROOTS_OF_UNITY = [ + [_1n, _0n], + [rv1, -rv1], + [_0n, _1n], + [rv1, rv1], + [-_1n, _0n], + [-rv1, rv1], + [_0n, -_1n], + [-rv1, -rv1], +].map((pair) => Fp2.fromBigTuple(pair)); +// eta values, used for computing sqrt(g(X1(t))) +// const FP2_ETAs = [ +// [ev1, ev2], +// [-ev2, ev1], +// [ev3, ev4], +// [-ev4, ev3], +// ].map((pair) => Fp2.fromBigTuple(pair)); + +// Finite extension field over irreducible polynominal. +// Fp2(v) / (v³ - ξ) where ξ = u + 1 +type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +type Fp6 = { c0: Fp2; c1: Fp2; c2: Fp2 }; +const Fp6Add = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), +}); +const Fp6Subtract = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), +}); +const Fp6Multiply = ({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) => { + if (typeof rhs === 'bigint') { + return { + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }; + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return { + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add( + t0, + Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2))) + ), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add( + Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), + Fp2.mulByNonresidue(t2) + ), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }; +}; +const Fp6Square = ({ c0, c1, c2 }: Fp6) => { + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return { + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }; +}; +type Fp6Utils = { + fromBigSix: (tuple: BigintSix) => Fp6; + mulByNonresidue: (num: Fp6) => Fp6; + frobeniusMap(num: Fp6, power: number): Fp6; + multiplyBy1(num: Fp6, b1: Fp2): Fp6; + multiplyBy01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + multiplyByFp2(lhs: Fp6, rhs: Fp2): Fp6; +}; + +const Fp6: mod.IField & Fp6Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 3 * Fp2.BITS, + BYTES: 3 * Fp2.BYTES, + MASK: bitMask(3 * Fp2.BITS), + ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }, + ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }, + create: (num) => num, + isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2), + is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2), + neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => + Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2), + sqrt: () => { + throw new Error('Not implemented'); + }, + // Do we need division by bigint at all? Should be done via order: + div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp6, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums), + // Normalized + add: Fp6Add, + sub: Fp6Subtract, + mul: Fp6Multiply, + sqr: Fp6Square, + // NonNormalized stuff + addN: Fp6Add, + subN: Fp6Subtract, + mulN: Fp6Multiply, + sqrN: Fp6Square, + + inv: ({ c0, c1, c2 }) => { + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv( + Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)) + ); + return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }; + }, + // Bytes utils + fromBytes: (b: Uint8Array): Fp6 => { + if (b.length !== Fp6.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)), + c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)), + c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)), + }; + }, + toBytes: ({ c0, c1, c2 }): Uint8Array => + concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)), + cmov: ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c) => ({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }), + // Utils + // fromTriple(triple: [Fp2, Fp2, Fp2]) { + // return new Fp6(...triple); + // } + // toString() { + // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`; + // } + fromBigSix: (t: BigintSix): Fp6 => { + if (!Array.isArray(t) || t.length !== 6) throw new Error('Invalid Fp6 usage'); + return { + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }; + }, + frobeniusMap: ({ c0, c1, c2 }, power: number) => ({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }), + + // Sparse multiplication + multiplyBy1: ({ c0, c1, c2 }, b1: Fp2): Fp6 => ({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }), + // Sparse multiplication + multiplyBy01({ c0, c1, c2 }, b0: Fp2, b1: Fp2): Fp6 { + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return { + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }; + }, + + multiplyByFp2: ({ c0, c1, c2 }, rhs: Fp2): Fp6 => ({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }), +}; + +const FP6_FROBENIUS_COEFFICIENTS_1 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt('0x0'), + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [BigInt('0x0'), BigInt('0x1')], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt('0x0'), + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + ], +].map((pair) => Fp2.fromBigTuple(pair)); +const FP6_FROBENIUS_COEFFICIENTS_2 = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff' + ), + BigInt('0x0'), + ], +].map((pair) => Fp2.fromBigTuple(pair)); + +// Finite extension field over irreducible polynominal. +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp₆(w) / (w² - γ) where γ = v +type Fp12 = { c0: Fp6; c1: Fp6 }; +// The BLS parameter x for BLS12-381 +const BLS_X = BigInt('0xd201000000010000'); +const BLS_X_LEN = bitLen(BLS_X); + +// prettier-ignore +type BigintTwelve = [ + bigint, bigint, bigint, bigint, bigint, bigint, + bigint, bigint, bigint, bigint, bigint, bigint + ]; +const Fp12Add = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), +}); +const Fp12Subtract = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), +}); +const Fp12Multiply = ({ c0, c1 }: Fp12, rhs: Fp12 | bigint) => { + if (typeof rhs === 'bigint') return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }; + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return { + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }; +}; +const Fp12Square = ({ c0, c1 }: Fp12) => { + let ab = Fp6.mul(c0, c1); // c0 * c1 + return { + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub( + Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), + Fp6.mulByNonresidue(ab) + ), + c1: Fp6.add(ab, ab), + }; // AB + AB +}; +function Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } { + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; +} +type Fp12Utils = { + fromBigTwelve: (t: BigintTwelve) => Fp12; + frobeniusMap(num: Fp12, power: number): Fp12; + multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + multiplyByFp2(lhs: Fp12, rhs: Fp2): Fp12; + conjugate(num: Fp12): Fp12; + finalExponentiate(num: Fp12): Fp12; + _cyclotomicSquare(num: Fp12): Fp12; + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; + +const Fp12: mod.IField & Fp12Utils = { + ORDER: Fp2.ORDER, // TODO: unused, but need to verify + BITS: 2 * Fp2.BITS, + BYTES: 2 * Fp2.BYTES, + MASK: bitMask(2 * Fp2.BITS), + ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO }, + ONE: { c0: Fp6.ONE, c1: Fp6.ZERO }, + create: (num) => num, + isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1), + is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1), + neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1), + sqrt: () => { + throw new Error('Not implemented'); + }, + inv: ({ c0, c1 }) => { + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w + }, + div: (lhs, rhs) => + Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)), + pow: (num, power) => mod.FpPow(Fp12, num, power), + invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums), + // Normalized + add: Fp12Add, + sub: Fp12Subtract, + mul: Fp12Multiply, + sqr: Fp12Square, + // NonNormalized stuff + addN: Fp12Add, + subN: Fp12Subtract, + mulN: Fp12Multiply, + sqrN: Fp12Square, + + // Bytes utils + fromBytes: (b: Uint8Array): Fp12 => { + if (b.length !== Fp12.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); + return { + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }; + }, + toBytes: ({ c0, c1 }): Uint8Array => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)), + cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }), + // Utils + // toString() { + // return `Fp12(${this.c0} + ${this.c1} * w)`; + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve: (t: BigintTwelve): Fp12 => ({ + c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix), + c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix), + }), + // Raises to q**i -th power + frobeniusMap(lhs, power: number) { + const r0 = Fp6.frobeniusMap(lhs.c0, power); + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12]; + return { + c0: r0, + c1: Fp6.create({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }; + }, + // Sparse multiplication + multiplyBy014: ({ c0, c1 }, o0: Fp2, o1: Fp2, o4: Fp2) => { + let t0 = Fp6.multiplyBy01(c0, o0, o1); + let t1 = Fp6.multiplyBy1(c1, o4); + return { + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }; + }, + multiplyByFp2: ({ c0, c1 }, rhs: Fp2): Fp12 => ({ + c0: Fp6.multiplyByFp2(c0, rhs), + c1: Fp6.multiplyByFp2(c1, rhs), + }), + conjugate: ({ c0, c1 }): Fp12 => ({ c0, c1: Fp6.neg(c1) }), + + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicSquare: ({ c0, c1 }): Fp12 => { + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2); + let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return { + c0: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Fp6.create({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }; // 2 * (T6 + c1c2) + T6 + }, + _cyclotomicExp(num, n) { + let z = Fp12.ONE; + for (let i = BLS_X_LEN - 1; i >= 0; i--) { + z = Fp12._cyclotomicSquare(z); + if (bitGet(n, i)) z = Fp12.mul(z, num); + } + return z; + }, + // https://eprint.iacr.org/2010/354.pdf + // https://eprint.iacr.org/2009/565.pdf + finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}; +const FP12_FROBENIUS_COEFFICIENTS = [ + [BigInt('0x1'), BigInt('0x0')], + [ + BigInt( + '0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8' + ), + BigInt( + '0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2' + ), + BigInt( + '0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' + ), + ], + [ + BigInt( + '0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995' + ), + BigInt( + '0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116' + ), + ], + [ + BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3' + ), + BigInt( + '0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8' + ), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09' + ), + BigInt( + '0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2' + ), + ], + [ + BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad' + ), + BigInt('0x0'), + ], + [ + BigInt( + '0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116' + ), + BigInt( + '0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995' + ), + ], +].map((n) => Fp2.fromBigTuple(n)); +// END OF CURVE FIELDS + +// HashToCurve + +// 3-isogeny map from E' to E +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3 +const isogenyMapG2 = isogenyMap( + Fp2, + [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], + ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))) as [Fp2[], Fp2[], Fp2[], Fp2[]] +); +// 11-isogeny map from E' to E +const isogenyMapG1 = isogenyMap( + Fp, + [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]] +); + +// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i +const G2_SWU = mapToCurveSimpleSWU(Fp2, { + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) +}); +// Optimized SWU Map - Fp to G1 +const G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create( + BigInt( + '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d' + ) + ), + B: Fp.create( + BigInt( + '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0' + ) + ), + Z: Fp.create(BigInt(11)), +}); + +// Endomorphisms (for fast cofactor clearing) +// Ψ(P) endomorphism +const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO }); +const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO }); +const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root }); +const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); +function psi(x: Fp2, y: Fp2): [Fp2, Fp2] { + // Untwist Fp2->Fp12 && frobenius(1) && twist back + const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; + const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + return [x2, y2]; +} +// Ψ endomorphism +function G2psi(c: ProjConstructor, P: ProjPointType) { + const affine = P.toAffine(); + const p = psi(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} +// Ψ²(P) endomorphism +// 1 / F2(2)^((p-1)/3) in GF(p²) +const PSI2_C1 = BigInt( + '0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac' +); + +function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] { + return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)]; +} +function G2psi2(c: ProjConstructor, P: ProjPointType) { + const affine = P.toAffine(); + const p = psi2(affine.x, affine.y); + return new c(p[0], p[1], Fp2.ONE); +} + +// Default hash_to_field options are for hash to G2. +// +// Parameter definitions are in section 5.3 of the spec unless otherwise noted. +// Parameter values come from section 8.8.2 of the spec. +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.8.2 +// +// Base field F is GF(p^m) +// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +// m = 2 (or 1 for G1 see section 8.8.1) +// k = 128 +const htfDefaults = Object.freeze({ + // DST: a domain separation tag + // defined in section 2.2.5 + // Use utils.getDSTLabel(), utils.setDSTLabel(value) + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + // p: the characteristic of F + // where F is a finite field of characteristic p and order q = p^m + p: Fp.ORDER, + // m: the extension degree of F, m >= 1 + // where F is a finite field of characteristic p and order q = p^m + m: 2, + // k: the target security level for the suite in bits + // defined in section 5.1 + k: 128, + // option to use a message that has already been processed by + // expand_message_xmd + expand: 'xmd', + // Hash functions for: expand_message_xmd is appropriate for use with a + // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. + // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 + hash: sha256, +} as const); + +// Encoding utils +// Point on G1 curve: (x, y) +const C_BIT_POS = Fp.BITS; // C_bit, compression bit for serialization flag +const I_BIT_POS = Fp.BITS + 1; // I_bit, point-at-infinity bit for serialization flag +const S_BIT_POS = Fp.BITS + 2; // S_bit, sign bit for serialization flag +// Compressed point of infinity +const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(_0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits + +function signatureG2ToRawBytes(point: ProjPointType) { + // NOTE: by some reasons it was missed in bls12-381, looks like bug + point.assertValidity(); + const len = Fp.BYTES; + if (point.equals(bls12_381.G2.ProjectivePoint.ZERO)) + return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const { x, y } = point.toAffine(); + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + const tmp = y1 > _0n ? y1 * _2n : y0 * _2n; + const aflag1 = Boolean((tmp / Fp.ORDER) & _1n); + const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); + const z2 = x0; + return concatB(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); +} + +// To verify curve parameters, see pairing-friendly-curves spec: +// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09 +// Basic math is done over finite fields over p. +// More complicated math is done over polynominal extension fields. +// To simplify calculations in Fp12, we construct extension tower: +// Fp₁₂ = Fp₆² => Fp₂³ +// Fp(u) / (u² - β) where β = -1 +// Fp₂(v) / (v³ - ξ) where ξ = u + 1 +// Fp₆(w) / (w² - γ) where γ = v +// Here goes constants && point encoding format +export const bls12_381: CurveFn = bls({ + // Fields + fields: { + Fp, + Fp2, + Fp6, + Fp12, + Fr, + }, + // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where + // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 + G1: { + Fp, + // cofactor; (z - 1)²/3 + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + // generator's coordinates + // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 + Gx: BigInt( + '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb' + ), + Gy: BigInt( + '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1' + ), + a: Fp.ZERO, + b: _4n, + htfDefaults: { ...htfDefaults, m: 1 }, + wrapPrivateKey: true, + allowInfinityPoint: true, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point): boolean => { + // φ endomorphism + const cubicRootOfUnityModP = BigInt( + '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ); + const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + + // todo: unroll + const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P + const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P + return u2P.equals(phi); + + // https://eprint.iacr.org/2019/814.pdf + // (z² − 1)/3 + // const c1 = BigInt('0x396c8c005555e1560000000055555555'); + // const P = this; + // const S = P.sigma(); + // const Q = S.double(); + // const S2 = S.sigma(); + // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O + // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1); + // const C = left.subtract(S2); + // return C.isZero(); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P + }, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G1_SWU(Fp.create(scalars[0])); + return isogenyMapG1(x, y); + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + bytes = bytes.slice(); + if (bytes.length === 48) { + // TODO: Fp.bytes + const P = Fp.ORDER; + const compressedValue = bytesToNumberBE(bytes); + const bflag = bitGet(compressedValue, I_BIT_POS); + // Zero + if (bflag === _1n) return { x: _0n, y: _0n }; + const x = Fp.create(compressedValue & Fp.MASK); + const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b + let y = Fp.sqrt(right); + if (!y) throw new Error('Invalid compressed G1 point'); + const aflag = bitGet(compressedValue, C_BIT_POS); + if ((y * _2n) / P !== aflag) y = Fp.neg(y); + return { x: Fp.create(x), y: Fp.create(y) }; + } else if (bytes.length === 96) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); + const x = bytesToNumberBE(bytes.subarray(0, Fp.BYTES)); + const y = bytesToNumberBE(bytes.subarray(Fp.BYTES)); + return { x: Fp.create(x), y: Fp.create(y) }; + } else { + throw new Error('Invalid point G1, expected 48/96 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return COMPRESSED_ZERO.slice(); + const P = Fp.ORDER; + let num; + num = bitSet(x, C_BIT_POS, Boolean((y * _2n) / P)); // set aflag + num = bitSet(num, S_BIT_POS, true); + return numberToBytesBE(num, Fp.BYTES); + } else { + if (isZero) { + // 2x PUBLIC_KEY_LENGTH + const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1)); + return x; + } else { + return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES)); + } + } + }, + }, + // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), + // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where + // G² - 1 + // h2q + G2: { + Fp: Fp2, + // cofactor + h: BigInt( + '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5' + ), + Gx: Fp2.fromBigTuple([ + BigInt( + '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8' + ), + BigInt( + '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e' + ), + ]), + // y = + // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, + // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 + Gy: Fp2.fromBigTuple([ + BigInt( + '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801' + ), + BigInt( + '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be' + ), + ]), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + hEff: BigInt( + '0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551' + ), + htfDefaults: { ...htfDefaults }, + wrapPrivateKey: true, + allowInfinityPoint: true, + mapToCurve: (scalars: bigint[]) => { + const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); + }, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, P): boolean => { + return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + // Older version: https://eprint.iacr.org/2019/814.pdf + // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O + // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero(); + }, + // Maps the point into the prime-order subgroup G2. + // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = bls12_381.params.x; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, + fromBytes: (bytes: Uint8Array): AffinePoint => { + bytes = bytes.slice(); + const m_byte = bytes[0] & 0xe0; + if (m_byte === 0x20 || m_byte === 0x60 || m_byte === 0xe0) { + throw new Error('Invalid encoding flag: ' + m_byte); + } + const bitC = m_byte & 0x80; // compression bit + const bitI = m_byte & 0x40; // point at infinity bit + const bitS = m_byte & 0x20; // sign bit + const L = Fp.BYTES; + const slc = (b: Uint8Array, from: number, to?: number) => bytesToNumberBE(b.slice(from, to)); + if (bytes.length === 96 && bitC) { + const b = bls12_381.params.G2b; + const P = Fp.ORDER; + + bytes[0] = bytes[0] & 0x1f; // clear flags + if (bitI) { + // check that all bytes are 0 + if (bytes.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { + throw new Error('Invalid compressed G2 point'); + } + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x_1 = slc(bytes, 0, L); + const x_0 = slc(bytes, L, 2 * L); + const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) }); + const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b + let y = Fp2.sqrt(right); + const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n; + y = bitS > 0 && Y_bit > 0 ? y : Fp2.neg(y); + return { x, y }; + } else if (bytes.length === 192 && !bitC) { + // Check if the infinity flag is set + if ((bytes[0] & (1 << 6)) !== 0) { + return { x: Fp2.ZERO, y: Fp2.ZERO }; + } + const x1 = slc(bytes, 0, L); + const x0 = slc(bytes, L, 2 * L); + const y1 = slc(bytes, 2 * L, 3 * L); + const y0 = slc(bytes, 3 * L, 4 * L); + return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) }; + } else { + throw new Error('Invalid point G2, expected 96/192 bytes'); + } + }, + toBytes: (c, point, isCompressed) => { + const { BYTES: len, ORDER: P } = Fp; + const isZero = point.equals(c.ZERO); + const { x, y } = point.toAffine(); + if (isCompressed) { + if (isZero) return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len)); + const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P); + // set compressed & sign bits (looks like different offsets than for G1/Fp?) + let x_1 = bitSet(x.c1, C_BIT_POS, flag); + x_1 = bitSet(x_1, S_BIT_POS, true); + return concatB(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + } else { + if (isZero) return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6; + const { re: x0, im: x1 } = Fp2.reim(x); + const { re: y0, im: y1 } = Fp2.reim(y); + return concatB( + numberToBytesBE(x1, len), + numberToBytesBE(x0, len), + numberToBytesBE(y1, len), + numberToBytesBE(y0, len) + ); + } + }, + Signature: { + // TODO: Optimize, it's very slow because of sqrt. + fromHex(hex: Hex): ProjPointType { + hex = ensureBytes('signatureHex', hex); + const P = Fp.ORDER; + const half = hex.length / 2; + if (half !== 48 && half !== 96) + throw new Error('Invalid compressed signature length, must be 96 or 192'); + const z1 = bytesToNumberBE(hex.slice(0, half)); + const z2 = bytesToNumberBE(hex.slice(half)); + // Indicates the infinity point + const bflag1 = bitGet(z1, I_BIT_POS); + if (bflag1 === _1n) return bls12_381.G2.ProjectivePoint.ZERO; + + const x1 = Fp.create(z1 & Fp.MASK); + const x2 = Fp.create(z2); + const x = Fp2.create({ c0: x2, c1: x1 }); + const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4 + // The slow part + let y = Fp2.sqrt(y2); + if (!y) throw new Error('Failed to find a square root'); + + // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1 + // If y1 happens to be zero, then use the bit of y0 + const { re: y0, im: y1 } = Fp2.reim(y); + const aflag1 = bitGet(z1, 381); + const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1; + const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1; + if (isGreater || isZero) y = Fp2.neg(y); + const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); + point.assertValidity(); + return point; + }, + toRawBytes(point: ProjPointType) { + return signatureG2ToRawBytes(point); + }, + toHex(point: ProjPointType) { + return bytesToHex(signatureG2ToRawBytes(point)); + }, + }, + }, + params: { + x: BLS_X, // The BLS parameter x for BLS12-381 + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves + }, + htfDefaults, + hash: sha256, + randomBytes, +}); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/bn254.ts b/test/merkletreejs/node_modules/@noble/curves/src/bn254.ts new file mode 100644 index 0000000..64ccfe0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/bn254.ts @@ -0,0 +1,21 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import { Field } from './abstract/modular.js'; +/** + * bn254 pairing-friendly curve. + * Previously known as alt_bn_128, when it had 128-bit security. + * Recent research shown it's weaker, the naming has been adjusted to its prime bit count. + * https://github.com/zcash/zcash/issues/2502 + */ +export const bn254 = weierstrass({ + a: BigInt(0), + b: BigInt(3), + Fp: Field(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + Gx: BigInt(1), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/ed25519.ts b/test/merkletreejs/node_modules/@noble/curves/src/ed25519.ts new file mode 100644 index 0000000..da610dc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/ed25519.ts @@ -0,0 +1,486 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { ExtPointType, twistedEdwards } from './abstract/edwards.js'; +import { montgomery } from './abstract/montgomery.js'; +import { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js'; +import { + bytesToHex, + bytesToNumberLE, + ensureBytes, + equalBytes, + Hex, + numberToBytesLE, +} from './abstract/utils.js'; +import { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js'; +import { AffinePoint } from './abstract/curve.js'; + +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + */ + +const ED25519_P = BigInt( + '57896044618658097711785492504343953926634992332820282019728792003956564819949' +); +// √(-1) aka √(a) aka 2^((p-1)/4) +const ED25519_SQRT_M1 = BigInt( + '19681161376707505956807079304988542015446066515923890162744021073123829784752' +); + +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5); +// prettier-ignore +const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + +function ed25519_pow_2_252_3(x: bigint) { + const P = ED25519_P; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ To pow to (p+3)/8, multiply it by x. + return { pow_p_5_8, b2 }; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} + +// sqrt(u/v) +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ED25519_P; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} + +// Just in case +export const ED25519_TORSION_SUBGROUP = [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]; + +const Fp = Field(ED25519_P, undefined, true); + +const ed25519Defaults = { + // Param: a + a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster + // d is equal to -121665/121666 over finite field. + // Negative number is P - number, and division is invert(number, P) + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n + Fp, + // Subgroup order: how many points curve has + // 2n**252n + 27742317777372353535851937790883648493n; + n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), + hash: sha512, + randomBytes, + adjustScalarBytes, + // dom2 + // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. + // Constant-time, u/√v + uvRatio, +} as const; + +export const ed25519 = twistedEdwards(ed25519Defaults); + +function ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) { + if (ctx.length > 255) throw new Error('Context is too big'); + return concatBytes( + utf8ToBytes('SigEd25519 no Ed25519 collisions'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); +} + +export const ed25519ctx = twistedEdwards({ ...ed25519Defaults, domain: ed25519_domain }); +export const ed25519ph = twistedEdwards({ + ...ed25519Defaults, + domain: ed25519_domain, + prehash: sha512, +}); + +export const x25519 = /* @__PURE__ */ (() => + montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, // n is 253 bits + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x: bigint): bigint => { + const P = ED25519_P; + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P); + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts ed25519 public key to x25519 public key. Uses formula: + * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * @example + * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey()); + * const aPriv = x25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array { + const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +/** + * Converts ed25519 secret key to x25519 secret key. + * @example + * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey()); + * const aPriv = ed25519.utils.randomPrivateKey(); + * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub) + */ +export function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array { + const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32)); + return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32); +} + +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since +// SageMath returns different root first and everything falls apart + +const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic + +const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1 +const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1) +const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic +const ELL2_J = BigInt(486662); + +// prettier-ignore +function map_to_curve_elligator2_curve25519(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} + +const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0 +function map_to_curve_elligator2_edwards25519(u: bigint) { + const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + + const inv = Fp.invertBatch([xd, yd]); // batch division + return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed25519.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]), + { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +function assertRstPoint(other: unknown) { + if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected'); +} + +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = BigInt( + '25063068953384623474111414158702152701244531502492656460079210482610430750235' +); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = BigInt( + '54469307008909316920995813868745141605393597292927456921205312896311721017578' +); +// 1-d² +const ONE_MINUS_D_SQ = BigInt( + '1159843021668779879193775521855586647937357759715417654439879720876111806838' +); +// (d-1)² +const D_MINUS_ONE_SQ = BigInt( + '40440834346308536858101042469323190826248399146238708352240133220865137265952' +); +// Calculates 1/√(number) +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const bytes255ToNumberLE = (bytes: Uint8Array) => + ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B); + +type ExtendedPoint = ExtPointType; + +// Computes Elligator map for Ristretto +// https://ristretto.group/formulas/elligator.html +function calcElligatorRistrettoMap(r0: bigint): ExtendedPoint { + const { d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) s_ = mod(-s_); + if (!Ns_D_is_sq) s = s_; // 7 + if (!Ns_D_is_sq) c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint, + * but it should work in its own namespace: do not combine those two. + * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448 + */ +class RistPoint { + static BASE: RistPoint; + static ZERO: RistPoint; + // Private property to discourage combining ExtendedPoint + RistrettoPoint + // Always use Ristretto encoding/decoding instead. + constructor(private readonly ep: ExtendedPoint) {} + + static fromAffine(ap: AffinePoint) { + return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap)); + } + + /** + * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`. + * The hash-to-group operation applies Elligator twice and adds the results. + * **Note:** this is one-way map, there is no conversion from point to hash. + * https://ristretto.group/formulas/elligator.html + * @param hex 64-byte output of a hash function + */ + static hashToCurve(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHash', hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new RistPoint(R1.add(R2)); + } + + /** + * Converts ristretto-encoded string to ristretto point. + * https://ristretto.group/formulas/decoding.html + * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: Hex): RistPoint { + hex = ensureBytes('ristrettoHex', hex, 32); + const { a, d } = ed25519.CURVE; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg); + return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t)); + } + + /** + * Encodes ristretto point to Uint8Array. + * https://ristretto.group/formulas/encoding.html + */ + toRawBytes(): Uint8Array { + let { ex: x, ey: y, ez: z, et: t } = this.ep; + const P = ed25519.CURVE.Fp.ORDER; + const mod = ed25519.CURVE.Fp.create; + const u1 = mod(mod(z + y) * mod(z - y)); // 1 + const u2 = mod(x * y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * t); // 6 + let D: bigint; // 7 + if (isNegativeLE(t * zInv, P)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } else { + D = D2; // 8 + } + if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9 + let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) s = mod(-s); + return numberToBytesLE(s, 32); // 11 + } + + toHex(): string { + return bytesToHex(this.toRawBytes()); + } + + toString(): string { + return this.toHex(); + } + + // Compare one point to another. + equals(other: RistPoint): boolean { + assertRstPoint(other); + const { ex: X1, ey: Y1 } = this.ep; + const { ex: X2, ey: Y2 } = other.ep; + const mod = ed25519.CURVE.Fp.create; + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + + add(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.add(other.ep)); + } + + subtract(other: RistPoint): RistPoint { + assertRstPoint(other); + return new RistPoint(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): RistPoint { + return new RistPoint(this.ep.multiplyUnsafe(scalar)); + } +} +export const RistrettoPoint = /* @__PURE__ */ (() => { + if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE); + if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO); + return RistPoint; +})(); + +// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/ +// Appendix B. Hashing to ristretto255 +export const hash_to_ristretto255 = (msg: Uint8Array, options: htfBasicOpts) => { + const d = options.DST; + const DST = typeof d === 'string' ? utf8ToBytes(d) : d; + const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512); + const P = RistPoint.hashToCurve(uniform_bytes); + return P; +}; diff --git a/test/merkletreejs/node_modules/@noble/curves/src/ed448.ts b/test/merkletreejs/node_modules/@noble/curves/src/ed448.ts new file mode 100644 index 0000000..b0cf63e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/ed448.ts @@ -0,0 +1,247 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3'; +import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { mod, pow2, Field } from './abstract/modular.js'; +import { montgomery } from './abstract/montgomery.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * * X448 ECDH + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ + +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439' +); + +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x: bigint): bigint { + const P = ed448P; + // prettier-ignore + const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} + +function adjustScalarBytes(bytes: Uint8Array): Uint8Array { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} + +const Fp = Field(ed448P, 456, true); +const _4n = BigInt(4); + +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt( + '726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358' + ), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt( + '181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779' + ), + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt( + '224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710' + ), + Gy: BigInt( + '298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660' + ), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => { + if (ctx.length > 255) throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes( + utf8ToBytes('SigEd448'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ); + }, + + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + uvRatio: (u: bigint, v: bigint): { isValid: boolean; value: bigint } => { + const P = ed448P; + // https://datatracker.ietf.org/doc/html/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; + }, +} as const; + +export const ed448 = twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +export const ed448ph = twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); + +export const x448 = /* @__PURE__ */ (() => + montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x: bigint): bigint => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, + }))(); + +/** + * Converts edwards448 public key to x448 public key. Uses formula: + * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + * @example + * const aPub = ed448.getPublicKey(utils.randomPrivateKey()); + * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub)) + */ +export function edwardsToMontgomeryPub(edwardsPub: string | Uint8Array): Uint8Array { + const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); + const _1n = BigInt(1); + return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n))); +} +export const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated + +// Hash To Curve Elligator2 Map +const ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_J = BigInt(156326); +function map_to_curve_elligator2_curve448(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +function map_to_curve_elligator2_edwards448(u: bigint) { + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + + const inv = Fp.invertBatch([xEd, yEd]); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} + +const htf = /* @__PURE__ */ (() => + createHasher( + ed448.ExtendedPoint, + (scalars: bigint[]) => map_to_curve_elligator2_edwards448(scalars[0]), + { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: Fp.ORDER, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/index.ts b/test/merkletreejs/node_modules/@noble/curves/src/index.ts new file mode 100644 index 0000000..0ffab52 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/index.ts @@ -0,0 +1 @@ +throw new Error('Incorrect usage. Import submodules instead'); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/jubjub.ts b/test/merkletreejs/node_modules/@noble/curves/src/jubjub.ts new file mode 100644 index 0000000..203cfa1 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/jubjub.ts @@ -0,0 +1,58 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha512'; +import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { twistedEdwards } from './abstract/edwards.js'; +import { blake2s } from '@noble/hashes/blake2s'; +import { Field } from './abstract/modular.js'; + +/** + * jubjub Twisted Edwards curve. + * https://neuromancer.sk/std/other/JubJub + * jubjub does not use EdDSA, so `hash`/sha512 params are passed because interface expects them. + */ + +export const jubjub = twistedEdwards({ + // Params: a, d + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + // Finite field 𝔽p over which we'll do calculations + // Same value as bls12-381 Fr (not Fp) + Fp: Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')), + // Subgroup order: how many points curve has + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + // Cofactor + h: BigInt(8), + // Base point (x, y) aka generator point + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), + hash: sha512, + randomBytes, +} as const); + +const GH_FIRST_BLOCK = utf8ToBytes( + '096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0' +); + +// Returns point at JubJub curve which is prime order and not zero +export function groupHash(tag: Uint8Array, personalization: Uint8Array) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(GH_FIRST_BLOCK); + h.update(tag); + // NOTE: returns ExtendedPoint, in case it will be multiplied later + let p = jubjub.ExtendedPoint.fromHex(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub.CURVE.h); + if (p.equals(jubjub.ExtendedPoint.ZERO)) throw new Error('Point has small order'); + return p; +} + +export function findGroupHash(m: Uint8Array, personalization: Uint8Array) { + const tag = concatBytes(m, new Uint8Array([0])); + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + return groupHash(tag, personalization); + } catch (e) {} + } + throw new Error('findGroupHash tag overflow'); +} diff --git a/test/merkletreejs/node_modules/@noble/curves/src/p256.ts b/test/merkletreejs/node_modules/@noble/curves/src/p256.ts new file mode 100644 index 0000000..164c470 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/p256.ts @@ -0,0 +1,48 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha256 } from '@noble/hashes/sha256'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 + +const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A = Fp.create(BigInt('-3')); +const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); + +// prettier-ignore +export const p256 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +} as const, sha256); +export const secp256r1 = p256; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-10')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp256r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/p384.ts b/test/merkletreejs/node_modules/@noble/curves/src/p384.ts new file mode 100644 index 0000000..436de9b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/p384.ts @@ -0,0 +1,52 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha384 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp = Field(P); +const CURVE_A = Fp.create(BigInt('-3')); +// prettier-ignore +const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); + +// prettier-ignore +export const p384 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +} as const, sha384); +export const secp384r1 = p384; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE_A, + B: CURVE_B, + Z: Fp.create(BigInt('-12')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp384r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/p521.ts b/test/merkletreejs/node_modules/@noble/curves/src/p521.ts new file mode 100644 index 0000000..cc9fbbc --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/p521.ts @@ -0,0 +1,68 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { createCurve } from './_shortw_utils.js'; +import { sha512 } from '@noble/hashes/sha512'; +import { Field } from './abstract/modular.js'; +import { mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import { createHasher } from './abstract/hash-to-curve.js'; + +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 + +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp = Field(P); + +const CURVE = { + a: Fp.create(BigInt('-3')), + b: BigInt( + '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00' + ), + Fp, + n: BigInt( + '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409' + ), + Gx: BigInt( + '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66' + ), + Gy: BigInt( + '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650' + ), + h: BigInt(1), +}; + +// prettier-ignore +export const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +} as const, sha512); +export const secp521r1 = p521; + +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: CURVE.a, + B: CURVE.b, + Z: Fp.create(BigInt('-4')), + }))(); + +const htf = /* @__PURE__ */ (() => + createHasher(secp521r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, + }))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/pasta.ts b/test/merkletreejs/node_modules/@noble/curves/src/pasta.ts new file mode 100644 index 0000000..faed89e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/pasta.ts @@ -0,0 +1,31 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { weierstrass } from './abstract/weierstrass.js'; +import { getHash } from './_shortw_utils.js'; +import * as mod from './abstract/modular.js'; + +export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001'); +export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001'); + +// https://neuromancer.sk/std/other/Pallas +export const pallas = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(p), + n: q, + Gx: mod.mod(BigInt(-1), p), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); +// https://neuromancer.sk/std/other/Vesta +export const vesta = weierstrass({ + a: BigInt(0), + b: BigInt(5), + Fp: mod.Field(q), + n: p, + Gx: mod.mod(BigInt(-1), q), + Gy: BigInt(2), + h: BigInt(1), + ...getHash(sha256), +}); diff --git a/test/merkletreejs/node_modules/@noble/curves/src/secp256k1.ts b/test/merkletreejs/node_modules/@noble/curves/src/secp256k1.ts new file mode 100644 index 0000000..7119222 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/curves/src/secp256k1.ts @@ -0,0 +1,274 @@ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +import { Field, mod, pow2 } from './abstract/modular.js'; +import { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js'; +import type { Hex, PrivKey } from './abstract/utils.js'; +import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js'; +import { createHasher, isogenyMap } from './abstract/hash-to-curve.js'; +import { createCurve } from './_shortw_utils.js'; + +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b; + +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y: bigint): bigint { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root'); + return root; +} + +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); + +export const secp256k1 = createCurve( + { + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k: bigint) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, + sha256 +); + +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {}; +function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} + +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1); +const numTo32b = (n: bigint) => numberToBytesBE(n, 32); +const modP = (x: bigint) => mod(x, secp256k1P); +const modN = (x: bigint) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q: PointType, a: bigint, b: bigint) => + Point.BASE.multiplyAndAddUnsafe(Q, a, b); + +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv: PrivKey) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x: bigint): PointType { + if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args: Uint8Array[]): bigint { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} + +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey: Hex): Uint8Array { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} + +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign( + message: Hex, + privateKey: PrivKey, + auxRand: Hex = randomBytes(32) +): Uint8Array { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced'); + return sig; +} + +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } catch (error) { + return false; + } +} + +export const schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))(); + +const isoMap = /* @__PURE__ */ (() => + isogenyMap( + Fp, + [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]] + ))(); +const mapSWU = /* @__PURE__ */ (() => + mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), + }))(); +const htf = /* @__PURE__ */ (() => + createHasher( + secp256k1.ProjectivePoint, + (scalars: bigint[]) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); + }, + { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + } + ))(); +export const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +export const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); diff --git a/test/merkletreejs/node_modules/@noble/hashes/LICENSE b/test/merkletreejs/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/README.md b/test/merkletreejs/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..83f6dd8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/README.md @@ -0,0 +1,536 @@ +# noble-hashes + +Audited & minimal JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2 & Scrypt. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: chained tests, sliding window tests, DoS tests, fuzzing +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🐢 Scrypt supports `N: 2**22`, while other implementations are limited to `2**20` +- 🦘 SHA3 supports Keccak, TupleHash, KangarooTwelve and MarsupilamiFourteen +- 🪶 Just 3.4k lines / 17KB gzipped. SHA256-only is 240 lines / 3KB gzipped + +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported in all major browsers and stable node.js versions +- All releases are signed with PGP keys +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [curves](https://github.com/paulmillr/noble-curves) + (4kb versions [secp256k1](https://github.com/paulmillr/noble-secp256k1), + [ed25519](https://github.com/paulmillr/noble-ed25519)), + [hashes](https://github.com/paulmillr/noble-hashes) + +## Usage + +> npm install @noble/hashes + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +The library is tree-shaking-friendly and does not expose root entry point as +`@noble/hashes`. Instead, you need to import specific primitives. +This is done to ensure small size of your apps. + +```js +import { sha256 } from '@noble/hashes/sha256'; // ECMAScript modules (ESM) and Common.js +// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha256'; // Deno +console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] +// you could also pass strings that will be UTF8-encoded to Uint8Array +console.log(sha256('abc')); // == sha256(new TextEncoder().encode('abc')) + +// sha384 is here, because it uses same internals as sha512 +import { sha512, sha512_256, sha384 } from '@noble/hashes/sha512'; +// prettier-ignore +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3'; +// prettier-ignore +import { + cshake128, cshake256, kmac128, kmac256, + k12, m14, + tuplehash256, parallelhash256, keccakprg +} from '@noble/hashes/sha3-addons'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { blake3 } from '@noble/hashes/blake3'; +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { hmac } from '@noble/hashes/hmac'; +import { hkdf } from '@noble/hashes/hkdf'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; + +import { sha1 } from '@noble/hashes/sha1'; // legacy + +// small utility method that converts bytes to hex +import { bytesToHex as toHex } from '@noble/hashes/utils'; +console.log(toHex(sha256('abc'))); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +``` + +## API + +All hash functions: + +- can be called directly, with `Uint8Array`. +- return `Uint8Array` +- can receive `string`, which is automatically converted to `Uint8Array` + via utf8 encoding **(not hex)** +- support hashing 4GB of data per update on 64-bit systems (unlimited with streaming) + +```ts +function hash(message: Uint8Array | string): Uint8Array; +hash(new Uint8Array([1, 3])); +hash('string') == hash(new TextEncoder().encode('string')); +``` + +All hash functions can be constructed via `hash.create()` method: + +- the result is `Hash` subclass instance, which has `update()` and `digest()` methods +- `digest()` finalizes the hash and makes it no longer usable + +```ts +hash + .create() + .update(new Uint8Array([1, 3])) + .digest(); +``` + +_Some_ hash functions can also receive `options` object, which can be either passed as a: + +- second argument to hash function: `blake3('abc', { key: 'd', dkLen: 32 })` +- first argument to class initializer: `blake3.create({ context: 'e', dkLen: 32 })` + +## Modules + +- [SHA2 (sha256, sha384, sha512, sha512_256)](#sha2-sha256-sha384-sha512-sha512_256) +- [SHA3 (FIPS, SHAKE, Keccak)](#sha3-fips-shake-keccak) +- [SHA3 Addons (cSHAKE, KMAC, KangarooTwelve, MarsupilamiFourteen)](#sha3-addons-cshake-kmac-tuplehash-parallelhash-kangarootwelve-marsupilamifourteen) +- [RIPEMD-160](#ripemd-160) +- [BLAKE2b, BLAKE2s](#blake2b-blake2s) +- [BLAKE3](#blake3) +- [SHA1 (legacy)](#sha1-legacy) +- [HMAC](#hmac) +- [HKDF](#hkdf) +- [PBKDF2](#pbkdf2) +- [Scrypt](#scrypt) +- [ESKDF](#eskdf) +- [utils](#utils) + +##### SHA2 (sha256, sha384, sha512, sha512_256) + +```typescript +import { sha256 } from '@noble/hashes/sha256'; +const h1a = sha256('abc'); +const h1b = sha256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +```typescript +import { sha512 } from '@noble/hashes/sha512'; +const h2a = sha512('abc'); +const h2b = sha512 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA512/256 variant +import { sha512_256 } from '@noble/hashes/sha512'; +const h3a = sha512_256('abc'); +const h3b = sha512_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA384 +import { sha384 } from '@noble/hashes/sha512'; +const h4a = sha384('abc'); +const h4b = sha384 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +##### SHA3 (FIPS, SHAKE, Keccak) + +```typescript +import { + sha3_224, + sha3_256, + sha3_384, + sha3_512, + keccak_224, + keccak_256, + keccak_384, + keccak_512, + shake128, + shake256, +} from '@noble/hashes/sha3'; +const h5a = sha3_256('abc'); +const h5b = sha3_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +const h6a = keccak_256('abc'); +const h7a = shake128('abc', { dkLen: 512 }); +const h7b = shake256('abc', { dkLen: 512 }); +``` + +See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +##### SHA3 Addons (cSHAKE, KMAC, TupleHash, ParallelHash, KangarooTwelve, MarsupilamiFourteen) + +```typescript +import { + cshake128, + cshake256, + kmac128, + kmac256, + k12, + m14, + tuplehash128, + tuplehash256, + parallelhash128, + parallelhash256, + keccakprg, +} from '@noble/hashes/sha3-addons'; +const h7c = cshake128('abc', { personalization: 'def' }); +const h7d = cshake256('abc', { personalization: 'def' }); +const h7e = kmac128('key', 'message'); +const h7f = kmac256('key', 'message'); +const h7h = k12('abc'); +const h7g = m14('abc'); +const h7i = tuplehash128(['ab', 'c']); // tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash(['abc']) +// Same as k12/blake3, but without reduced number of rounds. Doesn't speedup anything due lack of SIMD and threading, +// added for compatibility. +const h7j = parallelhash128('abc', { blockLen: 8 }); +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.feed('test'); +const rand1b = p.fetch(1); +``` + +- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): + cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants +- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), + [RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) + and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with + reduced number of rounds (same as Blake3 and ParallelHash). +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak + +##### RIPEMD-160 + +```typescript +import { ripemd160 } from '@noble/hashes/ripemd160'; +// function ripemd160(data: Uint8Array): Uint8Array; +const hash8 = ripemd160('abc'); +const hash9 = ripemd160() + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), +[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) + +##### BLAKE2b, BLAKE2s + +```typescript +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +const h10a = blake2s('abc'); +const b2params = { key: new Uint8Array([1]), personalization: t, salt: t, dkLen: 32 }; +const h10b = blake2s('abc', b2params); +const h10c = blake2s + .create(b2params) + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net). + +##### BLAKE3 + +```typescript +import { blake3 } from '@noble/hashes/blake3'; +// All params are optional +const h11 = blake3('abc', { dkLen: 256, key: 'def', context: 'fji' }); +``` + +##### SHA1 (legacy) + +SHA1 was cryptographically broken, however, it was not broken for cases like HMAC. + +See [RFC4226 B.2](https://datatracker.ietf.org/doc/html/rfc4226#appendix-B.2). + +Don't use it for a new protocol. + +```typescript +import { sha1 } from '@noble/hashes/sha1'; +const h12 = sha1('def'); +``` + +##### HMAC + +```typescript +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +const mac1 = hmac(sha256, 'key', 'message'); +const mac2 = hmac.create(sha256, Uint8Array.from([1, 2, 3])).update(Uint8Array.from([4, 5, 6])).digest(); +``` + +Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +##### HKDF + +```typescript +import { hkdf } from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = 'abc'; +const dkLen = 32; +const hk1 = hkdf(sha256, inputKey, salt, info, dkLen); + +// == same as +import * as hkdf from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +const prk = hkdf.extract(sha256, inputKey, salt); +const hk2 = hkdf.expand(sha256, prk, info, dkLen); +``` + +Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +##### PBKDF2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 32, + dkLen: 32, +}); +``` + +Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +##### Scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 22, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). +- `dkLen` is the length of output bytes +- It is common to use N from `2**10` to `2**22` and `{r: 8, p: 1, dkLen: 32}` +- `onProgress` can be used with async version of the function to report progress to a user. + +Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, +which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent +DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to +`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase +`maxmem` using the formula above. + +_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS +libs. Many other implementations don't support it. We cannot support `2**23`, +because there is a limitation in JS engines that makes allocating +arrays bigger than 4GB impossible, but we're looking into other possible solutions. + +##### Argon2 + +Experimental Argon2 RFC 9106 implementation. It may be removed at any time. + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2'; +const result = argon2id('password', 'salt', { t: 2, m: 65536, p: 1 }); +``` + +##### ESKDF + +A tiny stretched KDF for various applications like AES key-gen. Takes >= 2 seconds to execute. + +Takes following params: + +- `username` - username, email, or identifier, min: 8 characters, should have enough entropy +- `password` - min: 8 characters, should have enough entropy + +Produces ESKDF instance that has `deriveChildKey(protocol, accountId[, options])` function. + +- `protocol` - 3-15 character protocol name +- `accountId` - numeric identifier of account +- `options` - `keyLength: 32` with specified key length (default is 32), + or `modulus: 2n ** 221n - 17n` with specified modulus. It will fetch modulus + 64 bits of + data, execute modular division. The result will have negligible bias as per FIPS 186 B.4.1. + Can be used to generate, for example, elliptic curve keys. + +Takes username and password, then takes protocol name and account id. + +```typescript +import { eskdf } from '@noble/hashes/eskdf'; +const kdf = await eskdf('example@university', 'beginning-new-example'); +console.log(kdf.fingerprint); +const key1 = kdf.deriveChildKey('aes', 0); +const key2 = kdf.deriveChildKey('aes', 0, { keyLength: 16 }); +const ecc1 = kdf.deriveChildKey('ecc', 0, { modulus: 2n ** 252n - 27742317777372353535851937790883648493n }) +kdf.expire(); +``` + +##### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +## Security + +Noble is production-ready. + +1. The library has been audited in Jan 2022 by an independent security firm + cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). + No vulnerabilities have been found. The audit has been funded by + [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io). + Modules `blake3`, `sha3-addons`, `sha1` and `argon2` have not been audited. + See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: + _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to + achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. + Even statically typed Rust, a language without GC, + [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) + for some cases. If your goal is absolute security, don't use any JS lib — including + bindings to native ones. Use low-level libraries & languages. Nonetheless we're + targetting algorithmic constant time. +4. Memory dump considerations: the library shares state buffers between hash + function calls. The buffers are zeroed-out after each call. However, if an attacker + can read application memory, you are doomed in any case: + - At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings + - Input from a file will stay in file buffers + - Input / output will be re-used multiple times in application which means + it could stay in memory + - `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory + - There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +We consider infrastructure attacks like rogue NPM modules very important; that's +why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. +If your app uses 500 dependencies, any dep could get hacked and you'll be downloading +malware with every `npm install`. Our goal is to minimize this attack vector. + +## Speed + +Benchmarks measured on Apple M1 with macOS 12. +Note that PBKDF2 and Scrypt are tested with extremely high work factor. +To run benchmarks, execute `npm run bench:install` and then `npm run bench` + +``` +SHA256 32B x 1,219,512 ops/sec @ 820ns/op ± 2.58% (min: 625ns, max: 4ms) +SHA384 32B x 512,032 ops/sec @ 1μs/op +SHA512 32B x 509,943 ops/sec @ 1μs/op +SHA3-256, keccak256, shake256 32B x 199,600 ops/sec @ 5μs/op +Kangaroo12 32B x 336,360 ops/sec @ 2μs/op +Marsupilami14 32B x 298,418 ops/sec @ 3μs/op +BLAKE2b 32B x 379,794 ops/sec @ 2μs/op +BLAKE2s 32B x 515,995 ops/sec @ 1μs/op ± 1.07% (min: 1μs, max: 4ms) +BLAKE3 32B x 588,235 ops/sec @ 1μs/op ± 1.36% (min: 1μs, max: 5ms) +RIPEMD160 32B x 1,140,250 ops/sec @ 877ns/op ± 3.12% (min: 708ns, max: 6ms) +HMAC-SHA256 32B x 377,358 ops/sec @ 2μs/op + +HKDF-SHA256 32B x 108,377 ops/sec @ 9μs/op +PBKDF2-HMAC-SHA256 262144 x 3 ops/sec @ 326ms/op +PBKDF2-HMAC-SHA512 262144 x 1 ops/sec @ 970ms/op +Scrypt r: 8, p: 1, n: 262144 x 1 ops/sec @ 616ms/op +``` + +Compare to native node.js implementation that uses C bindings instead of pure-js code: + +``` +SHA256 32B node x 1,302,083 ops/sec @ 768ns/op ± 10.54% (min: 416ns, max: 7ms) +SHA384 32B node x 975,609 ops/sec @ 1μs/op ± 11.32% (min: 625ns, max: 8ms) +SHA512 32B node x 983,284 ops/sec @ 1μs/op ± 11.24% (min: 625ns, max: 8ms) +SHA3-256 32B node x 910,746 ops/sec @ 1μs/op ± 12.19% (min: 666ns, max: 10ms) +keccak, k12, m14 are not implemented +BLAKE2b 32B node x 967,117 ops/sec @ 1μs/op ± 11.26% (min: 625ns, max: 9ms) +BLAKE2s 32B node x 1,055,966 ops/sec @ 947ns/op ± 11.07% (min: 583ns, max: 7ms) +BLAKE3 is not implemented +RIPEMD160 32B node x 1,002,004 ops/sec @ 998ns/op ± 10.66% (min: 625ns, max: 7ms) +HMAC-SHA256 32B node x 919,963 ops/sec @ 1μs/op ± 6.13% (min: 833ns, max: 5ms) +HKDF-SHA256 32 node x 369,276 ops/sec @ 2μs/op ± 13.59% (min: 1μs, max: 9ms) +PBKDF2-HMAC-SHA256 262144 node x 25 ops/sec @ 39ms/op +PBKDF2-HMAC-SHA512 262144 node x 7 ops/sec @ 132ms/op +Scrypt r: 8, p: 1, n: 262144 node x 1 ops/sec @ 523ms/op +``` + +It is possible to [make this library 4x+ faster](./benchmark/README.md) by +_doing code generation of full loop unrolls_. We've decided against it. Reasons: + +- the library must be auditable, with minimum amount of code, and zero dependencies +- most method invocations with the lib are going to be something like hashing 32b to 64kb of data +- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead + +The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run. + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests. See [our approach to testing](./test/README.md) +5. `npm run test:dos` will test against DoS; by measuring function complexity. **Takes ~20 minutes** +6. `npm run test:big` will execute hashing on 4GB inputs, + scrypt with 1024 different `N, r, p` combinations, etc. **Takes several hours**. Using 8-32+ core CPU helps. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/test/merkletreejs/node_modules/@noble/hashes/_assert.d.ts b/test/merkletreejs/node_modules/@noble/hashes/_assert.d.ts new file mode 100644 index 0000000..b71d8e4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_assert.d.ts @@ -0,0 +1,21 @@ +export declare function number(n: number): void; +export declare function bool(b: boolean): void; +export declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +export declare function hash(hash: Hash): void; +export declare function exists(instance: any, checkFinished?: boolean): void; +export declare function output(out: any, instance: any): void; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; diff --git a/test/merkletreejs/node_modules/@noble/hashes/_assert.js b/test/merkletreejs/node_modules/@noble/hashes/_assert.js new file mode 100644 index 0000000..acf3491 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_assert.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_assert.js.map b/test/merkletreejs/node_modules/@noble/hashes/_assert.js.map new file mode 100644 index 0000000..94ac2c1 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":";;;AAAA,SAAgB,MAAM,CAAC,CAAS;IAC9B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,EAAE,CAAC,CAAC;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GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAND,wBAMC;AAED,MAAM,MAAM,GAAG;IACb,MAAM;IACN,IAAI;IACJ,KAAK;IACL,IAAI;IACJ,MAAM;IACN,MAAM;CACP,CAAC;AAEF,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_blake2.d.ts b/test/merkletreejs/node_modules/@noble/hashes/_blake2.d.ts new file mode 100644 index 0000000..352b978 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_blake2.d.ts @@ -0,0 +1,27 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE2> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/_blake2.js b/test/merkletreejs/node_modules/@noble/hashes/_blake2.js new file mode 100644 index 0000000..bf5dd93 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_blake2.js @@ -0,0 +1,111 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLAKE2 = exports.SIGMA = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +exports.SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +class BLAKE2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + _assert_js_1.default.number(blockLen); + _assert_js_1.default.number(outputLen); + _assert_js_1.default.number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + _assert_js_1.default.exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = (0, utils_js_1.u32)(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +exports.BLAKE2 = BLAKE2; +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_blake2.js.map b/test/merkletreejs/node_modules/@noble/hashes/_blake2.js.map new file mode 100644 index 0000000..88ca9c0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["src/_blake2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAuD;AACvD,gGAAgG;AAChG,kBAAkB;AACL,QAAA,KAAK,GAAG,IAAI,UAAU,CAAC;IAClC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EA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IAC/C,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACrE,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAM,EAAC;QAChE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AAlGD,wBAkGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_sha2.d.ts b/test/merkletreejs/node_modules/@noble/hashes/_sha2.d.ts new file mode 100644 index 0000000..883788f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_sha2.d.ts @@ -0,0 +1,23 @@ +import { Hash, Input } from './utils.js'; +export declare abstract class SHA2> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/_sha2.js b/test/merkletreejs/node_modules/@noble/hashes/_sha2.js new file mode 100644 index 0000000..398d446 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_sha2.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + _assert_js_1.default.exists(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = (0, utils_js_1.createView)(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.SHA2 = SHA2; +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_sha2.js.map b/test/merkletreejs/node_modules/@noble/hashes/_sha2.js.map new file mode 100644 index 0000000..cae147e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["src/_sha2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAA8D;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/F,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IAC9C,MAAM,EAAE,GAAG,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,CAAC;IACpC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IACzC,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AAC3C,CAAC;AAED,6BAA6B;AAC7B,MAAsB,IAAwB,SAAQ,eAAO;IAc3D,YACW,QAAgB,EAClB,SAAiB,EACf,SAAiB,EACjB,IAAa;QAEtB,KAAK,EAAE,CAAC;QALC,aAAQ,GAAR,QAAQ,CAAQ;QAClB,cAA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E,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACpE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AApGD,oBAoGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_u64.d.ts b/test/merkletreejs/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..9ac94f8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,35 @@ +export declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +export declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +export declare const toBig: (h: number, l: number) => bigint; +export declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (h: number, l: number) => number; + rotr32L: (h: number, l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; diff --git a/test/merkletreejs/node_modules/@noble/hashes/_u64.js b/test/merkletreejs/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..2e1936d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.add = exports.toBig = exports.split = exports.fromBig = void 0; +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h, l) => l; +const rotr32L = (h, l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig: exports.toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports.default = u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/_u64.js.map b/test/merkletreejs/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..aa363e0 --- /dev/null +++ b/test/merkletreejs/node_modules/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,EAAE,CAC3E,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,MAAM,KAAK,GAAG,CAAC,GAAW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK,EAAL,aAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kBAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/argon2.d.ts b/test/merkletreejs/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..15b6486 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,16 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; diff --git a/test/merkletreejs/node_modules/@noble/hashes/argon2.js b/test/merkletreejs/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..cf480c9 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,310 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argon2id = exports.argon2i = exports.argon2d = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const blake2b_js_1 = require("./blake2b.js"); +const _u64_js_1 = require("./_u64.js"); +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +var Types; +(function (Types) { + Types[Types["Argond2d"] = 0] = "Argond2d"; + Types[Types["Argon2i"] = 1] = "Argon2i"; + Types[Types["Argon2id"] = 2] = "Argon2id"; +})(Types || (Types = {})); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = _u64_js_1.default.add3L(Al, Bl, Cl); + return { h: _u64_js_1.default.add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = (0, utils_js_1.u8)(A); + const T = new Uint32Array(1); + const T8 = (0, utils_js_1.u8)(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b_js_1.blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b_js_1.blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = (0, blake2b_js_1.blake2b)(V)).subarray(0, 32), pos); + // Last block + out.set((0, blake2b_js_1.blake2b)(V, { dkLen: dkLen - pos }), pos); + return (0, utils_js_1.u32)(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = (0, utils_js_1.toBytes)(password); + salt = (0, utils_js_1.toBytes)(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + _assert_js_1.default.number(p); + _assert_js_1.default.number(dkLen); + _assert_js_1.default.number(m); + _assert_js_1.default.number(t); + _assert_js_1.default.number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (paralllelism) should be at least 1'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = (0, utils_js_1.toBytes)(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = (0, utils_js_1.toBytes)(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b_js_1.blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = (0, utils_js_1.u8)(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = (0, utils_js_1.u8)(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return (0, utils_js_1.u8)(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +const argon2d = (password, salt, opts) => argon2(Types.Argond2d, password, salt, opts); +exports.argon2d = argon2d; +const argon2i = (password, salt, opts) => argon2(Types.Argon2i, password, salt, opts); +exports.argon2i = argon2i; +const argon2id = (password, salt, opts) => argon2(Types.Argon2id, password, salt, opts); +exports.argon2id = argon2id; +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/argon2.js.map b/test/merkletreejs/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..ca36172 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAqD;AACrD,6CAAuC;AACvC,uCAA4B;AAE5B,8EAA8E;AAC9E,IAAK,KAIJ;AAJD,WAAK,KAAK;IACR,yCAAY,CAAA;IACZ,uCAAW,CAAA;IACX,yCAAY,CAAA;AACd,CAAC,EAJI,KAAK,KAAL,KAAK,QAIT;AAED,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjG,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE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I,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,OAAO,GAAG,CAAC,CAAC;gBAChE,KAAK,IAAI,KAAK,GAAG,QAAQ,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,EAAE;oBACxE,QAAQ,EAAE,CAAC;oBACX,YAAY,CACV,CAAC,EACD,OAAO,EACP,CAAC,EACD,CAAC,EACD,CAAC,EACD,KAAK,EACL,OAAO,EACP,UAAU,EACV,KAAK,EACL,MAAM,EACN,IAAI,EACJ,eAAe,EACf,OAAO,CACR,CAAC;iBACH;aACF;SACF;KACF;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAEM,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,OAAO,WAC2B;AACxC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADjC,QAAA,OAAO,WAC0B;AACvC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,QAAQ,YAC0B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake2b.d.ts b/test/merkletreejs/node_modules/@noble/hashes/blake2b.d.ts new file mode 100644 index 0000000..7a78c6b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +declare class BLAKE2b extends BLAKE2 { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake2b.js b/test/merkletreejs/node_modules/@noble/hashes/blake2b.js new file mode 100644 index 0000000..a25abda --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake2b.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Same as SHA-512 but LE +// prettier-ignore +const IV = new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = _blake2_js_1.SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2b = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake2b.js.map b/test/merkletreejs/node_modules/@noble/hashes/blake2b.js.map new file mode 100644 index 0000000..6cb986b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["src/blake2b.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAA4B;AAC5B,yCAAmE;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC;IACzB,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AACH,mBAAmB;AACnB,MAAM,GAAG,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEhC,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,GAAgB,EAAE,CAAS;IACjF,qBAAqB;IACrB,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,kBAAkB;IACtD,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,C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,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAG,IAAA,kCAAuB,EAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake2s.d.ts b/test/merkletreejs/node_modules/@noble/hashes/blake2s.d.ts new file mode 100644 index 0000000..d9dd59b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +export declare const IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +declare class BLAKE2s extends BLAKE2 { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake2s.js b/test/merkletreejs/node_modules/@noble/hashes/blake2s.js new file mode 100644 index 0000000..30bf033 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake2s.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2s = exports.compress = exports.IV = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +exports.IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 16); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 8); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +exports.compress = compress; +class BLAKE2s extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = exports.IV[0] | 0; + this.v1 = exports.IV[1] | 0; + this.v2 = exports.IV[2] | 0; + this.v3 = exports.IV[3] | 0; + this.v4 = exports.IV[4] | 0; + this.v5 = exports.IV[5] | 0; + this.v6 = exports.IV[6] | 0; + this.v7 = exports.IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake2_js_1.SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, exports.IV[0], exports.IV[1], exports.IV[2], exports.IV[3], l ^ exports.IV[4], h ^ exports.IV[5], isLast ? ~exports.IV[6] : exports.IV[6], exports.IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2s = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake2s.js.map b/test/merkletreejs/node_modules/@noble/hashes/blake2s.js.map new file mode 100644 index 0000000..ce187f2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAA4B;AAC5B,yCAAyE;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AACL,QAAA,EAAE,GAAG,IAAI,WAAW,CAAC;IAChC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AAEH,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,C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;;GAIG;AACU,QAAA,OAAO,GAAG,IAAA,kCAAuB,EAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake3.d.ts b/test/merkletreejs/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..13894cf --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE2 } from './_blake2.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +declare class BLAKE3 extends BLAKE2 implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake3.js b/test/merkletreejs/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..52689eb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,240 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake3 = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const _blake2_js_1 = require("./_blake2.js"); +const blake2s_js_1 = require("./blake2s.js"); +const utils_js_1 = require("./utils.js"); +// Flag bitset +var Flags; +(function (Flags) { + Flags[Flags["CHUNK_START"] = 1] = "CHUNK_START"; + Flags[Flags["CHUNK_END"] = 2] = "CHUNK_END"; + Flags[Flags["PARENT"] = 4] = "PARENT"; + Flags[Flags["ROOT"] = 8] = "ROOT"; + Flags[Flags["KEYED_HASH"] = 16] = "KEYED_HASH"; + Flags[Flags["DERIVE_KEY_CONTEXT"] = 32] = "DERIVE_KEY_CONTEXT"; + Flags[Flags["DERIVE_KEY_MATERIAL"] = 64] = "DERIVE_KEY_MATERIAL"; +})(Flags || (Flags = {})); +const SIGMA = (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends _blake2_js_1.BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + _assert_js_1.default.number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = (0, utils_js_1.toBytes)(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = (0, utils_js_1.u32)(key); + this.flags = flags | Flags.KEYED_HASH; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = (0, utils_js_1.u32)(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } + else { + this.IV = blake2s_js_1.IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = _u64_js_1.default.fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) + flags |= Flags.CHUNK_END; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = _u64_js_1.default.fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + _assert_js_1.default.exists(this, false); + _assert_js_1.default.bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + _assert_js_1.default.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + _assert_js_1.default.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/blake3.js.map b/test/merkletreejs/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..c7f09ac --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAA4B;AAC5B,6CAAsC;AACtC,6CAA4C;AAC5C,yCAA0F;AAE1F,cAAc;AACd,IAAK,KAQJ;AARD,WAAK,KAAK;IACR,+CAAoB,CAAA;IACpB,2CAAkB,CAAA;IAClB,qCAAe,CAAA;IACf,iCAAa,CAAA;IACb,8CAAmB,CAAA;IACnB,8DAA2B,CAAA;IAC3B,gEAA4B,CAAA;AAC9B,CAAC,EARI,KAAK,KAAL,KAAK,QAQT;AAED,MAAM,KAAK,GAAe,CAAC,GAAG,EAAE;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,CAAC,GAAa,EAAE,EAAE,CAChC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC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AC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,MAAM,GAAG,IAAA,qCAA0B,EAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/crypto.d.ts b/test/merkletreejs/node_modules/@noble/hashes/crypto.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/crypto.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/test/merkletreejs/node_modules/@noble/hashes/crypto.js b/test/merkletreejs/node_modules/@noble/hashes/crypto.js new file mode 100644 index 0000000..8226391 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/crypto.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/crypto.js.map b/test/merkletreejs/node_modules/@noble/hashes/crypto.js.map new file mode 100644 index 0000000..9f794e2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.d.ts b/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.js b/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.js new file mode 100644 index 0000000..a88676d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +const nc = require("node:crypto"); +exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.js.map b/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.js.map new file mode 100644 index 0000000..9287d27 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/eskdf.d.ts b/test/merkletreejs/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..f0fc54d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,46 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +type ESKDF = Promise Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +}>>; +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): ESKDF; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/eskdf.js b/test/merkletreejs/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..bc622b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.eskdf = exports.deriveMainSeed = exports.pbkdf2 = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const hkdf_js_1 = require("./hkdf.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const scrypt_js_1 = require("./scrypt.js"); +const utils_js_1 = require("./utils.js"); +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +function scrypt(password, salt) { + return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +exports.scrypt = scrypt; +// PBKDF2-HMAC-SHA256 +function pbkdf2(password, salt) { + return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +exports.pbkdf2 = pbkdf2; +// Combines two 32-byte byte arrays +function xor32(a, b) { + (0, _assert_js_1.bytes)(a, 32); + (0, _assert_js_1.bytes)(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +exports.deriveMainSeed = deriveMainSeed; +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = (0, utils_js_1.toBytes)(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + (0, utils_js_1.createView)(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = (0, utils_js_1.toBytes)(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = (0, utils_js_1.hexToBytes)(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + (0, _assert_js_1.bytes)(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +exports.eskdf = eskdf; +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/eskdf.js.map b/test/merkletreejs/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..70c49e9 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":";;;AAAA,6CAAoD;AACpD,uCAAiC;AACjC,2CAAqC;AACrC,2CAAgD;AAChD,2CAAgD;AAChD,yCAAyE;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAFD,wBAEC;AAED,qBAAqB;AACrB,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,O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M,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,WAAW,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,gCAAgC;QACzF,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;QAC5D,MAAM,GAAG,GAAG,IAAA,cAAI,EAAC,kBAAM,EAAE,IAAK,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QACvD,qCAAqC;QACrC,OAAO,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC;AAvBD,sBAuBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/_assert.js b/test/merkletreejs/node_modules/@noble/hashes/esm/_assert.js new file mode 100644 index 0000000..73a5c37 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_assert.js @@ -0,0 +1,43 @@ +export function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +export function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +export function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +export function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +export function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +export function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/_assert.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/_assert.js.map new file mode 100644 index 0000000..b36620a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,MAAM,CAAC,CAAS;IAC9B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,EAAE,CAAC,CAAC;AACzF,CAAC;AAED,MAAM,UAAU,IAAI,CAAC,CAAU;IAC7B,IAAI,OAAO,CAAC,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,KAA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,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/_blake2.js b/test/merkletreejs/node_modules/@noble/hashes/esm/_blake2.js new file mode 100644 index 0000000..42b621f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_blake2.js @@ -0,0 +1,107 @@ +import assert from './_assert.js'; +import { Hash, toBytes, u32 } from './utils.js'; +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +export class BLAKE2 extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + assert.number(blockLen); + assert.number(outputLen); + assert.number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + assert.exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + assert.exists(this); + assert.output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/_blake2.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/_blake2.js.map new file mode 100644 index 0000000..5fafed2 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["../src/_blake2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAS,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACvD,gGAAgG;AAChG,kBAAkB;AAClB,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC;IAClC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,E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/node_modules/@noble/hashes/esm/_sha2.js new file mode 100644 index 0000000..4d1bf27 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_sha2.js @@ -0,0 +1,114 @@ +import assert from './_assert.js'; +import { Hash, createView, toBytes } from './utils.js'; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +export class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + assert.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + assert.exists(this); + assert.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/_sha2.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/_sha2.js.map new file mode 100644 index 0000000..c9a4b7e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["../src/_sha2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAS,OAAO,EAAE,MAAM,YAAY,CAAC;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAA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_modules/@noble/hashes/esm/_u64.js b/test/merkletreejs/node_modules/@noble/hashes/esm/_u64.js new file mode 100644 index 0000000..40c88ac --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_u64.js @@ -0,0 +1,61 @@ +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +export function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +export function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +export const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h, l) => l; +const rotr32L = (h, l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +export function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/_u64.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/_u64.js.map new file mode 100644 index 0000000..8baa59c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["../src/_u64.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvC,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAExB,+EAA+E;AAC/E,MAAM,U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AE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/argon2.js b/test/merkletreejs/node_modules/@noble/hashes/esm/argon2.js new file mode 100644 index 0000000..73f8385 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/argon2.js @@ -0,0 +1,304 @@ +import assert from './_assert.js'; +import { toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import u64 from './_u64.js'; +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +var Types; +(function (Types) { + Types[Types["Argond2d"] = 0] = "Argond2d"; + Types[Types["Argon2i"] = 1] = "Argon2i"; + Types[Types["Argon2id"] = 2] = "Argon2id"; +})(Types || (Types = {})); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = u64.add3L(Al, Bl, Cl); + return { h: u64.add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assert.number(p); + assert.number(dkLen); + assert.number(m); + assert.number(t); + assert.number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (paralllelism) should be at least 1'); + if (dkLen < 1 || p >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +export const argon2d = (password, salt, opts) => argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password, salt, opts) => argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password, salt, opts) => argon2(Types.Argon2id, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/argon2.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/argon2.js.map new file mode 100644 index 0000000..2a46f5a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAS,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,GAAG,MAAM,WAAW,CAAC;AAE5B,8EAA8E;AAC9E,IAAK,KAIJ;AAJD,WAAK,KAAK;IACR,yCAAY,CAAA;IACZ,uCAAW,CAAA;IACX,yCAAY,CAAA;AACd,CAAC,EAJI,KAAK,KAAL,KAAK,QAIT;AAED,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjG,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,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AC;gBACrD,0BAA0B;gBAC1B,IAAI,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,OAAO,GAAG,CAAC,CAAC;gBAChE,KAAK,IAAI,KAAK,GAAG,QAAQ,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,EAAE;oBACxE,QAAQ,EAAE,CAAC;oBACX,YAAY,CACV,CAAC,EACD,OAAO,EACP,CAAC,EACD,CAAC,EACD,CAAC,EACD,KAAK,EACL,OAAO,EACP,UAAU,EACV,KAAK,EACL,MAAM,EACN,IAAI,EACJ,eAAe,EACf,OAAO,CACR,CAAC;iBACH;aACF;SACF;KACF;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC9C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/blake2b.js b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2b.js new file mode 100644 index 0000000..a52871c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2b.js @@ -0,0 +1,189 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; +// Same as SHA-512 but LE +// prettier-ignore +const IV = new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/blake2b.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2b.js.map new file mode 100644 index 0000000..5b5e5fa --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC;IACzB,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC;AACH,mBAAmB;AACnB,MAAM,GAAG,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEhC,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,GAAgB,EAA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CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC;QAC9B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,uBAAuB,CAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/blake2s.js b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2s.js new file mode 100644 index 0000000..ca92ef7 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2s.js @@ -0,0 +1,120 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +class BLAKE2s extends BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = u64.fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/blake2s.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2s.js.map new file mode 100644 index 0000000..47e74b1 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AAClB,MAAM,CAAC,MAAM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AAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,uBAAuB,CAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/blake3.js b/test/merkletreejs/node_modules/@noble/hashes/esm/blake3.js new file mode 100644 index 0000000..0e59be8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/blake3.js @@ -0,0 +1,237 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { u8, u32, toBytes, wrapXOFConstructorWithOpts } from './utils.js'; +// Flag bitset +var Flags; +(function (Flags) { + Flags[Flags["CHUNK_START"] = 1] = "CHUNK_START"; + Flags[Flags["CHUNK_END"] = 2] = "CHUNK_END"; + Flags[Flags["PARENT"] = 4] = "PARENT"; + Flags[Flags["ROOT"] = 8] = "ROOT"; + Flags[Flags["KEYED_HASH"] = 16] = "KEYED_HASH"; + Flags[Flags["DERIVE_KEY_CONTEXT"] = 32] = "DERIVE_KEY_CONTEXT"; + Flags[Flags["DERIVE_KEY_MATERIAL"] = 64] = "DERIVE_KEY_MATERIAL"; +})(Flags || (Flags = {})); +const SIGMA = (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + assert.number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } + else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = u64.fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) + flags |= Flags.CHUNK_END; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = u64.fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + assert.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/blake3.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/blake3.js.map new file mode 100644 index 0000000..f08f0fb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAS,EAAE,EAAE,GAAG,EAAE,OAAO,EAAW,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAE1F,cAAc;AACd,IAAK,KAQJ;AARD,WAAK,KAAK;IACR,+CAAoB,CAAA;IACpB,2CAAkB,CAAA;IAClB,qCAAe,CAAA;IACf,iCAAa,CAAA;IACb,8CAAmB,CAAA;IACnB,8DAA2B,CAAA;IAC3B,gEAA4B,CAAA;AAC9B,CAAC,EARI,KAAK,KAAL,KAAK,QAQT;AAED,MAAM,KAAK,GAAe,CAAC,GAAG,EAAE;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,I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,GAAe;QACrB,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC9E,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,GAAG,CAAC,KAAa;QACf,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACzB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,0BAA0B,CAAqB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/crypto.js b/test/merkletreejs/node_modules/@noble/hashes/esm/crypto.js new file mode 100644 index 0000000..8d499a0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/crypto.js @@ -0,0 +1,2 @@ +export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/crypto.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/crypto.js.map new file mode 100644 index 0000000..4b4fd3d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/cryptoNode.js b/test/merkletreejs/node_modules/@noble/hashes/esm/cryptoNode.js new file mode 100644 index 0000000..241f1da --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/cryptoNode.js @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/cryptoNode.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/cryptoNode.js.map new file mode 100644 index 0000000..f7ab75e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/eskdf.js b/test/merkletreejs/node_modules/@noble/hashes/esm/eskdf.js new file mode 100644 index 0000000..13253eb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/eskdf.js @@ -0,0 +1,155 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/eskdf.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/eskdf.js.map new file mode 100644 index 0000000..f53eebe --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["../src/eskdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAA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a,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/hkdf.js b/test/merkletreejs/node_modules/@noble/hashes/esm/hkdf.js new file mode 100644 index 0000000..d3a46e4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/hkdf.js @@ -0,0 +1,72 @@ +import assert from './_assert.js'; +import { toBytes } from './utils.js'; +import { hmac } from './hmac.js'; +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash, ikm, salt) { + assert.hash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = new Uint8Array([0]); +const EMPTY_BUFFER = new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash, prk, info, length = 32) { + assert.hash(hash); + assert.number(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/hkdf.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/hkdf.js.map new file mode 100644 index 0000000..6e80029 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC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C,SAAS,CAAC,CAAC;IACzC,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,EAAE,EAAE;QACjD,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC;QAC9B,oCAAoC;QACpC,2CAA2C;QAC3C,OAAO,CAAC,MAAM,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;aAC7C,MAAM,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,UAAU,CAAC,CAAC,CAAC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;KAC1B;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/hmac.js b/test/merkletreejs/node_modules/@noble/hashes/esm/hmac.js new file mode 100644 index 0000000..36ae4f4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/hmac.js @@ -0,0 +1,77 @@ +import assert from './_assert.js'; +import { Hash, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert.hash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assert.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert.exists(this); + assert.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/hmac.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/hmac.js.map new file mode 100644 index 0000000..e580ae4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACzD,kBAAkB;AAClB,MAAM,OAAO,IAAwB,SAAQ,IAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClB,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC;QACrC,wCAAwC;QACxC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1E,KAAK,IA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 No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/index.js b/test/merkletreejs/node_modules/@noble/hashes/esm/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/index.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/index.js.map new file mode 100644 index 0000000..90172aa --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/package.json b/test/merkletreejs/node_modules/@noble/hashes/esm/package.json new file mode 100644 index 0000000..cf1903a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/package.json @@ -0,0 +1,9 @@ +{ + "type": "module", + "browser": { + "node:crypto": false + }, + "node": { + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/pbkdf2.js b/test/merkletreejs/node_modules/@noble/hashes/esm/pbkdf2.js new file mode 100644 index 0000000..fe68436 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/pbkdf2.js @@ -0,0 +1,86 @@ +import assert from './_assert.js'; +import { hmac } from './hmac.js'; +import { createView, toBytes, checkOpts, asyncLoop } from './utils.js'; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assert.hash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assert.number(c); + assert.number(dkLen); + assert.number(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +export async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/pbkdf2.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/pbkdf2.js.map new file mode 100644 index 0000000..1710c5c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAsB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,E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AAC,CAAC;QACjC,MAAM,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;YACtC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/ripemd160.js b/test/merkletreejs/node_modules/@noble/hashes/esm/ripemd160.js new file mode 100644 index 0000000..fcf1f5e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/ripemd160.js @@ -0,0 +1,100 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = wrapConstructor(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/ripemd160.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/ripemd160.js.map new file mode 100644 index 0000000..bb6ab0f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,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,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/scrypt.js b/test/merkletreejs/node_modules/@noble/hashes/esm/scrypt.js new file mode 100644 index 0000000..204d41a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/scrypt.js @@ -0,0 +1,218 @@ +import assert from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, u32 } from './utils.js'; +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assert.number(N); + assert.number(r); + assert.number(p); + assert.number(dkLen); + assert.number(asyncTick); + assert.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/scrypt.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/scrypt.js.map new file mode 100644 index 0000000..d944f4c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../src/scrypt.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAS,GAAG,EAAE,MAAM,YAAY,CAAC;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,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C;QACf,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,SAAS,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;YAClC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha1.js b/test/merkletreejs/node_modules/@noble/hashes/esm/sha1.js new file mode 100644 index 0000000..f0691b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha1.js @@ -0,0 +1,85 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +export const sha1 = wrapConstructor(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha1.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/sha1.js.map new file mode 100644 index 0000000..dbf3cd3 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAEzF,4DAA4D;AAC5D,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AACnC,MAAM,IAAK,SAAQ,IAAU;IAO3B;QACE,KAAK,CAAC,EAAE,E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,CAAC,CAAC;YAChB,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,CAAC,CAAC;SACP;QACD,qDAAqD;QACrD,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha256.js b/test/merkletreejs/node_modules/@noble/hashes/esm/sha256.js new file mode 100644 index 0000000..841917e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha256.js @@ -0,0 +1,124 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = wrapConstructor(() => new SHA256()); +export const sha224 = wrapConstructor(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha256.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/sha256.js.map new file mode 100644 index 0000000..a986797 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,mBAAmB;AACnB,yFAAyF;AACzF,kBAAkB;AAClB,MAAM,QAAQ,GAAG,IAAI,WAAW,CAAC;IAC/B,UAAU,EAA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MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1D,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha3-addons.js b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3-addons.js new file mode 100644 index 0000000..cb1a2a8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3-addons.js @@ -0,0 +1,347 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +import { Keccak } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + constructor(capacity) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha3-addons.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3-addons.js.map new file mode 100644 index 0000000..3393dec --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"m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AAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha3.js b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3.js new file mode 100644 index 0000000..710eca4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3.js @@ -0,0 +1,206 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js'; +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = u64.split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => s > 32 ? u64.rotlBH(h, l, s) : u64.rotlSH(h, l, s); +const rotlL = (h, l, s) => s > 32 ? u64.rotlBL(h, l, s) : u64.rotlSL(h, l, s); +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +export class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + assert.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + assert.exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + assert.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +export const sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = gen(0x06, 136, 256 / 8); +export const sha3_384 = gen(0x06, 104, 384 / 8); +export const sha3_512 = gen(0x06, 72, 512 / 8); +export const keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = gen(0x01, 136, 256 / 8); +export const keccak_384 = gen(0x01, 104, 384 / 8); +export const keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +export const shake128 = genShake(0x1f, 168, 128 / 8); +export const shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha3.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3.js.map new file mode 100644 index 0000000..e64e81e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EACL,IAAI,EACJ,GAAG,EAEH,OAAO,EACP,eAAe,EACf,0BAA0B,GAE3B,MAAM,YAAY,CAAC;AAEpB,2CAA2C;AAC3C,MAAM,CAAC,OAA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test/merkletreejs/node_modules/@noble/hashes/esm/sha512.js b/test/merkletreejs/node_modules/@noble/hashes/esm/sha512.js new file mode 100644 index 0000000..aaec7e4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha512.js @@ -0,0 +1,231 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); +export class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +export const sha512 = wrapConstructor(() => new SHA512()); +export const sha512_224 = wrapConstructor(() => new SHA512_224()); +export const sha512_256 = wrapConstructor(() => new SHA512_256()); +export const sha384 = wrapConstructor(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/sha512.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/sha512.js.map new file mode 100644 index 0000000..e06ea23 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC;IACvC,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,o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AC,CAAC;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/utils.js b/test/merkletreejs/node_modules/@noble/hashes/esm/utils.js new file mode 100644 index 0000000..59e86f5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/utils.js @@ -0,0 +1,155 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +// For runtime check if class implements interface +export class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; +export function checkOpts(defaults, opts) { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +export function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +export function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +export function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/esm/utils.js.map b/test/merkletreejs/node_modules/@noble/hashes/esm/utils.js.map new file mode 100644 index 0000000..82e3954 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],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GAAU,EAAE,IAAQ,EAAc,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjG,MAAM,GAAG,GAAG,QAAQ,CAAC,EAAO,CAAC,CAAC;IAC9B,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/hkdf.d.ts b/test/merkletreejs/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..e1d683b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,26 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; diff --git a/test/merkletreejs/node_modules/@noble/hashes/hkdf.js b/test/merkletreejs/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..66dc8ba --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hkdf = exports.expand = exports.extract = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const hmac_js_1 = require("./hmac.js"); +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +function extract(hash, ikm, salt) { + _assert_js_1.default.hash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm)); +} +exports.extract = extract; +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = new Uint8Array([0]); +const EMPTY_BUFFER = new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +function expand(hash, prk, info, length = 32) { + _assert_js_1.default.hash(hash); + _assert_js_1.default.number(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac_js_1.hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +exports.expand = expand; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +exports.hkdf = hkdf; +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/hkdf.js.map b/test/merkletreejs/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..998a82f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAmD;AACnD,uCAAiC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,SAAgB,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,kEAAkE;IAClE,sD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G,MAAM,EAAE,OAAO,EAAE,EAAE;QACjD,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC;QAC9B,oCAAoC;QACpC,2CAA2C;QAC3C,OAAO,CAAC,MAAM,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;aAC7C,MAAM,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,UAAU,CAAC,CAAC,CAAC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;KAC1B;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AA5BD,wBA4BC;AAED;;;;;;;GAOG;AACI,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAN7C,QAAA,IAAI,QAMyC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/hmac.d.ts b/test/merkletreejs/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..63db656 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,25 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/hmac.js b/test/merkletreejs/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..4b2998e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + _assert_js_1.default.hash(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + _assert_js_1.default.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/hmac.js.map b/test/merkletreejs/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..a417288 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,yCAAyD;AACzD,kBAAkB;AAClB,MAAa,IAAwB,SAAQ,eAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClB,MAAM,GAAG,GAAG,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC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,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAnED,oBAmEC;AAED;;;;;GAKG;AACI,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AADvC,QAAA,IAAI,QACmC;AACpD,YAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/index.d.ts b/test/merkletreejs/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/test/merkletreejs/node_modules/@noble/hashes/index.js b/test/merkletreejs/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/index.js.map b/test/merkletreejs/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..b71bae6 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/package.json b/test/merkletreejs/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..b8fd0f0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/package.json @@ -0,0 +1,173 @@ +{ + "name": "@noble/hashes", + "version": "1.3.1", + "description": "Audited & minimal 0-dependency JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2, Scrypt", + "files": [ + "/*.js", + "/*.d.ts", + "/*.js.map", + "esm", + "src/*.ts" + ], + "scripts": { + "bench": "node benchmark/index.js noble", + "bench:all": "node benchmark/index.js", + "bench:install": "cd benchmark && npm install && cd ../../", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build; npm i; npm run build", + "build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.js", + "test:dos": "node test/slow-dos.test.js", + "test:big": "node test/slow-big.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-hashes.git" + }, + "license": "MIT", + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "devDependencies": { + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "engines": { + "node": ">= 16" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./crypto": { + "types": "./crypto.d.ts", + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./_assert": { + "types": "./_assert.d.ts", + "import": "./esm/_assert.js", + "default": "./_assert.js" + }, + "./_sha2": { + "types": "./_sha2.d.ts", + "import": "./esm/_sha2.js", + "default": "./_sha2.js" + }, + "./argon2": { + "types": "./argon2.d.ts", + "import": "./esm/argon2.js", + "default": "./argon2.js" + }, + "./blake2b": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./blake2s": { + "types": "./blake2s.d.ts", + "import": "./esm/blake2s.js", + "default": "./blake2s.js" + }, + "./blake3": { + "types": "./blake3.d.ts", + "import": "./esm/blake3.js", + "default": "./blake3.js" + }, + "./eskdf": { + "types": "./eskdf.d.ts", + "import": "./esm/eskdf.js", + "default": "./eskdf.js" + }, + "./hkdf": { + "types": "./hkdf.d.ts", + "import": "./esm/hkdf.js", + "default": "./hkdf.js" + }, + "./hmac": { + "types": "./hmac.d.ts", + "import": "./esm/hmac.js", + "default": "./hmac.js" + }, + "./pbkdf2": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./ripemd160": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./sha1": { + "types": "./sha1.d.ts", + "import": "./esm/sha1.js", + "default": "./sha1.js" + }, + "./sha3-addons": { + "types": "./sha3-addons.d.ts", + "import": "./esm/sha3-addons.js", + "default": "./sha3-addons.js" + }, + "./sha3": { + "types": "./sha3.d.ts", + "import": "./esm/sha3.js", + "default": "./sha3.js" + }, + "./sha256": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + } + }, + "keywords": [ + "sha", + "sha2", + "sha3", + "sha256", + "sha512", + "keccak", + "kangarootwelve", + "ripemd160", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.d.ts b/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..42f691c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,15 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; diff --git a/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.js b/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..fc20a33 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2Async = exports.pbkdf2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const hmac_js_1 = require("./hmac.js"); +const utils_js_1 = require("./utils.js"); +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + _assert_js_1.default.hash(hash); + const opts = (0, utils_js_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + _assert_js_1.default.number(c); + _assert_js_1.default.number(dkLen); + _assert_js_1.default.number(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0, utils_js_1.toBytes)(_password); + const salt = (0, utils_js_1.toBytes)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac_js_1.hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2 = pbkdf2; +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await (0, utils_js_1.asyncLoop)(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2Async = pbkdf2Async; +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.js.map b/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..6af49d8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,oBAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACjB,oBAA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AC,EAAE,EAAE;YACtC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAtBD,kCAsBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/ripemd160.d.ts b/test/merkletreejs/node_modules/@noble/hashes/ripemd160.d.ts new file mode 100644 index 0000000..92e662f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/ripemd160.d.ts @@ -0,0 +1,24 @@ +import { SHA2 } from './_sha2.js'; +export declare class RIPEMD160 extends SHA2 { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/ripemd160.js b/test/merkletreejs/node_modules/@noble/hashes/ripemd160.js new file mode 100644 index 0000000..2f702ba --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/ripemd160.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +class RIPEMD160 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/ripemd160.js.map b/test/merkletreejs/node_modules/@noble/hashes/ripemd160.js.map new file mode 100644 index 0000000..90c597d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["src/ripemd160.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACnF,MAAM,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACxD,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC3C,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;IAAE,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;QAAE,CAAC,CAAC,IAA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IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CACxB,CAAC;IACJ,CAAC;IACS,UAAU;QAClB,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAhED,8BAgEC;AAED;;;GAGG;AACU,QAAA,SAAS,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/scrypt.d.ts b/test/merkletreejs/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..82485b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,29 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; diff --git a/test/merkletreejs/node_modules/@noble/hashes/scrypt.js b/test/merkletreejs/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..b28c8d8 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,223 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptAsync = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const utils_js_1 = require("./utils.js"); +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = (0, utils_js_1.checkOpts)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + _assert_js_1.default.number(N); + _assert_js_1.default.number(r); + _assert_js_1.default.number(p); + _assert_js_1.default.number(dkLen); + _assert_js_1.default.number(asyncTick); + _assert_js_1.default.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0, utils_js_1.u32)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N)); + const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scrypt = scrypt; +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await (0, utils_js_1.asyncLoop)(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scryptAsync = scryptAsync; +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/scrypt.js.map b/test/merkletreejs/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..5be0b8c --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,2CAAqC;AACrC,2CAAqC;AACrC,yCAA8D;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,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CAAC,EAAE,EAAE;YACtC,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,2BAA2B;YACzE,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,IAAA,oBAAS,EAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;YAClC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC;AAzBD,kCAyBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha1.d.ts b/test/merkletreejs/node_modules/@noble/hashes/sha1.d.ts new file mode 100644 index 0000000..d9cb132 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha1.d.ts @@ -0,0 +1,21 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA1 extends SHA2 { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha1.js b/test/merkletreejs/node_modules/@noble/hashes/sha1.js new file mode 100644 index 0000000..8eff8bb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha1.js @@ -0,0 +1,88 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha1.js.map b/test/merkletreejs/node_modules/@noble/hashes/sha1.js.map new file mode 100644 index 0000000..c099ccb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,IAAI,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha256.d.ts b/test/merkletreejs/node_modules/@noble/hashes/sha256.d.ts new file mode 100644 index 0000000..3e1491d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha256.d.ts @@ -0,0 +1,34 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA256 extends SHA2 { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha256.js b/test/merkletreejs/node_modules/@noble/hashes/sha256.js new file mode 100644 index 0000000..7f897a4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha256.js @@ -0,0 +1,127 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha256.js.map b/test/merkletreejs/node_modules/@noble/hashes/sha256.js.map new file mode 100644 index 0000000..28623a9 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["src/sha256.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAAmD;AAEnD,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GA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UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACU,QAAA,MAAM,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7C,QAAA,MAAM,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.d.ts b/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..f6ae900 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,138 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.js b/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..1ac012d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,351 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccakprg = exports.m14 = exports.k12 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.cshake256 = exports.cshake128 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const sha3_js_1 = require("./sha3.js"); +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => cshakePers(new sha3_js_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); +exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = (0, utils_js_1.toBytes)(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = (0, utils_js_1.u32)(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +exports.kmac128 = (() => genKmac(168, 128 / 8))(); +exports.kmac256 = (() => genKmac(136, 256 / 8))(); +exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); +exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +exports.tuplehash128 = (() => genTuple(168, 128 / 8))(); +exports.tuplehash256 = (() => genTuple(136, 256 / 8))(); +exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))(); +exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + (0, _assert_js_1.number)(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))(); +exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))(); +exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))(); +exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends sha3_js_1.Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new sha3_js_1.Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +exports.k12 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +exports.m14 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends sha3_js_1.Keccak { + constructor(capacity) { + (0, _assert_js_1.number)(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +exports.keccakprg = keccakprg; +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.js.map b/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..406aeaa --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAyF;AACzF,uCAA8C;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAA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AI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAEM,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;AAAxD,QAAA,SAAS,aAA+C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha3.d.ts b/test/merkletreejs/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..2107cf6 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,97 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha3.js b/test/merkletreejs/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..7c2779f --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,211 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = _u64_js_1.default.split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => s > 32 ? _u64_js_1.default.rotlBH(h, l, s) : _u64_js_1.default.rotlSH(h, l, s); +const rotlL = (h, l, s) => s > 32 ? _u64_js_1.default.rotlBL(h, l, s) : _u64_js_1.default.rotlSL(h, l, s); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + _assert_js_1.default.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + _assert_js_1.default.exists(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + _assert_js_1.default.exists(this, false); + _assert_js_1.default.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + _assert_js_1.default.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + _assert_js_1.default.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha3.js.map b/test/merkletreejs/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..829c658 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["src/sha3.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAA4B;AAC5B,yCAQoB;AAEpB,2CAA2C;AAC3C,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAmC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtF,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1B,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AAC5B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,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AAG,GAAG,CAAC,CAAC,CAAC;AACrC,QAAA,UAAU,GAAG,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAIjD,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,SAAiB,EAAE,EAAE,CACvE,IAAA,qCAA0B,EACxB,CAAC,OAAkB,EAAE,EAAE,EAAE,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CACxF,CAAC;AAES,QAAA,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACxC,QAAA,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha512.d.ts b/test/merkletreejs/node_modules/@noble/hashes/sha512.d.ts new file mode 100644 index 0000000..b8ba9b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha512.d.ts @@ -0,0 +1,66 @@ +import { SHA2 } from './_sha2.js'; +export declare class SHA512 extends SHA2 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha512.js b/test/merkletreejs/node_modules/@noble/hashes/sha512.js new file mode 100644 index 0000000..951a314 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha512.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = _u64_js_1.default.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); +class SHA512 extends _sha2_js_1.SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7); + const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6); + const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41); + const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39); + const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl); + Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.SHA512 = SHA512; +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +exports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512()); +exports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224()); +exports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256()); +exports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/sha512.js.map b/test/merkletreejs/node_modules/@noble/hashes/sha512.js.map new file mode 100644 index 0000000..5f5cee4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["src/sha512.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,uCAA4B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,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QAIlB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,MAAM,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7C,QAAA,UAAU,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrD,QAAA,UAAU,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrD,QAAA,MAAM,GAAG,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/_assert.ts b/test/merkletreejs/node_modules/@noble/hashes/src/_assert.ts new file mode 100644 index 0000000..492c925 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/_assert.ts @@ -0,0 +1,49 @@ +export function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); +} + +export function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`); +} + +export function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} + +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +export function hash(hash: Hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} + +export function exists(instance: any, checkFinished = true) { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} +export function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; + +export default assert; diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/_blake2.ts b/test/merkletreejs/node_modules/@noble/hashes/src/_blake2.ts new file mode 100644 index 0000000..7adabeb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/_blake2.ts @@ -0,0 +1,125 @@ +import assert from './_assert.js'; +import { Hash, Input, toBytes, u32 } from './utils.js'; +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); + +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; + +export abstract class BLAKE2> extends Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number = 0; + protected pos: number = 0; + protected finished = false; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + opts: BlakeOpts = {}, + keyLen: number, + saltLen: number, + persLen: number + ) { + super(); + assert.number(blockLen); + assert.number(outputLen); + assert.number(keyLen); + if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data: Input) { + assert.exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: Uint8Array) { + assert.exists(this); + assert.output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/_sha2.ts b/test/merkletreejs/node_modules/@noble/hashes/src/_sha2.ts new file mode 100644 index 0000000..15f8f63 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/_sha2.ts @@ -0,0 +1,118 @@ +import assert from './_assert.js'; +import { Hash, createView, Input, toBytes } from './utils.js'; + +// Polyfill for Safari 14 +function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} + +// Base SHA2 class (RFC 6234) +export abstract class SHA2> extends Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + readonly padOffset: number, + readonly isLE: boolean + ) { + super(); + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: Input): this { + assert.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out: Uint8Array) { + assert.exists(this); + assert.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/_u64.ts b/test/merkletreejs/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..368de54 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,69 @@ +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); + +// We are not using BigUint64Array, because they are extremely slow as per 2022 +export function fromBig(n: bigint, le = false) { + if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} + +export function split(lst: bigint[], le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} + +export const toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h: number, l: number, s: number) => h >>> s; +const shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h: number, l: number) => l; +const rotr32L = (h: number, l: number) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s)); + +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +export function add(Ah: number, Al: number, Bh: number, Bl: number) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low: number, Ah: number, Bh: number, Ch: number) => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al: number, Bl: number, Cl: number, Dl: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/argon2.ts b/test/merkletreejs/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..27852bb --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,374 @@ +import assert from './_assert.js'; +import { Input, toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import u64 from './_u64.js'; + +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +enum Types { + Argond2d = 0, + Argon2i = 1, + Argon2id = 2, +} + +const ARGON2_SYNC_POINTS = 4; + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); + +function mul(a: number, b: number) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} + +function relPos(areaSize: number, relativePos: number) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} + +function mul2(a: number, b: number) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = u64.add3L(Al, Bl, Cl); + return { h: u64.add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer +const BUF = new Uint32Array(256); + +function G(a: number, b: number, c: number, d: number) { + let Al = BUF[2*a], Ah = BUF[2*a + 1]; // prettier-ignore + let Bl = BUF[2*b], Bh = BUF[2*b + 1]; // prettier-ignore + let Cl = BUF[2*c], Ch = BUF[2*c + 1]; // prettier-ignore + let Dl = BUF[2*d], Dh = BUF[2*d + 1]; // prettier-ignore + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: Uint32Array, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) BUF[i] = x[xPos + i] ^ x[yPos + i]; + + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} + +// Variable-Length Hash Function H' +function Hp(A: Uint32Array, dkLen: number) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} + +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} + +// RFC 9106 +export type ArgonOpts = { + t: number; // Time cost, iterations count + m: number; // Memory cost (in KB) + p: number; // Parallelization parameter + version?: number; // Default: 0x13 (19) + key?: Input; // Optional key + personalization?: Input; // Optional arbitrary extra data + dkLen?: number; // Desired number of returned bytes + asyncTick?: number; // Maximum time in ms for which async function can block execution + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +function argon2Init(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assert.number(p); + assert.number(dkLen); + assert.number(m); + assert.number(t); + assert.number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (dkLen < 1 || p >= 2 ** 32) throw new Error('Argon2: p (paralllelism) should be at least 1'); + if (dkLen < 1 || p >= 2 ** 32) throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32` + ); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} + +function argon2Output(B: Uint32Array, p: number, laneLen: number, dkLen: number) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} + +function processBlock( + B: Uint32Array, + address: Uint32Array, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + type, + password, + salt, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} + +export const argon2d = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2id, password, salt, opts); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/blake2b.ts b/test/merkletreejs/node_modules/@noble/hashes/src/blake2b.ts new file mode 100644 index 0000000..e2c6e98 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/blake2b.ts @@ -0,0 +1,203 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; + +// Same as SHA-512 but LE +// prettier-ignore +const IV = new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = new Uint32Array(32); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +function G2(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +class BLAKE2b extends BLAKE2 { + // Same as SHA-512, but LE + private v0l = IV[0] | 0; + private v0h = IV[1] | 0; + private v1l = IV[2] | 0; + private v1h = IV[3] | 0; + private v2l = IV[4] | 0; + private v2h = IV[5] | 0; + private v3l = IV[6] | 0; + private v3h = IV[7] | 0; + private v4l = IV[8] | 0; + private v4h = IV[9] | 0; + private v5l = IV[10] | 0; + private v5h = IV[11] | 0; + private v6l = IV[12] | 0; + private v6h = IV[13] | 0; + private v7l = IV[14] | 0; + private v7h = IV[15] | 0; + + constructor(opts: BlakeOpts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let {v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h} = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/blake2s.ts b/test/merkletreejs/node_modules/@noble/hashes/src/blake2s.ts new file mode 100644 index 0000000..f5824d4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/blake2s.ts @@ -0,0 +1,136 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; + +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +function G2(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +class BLAKE2s extends BLAKE2 { + // Internal state, same as SHA-256 + private v0 = IV[0] | 0; + private v1 = IV[1] | 0; + private v2 = IV[2] | 0; + private v3 = IV[3] | 0; + private v4 = IV[4] | 0; + private v5 = IV[5] | 0; + private v6 = IV[6] | 0; + private v7 = IV[7] | 0; + + constructor(opts: BlakeOpts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + const { h, l } = u64.fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/blake3.ts b/test/merkletreejs/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..873d0da --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,246 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { Input, u8, u32, toBytes, HashXOF, wrapXOFConstructorWithOpts } from './utils.js'; + +// Flag bitset +enum Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +} + +const SIGMA: Uint8Array = (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +// - key: is 256-bit key +// - context: string should be hardcoded, globally unique, and application - specific. +// A good default format for the context string is "[application] [commit timestamp] [purpose]" +// - Only one of 'key' (keyed mode) or 'context' (derive key mode) can be used at same time +export type Blake3Opts = { dkLen?: number; key?: Input; context?: Input }; + +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 implements HashXOF { + private IV: Uint32Array; + private flags = 0 | 0; + private state: Uint32Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + private chunkOut = 0; // index of output chunk + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + assert.number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + protected get() { + return []; + } + protected set() {} + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = u64.fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: BLAKE3): BLAKE3 { + to = super._cloneInto(to) as BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = u64.fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + protected finish() { + if (this.finished) return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: Uint8Array) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + assert.output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} + +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/crypto.ts b/test/merkletreejs/node_modules/@noble/hashes/src/crypto.ts new file mode 100644 index 0000000..eaea6be --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/crypto.ts @@ -0,0 +1,5 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +export const crypto = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/cryptoNode.ts b/test/merkletreejs/node_modules/@noble/hashes/src/cryptoNode.ts new file mode 100644 index 0000000..6fdba9e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/cryptoNode.ts @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = + nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/eskdf.ts b/test/merkletreejs/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..b4c224b --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,183 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; + +// Scrypt KDF +export function scrypt(password: string, salt: string): Uint8Array { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password: string, salt: string): Uint8Array { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays +function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username: string, password: string): Uint8Array { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt: Uint8Array; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key: Uint8Array, modulus: bigint): Uint8Array { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +// We are not using classes because constructor cannot be async +type ESKDF = Promise< + Readonly<{ + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; + }> +>; + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username: string, password: string): ESKDF { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK(protocol: string, accountId: AccountID = 0, options?: KeyOpts): Uint8Array { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/hkdf.ts b/test/merkletreejs/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..2605898 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,79 @@ +import assert from './_assert.js'; +import { CHash, Input, toBytes } from './utils.js'; +import { hmac } from './hmac.js'; + +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ + +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash: CHash, ikm: Input, salt?: Input) { + assert.hash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} + +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = new Uint8Array([0]); +const EMPTY_BUFFER = new Uint8Array(); + +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) { + assert.hash(hash); + assert.number(length); + if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} + +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = ( + hash: CHash, + ikm: Input, + salt: Input | undefined, + info: Input | undefined, + length: number +) => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/hmac.ts b/test/merkletreejs/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..1efd2b7 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,81 @@ +import assert from './_assert.js'; +import { Hash, CHash, Input, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished = false; + private destroyed = false; + + constructor(hash: CHash, _key: Input) { + super(); + assert.hash(hash); + const key = toBytes(_key); + this.iHash = hash.create() as T; + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf: Input) { + assert.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: Uint8Array) { + assert.exists(this); + assert.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to?: HMAC): HMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} + +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash: CHash, key: Input, message: Input): Uint8Array => + new HMAC(hash, key).update(message).digest(); +hmac.create = (hash: CHash, key: Input) => new HMAC(hash, key); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/index.ts b/test/merkletreejs/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..1505776 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1 @@ +throw new Error('noble-hashes have no entry-point: consult README for usage'); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/pbkdf2.ts b/test/merkletreejs/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..2a46476 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,97 @@ +import assert from './_assert.js'; +import { hmac } from './hmac.js'; +import { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js'; + +// PBKDF (RFC 2898) +export type Pbkdf2Opt = { + c: number; // Iterations + dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key + asyncTick?: number; // Maximum time in ms for which async function can block execution +}; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) { + assert.hash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assert.number(c); + assert.number(dkLen); + assert.number(asyncTick); + if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} + +function pbkdf2Output>( + PRF: Hash, + PRFSalt: Hash, + DK: Uint8Array, + prfW: Hash, + u: Uint8Array +) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; +} + +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +export async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/ripemd160.ts b/test/merkletreejs/node_modules/@noble/hashes/src/ripemd160.ts new file mode 100644 index 0000000..dff071a --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/ripemd160.ts @@ -0,0 +1,108 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); + +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); + +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word: number, shift: number) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, + bl = this.h1 | 0, br = bl, + cl = this.h2 | 0, cr = cl, + dl = this.h3 | 0, dr = dl, + el = this.h4 | 0, er = el; + + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0 + ); + } + protected roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = wrapConstructor(() => new RIPEMD160()); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/scrypt.ts b/test/merkletreejs/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..f11b2b5 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,240 @@ +import assert from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, Input, u32 } from './utils.js'; + +// RFC 7914 Scrypt KDF + +// Left rotate for uint32 +const rotl = (a: number, b: number) => (a << b) | (a >>> (32 - b)); + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa( + prev: Uint32Array, + pi: number, + input: Uint32Array, + ii: number, + out: Uint32Array, + oi: number +) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} + +export type ScryptOpts = { + N: number; // cost factor + r: number; // block size + p: number; // parallelization + dkLen?: number; // key length + asyncTick?: number; // block execution max time + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assert.number(N); + assert.number(r); + assert.number(p); + assert.number(dkLen); + assert.number(asyncTick); + assert.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error( + 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32' + ); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error( + 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)' + ); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error( + 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32' + ); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error( + `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)` + ); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} + +function scryptOutput( + password: Input, + dkLen: number, + B: Uint8Array, + V: Uint32Array, + tmp: Uint32Array +) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} + +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/sha1.ts b/test/merkletreejs/node_modules/@noble/hashes/src/sha1.ts new file mode 100644 index 0000000..80b3686 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/sha1.ts @@ -0,0 +1,86 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. + +// RFC 3174 +const rotl = (word: number, shift: number) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends SHA2 { + private A = IV[0] | 0; + private B = IV[1] | 0; + private C = IV[2] | 0; + private D = IV[3] | 0; + private E = IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + protected roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} + +export const sha1 = wrapConstructor(() => new SHA1()); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/sha256.ts b/test/merkletreejs/node_modules/@noble/hashes/src/sha256.ts new file mode 100644 index 0000000..76fdd11 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/sha256.ts @@ -0,0 +1,130 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; + +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends SHA2 { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = IV[0] | 0; + B = IV[1] | 0; + C = IV[2] | 0; + D = IV[3] | 0; + E = IV[4] | 0; + F = IV[5] | 0; + G = IV[6] | 0; + H = IV[7] | 0; + + constructor() { + super(64, 32, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + protected roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + A = 0xc1059ed8 | 0; + B = 0x367cd507 | 0; + C = 0x3070dd17 | 0; + D = 0xf70e5939 | 0; + E = 0xffc00b31 | 0; + F = 0x68581511 | 0; + G = 0x64f98fa7 | 0; + H = 0xbefa4fa4 | 0; + constructor() { + super(); + this.outputLen = 28; + } +} + +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = wrapConstructor(() => new SHA256()); +export const sha224 = wrapConstructor(() => new SHA224()); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/sha3-addons.ts b/test/merkletreejs/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..1015250 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,398 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, wrapConstructorWithOpts, u32, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} + +function rightEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; + +// Personalization +function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} + +const gencShake = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructorWithOpts((opts: cShakeOpts = {}) => + cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) + ); + +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); + +class KMAC extends Keccak implements HashXOF { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: Input, + opts: cShakeOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish() { + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: KMAC): KMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as KMAC; + } + clone(): KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false) { + const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key: Input, opts: cShakeOpts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} + +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); + +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + protected finish() { + if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: TupleHash): TupleHash { + to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as TupleHash; + } + clone(): TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false) { + const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { + const h = tuple.create(opts); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: cShakeOpts = {}) => + new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} + +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); + +// ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) +type ParallelOpts = cShakeOpts & { blockLen?: number }; + +class ParallelHash extends Keccak implements HashXOF { + private leafHash?: Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + protected leafCons: () => Hash, + enableXOF: boolean, + opts: ParallelOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B ||= 8; + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish() { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: ParallelHash): ParallelHash { + to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as ParallelHash; + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +) { + const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: ParallelOpts = {}) => + new ParallelHash( + blockLen, + chooseLen(opts, outputLen), + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + return parallel; +} + +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); + +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n: number): Uint8Array { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +export type KangarooOpts = { dkLen?: number; personalization?: Input }; +const EMPTY = new Uint8Array([]); + +class KangarooTwelve extends Keccak implements HashXOF { + readonly chunkLen = 8192; + private leafHash?: Keccak; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + protected leafLen: number, + outputLen: number, + rounds: number, + opts: KangarooOpts + ) { + super(blockLen, 0x07, outputLen, true, rounds); + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data: Input) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to?: KangarooTwelve): KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): KangarooTwelve { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) + ))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) + ))(); + +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: Input) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data: Input) { + return this.update(data); + } + protected finish() {} + digestInto(out: Uint8Array): Uint8Array { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes: number): Uint8Array { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: KeccakPRG): KeccakPRG { + const { rate } = this; + to ||= new KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): KeccakPRG { + return this._cloneInto(); + } +} + +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/sha3.ts b/test/merkletreejs/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..6f1b937 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,222 @@ +import assert from './_assert.js'; +import u64 from './_u64.js'; +import { + Hash, + u32, + Input, + toBytes, + wrapConstructor, + wrapXOFConstructorWithOpts, + HashXOF, +} from './utils.js'; + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = u64.split(_SHA3_IOTA, true); + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => + s > 32 ? u64.rotlBH(h, l, s) : u64.rotlSH(h, l, s); +const rotlL = (h: number, l: number, s: number) => + s > 32 ? u64.rotlBL(h, l, s) : u64.rotlSL(h, l, s); + +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s: Uint32Array, rounds: number = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} + +export class Keccak extends Hash implements HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + public blockLen: number, + public suffix: number, + public outputLen: number, + protected enableXOF = false, + protected rounds: number = 24 + ) { + super(); + // Can be passed from user as dkLen + assert.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + protected keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data: Input) { + assert.exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: Uint8Array): Uint8Array { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + assert.output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const gen = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + +export const sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = gen(0x06, 136, 256 / 8); +export const sha3_384 = gen(0x06, 104, 384 / 8); +export const sha3_512 = gen(0x06, 72, 512 / 8); +export const keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = gen(0x01, 136, 256 / 8); +export const keccak_384 = gen(0x01, 104, 384 / 8); +export const keccak_512 = gen(0x01, 72, 512 / 8); + +export type ShakeOpts = { dkLen?: number }; + +const genShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, ShakeOpts>( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true) + ); + +export const shake128 = genShake(0x1f, 168, 128 / 8); +export const shake256 = genShake(0x1f, 136, 256 / 8); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/sha512.ts b/test/merkletreejs/node_modules/@noble/hashes/src/sha512.ts new file mode 100644 index 0000000..fd6484e --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/sha512.ts @@ -0,0 +1,247 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); + +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); + +export class SHA512 extends SHA2 { + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + Ah = 0x6a09e667 | 0; + Al = 0xf3bcc908 | 0; + Bh = 0xbb67ae85 | 0; + Bl = 0x84caa73b | 0; + Ch = 0x3c6ef372 | 0; + Cl = 0xfe94f82b | 0; + Dh = 0xa54ff53a | 0; + Dl = 0x5f1d36f1 | 0; + Eh = 0x510e527f | 0; + El = 0xade682d1 | 0; + Fh = 0x9b05688c | 0; + Fl = 0x2b3e6c1f | 0; + Gh = 0x1f83d9ab | 0; + Gl = 0xfb41bd6b | 0; + Hh = 0x5be0cd19 | 0; + Hl = 0x137e2179 | 0; + + constructor() { + super(128, 64, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + protected process(view: DataView, offset: number) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + protected roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +class SHA512_224 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x8c3d37c8 | 0; + Al = 0x19544da2 | 0; + Bh = 0x73e19966 | 0; + Bl = 0x89dcd4d6 | 0; + Ch = 0x1dfab7ae | 0; + Cl = 0x32ff9c82 | 0; + Dh = 0x679dd514 | 0; + Dl = 0x582f9fcf | 0; + Eh = 0x0f6d2b69 | 0; + El = 0x7bd44da8 | 0; + Fh = 0x77e36f73 | 0; + Fl = 0x04c48942 | 0; + Gh = 0x3f9d85a8 | 0; + Gl = 0x6a1d36c8 | 0; + Hh = 0x1112e6ad | 0; + Hl = 0x91d692a1 | 0; + + constructor() { + super(); + this.outputLen = 28; + } +} + +class SHA512_256 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x22312194 | 0; + Al = 0xfc2bf72c | 0; + Bh = 0x9f555fa3 | 0; + Bl = 0xc84c64c2 | 0; + Ch = 0x2393b86b | 0; + Cl = 0x6f53b151 | 0; + Dh = 0x96387719 | 0; + Dl = 0x5940eabd | 0; + Eh = 0x96283ee2 | 0; + El = 0xa88effe3 | 0; + Fh = 0xbe5e1e25 | 0; + Fl = 0x53863992 | 0; + Gh = 0x2b0199fc | 0; + Gl = 0x2c85b8aa | 0; + Hh = 0x0eb72ddc | 0; + Hl = 0x81c52ca2 | 0; + + constructor() { + super(); + this.outputLen = 32; + } +} + +class SHA384 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0xcbbb9d5d | 0; + Al = 0xc1059ed8 | 0; + Bh = 0x629a292a | 0; + Bl = 0x367cd507 | 0; + Ch = 0x9159015a | 0; + Cl = 0x3070dd17 | 0; + Dh = 0x152fecd8 | 0; + Dl = 0xf70e5939 | 0; + Eh = 0x67332667 | 0; + El = 0xffc00b31 | 0; + Fh = 0x8eb44a87 | 0; + Fl = 0x68581511 | 0; + Gh = 0xdb0c2e0d | 0; + Gl = 0x64f98fa7 | 0; + Hh = 0x47b5481d | 0; + Hl = 0xbefa4fa4 | 0; + + constructor() { + super(); + this.outputLen = 48; + } +} + +export const sha512 = wrapConstructor(() => new SHA512()); +export const sha512_224 = wrapConstructor(() => new SHA512_224()); +export const sha512_256 = wrapConstructor(() => new SHA512_256()); +export const sha384 = wrapConstructor(() => new SHA384()); diff --git a/test/merkletreejs/node_modules/@noble/hashes/src/utils.ts b/test/merkletreejs/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..ce0d84d --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,216 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; + +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift); + +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); + +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => {}; + +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + // Safe version that clones internal state + clone(): T { + return this._cloneInto(); + } +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream + xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf +}; + +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj: any) => + Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; + +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +export type CHash = ReturnType; + +export function wrapConstructor>(hashCons: () => Hash) { + const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +export function wrapConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => Hash +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +export function wrapXOFConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => HashXOF +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32): Uint8Array { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} diff --git a/test/merkletreejs/node_modules/@noble/hashes/utils.d.ts b/test/merkletreejs/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..a0017e4 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,90 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const isLE: boolean; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; diff --git a/test/merkletreejs/node_modules/@noble/hashes/utils.js b/test/merkletreejs/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..ffd37be --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/utils.js @@ -0,0 +1,175 @@ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +const crypto_1 = require("@noble/hashes/crypto"); +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; +function checkOpts(defaults, opts) { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@noble/hashes/utils.js.map b/test/merkletreejs/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..b789568 --- /dev/null +++ b/test/merkletreejs/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,iDAA8C;AAM9C,MAAM,GAAG,GAA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AAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjG,MAAM,GAAG,GAAG,QAAQ,CAAC,EAAO,CAAC,CAAC;IAC9B,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AATD,gEASC;AAED;;GAEG;AACH,SAAgB,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,eAAM,IAAI,OAAO,eAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,eAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AALD,kCAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/base/LICENSE b/test/merkletreejs/node_modules/@scure/base/LICENSE new file mode 100644 index 0000000..5b91e4c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. diff --git a/test/merkletreejs/node_modules/@scure/base/README.md b/test/merkletreejs/node_modules/@scure/base/README.md new file mode 100644 index 0000000..653e948 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/README.md @@ -0,0 +1,201 @@ +# scure-base + +Audited & minimal implementation of bech32, base64, base58, base32 & base16. + +- 🔒 [Audited](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 📦 ESM and common.js +- ✍️ Written in [functional style](#design-rationale), easily composable +- 💼 Matches specs + - [BIP173](https://en.bitcoin.it/wiki/BIP_0173), [BIP350](https://en.bitcoin.it/wiki/BIP_0350) for bech32 / bech32m + - [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648) (aka RFC 3548) for Base16, Base32, Base32Hex, Base64, Base64Url + - [Base58](https://www.ietf.org/archive/id/draft-msporny-base58-03.txt), + [Base58check](https://en.bitcoin.it/wiki/Base58Check_encoding), + [Base32 Crockford](https://www.crockford.com/base32.html) + +Check out [Projects using scure-base](#projects-using-scure-base). + +### This library belongs to _scure_ + +> **scure** — secure, independently audited packages for every use case. + +- Minimal or zero dependencies +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer), + [starknet](https://github.com/paulmillr/scure-starknet) + +## Usage + +> npm install @scure/base + +We support all major platforms and runtimes. The library is hybrid ESM / Common.js package. + +```js +import { base16, base32, base64, base58 } from '@scure/base'; +// Flavors +import { + base58xmr, + base58xrp, + base32hex, + base32crockford, + base64url, + base64urlnopad, +} from '@scure/base'; + +const data = Uint8Array.from([1, 2, 3]); +base64.decode(base64.encode(data)); + +// Convert utf8 string to Uint8Array +const data2 = new TextEncoder().encode('hello'); +base58.encode(data2); + +// Everything has the same API except for bech32 and base58check +base32.encode(data); +base16.encode(data); +base32hex.encode(data); +``` + +base58check is a special case: you need to pass `sha256()` function: + +```js +import { base58check } from '@scure/base'; +base58check(sha256).encode(data); +``` + +Alternative API: + +```js +import { str, bytes } from '@scure/base'; +const encoded = str('base64', data); +const data = bytes('base64', encoded); +``` + +## Bech32, Bech32m and Bitcoin + +We provide low-level bech32 operations. +If you need high-level methods for BTC (addresses, and others), use +[scure-btc-signer](https://github.com/paulmillr/scure-btc-signer) instead. + +Bitcoin addresses use both 5-bit words and bytes representations. +They can't be parsed using `bech32.decodeToBytes`. Instead, do something this: + +```ts +const decoded = bech32.decode(address); +// NOTE: words in bitcoin addresses contain version as first element, +// with actual witnes program words in rest +// BIP-141: The value of the first push is called the "version byte". +// The following byte vector pushed is called the "witness program". +const [version, ...dataW] = decoded.words; +const program = bech32.fromWords(dataW); // actual witness program +``` + +Same applies to Lightning Invoice Protocol +[BOLT-11](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md). +We have many tests in `./test/bip173.test.js` that serve as minimal examples of +Bitcoin address and Lightning Invoice Protocol parsers. +Keep in mind that you'll need to verify the examples before using them in your code. + +## Design rationale + +The code may feel unnecessarily complicated; but actually it's much easier to reason about. +Any encoding library consists of two functions: + +``` +encode(A) -> B +decode(B) -> A + where X = decode(encode(X)) + # encode(decode(X)) can be !== X! + # because decoding can normalize input + +e.g. +base58checksum = { + encode(): { + // checksum + // radix conversion + // alphabet + }, + decode(): { + // alphabet + // radix conversion + // checksum + } +} +``` + +But instead of creating two big functions for each specific case, +we create them from tiny composamble building blocks: + +``` +base58checksum = chain(checksum(), radix(), alphabet()) +``` + +Which is the same as chain/pipe/sequence function in Functional Programming, +but significantly more useful since it enforces same order of execution of encode/decode. +Basically you only define encode (in declarative way) and get correct decode for free. +So, instead of reasoning about two big functions you need only reason about primitives and encode chain. +The design revealed obvious bug in older version of the lib, +where xmr version of base58 had errors in decode's block processing. + +Besides base-encodings, we can reuse the same approach with any encode/decode function +(`bytes2number`, `bytes2u32`, etc). +For example, you can easily encode entropy to mnemonic (BIP-39): + +```ts +export function getCoder(wordlist: string[]) { + if (!Array.isArray(wordlist) || wordlist.length !== 2 ** 11 || typeof wordlist[0] !== 'string') { + throw new Error('Worlist: expected array of 2048 strings'); + } + return mbc.chain(mbu.checksum(1, checksum), mbu.radix2(11, true), mbu.alphabet(wordlist)); +} +``` + +## base58 is O(n^2) and radixes + +`Uint8Array` is represented as big-endian number: + +``` +[1, 2, 3, 4, 5] -> 1*(256**4) + 2*(256**3) 3*(256**2) + 4*(256**1) + 5*(256**0) +where 256 = 2**8 (8 bits per byte) +``` + +which is then converted to a number in another radix/base (16/32/58/64, etc). + +However, generic conversion between bases has [quadratic O(n^2) time complexity](https://cs.stackexchange.com/q/21799). + +Which means base58 has quadratic time complexity too. Use base58 only when you have small +constant sized input, because variable length sized input from user can cause DoS. + +On the other hand, if both bases are power of same number (like `2**8 <-> 2**64`), +there is linear algorithm. For now we have implementation for power-of-two bases only (radix2). + +## Security + +The library has been independently audited: + +- at version 1.0.0, in Jan 2022, by [cure53](https://cure53.de) + - PDFs: [online](https://cure53.de/pentest-report_hashing-libs.pdf), [offline](./audit/2022-01-05-cure53-audit-nbl2.pdf) + - [Changes since audit](https://github.com/paulmillr/scure-base/compare/1.0.0..main). + - The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io) + +The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography). +At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), +it was extracted to a separate package called `micro-base`. +After the audit we've decided to use `@scure` NPM namespace for security. + +## Resources + +### Projects using scure-base + +- [prefixed-api-key](https://github.com/truestamp/prefixed-api-key): + A re-write of seamapi/prefixed-api-key that enhances the + cryptographic security properties and safety when verifying a key. The keys and verifiers + of these two libraries are not compatible. + [Motivating post on the issues with using JWT from fly.io](https://fly.io/blog/api-tokens-a-tedious-survey/) + +## License + +MIT (c) Paul Miller [(https://paulmillr.com)](https://paulmillr.com), see LICENSE file. diff --git a/test/merkletreejs/node_modules/@scure/base/index.ts b/test/merkletreejs/node_modules/@scure/base/index.ts new file mode 100644 index 0000000..3b2ddc1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/index.ts @@ -0,0 +1,565 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// Utilities +/** + * @__NO_SIDE_EFFECTS__ + */ +export function assertNumber(n: number) { + if (!Number.isSafeInteger(n)) throw new Error(`Wrong integer: ${n}`); +} +export interface Coder { + encode(from: F): T; + decode(to: T): F; +} + +export interface BytesCoder extends Coder { + encode: (data: Uint8Array) => string; + decode: (str: string) => Uint8Array; +} + +// TODO: some recusive type inference so it would check correct order of input/output inside rest? +// like , , +type Chain = [Coder, ...Coder[]]; +// Extract info from Coder type +type Input = F extends Coder ? T : never; +type Output = F extends Coder ? T : never; +// Generic function for arrays +type First = T extends [infer U, ...any[]] ? U : never; +type Last = T extends [...any[], infer U] ? U : never; +type Tail = T extends [any, ...infer U] ? U : never; + +type AsChain> = { + // C[K] = Coder, Input> + [K in keyof C]: Coder, Input>; +}; + +/** + * @__NO_SIDE_EFFECTS__ + */ +function chain>(...args: T): Coder>, Output>> { + // Wrap call in closure so JIT can inline calls + const wrap = (a: any, b: any) => (c: any) => a(b(c)); + // Construct chain of args[-1].encode(args[-2].encode([...])) + const encode = Array.from(args) + .reverse() + .reduce((acc, i: any) => (acc ? wrap(acc, i.encode) : i.encode), undefined) as any; + // Construct chain of args[0].decode(args[1].decode(...)) + const decode = args.reduce( + (acc, i: any) => (acc ? wrap(acc, i.decode) : i.decode), + undefined + ) as any; + return { encode, decode }; +} + +type Alphabet = string[] | string; + +/** + * Encodes integer radix representation to array of strings using alphabet and back + * @__NO_SIDE_EFFECTS__ + */ +function alphabet(alphabet: Alphabet): Coder { + return { + encode: (digits: number[]) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]!; + }); + }, + decode: (input: string[]) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function join(separator = ''): Coder { + if (typeof separator !== 'string') throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} + +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +function padding(bits: number, chr = '='): Coder { + assertNumber(bits); + if (typeof chr !== 'string') throw new Error('padding chr should be string'); + return { + encode(data: string[]): string[] { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) data.push(chr); + return data; + }, + decode(input: string[]): string[] { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function normalize(fn: (val: T) => T): Coder { + if (typeof fn !== 'function') throw new Error('normalize fn should be function'); + return { encode: (from: T) => from, decode: (to: T) => fn(to) }; +} + +/** + * Slow: O(n^2) time complexity + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix(data: number[], from: number, to: number) { + // base 1 is impossible + if (from < 2) throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) throw new Error('convertRadix: data should be array'); + if (!data.length) return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]!; + const digitBase = from * carry + digit; + if ( + !Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry + ) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + const rounded = Math.floor(digitBase / to); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) continue; + else if (!rounded) pos = i; + else done = false; + } + res.push(carry); + if (done) break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0); + return res.reverse(); +} + +const gcd = /* @__NO_SIDE_EFFECTS__ */ (a: number, b: number): number => (!b ? a : gcd(b, a % b)); +const radix2carry = /*@__NO_SIDE_EFFECTS__ */ (from: number, to: number) => + from + (to - gcd(from, to)); +/** + * Implemented with numbers, because BigInt is 5x slower + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] { + if (!Array.isArray(data)) throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error( + `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}` + ); + } + let carry = 0; + let pos = 0; // bitwise position in current element + const mask = 2 ** to - 1; + const res: number[] = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; // clean carry, otherwise it will cause overflow + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) throw new Error('Excess padding'); + if (!padding && carry) throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) res.push(carry >>> 0); + return res; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function radix(num: number): Coder { + assertNumber(num); + return { + encode: (bytes: Uint8Array) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits: number[]) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of strings'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} + +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +function radix2(bits: number, revPadding = false): Coder { + assertNumber(bits); + if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes: Uint8Array) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits: number[]) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of strings'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} + +type ArgumentTypes = F extends (...args: infer A) => any ? A : never; +/** + * @__NO_SIDE_EFFECTS__ + */ +function unsafeWrapper any>(fn: T) { + if (typeof fn !== 'function') throw new Error('unsafeWrapper fn should be function'); + return function (...args: ArgumentTypes): ReturnType | void { + try { + return fn.apply(null, args); + } catch (e) {} + }; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function checksum( + len: number, + fn: (data: Uint8Array) => Uint8Array +): Coder { + assertNumber(len); + if (typeof fn !== 'function') throw new Error('checksum fn should be function'); + return { + encode(data: Uint8Array) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data: Uint8Array) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum'); + return payload; + }, + }; +} +export const utils = { alphabet, chain, checksum, radix, radix2, join, padding }; + +// RFC 4648 aka RFC 3548 +// --------------------- +export const base16: BytesCoder = /* @__PURE__ */ chain( + radix2(4), + alphabet('0123456789ABCDEF'), + join('') +); +export const base32: BytesCoder = /* @__PURE__ */ chain( + radix2(5), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), + padding(5), + join('') +); +export const base32hex: BytesCoder = /* @__PURE__ */ chain( + radix2(5), + alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), + padding(5), + join('') +); +export const base32crockford: BytesCoder = /* @__PURE__ */ chain( + radix2(5), + alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), + join(''), + normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')) +); +export const base64: BytesCoder = /* @__PURE__ */ chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), + padding(6), + join('') +); +export const base64url: BytesCoder = /* @__PURE__ */ chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), + padding(6), + join('') +); +export const base64urlnopad: BytesCoder = /* @__PURE__ */ chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), + join('') +); + +// base58 code +// ----------- +const genBase58 = (abc: string) => chain(radix(58), alphabet(abc), join('')); + +export const base58: BytesCoder = /* @__PURE__ */ genBase58( + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +); +export const base58flickr: BytesCoder = /* @__PURE__ */ genBase58( + '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' +); +export const base58xrp: BytesCoder = /* @__PURE__ */ genBase58( + 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz' +); + +// xmr ver is done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. +// Block encoding significantly reduces quadratic complexity of base58. + +// Data len (index) -> encoded block len +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +export const base58xmr: BytesCoder = { + encode(data: Uint8Array) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1'); + } + return res; + }, + decode(str: string) { + let res: number[] = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; + +export const base58check = /* @__PURE__ */ (sha256: (data: Uint8Array) => Uint8Array): BytesCoder => + chain( + checksum(4, (data) => sha256(sha256(data))), + base58 + ); + +// Bech32 code +// ----------- +export interface Bech32Decoded { + prefix: Prefix; + words: number[]; +} +export interface Bech32DecodedWithArray { + prefix: Prefix; + words: number[]; + bytes: Uint8Array; +} + +const BECH_ALPHABET: Coder = /* @__PURE__ */ chain( + alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), + join('') +); + +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +/** + * @__NO_SIDE_EFFECTS__ + */ +function bech32Polymod(pre: number): number { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!; + } + return chk; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function bechChecksum(prefix: string, words: number[], encodingConst = 1): string { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function genBech32(encoding: 'bech32' | 'bech32m') { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + + function encode( + prefix: Prefix, + words: number[] | Uint8Array, + limit: number | false = 90 + ): `${Lowercase}1${string}` { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + const lowered = prefix.toLowerCase(); + const sum = bechChecksum(lowered, words, ENCODING_CONST); + return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`; + } + + function decode( + str: `${Prefix}1${string}`, + limit?: number | false + ): Bech32Decoded; + function decode(str: string, limit?: number | false): Bech32Decoded; + function decode(str: string, limit: number | false = 90): Bech32Decoded { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + // don't allow mixed case + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words = str.slice(sepIndex + 1); + if (_words.length < 6) throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(_words).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + + const decodeUnsafe = unsafeWrapper(decode); + + function decodeToBytes(str: string): Bech32DecodedWithArray { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} + +export const bech32 = /* @__PURE__ */ genBech32('bech32'); +export const bech32m = /* @__PURE__ */ genBech32('bech32m'); + +declare const TextEncoder: any; +declare const TextDecoder: any; + +export const utf8: BytesCoder = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; + +export const hex: BytesCoder = /* @__PURE__ */ chain( + radix2(4), + alphabet('0123456789abcdef'), + join(''), + normalize((s: string) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); + }) +); + +// prettier-ignore +const CODERS = { + utf8, hex, base16, base32, base64, base64url, base58, base58xmr +}; +type CoderType = keyof typeof CODERS; +const coderTypeError = + 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr'; + +export const bytesToString = (type: CoderType, bytes: Uint8Array): string => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError); + if (!(bytes instanceof Uint8Array)) throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +export const str = bytesToString; // as in python, but for bytes only + +export const stringToBytes = (type: CoderType, str: string): Uint8Array => { + if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError); + if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +export const bytes = stringToBytes; diff --git a/test/merkletreejs/node_modules/@scure/base/lib/esm/index.js b/test/merkletreejs/node_modules/@scure/base/lib/esm/index.js new file mode 100644 index 0000000..315a338 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/lib/esm/index.js @@ -0,0 +1,462 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities +/** + * @__NO_SIDE_EFFECTS__ + */ +export function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function chain(...args) { + // Wrap call in closure so JIT can inline calls + const wrap = (a, b) => (c) => a(b(c)); + // Construct chain of args[-1].encode(args[-2].encode([...])) + const encode = Array.from(args) + .reverse() + .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined); + // Construct chain of args[0].decode(args[1].decode(...)) + const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined); + return { encode, decode }; +} +/** + * Encodes integer radix representation to array of strings using alphabet and back + * @__NO_SIDE_EFFECTS__ + */ +function alphabet(alphabet) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function join(separator = '') { + if (typeof separator !== 'string') + throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') + throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +function padding(bits, chr = '=') { + assertNumber(bits); + if (typeof chr !== 'string') + throw new Error('padding chr should be string'); + return { + encode(data) { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function normalize(fn) { + if (typeof fn !== 'function') + throw new Error('normalize fn should be function'); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +/** + * Slow: O(n^2) time complexity + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix(data, from, to) { + // base 1 is impossible + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error('convertRadix: data should be array'); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + const rounded = Math.floor(digitBase / to); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!rounded) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = /* @__NO_SIDE_EFFECTS__ */ (a, b) => (!b ? a : gcd(b, a % b)); +const radix2carry = /*@__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to)); +/** + * Implemented with numbers, because BigInt is 5x slower + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix2(data, from, to, padding) { + if (!Array.isArray(data)) + throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; // bitwise position in current element + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; // clean carry, otherwise it will cause overflow + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function radix(num) { + assertNumber(num); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of strings'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of strings'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function unsafeWrapper(fn) { + if (typeof fn !== 'function') + throw new Error('unsafeWrapper fn should be function'); + return function (...args) { + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== 'function') + throw new Error('checksum fn should be function'); + return { + encode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +export const utils = { alphabet, chain, checksum, radix, radix2, join, padding }; +// RFC 4648 aka RFC 3548 +// --------------------- +export const base16 = /* @__PURE__ */ chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); +export const base32 = /* @__PURE__ */ chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +export const base32hex = /* @__PURE__ */ chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +export const base32crockford = /* @__PURE__ */ chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); +export const base64 = /* @__PURE__ */ chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); +export const base64url = /* @__PURE__ */ chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); +export const base64urlnopad = /* @__PURE__ */ chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')); +// base58 code +// ----------- +const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); +export const base58 = /* @__PURE__ */ genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); +export const base58flickr = /* @__PURE__ */ genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); +export const base58xrp = /* @__PURE__ */ genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); +// xmr ver is done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. +// Block encoding significantly reduces quadratic complexity of base58. +// Data len (index) -> encoded block len +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +export const base58xmr = { + encode(data) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; +export const base58check = /* @__PURE__ */ (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58); +const BECH_ALPHABET = /* @__PURE__ */ chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +/** + * @__NO_SIDE_EFFECTS__ + */ +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function genBech32(encoding) { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + const lowered = prefix.toLowerCase(); + const sum = bechChecksum(lowered, words, ENCODING_CONST); + return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`; + } + function decode(str, limit = 90) { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + // don't allow mixed case + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words = str.slice(sepIndex + 1); + if (_words.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(_words).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} +export const bech32 = /* @__PURE__ */ genBech32('bech32'); +export const bech32m = /* @__PURE__ */ genBech32('bech32m'); +export const utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; +export const hex = /* @__PURE__ */ chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); +})); +// prettier-ignore +const CODERS = { + utf8, hex, base16, base32, base64, base64url, base58, base58xmr +}; +const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr'; +export const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!(bytes instanceof Uint8Array)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +export const str = bytesToString; // as in python, but for bytes only +export const stringToBytes = (type, str) => { + if (!CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +export const bytes = stringToBytes; diff --git a/test/merkletreejs/node_modules/@scure/base/lib/esm/package.json b/test/merkletreejs/node_modules/@scure/base/lib/esm/package.json new file mode 100644 index 0000000..8769641 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/lib/esm/package.json @@ -0,0 +1 @@ +{ "type": "module", "sideEffects": false } diff --git a/test/merkletreejs/node_modules/@scure/base/lib/index.d.ts b/test/merkletreejs/node_modules/@scure/base/lib/index.d.ts new file mode 100644 index 0000000..33082b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/lib/index.d.ts @@ -0,0 +1,128 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * @__NO_SIDE_EFFECTS__ + */ +export declare function assertNumber(n: number): void; +export interface Coder { + encode(from: F): T; + decode(to: T): F; +} +export interface BytesCoder extends Coder { + encode: (data: Uint8Array) => string; + decode: (str: string) => Uint8Array; +} +type Chain = [Coder, ...Coder[]]; +type Input = F extends Coder ? T : never; +type Output = F extends Coder ? T : never; +type First = T extends [infer U, ...any[]] ? U : never; +type Last = T extends [...any[], infer U] ? U : never; +type Tail = T extends [any, ...infer U] ? U : never; +type AsChain> = { + [K in keyof C]: Coder, Input>; +}; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function chain>(...args: T): Coder>, Output>>; +type Alphabet = string[] | string; +/** + * Encodes integer radix representation to array of strings using alphabet and back + * @__NO_SIDE_EFFECTS__ + */ +declare function alphabet(alphabet: Alphabet): Coder; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function join(separator?: string): Coder; +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +declare function padding(bits: number, chr?: string): Coder; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function radix(num: number): Coder; +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +declare function radix2(bits: number, revPadding?: boolean): Coder; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function checksum(len: number, fn: (data: Uint8Array) => Uint8Array): Coder; +export declare const utils: { + alphabet: typeof alphabet; + chain: typeof chain; + checksum: typeof checksum; + radix: typeof radix; + radix2: typeof radix2; + join: typeof join; + padding: typeof padding; +}; +export declare const base16: BytesCoder; +export declare const base32: BytesCoder; +export declare const base32hex: BytesCoder; +export declare const base32crockford: BytesCoder; +export declare const base64: BytesCoder; +export declare const base64url: BytesCoder; +export declare const base64urlnopad: BytesCoder; +export declare const base58: BytesCoder; +export declare const base58flickr: BytesCoder; +export declare const base58xrp: BytesCoder; +export declare const base58xmr: BytesCoder; +export declare const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder; +export interface Bech32Decoded { + prefix: Prefix; + words: number[]; +} +export interface Bech32DecodedWithArray { + prefix: Prefix; + words: number[]; + bytes: Uint8Array; +} +export declare const bech32: { + encode: (prefix: Prefix, words: number[] | Uint8Array, limit?: number | false) => `${Lowercase}1${string}`; + decode: { + (str: `${Prefix_1}1${string}`, limit?: number | false): Bech32Decoded; + (str: string, limit?: number | false): Bech32Decoded; + }; + decodeToBytes: (str: string) => Bech32DecodedWithArray; + decodeUnsafe: (str: string, limit?: number | false | undefined) => void | Bech32Decoded; + fromWords: (to: number[]) => Uint8Array; + fromWordsUnsafe: (to: number[]) => void | Uint8Array; + toWords: (from: Uint8Array) => number[]; +}; +export declare const bech32m: { + encode: (prefix: Prefix, words: number[] | Uint8Array, limit?: number | false) => `${Lowercase}1${string}`; + decode: { + (str: `${Prefix_1}1${string}`, limit?: number | false): Bech32Decoded; + (str: string, limit?: number | false): Bech32Decoded; + }; + decodeToBytes: (str: string) => Bech32DecodedWithArray; + decodeUnsafe: (str: string, limit?: number | false | undefined) => void | Bech32Decoded; + fromWords: (to: number[]) => Uint8Array; + fromWordsUnsafe: (to: number[]) => void | Uint8Array; + toWords: (from: Uint8Array) => number[]; +}; +export declare const utf8: BytesCoder; +export declare const hex: BytesCoder; +declare const CODERS: { + utf8: BytesCoder; + hex: BytesCoder; + base16: BytesCoder; + base32: BytesCoder; + base64: BytesCoder; + base64url: BytesCoder; + base58: BytesCoder; + base58xmr: BytesCoder; +}; +type CoderType = keyof typeof CODERS; +export declare const bytesToString: (type: CoderType, bytes: Uint8Array) => string; +export declare const str: (type: CoderType, bytes: Uint8Array) => string; +export declare const stringToBytes: (type: CoderType, str: string) => Uint8Array; +export declare const bytes: (type: CoderType, str: string) => Uint8Array; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/base/lib/index.d.ts.map b/test/merkletreejs/node_modules/@scure/base/lib/index.d.ts.map new file mode 100644 index 0000000..dcd751d --- /dev/null +++ b/test/merkletreejs/node_modules/@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QJ,CAAC;AAC1D,eAAO,MAAM,OAAO;2DArDT,MAAM,EAAE,GAAG,UAAU,UACrB,MAAM,GAAG,KAAK;;wEAgBb,MAAM,GAAG,KAAK;cAEH,MAAM,UAAU,MAAM,GAAG,KAAK,GAAG,aAAa;;yBAyBvC,MAAM,KAAG,sBAAsB;;;;;CASF,CAAC;AAK5D,eAAO,MAAM,IAAI,EAAE,UAGlB,CAAC;AAEF,eAAO,MAAM,GAAG,EAAE,UASjB,CAAC;AAGF,QAAA,MAAM,MAAM;;;;;;;;;CAEX,CAAC;AACF,KAAK,SAAS,GAAG,MAAM,OAAO,MAAM,CAAC;AAIrC,eAAO,MAAM,aAAa,SAAU,SAAS,SAAS,UAAU,KAAG,MAIlE,CAAC;AACF,eAAO,MAAM,GAAG,SALoB,SAAS,SAAS,UAAU,KAAG,MAKnC,CAAC;AAEjC,eAAO,MAAM,aAAa,SAAU,SAAS,OAAO,MAAM,KAAG,UAI5D,CAAC;AACF,eAAO,MAAM,KAAK,SALkB,SAAS,OAAO,MAAM,KAAG,UAK3B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/base/lib/index.js b/test/merkletreejs/node_modules/@scure/base/lib/index.js new file mode 100644 index 0000000..a52c4ea --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/lib/index.js @@ -0,0 +1,469 @@ +"use strict"; +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64urlnopad = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; +// Utilities +/** + * @__NO_SIDE_EFFECTS__ + */ +function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); +} +exports.assertNumber = assertNumber; +/** + * @__NO_SIDE_EFFECTS__ + */ +function chain(...args) { + // Wrap call in closure so JIT can inline calls + const wrap = (a, b) => (c) => a(b(c)); + // Construct chain of args[-1].encode(args[-2].encode([...])) + const encode = Array.from(args) + .reverse() + .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined); + // Construct chain of args[0].decode(args[1].decode(...)) + const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined); + return { encode, decode }; +} +/** + * Encodes integer radix representation to array of strings using alphabet and back + * @__NO_SIDE_EFFECTS__ + */ +function alphabet(alphabet) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function join(separator = '') { + if (typeof separator !== 'string') + throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') + throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +function padding(bits, chr = '=') { + assertNumber(bits); + if (typeof chr !== 'string') + throw new Error('padding chr should be string'); + return { + encode(data) { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function normalize(fn) { + if (typeof fn !== 'function') + throw new Error('normalize fn should be function'); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +/** + * Slow: O(n^2) time complexity + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix(data, from, to) { + // base 1 is impossible + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error('convertRadix: data should be array'); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + const rounded = Math.floor(digitBase / to); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!rounded) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = /* @__NO_SIDE_EFFECTS__ */ (a, b) => (!b ? a : gcd(b, a % b)); +const radix2carry = /*@__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to)); +/** + * Implemented with numbers, because BigInt is 5x slower + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix2(data, from, to, padding) { + if (!Array.isArray(data)) + throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; // bitwise position in current element + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; // clean carry, otherwise it will cause overflow + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function radix(num) { + assertNumber(num); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of strings'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of strings'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function unsafeWrapper(fn) { + if (typeof fn !== 'function') + throw new Error('unsafeWrapper fn should be function'); + return function (...args) { + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== 'function') + throw new Error('checksum fn should be function'); + return { + encode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding }; +// RFC 4648 aka RFC 3548 +// --------------------- +exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); +exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); +exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); +exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); +exports.base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')); +// base58 code +// ----------- +const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); +exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); +exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); +exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); +// xmr ver is done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. +// Block encoding significantly reduces quadratic complexity of base58. +// Data len (index) -> encoded block len +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +exports.base58xmr = { + encode(data) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = exports.base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; +const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58); +exports.base58check = base58check; +const BECH_ALPHABET = /* @__PURE__ */ chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +/** + * @__NO_SIDE_EFFECTS__ + */ +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function genBech32(encoding) { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + const lowered = prefix.toLowerCase(); + const sum = bechChecksum(lowered, words, ENCODING_CONST); + return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`; + } + function decode(str, limit = 90) { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + // don't allow mixed case + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words = str.slice(sepIndex + 1); + if (_words.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(_words).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} +exports.bech32 = genBech32('bech32'); +exports.bech32m = genBech32('bech32m'); +exports.utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; +exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); +})); +// prettier-ignore +const CODERS = { + utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr +}; +const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr'; +const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!(bytes instanceof Uint8Array)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +exports.bytesToString = bytesToString; +exports.str = exports.bytesToString; // as in python, but for bytes only +const stringToBytes = (type, str) => { + if (!CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +exports.stringToBytes = stringToBytes; +exports.bytes = exports.stringToBytes; diff --git a/test/merkletreejs/node_modules/@scure/base/package.json b/test/merkletreejs/node_modules/@scure/base/package.json new file mode 100644 index 0000000..33d31f3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/base/package.json @@ -0,0 +1,60 @@ +{ + "name": "@scure/base", + "version": "1.1.3", + "description": "Secure, audited & 0-dep implementation of base64, bech32, base58, base32 & base16", + "files": [ + "lib/index.js", + "lib/esm/index.js", + "lib/esm/package.json", + "lib/index.d.ts", + "lib/index.d.ts.map", + "index.ts" + ], + "main": "lib/index.js", + "module": "lib/esm/index.js", + "types": "lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "import": "./lib/esm/index.js", + "default": "./lib/index.js" + } + }, + "scripts": { + "bench": "node test/benchmark/index.js", + "build": "tsc && tsc -p tsconfig.esm.json", + "lint": "prettier --check index.ts", + "format": "prettier --write index.ts", + "test": "node test/index.js", + "test:deno": "deno test test/deno.ts" + }, + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT", + "homepage": "https://paulmillr.com/noble/#scure", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/scure-base.git" + }, + "devDependencies": { + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "keywords": [ + "bech32", + "bech32m", + "base64", + "base58", + "base32", + "base16", + "rfc4648", + "rfc3548", + "crockford", + "encode", + "encoder", + "base-x", + "base" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/LICENSE b/test/merkletreejs/node_modules/@scure/bip32/LICENSE new file mode 100644 index 0000000..68222b8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +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. diff --git a/test/merkletreejs/node_modules/@scure/bip32/README.md b/test/merkletreejs/node_modules/@scure/bip32/README.md new file mode 100644 index 0000000..ea5bfbb --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/README.md @@ -0,0 +1,107 @@ +# scure-bip32 + +Secure, [audited](#security) & minimal implementation of BIP32 hierarchical deterministic (HD) wallets over secp256k1. + +Compared to popular `hdkey` package, scure-bip32: + +- Supports ESM and common.js +- Is 418KB all-bundled instead of 5.9MB +- Uses 3 dependencies instead of 24 +- Had an external security [audit](#security) by Cure53 + +Check out [scure-bip39](https://github.com/paulmillr/scure-bip39) if you need mnemonic phrases. See [ed25519-keygen](https://github.com/paulmillr/ed25519-keygen) if you need SLIP-0010/BIP32 ed25519 hdkey implementation. + +### This library belongs to *scure* + +> **scure** — secure, independently audited packages for every use case. + +- Audited by a third-party +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer) + +## Usage + +> npm install @scure/bip32 + +This module exports a single class `HDKey`, which should be used like this: + +```ts +const { HDKey } = require("@scure/bip32"); +const hdkey1 = HDKey.fromMasterSeed(seed); +const hdkey2 = HDKey.fromExtendedKey(base58key); +const hdkey3 = HDKey.fromJSON({ xpriv: string }); + +// props +[hdkey1.depth, hdkey1.index, hdkey1.chainCode]; +console.log(hdkey2.privateKey, hdkey2.publicKey); +console.log(hdkey3.derive("m/0/2147483647'/1")); +const sig = hdkey3.sign(hash); +hdkey3.verify(hash, sig); +``` + +Note: `chainCode` property is essentially a private part +of a secret "master" key, it should be guarded from unauthorized access. + +The full API is: + +```ts +class HDKey { + public static HARDENED_OFFSET: number; + public static fromMasterSeed(seed: Uint8Array, versions: Versions): HDKey; + public static fromExtendedKey(base58key: string, versions: Versions): HDKey; + public static fromJSON(json: { xpriv: string }): HDKey; + + readonly versions: Versions; + readonly depth: number = 0; + readonly index: number = 0; + readonly chainCode: Uint8Array | null = null; + readonly parentFingerprint: number = 0; + + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + + derive(path: string): HDKey; + deriveChild(index: number): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; +} + +interface Versions { + private: number; + public: number; +} +``` + +The `hdkey` submodule provides a library for keys derivation according to +[BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). + +It has almost the exact same API than the version `1.x` of +[`hdkey` from cryptocoinjs](https://github.com/cryptocoinjs/hdkey), +but it's backed by this package's primitives, and has built-in TypeScript types. +Its only difference is that it has to be be used with a named import. +The implementation is [loosely based on hdkey, which has MIT License](#LICENSE). + +## Security + +The library has been audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). See [changes since audit](https://github.com/paulmillr/scure-bip32/compare/1.0.1..main). + +1. The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) +2. At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), it + was extracted to a separate package called `micro-bip32` +3. After the audit we've decided to use NPM namespace for security. Since `@micro` namespace was taken, we've renamed the package to `@scure/bip32` + +## License + +[MIT License](./LICENSE) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) diff --git a/test/merkletreejs/node_modules/@scure/bip32/index.ts b/test/merkletreejs/node_modules/@scure/bip32/index.ts new file mode 100644 index 0000000..d0496ef --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/index.ts @@ -0,0 +1,307 @@ +/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { sha256 } from '@noble/hashes/sha256'; +import { sha512 } from '@noble/hashes/sha512'; +import { bytes as assertBytes } from '@noble/hashes/_assert'; +import { bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { secp256k1 as secp } from '@noble/curves/secp256k1'; +import { mod } from '@noble/curves/abstract/modular'; +import { base58check as base58checker } from '@scure/base'; + +const Point = secp.ProjectivePoint; +const base58check = base58checker(sha256); + +function bytesToNumber(bytes: Uint8Array): bigint { + return BigInt(`0x${bytesToHex(bytes)}`); +} + +function numberToBytes(num: bigint): Uint8Array { + return hexToBytes(num.toString(16).padStart(64, '0')); +} + +const MASTER_SECRET = utf8ToBytes('Bitcoin seed'); +// Bitcoin hardcoded by default +const BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e }; +export const HARDENED_OFFSET: number = 0x80000000; + +export interface Versions { + private: number; + public: number; +} + +const hash160 = (data: Uint8Array) => ripemd160(sha256(data)); +const fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false); +const toU32 = (n: number) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; + +interface HDKeyOpt { + versions: Versions; + depth?: number; + index?: number; + parentFingerprint?: number; + chainCode: Uint8Array; + publicKey?: Uint8Array; + privateKey?: Uint8Array | bigint; +} + +export class HDKey { + get fingerprint(): number { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier(): Uint8Array | undefined { + return this.pubHash; + } + get pubKeyHash(): Uint8Array | undefined { + return this.pubHash; + } + get privateKey(): Uint8Array | null { + return this.privKeyBytes || null; + } + get publicKey(): Uint8Array | null { + return this.pubKey || null; + } + get privateExtendedKey(): string { + const priv = this.privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode( + this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv)) + ); + } + get publicExtendedKey(): string { + if (!this.pubKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this.pubKey)); + } + + public static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey { + assertBytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error( + `HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)` + ); + } + const I = hmac(sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + + public static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey { + // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + const keyBuffer: Uint8Array = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } else { + return new HDKey({ ...opt, publicKey: key }); + } + } + + public static fromJSON(json: { xpriv: string }): HDKey { + return HDKey.fromExtendedKey(json.xpriv); + } + public readonly versions: Versions; + public readonly depth: number = 0; + public readonly index: number = 0; + public readonly chainCode: Uint8Array | null = null; + public readonly parentFingerprint: number = 0; + private privKey?: bigint; + private privKeyBytes?: Uint8Array; + private pubKey?: Uint8Array; + private pubHash: Uint8Array | undefined; + + constructor(opt: HDKeyOpt) { + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error('Invalid private key'); + } + this.privKey = + typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp.getPublicKey(opt.privateKey, true); + } else if (opt.publicKey) { + this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point + } else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this.pubKey); + } + + public derive(path: string): HDKey { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + // tslint:disable-next-line + let child: HDKey = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + // hardened key + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + + public deriveChild(index: number): HDKey { + if (!this.pubKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + // Hardened + const priv = this.privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + // Hardened child: 0x00 || ser256(kpar) || ser32(index) + data = concatBytes(new Uint8Array([0]), priv, data); + } else { + // Normal child: serP(point(kpar)) || ser32(index) + data = concatBytes(this.pubKey, data); + } + const I = hmac(sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp.utils.isValidPrivateKey(childTweak)) { + throw new Error('Tweak bigger than curve order'); + } + const opt: HDKeyOpt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + // Private parent key -> private child key + if (this.privateKey) { + const added = mod(this.privKey! + childTweak, secp.CURVE.n); + if (!secp.utils.isValidPrivateKey(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = added; + } else { + const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); + // Cryptographically impossible: hmac-sha512 preimage would need to be found + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } catch (err) { + return this.deriveChild(index + 1); + } + } + + public sign(hash: Uint8Array): Uint8Array { + if (!this.privateKey) { + throw new Error('No privateKey set!'); + } + assertBytes(hash, 32); + return secp.sign(hash, this.privKey!).toCompactRawBytes(); + } + + public verify(hash: Uint8Array, signature: Uint8Array): boolean { + assertBytes(hash, 32); + assertBytes(signature, 64); + if (!this.publicKey) { + throw new Error('No publicKey set!'); + } + let sig; + try { + sig = secp.Signature.fromCompact(signature); + } catch (error) { + return false; + } + return secp.verify(sig, hash, this.publicKey); + } + + public wipePrivateData(): this { + this.privKey = undefined; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = undefined; + } + return this; + } + public toJSON(): { xpriv: string; xpub: string } { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + + private serialize(version: number, key: Uint8Array) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + assertBytes(key, 33); + // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + return concatBytes( + toU32(version), + new Uint8Array([this.depth]), + toU32(this.parentFingerprint), + toU32(this.index), + this.chainCode, + key + ); + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/lib/esm/index.js b/test/merkletreejs/node_modules/@scure/bip32/lib/esm/index.js new file mode 100644 index 0000000..a5e768b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/lib/esm/index.js @@ -0,0 +1,257 @@ +import { hmac } from '@noble/hashes/hmac'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { sha256 } from '@noble/hashes/sha256'; +import { sha512 } from '@noble/hashes/sha512'; +import { bytes as assertBytes } from '@noble/hashes/_assert'; +import { bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes } from '@noble/hashes/utils'; +import { secp256k1 as secp } from '@noble/curves/secp256k1'; +import { mod } from '@noble/curves/abstract/modular'; +import { base58check as base58checker } from '@scure/base'; +const Point = secp.ProjectivePoint; +const base58check = base58checker(sha256); +function bytesToNumber(bytes) { + return BigInt(`0x${bytesToHex(bytes)}`); +} +function numberToBytes(num) { + return hexToBytes(num.toString(16).padStart(64, '0')); +} +const MASTER_SECRET = utf8ToBytes('Bitcoin seed'); +const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e }; +export const HARDENED_OFFSET = 0x80000000; +const hash160 = (data) => ripemd160(sha256(data)); +const fromU32 = (data) => createView(data).getUint32(0, false); +const toU32 = (n) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; +export class HDKey { + get fingerprint() { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + get privateKey() { + return this.privKeyBytes || null; + } + get publicKey() { + return this.pubKey || null; + } + get privateExtendedKey() { + const priv = this.privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv))); + } + get publicExtendedKey() { + if (!this.pubKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this.pubKey)); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + assertBytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`); + } + const I = hmac(sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + const keyBuffer = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } + else { + return new HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return HDKey.fromExtendedKey(json.xpriv); + } + constructor(opt) { + this.depth = 0; + this.index = 0; + this.chainCode = null; + this.parentFingerprint = 0; + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error('Invalid private key'); + } + this.privKey = + typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp.getPublicKey(opt.privateKey, true); + } + else if (opt.publicKey) { + this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); + } + else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this.pubKey); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + deriveChild(index) { + if (!this.pubKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + const priv = this.privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + data = concatBytes(new Uint8Array([0]), priv, data); + } + else { + data = concatBytes(this.pubKey, data); + } + const I = hmac(sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp.utils.isValidPrivateKey(childTweak)) { + throw new Error('Tweak bigger than curve order'); + } + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + if (this.privateKey) { + const added = mod(this.privKey + childTweak, secp.CURVE.n); + if (!secp.utils.isValidPrivateKey(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = added; + } + else { + const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } + catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash) { + if (!this.privateKey) { + throw new Error('No privateKey set!'); + } + assertBytes(hash, 32); + return secp.sign(hash, this.privKey).toCompactRawBytes(); + } + verify(hash, signature) { + assertBytes(hash, 32); + assertBytes(signature, 64); + if (!this.publicKey) { + throw new Error('No publicKey set!'); + } + let sig; + try { + sig = secp.Signature.fromCompact(signature); + } + catch (error) { + return false; + } + return secp.verify(sig, hash, this.publicKey); + } + wipePrivateData() { + this.privKey = undefined; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = undefined; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + assertBytes(key, 33); + return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/lib/esm/index.js.map b/test/merkletreejs/node_modules/@scure/bip32/lib/esm/index.js.map new file mode 100644 index 0000000..a764a14 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACnG,OAAO,EAAE,SAAS,IAAI,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,WAAW,IAAI,aAAa,EAAE,MAAM,aAAa,CAAC;AAE3D,MAAM,KAAK,GAAG,IAAI,CAAC,eAAe,CAAC;AACnC,MAAM,WAAW,GAAG,aAAa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AC,iBAAiB;SAC7B,CAAC;IACJ,CAAC;IAEO,SAAS,CAAC,OAAe,EAAE,GAAe;QAChD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QACD,WAAW,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAErB,OAAO,WAAW,CAChB,KAAK,CAAC,OAAO,CAAC,EACd,IAAI,UAAU,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAC5B,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAC7B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EACjB,IAAI,CAAC,SAAS,EACd,GAAG,CACJ,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/lib/esm/package.json b/test/merkletreejs/node_modules/@scure/bip32/lib/esm/package.json new file mode 100644 index 0000000..e8309c4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/lib/esm/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "browser": { + "crypto": false + } +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/lib/index.d.ts b/test/merkletreejs/node_modules/@scure/bip32/lib/index.d.ts new file mode 100644 index 0000000..753367b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/lib/index.d.ts @@ -0,0 +1,49 @@ +export declare const HARDENED_OFFSET: number; +export interface Versions { + private: number; + public: number; +} +interface HDKeyOpt { + versions: Versions; + depth?: number; + index?: number; + parentFingerprint?: number; + chainCode: Uint8Array; + publicKey?: Uint8Array; + privateKey?: Uint8Array | bigint; +} +export declare class HDKey { + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + static fromMasterSeed(seed: Uint8Array, versions?: Versions): HDKey; + static fromExtendedKey(base58key: string, versions?: Versions): HDKey; + static fromJSON(json: { + xpriv: string; + }): HDKey; + readonly versions: Versions; + readonly depth: number; + readonly index: number; + readonly chainCode: Uint8Array | null; + readonly parentFingerprint: number; + private privKey?; + private privKeyBytes?; + private pubKey?; + private pubHash; + constructor(opt: HDKeyOpt); + derive(path: string): HDKey; + deriveChild(index: number): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; + toJSON(): { + xpriv: string; + xpub: string; + }; + private serialize; +} +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/lib/index.js b/test/merkletreejs/node_modules/@scure/bip32/lib/index.js new file mode 100644 index 0000000..04722bd --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/lib/index.js @@ -0,0 +1,261 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HDKey = exports.HARDENED_OFFSET = void 0; +const hmac_1 = require("@noble/hashes/hmac"); +const ripemd160_1 = require("@noble/hashes/ripemd160"); +const sha256_1 = require("@noble/hashes/sha256"); +const sha512_1 = require("@noble/hashes/sha512"); +const _assert_1 = require("@noble/hashes/_assert"); +const utils_1 = require("@noble/hashes/utils"); +const secp256k1_1 = require("@noble/curves/secp256k1"); +const modular_1 = require("@noble/curves/abstract/modular"); +const base_1 = require("@scure/base"); +const Point = secp256k1_1.secp256k1.ProjectivePoint; +const base58check = (0, base_1.base58check)(sha256_1.sha256); +function bytesToNumber(bytes) { + return BigInt(`0x${(0, utils_1.bytesToHex)(bytes)}`); +} +function numberToBytes(num) { + return (0, utils_1.hexToBytes)(num.toString(16).padStart(64, '0')); +} +const MASTER_SECRET = (0, utils_1.utf8ToBytes)('Bitcoin seed'); +const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e }; +exports.HARDENED_OFFSET = 0x80000000; +const hash160 = (data) => (0, ripemd160_1.ripemd160)((0, sha256_1.sha256)(data)); +const fromU32 = (data) => (0, utils_1.createView)(data).getUint32(0, false); +const toU32 = (n) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + (0, utils_1.createView)(buf).setUint32(0, n, false); + return buf; +}; +class HDKey { + get fingerprint() { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + get privateKey() { + return this.privKeyBytes || null; + } + get publicKey() { + return this.pubKey || null; + } + get privateExtendedKey() { + const priv = this.privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode(this.serialize(this.versions.private, (0, utils_1.concatBytes)(new Uint8Array([0]), priv))); + } + get publicExtendedKey() { + if (!this.pubKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this.pubKey)); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + (0, _assert_1.bytes)(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`); + } + const I = (0, hmac_1.hmac)(sha512_1.sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + const keyBuffer = base58check.decode(base58key); + const keyView = (0, utils_1.createView)(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } + else { + return new HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return HDKey.fromExtendedKey(json.xpriv); + } + constructor(opt) { + this.depth = 0; + this.index = 0; + this.chainCode = null; + this.parentFingerprint = 0; + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error('Invalid private key'); + } + this.privKey = + typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp256k1_1.secp256k1.getPublicKey(opt.privateKey, true); + } + else if (opt.publicKey) { + this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); + } + else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this.pubKey); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= exports.HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + if (m[2] === "'") { + idx += exports.HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + deriveChild(index) { + if (!this.pubKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= exports.HARDENED_OFFSET) { + const priv = this.privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + data = (0, utils_1.concatBytes)(new Uint8Array([0]), priv, data); + } + else { + data = (0, utils_1.concatBytes)(this.pubKey, data); + } + const I = (0, hmac_1.hmac)(sha512_1.sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(childTweak)) { + throw new Error('Tweak bigger than curve order'); + } + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + if (this.privateKey) { + const added = (0, modular_1.mod)(this.privKey + childTweak, secp256k1_1.secp256k1.CURVE.n); + if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = added; + } + else { + const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } + catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash) { + if (!this.privateKey) { + throw new Error('No privateKey set!'); + } + (0, _assert_1.bytes)(hash, 32); + return secp256k1_1.secp256k1.sign(hash, this.privKey).toCompactRawBytes(); + } + verify(hash, signature) { + (0, _assert_1.bytes)(hash, 32); + (0, _assert_1.bytes)(signature, 64); + if (!this.publicKey) { + throw new Error('No publicKey set!'); + } + let sig; + try { + sig = secp256k1_1.secp256k1.Signature.fromCompact(signature); + } + catch (error) { + return false; + } + return secp256k1_1.secp256k1.verify(sig, hash, this.publicKey); + } + wipePrivateData() { + this.privKey = undefined; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = undefined; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + (0, _assert_1.bytes)(key, 33); + return (0, utils_1.concatBytes)(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); + } +} +exports.HDKey = HDKey; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/lib/index.js.map b/test/merkletreejs/node_modules/@scure/bip32/lib/index.js.map new file mode 100644 index 0000000..81026d4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;AACA,6CAA0C;AAC1C,uDAAoD;AACpD,iDAA8C;AAC9C,iDAA8C;AAC9C,mDAA6D;AAC7D,+CAAmG;AACnG,uDAA4D;AAC5D,4DAAqD;AACrD,sCAA2D;AAE3D,MAAM,KAAK,GAAG,qBAAI,CAAC,eAAe,CAAC;AACnC,MAAM,WAAW,GAAG,IAAA,kBAAa,EAAC,eAAM,CAAC,CAAC;AAE1C,SAAS,aAAa,CAAC,KAAiB;IACtC,OAAO,MAAM,CAAC,KAAK,IAAA,kBAAU,EAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED,SAAS,aAAa,CAAC,GAAW;IAChC,OAAO,IAAA,kBAAU,EAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,aAAa,GAAG,IAAA,mBAAW,EAAC,cAAc,CAAC,CAAC;AAElD,MAAM,gBAAgB,GAAa,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;AAClE,QAAA,eAAe,GAAW,UAAU,CAAC;AAOlD,MAAM,OAAO,GAAG,CAAC,IAAgB,EAAE,EAAE,CAAC,IAAA,qBAAS,EAAC,IAAA,eAAM,EAAC,IAAI,CAAC,CAAC,CAAC;AAC9D,MAAM,OAAO,GAAG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/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/LICENSE b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/README.md b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..6f71600 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/README.md @@ -0,0 +1,534 @@ +# noble-hashes + +Audited & minimal JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2 & Scrypt. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: chained tests, sliding window tests, DoS tests, fuzzing +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🐢 Scrypt supports `N: 2**22`, while other implementations are limited to `2**20` +- 🦘 SHA3 supports Keccak, TupleHash, KangarooTwelve and MarsupilamiFourteen +- 🪶 Just 3.4k lines / 17KB gzipped. SHA256-only is 240 lines / 3KB gzipped + +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported on all major platforms +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) + +## Usage + +> npm install @noble/hashes + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +```js +// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size +import { sha256 } from '@noble/hashes/sha256'; // ECMAScript modules (ESM) and Common.js +// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha256'; // Deno +console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] +// you could also pass strings that will be UTF8-encoded to Uint8Array +console.log(sha256('abc')); // == sha256(new TextEncoder().encode('abc')) + +// sha384 is here, because it uses same internals as sha512 +import { sha512, sha512_256, sha384 } from '@noble/hashes/sha512'; +// prettier-ignore +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3'; +// prettier-ignore +import { + cshake128, cshake256, kmac128, kmac256, + k12, m14, + tuplehash256, parallelhash256, keccakprg +} from '@noble/hashes/sha3-addons'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { blake3 } from '@noble/hashes/blake3'; +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { hmac } from '@noble/hashes/hmac'; +import { hkdf } from '@noble/hashes/hkdf'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; + +import { sha1 } from '@noble/hashes/sha1'; // legacy + +// small utility method that converts bytes to hex +import { bytesToHex as toHex } from '@noble/hashes/utils'; +console.log(toHex(sha256('abc'))); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +``` + +## API + +All hash functions: + +- can be called directly, with `Uint8Array`. +- return `Uint8Array` +- can receive `string`, which is automatically converted to `Uint8Array` + via utf8 encoding **(not hex)** +- support hashing 4GB of data per update on 64-bit systems (unlimited with streaming) + +```ts +function hash(message: Uint8Array | string): Uint8Array; +hash(new Uint8Array([1, 3])); +hash('string') == hash(new TextEncoder().encode('string')); +``` + +All hash functions can be constructed via `hash.create()` method: + +- the result is `Hash` subclass instance, which has `update()` and `digest()` methods +- `digest()` finalizes the hash and makes it no longer usable + +```ts +hash + .create() + .update(new Uint8Array([1, 3])) + .digest(); +``` + +_Some_ hash functions can also receive `options` object, which can be either passed as a: + +- second argument to hash function: `blake3('abc', { key: 'd', dkLen: 32 })` +- first argument to class initializer: `blake3.create({ context: 'e', dkLen: 32 })` + +## Modules + +- [SHA2 (sha256, sha384, sha512, sha512_256)](#sha2-sha256-sha384-sha512-sha512_256) +- [SHA3 (FIPS, SHAKE, Keccak)](#sha3-fips-shake-keccak) +- [SHA3 Addons (cSHAKE, KMAC, KangarooTwelve, MarsupilamiFourteen)](#sha3-addons-cshake-kmac-tuplehash-parallelhash-kangarootwelve-marsupilamifourteen) +- [RIPEMD-160](#ripemd-160) +- [BLAKE2b, BLAKE2s](#blake2b-blake2s) +- [BLAKE3](#blake3) +- [SHA1 (legacy)](#sha1-legacy) +- [HMAC](#hmac) +- [HKDF](#hkdf) +- [PBKDF2](#pbkdf2) +- [Scrypt](#scrypt) +- [ESKDF](#eskdf) +- [utils](#utils) + +##### SHA2 (sha256, sha384, sha512, sha512_256) + +```typescript +import { sha256 } from '@noble/hashes/sha256'; +const h1a = sha256('abc'); +const h1b = sha256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +```typescript +import { sha512 } from '@noble/hashes/sha512'; +const h2a = sha512('abc'); +const h2b = sha512 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA512/256 variant +import { sha512_256 } from '@noble/hashes/sha512'; +const h3a = sha512_256('abc'); +const h3b = sha512_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA384 +import { sha384 } from '@noble/hashes/sha512'; +const h4a = sha384('abc'); +const h4b = sha384 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +##### SHA3 (FIPS, SHAKE, Keccak) + +```typescript +import { + sha3_224, + sha3_256, + sha3_384, + sha3_512, + keccak_224, + keccak_256, + keccak_384, + keccak_512, + shake128, + shake256, +} from '@noble/hashes/sha3'; +const h5a = sha3_256('abc'); +const h5b = sha3_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +const h6a = keccak_256('abc'); +const h7a = shake128('abc', { dkLen: 512 }); +const h7b = shake256('abc', { dkLen: 512 }); +``` + +See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +##### SHA3 Addons (cSHAKE, KMAC, TupleHash, ParallelHash, KangarooTwelve, MarsupilamiFourteen) + +```typescript +import { + cshake128, + cshake256, + kmac128, + kmac256, + k12, + m14, + tuplehash128, + tuplehash256, + parallelhash128, + parallelhash256, + keccakprg, +} from '@noble/hashes/sha3-addons'; +const h7c = cshake128('abc', { personalization: 'def' }); +const h7d = cshake256('abc', { personalization: 'def' }); +const h7e = kmac128('key', 'message'); +const h7f = kmac256('key', 'message'); +const h7h = k12('abc'); +const h7g = m14('abc'); +const h7i = tuplehash128(['ab', 'c']); // tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash(['abc']) +// Same as k12/blake3, but without reduced number of rounds. Doesn't speedup anything due lack of SIMD and threading, +// added for compatibility. +const h7j = parallelhash128('abc', { blockLen: 8 }); +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.feed('test'); +const rand1b = p.fetch(1); +``` + +- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): + cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants +- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), + [RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) + and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with + reduced number of rounds (same as Blake3 and ParallelHash). +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak + +##### RIPEMD-160 + +```typescript +import { ripemd160 } from '@noble/hashes/ripemd160'; +// function ripemd160(data: Uint8Array): Uint8Array; +const hash8 = ripemd160('abc'); +const hash9 = ripemd160() + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), +[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) + +##### BLAKE2b, BLAKE2s + +```typescript +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +const h10a = blake2s('abc'); +const b2params = { key: new Uint8Array([1]), personalization: t, salt: t, dkLen: 32 }; +const h10b = blake2s('abc', b2params); +const h10c = blake2s + .create(b2params) + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net). + +##### BLAKE3 + +```typescript +import { blake3 } from '@noble/hashes/blake3'; +// All params are optional +const h11 = blake3('abc', { dkLen: 256, key: 'def', context: 'fji' }); +``` + +##### SHA1 (legacy) + +SHA1 was cryptographically broken, however, it was not broken for cases like HMAC. + +See [RFC4226 B.2](https://datatracker.ietf.org/doc/html/rfc4226#appendix-B.2). + +Don't use it for a new protocol. + +```typescript +import { sha1 } from '@noble/hashes/sha1'; +const h12 = sha1('def'); +``` + +##### HMAC + +```typescript +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +const mac1 = hmac(sha256, 'key', 'message'); +const mac2 = hmac.create(sha256, Uint8Array.from([1, 2, 3])).update(Uint8Array.from([4, 5, 6])).digest(); +``` + +Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +##### HKDF + +```typescript +import { hkdf } from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = 'abc'; +const dkLen = 32; +const hk1 = hkdf(sha256, inputKey, salt, info, dkLen); + +// == same as +import * as hkdf from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +const prk = hkdf.extract(sha256, inputKey, salt); +const hk2 = hkdf.expand(sha256, prk, info, dkLen); +``` + +Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +##### PBKDF2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 32, + dkLen: 32, +}); +``` + +Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +##### Scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 22, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). +- `dkLen` is the length of output bytes +- It is common to use N from `2**10` to `2**22` and `{r: 8, p: 1, dkLen: 32}` +- `onProgress` can be used with async version of the function to report progress to a user. + +Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, +which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent +DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to +`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase +`maxmem` using the formula above. + +_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS +libs. Many other implementations don't support it. We cannot support `2**23`, +because there is a limitation in JS engines that makes allocating +arrays bigger than 4GB impossible, but we're looking into other possible solutions. + +##### Argon2 + +Experimental Argon2 RFC 9106 implementation. It may be removed at any time. + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2'; +const result = argon2id('password', 'salt', { t: 2, m: 65536, p: 1 }); +``` + +##### ESKDF + +A tiny stretched KDF for various applications like AES key-gen. Takes >= 2 seconds to execute. + +Takes following params: + +- `username` - username, email, or identifier, min: 8 characters, should have enough entropy +- `password` - min: 8 characters, should have enough entropy + +Produces ESKDF instance that has `deriveChildKey(protocol, accountId[, options])` function. + +- `protocol` - 3-15 character protocol name +- `accountId` - numeric identifier of account +- `options` - `keyLength: 32` with specified key length (default is 32), + or `modulus: 2n ** 221n - 17n` with specified modulus. It will fetch modulus + 64 bits of + data, execute modular division. The result will have negligible bias as per FIPS 186 B.4.1. + Can be used to generate, for example, elliptic curve keys. + +Takes username and password, then takes protocol name and account id. + +```typescript +import { eskdf } from '@noble/hashes/eskdf'; +const kdf = await eskdf('example@university', 'beginning-new-example'); +console.log(kdf.fingerprint); +const key1 = kdf.deriveChildKey('aes', 0); +const key2 = kdf.deriveChildKey('aes', 0, { keyLength: 16 }); +const ecc1 = kdf.deriveChildKey('ecc', 0, { modulus: 2n ** 252n - 27742317777372353535851937790883648493n }) +kdf.expire(); +``` + +##### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +## Security + +Noble is production-ready. + +1. The library has been audited in Jan 2022 by an independent security firm + cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). + No vulnerabilities have been found. The audit has been funded by + [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io). + Modules `blake3`, `sha3-addons`, `sha1` and `argon2` have not been audited. + See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: + _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to + achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. + Even statically typed Rust, a language without GC, + [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) + for some cases. If your goal is absolute security, don't use any JS lib — including + bindings to native ones. Use low-level libraries & languages. Nonetheless we're + targetting algorithmic constant time. +4. Memory dump considerations: the library shares state buffers between hash + function calls. The buffers are zeroed-out after each call. However, if an attacker + can read application memory, you are doomed in any case: + - At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings + - Input from a file will stay in file buffers + - Input / output will be re-used multiple times in application which means + it could stay in memory + - `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory + - There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +We consider infrastructure attacks like rogue NPM modules very important; that's +why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. +If your app uses 500 dependencies, any dep could get hacked and you'll be downloading +malware with every `npm install`. Our goal is to minimize this attack vector. + +## Speed + +Benchmarks measured on Apple M1 with macOS 12. +Note that PBKDF2 and Scrypt are tested with extremely high work factor. +To run benchmarks, execute `npm run bench:install` and then `npm run bench` + +``` +SHA256 32B x 1,219,512 ops/sec @ 820ns/op ± 2.58% (min: 625ns, max: 4ms) +SHA384 32B x 512,032 ops/sec @ 1μs/op +SHA512 32B x 509,943 ops/sec @ 1μs/op +SHA3-256, keccak256, shake256 32B x 199,600 ops/sec @ 5μs/op +Kangaroo12 32B x 336,360 ops/sec @ 2μs/op +Marsupilami14 32B x 298,418 ops/sec @ 3μs/op +BLAKE2b 32B x 379,794 ops/sec @ 2μs/op +BLAKE2s 32B x 515,995 ops/sec @ 1μs/op ± 1.07% (min: 1μs, max: 4ms) +BLAKE3 32B x 588,235 ops/sec @ 1μs/op ± 1.36% (min: 1μs, max: 5ms) +RIPEMD160 32B x 1,140,250 ops/sec @ 877ns/op ± 3.12% (min: 708ns, max: 6ms) +HMAC-SHA256 32B x 377,358 ops/sec @ 2μs/op + +HKDF-SHA256 32B x 108,377 ops/sec @ 9μs/op +PBKDF2-HMAC-SHA256 262144 x 3 ops/sec @ 326ms/op +PBKDF2-HMAC-SHA512 262144 x 1 ops/sec @ 970ms/op +Scrypt r: 8, p: 1, n: 262144 x 1 ops/sec @ 616ms/op +``` + +Compare to native node.js implementation that uses C bindings instead of pure-js code: + +``` +SHA256 32B node x 1,302,083 ops/sec @ 768ns/op ± 10.54% (min: 416ns, max: 7ms) +SHA384 32B node x 975,609 ops/sec @ 1μs/op ± 11.32% (min: 625ns, max: 8ms) +SHA512 32B node x 983,284 ops/sec @ 1μs/op ± 11.24% (min: 625ns, max: 8ms) +SHA3-256 32B node x 910,746 ops/sec @ 1μs/op ± 12.19% (min: 666ns, max: 10ms) +keccak, k12, m14 are not implemented +BLAKE2b 32B node x 967,117 ops/sec @ 1μs/op ± 11.26% (min: 625ns, max: 9ms) +BLAKE2s 32B node x 1,055,966 ops/sec @ 947ns/op ± 11.07% (min: 583ns, max: 7ms) +BLAKE3 is not implemented +RIPEMD160 32B node x 1,002,004 ops/sec @ 998ns/op ± 10.66% (min: 625ns, max: 7ms) +HMAC-SHA256 32B node x 919,963 ops/sec @ 1μs/op ± 6.13% (min: 833ns, max: 5ms) +HKDF-SHA256 32 node x 369,276 ops/sec @ 2μs/op ± 13.59% (min: 1μs, max: 9ms) +PBKDF2-HMAC-SHA256 262144 node x 25 ops/sec @ 39ms/op +PBKDF2-HMAC-SHA512 262144 node x 7 ops/sec @ 132ms/op +Scrypt r: 8, p: 1, n: 262144 node x 1 ops/sec @ 523ms/op +``` + +It is possible to [make this library 4x+ faster](./benchmark/README.md) by +_doing code generation of full loop unrolls_. We've decided against it. Reasons: + +- the library must be auditable, with minimum amount of code, and zero dependencies +- most method invocations with the lib are going to be something like hashing 32b to 64kb of data +- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead + +The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run. + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests. See [our approach to testing](./test/README.md) +5. `npm run test:dos` will test against DoS; by measuring function complexity. **Takes ~20 minutes** +6. `npm run test:big` will execute hashing on 4GB inputs, + scrypt with 1024 different `N, r, p` combinations, etc. **Takes several hours**. Using 8-32+ core CPU helps. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.d.ts new file mode 100644 index 0000000..32a720b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.d.ts @@ -0,0 +1,22 @@ +declare function number(n: number): void; +declare function bool(b: boolean): void; +declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +declare function hash(hash: Hash): void; +declare function exists(instance: any, checkFinished?: boolean): void; +declare function output(out: any, instance: any): void; +export { number, bool, bytes, hash, exists, output }; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.js new file mode 100644 index 0000000..920cdd9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { number, bool, bytes, hash, exists, output }; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.js.map new file mode 100644 index 0000000..f3cc515 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names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AAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AASmC,wBAAM;AAR1C,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAE2C,wBAAM;AAElD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.d.ts new file mode 100644 index 0000000..352b978 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.d.ts @@ -0,0 +1,27 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE2> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.js new file mode 100644 index 0000000..9a5a45d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLAKE2 = exports.SIGMA = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +exports.SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +class BLAKE2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.number)(blockLen); + (0, _assert_js_1.number)(outputLen); + (0, _assert_js_1.number)(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + (0, _assert_js_1.exists)(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = (0, utils_js_1.u32)(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +exports.BLAKE2 = BLAKE2; +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.js.map new file mode 100644 index 0000000..85cf0b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["src/_blake2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAuD;AAEvD,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AACL,QAAA,KAAK,GAAmB,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE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EAAE,CAAC;IACZ,CAAC;CACF;AAlGD,wBAkGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.d.ts new file mode 100644 index 0000000..883788f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.d.ts @@ -0,0 +1,23 @@ +import { Hash, Input } from './utils.js'; +export declare abstract class SHA2> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.js new file mode 100644 index 0000000..7a45349 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + (0, _assert_js_1.exists)(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = (0, utils_js_1.createView)(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.SHA2 = SHA2; +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.js.map new file mode 100644 index 0000000..9c9c8eb --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["src/_sha2.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAC9C,yCAA8D;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/F,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IAC9C,MAAM,EAAE,GAAG,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,CAAC;IACpC,M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ACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,EAAO,EAAC;QAC5C,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACpE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AApGD,oBAoGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..59fd1c2 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,54 @@ +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +declare const toBig: (h: number, l: number) => bigint; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare const rotlSH: (h: number, l: number, s: number) => number; +declare const rotlSL: (h: number, l: number, s: number) => number; +declare const rotlBH: (h: number, l: number, s: number) => number; +declare const rotlBL: (h: number, l: number, s: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, _l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (_h: number, l: number) => number; + rotr32L: (h: number, _l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..c5080f0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.add = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = exports.split = exports.fromBig = void 0; +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +exports.shrSH = shrSH; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.shrSL = shrSL; +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +exports.rotrSH = rotrSH; +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.rotrSL = rotrSL; +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +exports.rotrBH = rotrBH; +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +exports.rotrBL = rotrBL; +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +exports.rotr32H = rotr32H; +const rotr32L = (h, _l) => h; +exports.rotr32L = rotr32L; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +exports.rotlSH = rotlSH; +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +exports.rotlSL = rotlSL; +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +exports.rotlBH = rotlBH; +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +exports.rotlBL = rotlBL; +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +exports.add3L = add3L; +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +exports.add3H = add3H; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +exports.add4L = add4L; +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +exports.add4H = add4H; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +exports.add5L = add5L; +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +exports.add5H = add5H; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports.default = u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..6116a39 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":";;;AAAA,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAExC,+EAA+E;AAC/E,SAAS,OAAO,CAAC,CAAS,EAAE,EAAE,GAAG,KAAK;IACpC,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC;IAClF,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,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AAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AASpB,sBAAK;AAExC,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kBAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..15b6486 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,16 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..2754f8c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,303 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argon2id = exports.argon2i = exports.argon2d = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const blake2b_js_1 = require("./blake2b.js"); +const _u64_js_1 = require("./_u64.js"); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = (0, _u64_js_1.add3L)(Al, Bl, Cl); + return { h: (0, _u64_js_1.add3H)(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotr32H)(Dh, Dl), Dl: (0, _u64_js_1.rotr32L)(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrSH)(Bh, Bl, 24), Bl: (0, _u64_js_1.rotrSL)(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotrSH)(Dh, Dl, 16), Dl: (0, _u64_js_1.rotrSL)(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrBH)(Bh, Bl, 63), Bl: (0, _u64_js_1.rotrBL)(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = (0, utils_js_1.u8)(A); + const T = new Uint32Array(1); + const T8 = (0, utils_js_1.u8)(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b_js_1.blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b_js_1.blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = (0, blake2b_js_1.blake2b)(V)).subarray(0, 32), pos); + // Last block + out.set((0, blake2b_js_1.blake2b)(V, { dkLen: dkLen - pos }), pos); + return (0, utils_js_1.u32)(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = (0, utils_js_1.toBytes)(password); + salt = (0, utils_js_1.toBytes)(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(m); + (0, _assert_js_1.number)(t); + (0, _assert_js_1.number)(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = (0, utils_js_1.toBytes)(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = (0, utils_js_1.toBytes)(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b_js_1.blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = (0, utils_js_1.u8)(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = (0, utils_js_1.u8)(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return (0, utils_js_1.u8)(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +exports.argon2d = argon2d; +const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +exports.argon2i = argon2i; +const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +exports.argon2id = argon2id; +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..a88b252 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAqD;AACrD,6CAAuC;AACvC,uCAA2F;AAS3F,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjG,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,GAAG,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;IACnD,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EA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C5C,CAAC;AAEM,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,OAAO,WAC2B;AACxC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,wBAAgB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADjC,QAAA,OAAO,WAC0B;AACvC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,QAAQ,YAC0B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.d.ts new file mode 100644 index 0000000..7a78c6b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +declare class BLAKE2b extends BLAKE2 { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.js new file mode 100644 index 0000000..9d41df5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = _blake2_js_1.SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2b = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.js.map new file mode 100644 index 0000000..4e936fb --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","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CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.d.ts new file mode 100644 index 0000000..d9dd59b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +export declare const IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +declare class BLAKE2s extends BLAKE2 { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.js new file mode 100644 index 0000000..ace7513 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2s = exports.compress = exports.IV = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +exports.IV = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 16); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 8); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +exports.compress = compress; +class BLAKE2s extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = exports.IV[0] | 0; + this.v1 = exports.IV[1] | 0; + this.v2 = exports.IV[2] | 0; + this.v3 = exports.IV[3] | 0; + this.v4 = exports.IV[4] | 0; + this.v5 = exports.IV[5] | 0; + this.v6 = exports.IV[6] | 0; + this.v7 = exports.IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake2_js_1.SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, exports.IV[0], exports.IV[1], exports.IV[2], exports.IV[3], l ^ exports.IV[4], h ^ exports.IV[5], isLast ? ~exports.IV[6] : exports.IV[6], exports.IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2s = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.js.map new file mode 100644 index 0000000..ac692b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAAoC;AACpC,yCAAyE;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AACL,QAAA,EAAE,GAAkB,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAEnJ,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,SAAS,EAAE,CAAC,CAAS,E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AE,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,UAAE,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,UAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,UAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAE,CAAC,CAAC,CAAC,EAAE,UAAE,CAAC,CAAC,CAAC,CACjF,CAAC;QACJ,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..13894cf --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE2 } from './_blake2.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +declare class BLAKE3 extends BLAKE2 implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..3c339f5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,229 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake3 = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const _blake2_js_1 = require("./_blake2.js"); +const blake2s_js_1 = require("./blake2s.js"); +const utils_js_1 = require("./utils.js"); +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends _blake2_js_1.BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + (0, _assert_js_1.number)(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = (0, utils_js_1.toBytes)(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = (0, utils_js_1.u32)(key); + this.flags = flags | 16 /* Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = (0, utils_js_1.u32)(context_key); + this.flags = flags | 64 /* Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = blake2s_js_1.IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* Flags.PARENT */; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* Flags.CHUNK_START */ : 0) | 2 /* Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..7ed8fd6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAC7D,uCAAoC;AACpC,6CAAsC;AACtC,6CAA4C;AAC5C,yCAA0F;AAe1F,MAAM,KAAK,GAAe,eAAe,CAAC,CAAC,GAAG,EAAE;IAC9C,MAAM,EAAE,GAAG,KAAK,CAA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AC;IACD,GAAG,CAAC,KAAa;QACf,IAAA,mBAAM,EAAC,KAAK,CAAC,CAAC;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,IAAA,mBAAM,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,MAAM,GAAmB,IAAA,qCAA0B,EAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.js new file mode 100644 index 0000000..8226391 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.js.map new file mode 100644 index 0000000..9f794e2 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.js new file mode 100644 index 0000000..a88676d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +const nc = require("node:crypto"); +exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.js.map new file mode 100644 index 0000000..9287d27 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..f0fc54d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,46 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +type ESKDF = Promise Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +}>>; +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): ESKDF; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..bc622b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.eskdf = exports.deriveMainSeed = exports.pbkdf2 = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const hkdf_js_1 = require("./hkdf.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const scrypt_js_1 = require("./scrypt.js"); +const utils_js_1 = require("./utils.js"); +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +function scrypt(password, salt) { + return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +exports.scrypt = scrypt; +// PBKDF2-HMAC-SHA256 +function pbkdf2(password, salt) { + return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +exports.pbkdf2 = pbkdf2; +// Combines two 32-byte byte arrays +function xor32(a, b) { + (0, _assert_js_1.bytes)(a, 32); + (0, _assert_js_1.bytes)(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +exports.deriveMainSeed = deriveMainSeed; +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = (0, utils_js_1.toBytes)(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + (0, utils_js_1.createView)(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = (0, utils_js_1.toBytes)(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = (0, utils_js_1.hexToBytes)(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + (0, _assert_js_1.bytes)(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +exports.eskdf = eskdf; +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..70c49e9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":";;;AAAA,6CAAoD;AACpD,uCAAiC;AACjC,2CAAqC;AACrC,2CAAgD;AAChD,2CAAgD;AAChD,yCAAyE;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAFD,wBAEC;AAED,qBAAqB;AACrB,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,kBAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1E,CAAC;AAFD,wBAEC;AAED,mCAAmC;AACnC,SAAS,KAAK,CAAC,CAAa,EAAE,CAAa;IACzC,IAAA,kBAAW,EAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACnB,IAAA,kBAAW,EAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACnB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IA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C,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC;AAvBD,sBAuBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js new file mode 100644 index 0000000..4259cea --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js @@ -0,0 +1,37 @@ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +export { number, bool, bytes, hash, exists, output }; +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js.map new file mode 100644 index 0000000..d8f294f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,EAAE,CAAC,CAAC;AACzF,CAAC;AAED,SAAS,IAAI,CAAC,CAAU;IACtB,IAAI,OAAO,CAAC,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,SAAS,KAAK,CAAC,CAAyB,EAAE,GAAG,OAAiB;IAC5D,IAAI,CAAC,CAAC,CAAC,YAAY,UAAU,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,OAAO,mBAAmB,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;AAC3F,CAAC;AAQD,SAAS,IAAI,CAAC,IAAU;IACtB,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU;QACjE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACvB,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACxB,CAAC;AAED,SAAS,MAAM,CAAC,QAAa,EAAE,aAAa,GAAG,IAAI;IACjD,IAAI,QAAQ,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC5E,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AACD,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAErD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_blake2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_blake2.js new file mode 100644 index 0000000..948e01b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_blake2.js @@ -0,0 +1,108 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, toBytes, u32 } from './utils.js'; +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +export class BLAKE2 extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_blake2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_blake2.js.map new file mode 100644 index 0000000..4222d07 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["../src/_blake2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,IAAI,EAAS,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEvD,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AAClB,MAAM,CAAC,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EA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IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACrE,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAM,EAAC;QAChE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js new file mode 100644 index 0000000..cd26ea4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js @@ -0,0 +1,114 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, toBytes } from './utils.js'; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +export class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js.map new file mode 100644 index 0000000..1675e44 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["../src/_sha2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,UAAU,EAAS,OAAO,EAAE,MAAM,YAAY,CAAC;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;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letreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_u64.js new file mode 100644 index 0000000..66cce47 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_u64.js @@ -0,0 +1,62 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_u64.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_u64.js.map new file mode 100644 index 0000000..b2339ed --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"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AE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,MAAM,KAAK,GAAG,CAAC,GAAW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,OAAO,EACL,OAAO,EAAE,KAAK,EAAE,KAAK,EACrB,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAC9B,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAC9C,CAAC;AACF,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/argon2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/argon2.js new file mode 100644 index 0000000..1e5a6b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/argon2.js @@ -0,0 +1,297 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +export const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +export const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +export const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/argon2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/argon2.js.map new file mode 100644 index 0000000..267eb62 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAA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AC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2b.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2b.js new file mode 100644 index 0000000..29cecc5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2b.js @@ -0,0 +1,189 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2b.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2b.js.map new file mode 100644 index 0000000..a448786 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UA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I,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2s.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2s.js new file mode 100644 index 0000000..5c64991 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2s.js @@ -0,0 +1,118 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = /* @__PURE__ */ new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +class BLAKE2s extends BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2s.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2s.js.map new file mode 100644 index 0000000..44cce78 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AAClB,MAAM,CAAC,MAAM,EAAE,GAAG,eAAe,CAAA,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAEnJ,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,C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C,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CACjF,CAAC;QACJ,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,eAAe,CAAC,uBAAuB,CAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake3.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake3.js new file mode 100644 index 0000000..af92963 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake3.js @@ -0,0 +1,226 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { u8, u32, toBytes, wrapXOFConstructorWithOpts } from './utils.js'; +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | 16 /* Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | 64 /* Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* Flags.PARENT */; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* Flags.CHUNK_START */ : 0) | 2 /* Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake3.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake3.js.map new file mode 100644 index 0000000..50f489b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAS,EAAE,EAAE,GAAG,EAAE,OAAO,EAAW,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CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,GAAG,CAAC,KAAa;QACf,MAAM,CAAC,KAAK,CAAC,CAAC;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,0BAA0B,CAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/crypto.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/crypto.js new file mode 100644 index 0000000..8d499a0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/crypto.js @@ -0,0 +1,2 @@ +export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/crypto.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/crypto.js.map new file mode 100644 index 0000000..4b4fd3d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/cryptoNode.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/cryptoNode.js new file mode 100644 index 0000000..241f1da --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/cryptoNode.js @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/cryptoNode.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/cryptoNode.js.map new file mode 100644 index 0000000..f7ab75e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/eskdf.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/eskdf.js new file mode 100644 index 0000000..13253eb --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/eskdf.js @@ -0,0 +1,155 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/eskdf.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/eskdf.js.map new file mode 100644 index 0000000..f53eebe --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["../src/eskdf.ts"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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hkdf.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hkdf.js new file mode 100644 index 0000000..8fbdac8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hkdf.js @@ -0,0 +1,72 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { toBytes } from './utils.js'; +import { hmac } from './hmac.js'; +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash, ikm, salt) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash, prk, info, length = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hkdf.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hkdf.js.map new file mode 100644 index 0000000..868bdb5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hkdf.js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AE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js new file mode 100644 index 0000000..520f776 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js @@ -0,0 +1,77 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assertExists(this); + assertBytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js.map new file mode 100644 index 0000000..e04539d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAChG,OAAO,EAAE,IAAI,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACzD,kBAAkB;AAClB,MAAM,OAAO,IAAwB,SAAQ,IAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,UAAU,CAAC,IAAI,CAAC,CAAC;QACjB,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM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,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACpD,IAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/index.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/index.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/index.js.map new file mode 100644 index 0000000..90172aa --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/package.json b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/package.json new file mode 100644 index 0000000..f42e46b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/package.json @@ -0,0 +1,10 @@ +{ + "type": "module", + "sideEffects": false, + "browser": { + "node:crypto": false + }, + "node": { + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/pbkdf2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/pbkdf2.js new file mode 100644 index 0000000..3f0c11f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/pbkdf2.js @@ -0,0 +1,86 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { createView, toBytes, checkOpts, asyncLoop } from './utils.js'; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +export async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/pbkdf2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/pbkdf2.js.map new file mode 100644 index 0000000..b404934 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAsB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,YAAY,CAAC,CAAC,CAAC,CAAC;IAChB,YAAY,CAAC,KAAK,CAAC,CAAC;IACpB,YAAY,CAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,0CAA0C;IAC1C,MAAM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} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js new file mode 100644 index 0000000..1e23958 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js @@ -0,0 +1,104 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js.map new file mode 100644 index 0000000..7964756 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACnG,MAAM,EAAE,GAAG,eAAe,CAAC,UAAU,CAAC,IAAI,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,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;gBACjF,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,kBAAkB;aAC9E;SACF;QACD,qDAAqD;QACrD,IAAI,CAAC,GAAG,CACN,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EACvB,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CACxB,CAAC;IACJ,CAAC;IACS,UAAU;QAClB,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/scrypt.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/scrypt.js new file mode 100644 index 0000000..37012f5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/scrypt.js @@ -0,0 +1,218 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, u32 } from './utils.js'; +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/scrypt.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/scrypt.js.map new file mode 100644 index 0000000..0fa6c1f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_mod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,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,SAAS,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACjC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha1.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha1.js new file mode 100644 index 0000000..563bff5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha1.js @@ -0,0 +1,87 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha1.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha1.js.map new file mode 100644 index 0000000..55249de --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC3D,CAAC,CAAC;AAEH,4DAA4D;AAC5D,mDAAmD;AACnD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AACnD,MAAM,IAAK,SAAQ,I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,GAAG,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAChB,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,CAAC,CAAC;SACP;QACD,qDAAqD;QACrD,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js new file mode 100644 index 0000000..e92203c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js @@ -0,0 +1,126 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js.map new file mode 100644 index 0000000..0236fa8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,gEAAgE;AAChE,0DAA0D;AAE1D,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CA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G,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3-addons.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3-addons.js new file mode 100644 index 0000000..449b3a3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3-addons.js @@ -0,0 +1,347 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +import { Keccak } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + constructor(capacity) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3-addons.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3-addons.js.map new file mode 100644 index 0000000..7600a9a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAiB,MAAM,YAAY,CAAC;AACzF,OAAO,EAAE,MAAM,EAAa,MAAM,WAAW,CAAC;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAA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,CAAC,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QACvF,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE;YAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3.js new file mode 100644 index 0000000..0879d36 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3.js @@ -0,0 +1,208 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js'; +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +export class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3.js.map new file mode 100644 index 0000000..32d5b16 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EACL,IAAI,EACJ,GAAG,EAEH,OAAO,EACP,eAAe,EACf,0BAA0B,GAE3B,MAAM,YAAY,CAAC;AAEpB,oGAAoG;AACpG,iCAAiC;AAEjC,2CAA2C;AAC3C,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAmC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtF,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAA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AAe,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAC/D,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAClE;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AAIjE,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,SAAiB,EAAE,EAAE,CACvE,0BAA0B,CACxB,CAAC,OAAkB,EAAE,EAAE,EAAE,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CACxF,CAAC;AAEJ,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACrE,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js new file mode 100644 index 0000000..f938b6d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js @@ -0,0 +1,231 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js.map new file mode 100644 index 0000000..4c9e3e6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC;IAC9D,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBA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Ae,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js new file mode 100644 index 0000000..80c0949 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js @@ -0,0 +1,154 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +// For runtime check if class implements interface +export class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +const toStr = {}.toString; +export function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +export function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +export function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +export function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js.map new file mode 100644 index 0000000..19d87a9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAM9C,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AACjE,+BAA+B;AAC/B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAClG,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,GAAe,EAAE,EAAE,CACrC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;AAE9E,qBAAqB;AACrB,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAe,EAAE,EAAE,CAC5C,IAAI,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAE3D,+DAA+D;AAC/D,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC;AAE/F,iFAAiF;AACjF,w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,0BAA0B,CACxC,QAAkC;IAElC,MAAM,KAAK,GAAG,CAAC,GAAU,EAAE,IAAQ,EAAc,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjG,MAAM,GAAG,GAAG,QAAQ,CAAC,EAAO,CAAC,CAAC;IAC9B,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..e1d683b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,26 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..021b68e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hkdf = exports.expand = exports.extract = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const hmac_js_1 = require("./hmac.js"); +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +function extract(hash, ikm, salt) { + (0, _assert_js_1.hash)(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm)); +} +exports.extract = extract; +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +function expand(hash, prk, info, length = 32) { + (0, _assert_js_1.hash)(hash); + (0, _assert_js_1.number)(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac_js_1.hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +exports.expand = expand; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +exports.hkdf = hkdf; +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..7790e7c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mapp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kletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..63db656 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,25 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..0fc2d02 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.hash)(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + (0, _assert_js_1.exists)(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.bytes)(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..798c5fa --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":";;;AAAA,6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AAG,IAAI,CAAC;QACxE,EAAE,GAAG,EAAU,CAAC;QAChB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAnED,oBAmEC;AAED;;;;;GAKG;AACI,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AADvC,QAAA,IAAI,QACmC;AACpD,YAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..b71bae6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/package.json b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..9a668d3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/package.json @@ -0,0 +1,174 @@ +{ + "name": "@noble/hashes", + "version": "1.3.2", + "description": "Audited & minimal 0-dependency JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2, Scrypt", + "files": [ + "/*.js", + "/*.d.ts", + "/*.js.map", + "esm", + "src/*.ts" + ], + "scripts": { + "bench": "node benchmark/index.js noble", + "bench:all": "node benchmark/index.js", + "bench:install": "cd benchmark && npm install && cd ../../", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build; npm i; npm run build", + "build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.js", + "test:dos": "node test/slow-dos.test.js", + "test:big": "node test/slow-big.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-hashes.git" + }, + "license": "MIT", + "sideEffects": false, + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "devDependencies": { + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "engines": { + "node": ">= 16" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./crypto": { + "types": "./crypto.d.ts", + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./_assert": { + "types": "./_assert.d.ts", + "import": "./esm/_assert.js", + "default": "./_assert.js" + }, + "./_sha2": { + "types": "./_sha2.d.ts", + "import": "./esm/_sha2.js", + "default": "./_sha2.js" + }, + "./argon2": { + "types": "./argon2.d.ts", + "import": "./esm/argon2.js", + "default": "./argon2.js" + }, + "./blake2b": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./blake2s": { + "types": "./blake2s.d.ts", + "import": "./esm/blake2s.js", + "default": "./blake2s.js" + }, + "./blake3": { + "types": "./blake3.d.ts", + "import": "./esm/blake3.js", + "default": "./blake3.js" + }, + "./eskdf": { + "types": "./eskdf.d.ts", + "import": "./esm/eskdf.js", + "default": "./eskdf.js" + }, + "./hkdf": { + "types": "./hkdf.d.ts", + "import": "./esm/hkdf.js", + "default": "./hkdf.js" + }, + "./hmac": { + "types": "./hmac.d.ts", + "import": "./esm/hmac.js", + "default": "./hmac.js" + }, + "./pbkdf2": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./ripemd160": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./sha1": { + "types": "./sha1.d.ts", + "import": "./esm/sha1.js", + "default": "./sha1.js" + }, + "./sha3-addons": { + "types": "./sha3-addons.d.ts", + "import": "./esm/sha3-addons.js", + "default": "./sha3-addons.js" + }, + "./sha3": { + "types": "./sha3.d.ts", + "import": "./esm/sha3.js", + "default": "./sha3.js" + }, + "./sha256": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + } + }, + "keywords": [ + "sha", + "sha2", + "sha3", + "sha256", + "sha512", + "keccak", + "kangarootwelve", + "ripemd160", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..42f691c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,15 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..a667178 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2Async = exports.pbkdf2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const hmac_js_1 = require("./hmac.js"); +const utils_js_1 = require("./utils.js"); +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + (0, _assert_js_1.hash)(hash); + const opts = (0, utils_js_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + (0, _assert_js_1.number)(c); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0, utils_js_1.toBytes)(_password); + const salt = (0, utils_js_1.toBytes)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac_js_1.hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2 = pbkdf2; +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await (0, utils_js_1.asyncLoop)(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2Async = pbkdf2Async; +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..a8f30b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,6CAA0E;AAC1E,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,IAAA,mBAAY,EAAC,CAAC,CAAC,CAAC;IAChB,IAAA,mBAAY,EAAC,KAAK,CAAC,CAAC;IACpB,IAAA,mBAAY,EAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,0CAA0C;IAC1C,MAAM,GAAG,GAAG,cAAI,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,E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AAI,EAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE;QACjE,+BAA+B;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,MAAM,IAAA,oBAAS,EAAC,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACrC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAtBD,kCAsBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.d.ts new file mode 100644 index 0000000..92e662f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.d.ts @@ -0,0 +1,24 @@ +import { SHA2 } from './_sha2.js'; +export declare class RIPEMD160 extends SHA2 { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.js new file mode 100644 index 0000000..7d6e057 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.js.map new file mode 100644 index 0000000..396a517 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/ripemd160.js.map @@ -0,0 +1 @@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IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAhED,8BAgEC;AAED;;;GAGG;AACU,QAAA,SAAS,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..82485b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,29 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..2f118db --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,223 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptAsync = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const utils_js_1 = require("./utils.js"); +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = (0, utils_js_1.checkOpts)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + (0, _assert_js_1.number)(N); + (0, _assert_js_1.number)(r); + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + (0, _assert_js_1.number)(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0, utils_js_1.u32)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N)); + const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scrypt = scrypt; +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await (0, utils_js_1.asyncLoop)(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scryptAsync = scryptAsync; +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..873dc15 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,2CAAqC;AACrC,2CAAqC;AACrC,yCAA8D;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE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W,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,2BAA2B;YACzE,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,IAAA,oBAAS,EAAC,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACjC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC;AAzBD,kCAyBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.d.ts new file mode 100644 index 0000000..d9cb132 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.d.ts @@ -0,0 +1,21 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA1 extends SHA2 { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.js new file mode 100644 index 0000000..10c6953 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.js.map new file mode 100644 index 0000000..4b0ccbd --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,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,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,IAAI,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.d.ts new file mode 100644 index 0000000..3e1491d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.d.ts @@ -0,0 +1,34 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA256 extends SHA2 { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.js new file mode 100644 index 0000000..24fe574 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.js.map new file mode 100644 index 0000000..a2fd853 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["src/sha256.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAAmD;AAEnD,gEA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AC,EAAE,CAAC,CAAC,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AACD,4EAA4E;AAC5E,MAAM,MAAO,SAAQ,MAAM;IASzB;QACE,KAAK,EAAE,CAAC;QATV,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACU,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..cf7c3a0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,138 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(_out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..e5317b1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,351 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccakprg = exports.m14 = exports.k12 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.cshake256 = exports.cshake128 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const sha3_js_1 = require("./sha3.js"); +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => cshakePers(new sha3_js_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); +exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = (0, utils_js_1.toBytes)(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = (0, utils_js_1.u32)(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +exports.kmac128 = (() => genKmac(168, 128 / 8))(); +exports.kmac256 = (() => genKmac(136, 256 / 8))(); +exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); +exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +exports.tuplehash128 = (() => genTuple(168, 128 / 8))(); +exports.tuplehash256 = (() => genTuple(136, 256 / 8))(); +exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))(); +exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + (0, _assert_js_1.number)(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))(); +exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))(); +exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))(); +exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends sha3_js_1.Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new sha3_js_1.Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +exports.k12 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +exports.m14 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends sha3_js_1.Keccak { + constructor(capacity) { + (0, _assert_js_1.number)(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +exports.keccakprg = keccakprg; +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..7232b4f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAA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AAS,aAA+C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..2107cf6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,97 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..e1b7530 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,213 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0, _assert_js_1.number)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0, _assert_js_1.exists)(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..fd68950 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["src/sha3.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAC7D,uCAAkE;AAClE,yCAQoB;AAEpB,oGAAoG;AACpG,iCAAiC;AAEjC,2CAA2C;AAC3C,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAmC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtF,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,KAAK,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1C,MAAM,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC5C,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,EAAE,EAAE,KAAK,EAAE,EAAE;IAC9D,KAAK;IACL,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAClC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAA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E,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CACxF,CAAC;AAES,QAAA,QAAQ,GAAmB,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACxD,QAAA,QAAQ,GAAmB,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.d.ts new file mode 100644 index 0000000..b8ba9b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.d.ts @@ -0,0 +1,66 @@ +import { SHA2 } from './_sha2.js'; +export declare class SHA512 extends SHA2 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.js new file mode 100644 index 0000000..1d3482a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js_1.default.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends _sha2_js_1.SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7); + const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6); + const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41); + const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39); + const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl); + Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.SHA512 = SHA512; +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +exports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512()); +exports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224()); +exports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256()); +exports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.js.map new file mode 100644 index 0000000..700a8e7 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["src/sha512.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,uCAA4B;AAC5B,yCAA6C;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CA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AAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QAIlB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_assert.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_assert.ts new file mode 100644 index 0000000..11d28ea --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_assert.ts @@ -0,0 +1,43 @@ +function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); +} + +function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`); +} + +function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} + +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +function hash(hash: Hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} + +function exists(instance: any, checkFinished = true) { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} +function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +export { number, bool, bytes, hash, exists, output }; + +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_blake2.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_blake2.ts new file mode 100644 index 0000000..6aa4a74 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_blake2.ts @@ -0,0 +1,128 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, Input, toBytes, u32 } from './utils.js'; + +// Blake is based on ChaCha permutation. + +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); + +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; + +export abstract class BLAKE2> extends Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number = 0; + protected pos: number = 0; + protected finished = false; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + opts: BlakeOpts = {}, + keyLen: number, + saltLen: number, + persLen: number + ) { + super(); + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data: Input) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_sha2.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_sha2.ts new file mode 100644 index 0000000..bd99103 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_sha2.ts @@ -0,0 +1,118 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, Input, toBytes } from './utils.js'; + +// Polyfill for Safari 14 +function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} + +// Base SHA2 class (RFC 6234) +export abstract class SHA2> extends Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + readonly padOffset: number, + readonly isLE: boolean + ) { + super(); + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: Input): this { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..efc55b4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,77 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); + +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n: bigint, le = false) { + if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} + +function split(lst: bigint[], le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} + +const toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h: number, _l: number, s: number) => h >>> s; +const shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h: number, l: number) => l; +const rotr32L = (h: number, _l: number) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s)); + +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah: number, Al: number, Bh: number, Bl: number) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low: number, Ah: number, Bh: number, Ch: number) => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al: number, Bl: number, Cl: number, Dl: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +export { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/argon2.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..d727b0f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,374 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; + +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +const enum Types { + Argond2d = 0, + Argon2i = 1, + Argon2id = 2, +} + +const ARGON2_SYNC_POINTS = 4; + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); + +function mul(a: number, b: number) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} + +function relPos(areaSize: number, relativePos: number) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} + +function mul2(a: number, b: number) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer +const BUF = new Uint32Array(256); + +function G(a: number, b: number, c: number, d: number) { + let Al = BUF[2*a], Ah = BUF[2*a + 1]; // prettier-ignore + let Bl = BUF[2*b], Bh = BUF[2*b + 1]; // prettier-ignore + let Cl = BUF[2*c], Ch = BUF[2*c + 1]; // prettier-ignore + let Dl = BUF[2*d], Dh = BUF[2*d + 1]; // prettier-ignore + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: Uint32Array, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) BUF[i] = x[xPos + i] ^ x[yPos + i]; + + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} + +// Variable-Length Hash Function H' +function Hp(A: Uint32Array, dkLen: number) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} + +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} + +// RFC 9106 +export type ArgonOpts = { + t: number; // Time cost, iterations count + m: number; // Memory cost (in KB) + p: number; // Parallelization parameter + version?: number; // Default: 0x13 (19) + key?: Input; // Optional key + personalization?: Input; // Optional arbitrary extra data + dkLen?: number; // Desired number of returned bytes + asyncTick?: number; // Maximum time in ms for which async function can block execution + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +function argon2Init(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32` + ); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} + +function argon2Output(B: Uint32Array, p: number, laneLen: number, dkLen: number) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} + +function processBlock( + B: Uint32Array, + address: Uint32Array, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + type, + password, + salt, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} + +export const argon2d = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2id, password, salt, opts); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake2b.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake2b.ts new file mode 100644 index 0000000..5784742 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake2b.ts @@ -0,0 +1,205 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; + +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +function G2(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +class BLAKE2b extends BLAKE2 { + // Same as SHA-512, but LE + private v0l = IV[0] | 0; + private v0h = IV[1] | 0; + private v1l = IV[2] | 0; + private v1h = IV[3] | 0; + private v2l = IV[4] | 0; + private v2h = IV[5] | 0; + private v3l = IV[6] | 0; + private v3h = IV[7] | 0; + private v4l = IV[8] | 0; + private v4h = IV[9] | 0; + private v5l = IV[10] | 0; + private v5h = IV[11] | 0; + private v6l = IV[12] | 0; + private v6h = IV[13] | 0; + private v7l = IV[14] | 0; + private v7h = IV[15] | 0; + + constructor(opts: BlakeOpts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let {v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h} = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2b(opts) +); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake2s.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake2s.ts new file mode 100644 index 0000000..a609886 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake2s.ts @@ -0,0 +1,136 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; + +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = /* @__PURE__ */new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +function G2(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +class BLAKE2s extends BLAKE2 { + // Internal state, same as SHA-256 + private v0 = IV[0] | 0; + private v1 = IV[1] | 0; + private v2 = IV[2] | 0; + private v3 = IV[3] | 0; + private v4 = IV[4] | 0; + private v5 = IV[5] | 0; + private v6 = IV[6] | 0; + private v7 = IV[7] | 0; + + constructor(opts: BlakeOpts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2s(opts) +); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake3.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..01d7d54 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,250 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { Input, u8, u32, toBytes, HashXOF, wrapXOFConstructorWithOpts } from './utils.js'; + +// Blake3 is single-option Blake2 with reduced security (round count). + +// Flag bitset +const enum Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +} + +const SIGMA: Uint8Array = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +// - key: is 256-bit key +// - context: string should be hardcoded, globally unique, and application - specific. +// A good default format for the context string is "[application] [commit timestamp] [purpose]" +// - Only one of 'key' (keyed mode) or 'context' (derive key mode) can be used at same time +export type Blake3Opts = { dkLen?: number; key?: Input; context?: Input }; + +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 implements HashXOF { + private IV: Uint32Array; + private flags = 0 | 0; + private state: Uint32Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + private chunkOut = 0; // index of output chunk + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + protected get() { + return []; + } + protected set() {} + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: BLAKE3): BLAKE3 { + to = super._cloneInto(to) as BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + protected finish() { + if (this.finished) return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: Uint8Array) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} + +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts( + (opts) => new BLAKE3(opts) +); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/crypto.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/crypto.ts new file mode 100644 index 0000000..eaea6be --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/crypto.ts @@ -0,0 +1,5 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +export const crypto = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/cryptoNode.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/cryptoNode.ts new file mode 100644 index 0000000..6fdba9e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/cryptoNode.ts @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = + nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/eskdf.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..b4c224b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,183 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; + +// Scrypt KDF +export function scrypt(password: string, salt: string): Uint8Array { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password: string, salt: string): Uint8Array { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays +function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username: string, password: string): Uint8Array { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt: Uint8Array; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key: Uint8Array, modulus: bigint): Uint8Array { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +// We are not using classes because constructor cannot be async +type ESKDF = Promise< + Readonly<{ + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; + }> +>; + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username: string, password: string): ESKDF { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK(protocol: string, accountId: AccountID = 0, options?: KeyOpts): Uint8Array { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/hkdf.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..6d880d1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,79 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { CHash, Input, toBytes } from './utils.js'; +import { hmac } from './hmac.js'; + +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ + +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash: CHash, ikm: Input, salt?: Input) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} + +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); + +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} + +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = ( + hash: CHash, + ikm: Input, + salt: Input | undefined, + info: Input | undefined, + length: number +) => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..bebf4b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,81 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, CHash, Input, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished = false; + private destroyed = false; + + constructor(hash: CHash, _key: Input) { + super(); + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create() as T; + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf: Input) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: Uint8Array) { + assertExists(this); + assertBytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to?: HMAC): HMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} + +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash: CHash, key: Input, message: Input): Uint8Array => + new HMAC(hash, key).update(message).digest(); +hmac.create = (hash: CHash, key: Input) => new HMAC(hash, key); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/index.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..1505776 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1 @@ +throw new Error('noble-hashes have no entry-point: consult README for usage'); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/pbkdf2.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..b5f7e6a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,97 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js'; + +// PBKDF (RFC 2898) +export type Pbkdf2Opt = { + c: number; // Iterations + dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key + asyncTick?: number; // Maximum time in ms for which async function can block execution +}; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} + +function pbkdf2Output>( + PRF: Hash, + PRFSalt: Hash, + DK: Uint8Array, + prfW: Hash, + u: Uint8Array +) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; +} + +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +export async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/ripemd160.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/ripemd160.ts new file mode 100644 index 0000000..5f32380 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/ripemd160.ts @@ -0,0 +1,110 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word: number, shift: number) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, + bl = this.h1 | 0, br = bl, + cl = this.h2 | 0, cr = cl, + dl = this.h3 | 0, dr = dl, + el = this.h4 | 0, er = el; + + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0 + ); + } + protected roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/scrypt.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..85b68d8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,240 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, Input, u32 } from './utils.js'; + +// RFC 7914 Scrypt KDF + +// Left rotate for uint32 +const rotl = (a: number, b: number) => (a << b) | (a >>> (32 - b)); + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa( + prev: Uint32Array, + pi: number, + input: Uint32Array, + ii: number, + out: Uint32Array, + oi: number +) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} + +export type ScryptOpts = { + N: number; // cost factor + r: number; // block size + p: number; // parallelization + dkLen?: number; // key length + asyncTick?: number; // block execution max time + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error( + 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32' + ); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error( + 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)' + ); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error( + 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32' + ); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error( + `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)` + ); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} + +function scryptOutput( + password: Input, + dkLen: number, + B: Uint8Array, + V: Uint32Array, + tmp: Uint32Array +) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} + +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha1.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha1.ts new file mode 100644 index 0000000..1fec224 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha1.ts @@ -0,0 +1,88 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. + +// RFC 3174 +const rotl = (word: number, shift: number) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends SHA2 { + private A = IV[0] | 0; + private B = IV[1] | 0; + private C = IV[2] | 0; + private D = IV[3] | 0; + private E = IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + protected roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} + +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha256.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha256.ts new file mode 100644 index 0000000..6f88b9a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha256.ts @@ -0,0 +1,133 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. + +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends SHA2 { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = IV[0] | 0; + B = IV[1] | 0; + C = IV[2] | 0; + D = IV[3] | 0; + E = IV[4] | 0; + F = IV[5] | 0; + G = IV[6] | 0; + H = IV[7] | 0; + + constructor() { + super(64, 32, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + protected roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + A = 0xc1059ed8 | 0; + B = 0x367cd507 | 0; + C = 0x3070dd17 | 0; + D = 0xf70e5939 | 0; + E = 0xffc00b31 | 0; + F = 0x68581511 | 0; + G = 0x64f98fa7 | 0; + H = 0xbefa4fa4 | 0; + constructor() { + super(); + this.outputLen = 28; + } +} + +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha3-addons.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..1d5fbf9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,398 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, wrapConstructorWithOpts, u32, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} + +function rightEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; + +// Personalization +function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} + +const gencShake = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructorWithOpts((opts: cShakeOpts = {}) => + cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) + ); + +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); + +class KMAC extends Keccak implements HashXOF { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: Input, + opts: cShakeOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish() { + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: KMAC): KMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as KMAC; + } + clone(): KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false) { + const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key: Input, opts: cShakeOpts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} + +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); + +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + protected finish() { + if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: TupleHash): TupleHash { + to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as TupleHash; + } + clone(): TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false) { + const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { + const h = tuple.create(opts); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: cShakeOpts = {}) => + new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} + +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); + +// ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) +type ParallelOpts = cShakeOpts & { blockLen?: number }; + +class ParallelHash extends Keccak implements HashXOF { + private leafHash?: Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + protected leafCons: () => Hash, + enableXOF: boolean, + opts: ParallelOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B ||= 8; + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish() { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: ParallelHash): ParallelHash { + to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as ParallelHash; + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +) { + const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: ParallelOpts = {}) => + new ParallelHash( + blockLen, + chooseLen(opts, outputLen), + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + return parallel; +} + +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); + +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n: number): Uint8Array { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +export type KangarooOpts = { dkLen?: number; personalization?: Input }; +const EMPTY = new Uint8Array([]); + +class KangarooTwelve extends Keccak implements HashXOF { + readonly chunkLen = 8192; + private leafHash?: Keccak; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + protected leafLen: number, + outputLen: number, + rounds: number, + opts: KangarooOpts + ) { + super(blockLen, 0x07, outputLen, true, rounds); + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data: Input) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to?: KangarooTwelve): KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): KangarooTwelve { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) + ))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) + ))(); + +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: Input) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data: Input) { + return this.update(data); + } + protected finish() {} + digestInto(_out: Uint8Array): Uint8Array { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes: number): Uint8Array { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: KeccakPRG): KeccakPRG { + const { rate } = this; + to ||= new KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): KeccakPRG { + return this._cloneInto(); + } +} + +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha3.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..c730b06 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,223 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { + Hash, + u32, + Input, + toBytes, + wrapConstructor, + wrapXOFConstructorWithOpts, + HashXOF, +} from './utils.js'; + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s: Uint32Array, rounds: number = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} + +export class Keccak extends Hash implements HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + public blockLen: number, + public suffix: number, + public outputLen: number, + protected enableXOF = false, + protected rounds: number = 24 + ) { + super(); + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + protected keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data: Input) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: Uint8Array): Uint8Array { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const gen = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); + +export type ShakeOpts = { dkLen?: number }; + +const genShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, ShakeOpts>( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true) + ); + +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha512.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha512.ts new file mode 100644 index 0000000..27b7ac5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha512.ts @@ -0,0 +1,246 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); + +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends SHA2 { + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + Ah = 0x6a09e667 | 0; + Al = 0xf3bcc908 | 0; + Bh = 0xbb67ae85 | 0; + Bl = 0x84caa73b | 0; + Ch = 0x3c6ef372 | 0; + Cl = 0xfe94f82b | 0; + Dh = 0xa54ff53a | 0; + Dl = 0x5f1d36f1 | 0; + Eh = 0x510e527f | 0; + El = 0xade682d1 | 0; + Fh = 0x9b05688c | 0; + Fl = 0x2b3e6c1f | 0; + Gh = 0x1f83d9ab | 0; + Gl = 0xfb41bd6b | 0; + Hh = 0x5be0cd19 | 0; + Hl = 0x137e2179 | 0; + + constructor() { + super(128, 64, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + protected process(view: DataView, offset: number) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + protected roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +class SHA512_224 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x8c3d37c8 | 0; + Al = 0x19544da2 | 0; + Bh = 0x73e19966 | 0; + Bl = 0x89dcd4d6 | 0; + Ch = 0x1dfab7ae | 0; + Cl = 0x32ff9c82 | 0; + Dh = 0x679dd514 | 0; + Dl = 0x582f9fcf | 0; + Eh = 0x0f6d2b69 | 0; + El = 0x7bd44da8 | 0; + Fh = 0x77e36f73 | 0; + Fl = 0x04c48942 | 0; + Gh = 0x3f9d85a8 | 0; + Gl = 0x6a1d36c8 | 0; + Hh = 0x1112e6ad | 0; + Hl = 0x91d692a1 | 0; + + constructor() { + super(); + this.outputLen = 28; + } +} + +class SHA512_256 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x22312194 | 0; + Al = 0xfc2bf72c | 0; + Bh = 0x9f555fa3 | 0; + Bl = 0xc84c64c2 | 0; + Ch = 0x2393b86b | 0; + Cl = 0x6f53b151 | 0; + Dh = 0x96387719 | 0; + Dl = 0x5940eabd | 0; + Eh = 0x96283ee2 | 0; + El = 0xa88effe3 | 0; + Fh = 0xbe5e1e25 | 0; + Fl = 0x53863992 | 0; + Gh = 0x2b0199fc | 0; + Gl = 0x2c85b8aa | 0; + Hh = 0x0eb72ddc | 0; + Hl = 0x81c52ca2 | 0; + + constructor() { + super(); + this.outputLen = 32; + } +} + +class SHA384 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0xcbbb9d5d | 0; + Al = 0xc1059ed8 | 0; + Bh = 0x629a292a | 0; + Bl = 0x367cd507 | 0; + Ch = 0x9159015a | 0; + Cl = 0x3070dd17 | 0; + Dh = 0x152fecd8 | 0; + Dl = 0xf70e5939 | 0; + Eh = 0x67332667 | 0; + El = 0xffc00b31 | 0; + Fh = 0x8eb44a87 | 0; + Fl = 0x68581511 | 0; + Gh = 0xdb0c2e0d | 0; + Gl = 0x64f98fa7 | 0; + Hh = 0x47b5481d | 0; + Hl = 0xbefa4fa4 | 0; + + constructor() { + super(); + this.outputLen = 48; + } +} + +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..81e5256 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,215 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; + +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift); + +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); + +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => {}; + +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + // Safe version that clones internal state + clone(): T { + return this._cloneInto(); + } +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream + xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf +}; + +const toStr = {}.toString; +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +export type CHash = ReturnType; + +export function wrapConstructor>(hashCons: () => Hash) { + const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +export function wrapConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => Hash +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +export function wrapXOFConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => HashXOF +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32): Uint8Array { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.d.ts b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..a0017e4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,90 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const isLE: boolean; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.js b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..2ffcbbe --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.js @@ -0,0 +1,174 @@ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +const crypto_1 = require("@noble/hashes/crypto"); +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.js.map b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..4fc2171 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,iDAA8C;AAM9C,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AACjE,+BAA+B;AACxB,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;A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C;AAED;;GAEG;AACH,SAAgB,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,eAAM,IAAI,OAAO,eAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,eAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AALD,kCAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip32/package.json b/test/merkletreejs/node_modules/@scure/bip32/package.json new file mode 100644 index 0000000..dcfaf67 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip32/package.json @@ -0,0 +1,72 @@ +{ + "name": "@scure/bip32", + "version": "1.3.1", + "description": "Secure, audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets over secp256k1", + "files": [ + "index.ts", + "lib/index.js", + "lib/index.d.ts", + "lib/index.js.map", + "lib/esm/package.json", + "lib/esm/index.js", + "lib/esm/index.js.map" + ], + "main": "lib/index.js", + "module": "lib/esm/index.js", + "types": "lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "import": "./lib/esm/index.js", + "default": "./lib/index.js" + } + }, + "dependencies": { + "@noble/curves": "~1.1.0", + "@noble/hashes": "~1.3.1", + "@scure/base": "~1.1.0" + }, + "devDependencies": { + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/scure-bip32.git" + }, + "contributors": [ + { + "name": "Patricio Palladino", + "email": "patricio@nomiclabs.io" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "license": "MIT", + "scripts": { + "build": "tsc -d && tsc -p tsconfig.esm.json", + "lint": "prettier --check 'index.ts' 'test/*.test.ts'", + "format": "prettier --write 'index.ts' 'test/*.test.ts'", + "test": "cd test && tsc && node hdkey.test.js" + }, + "keywords": [ + "bip32", + "hierarchical", + "deterministic", + "hd key", + "bip0032", + "bip-32", + "bip39", + "micro", + "scure", + "mnemonic", + "phrase", + "code" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/LICENSE b/test/merkletreejs/node_modules/@scure/bip39/LICENSE new file mode 100644 index 0000000..68222b8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +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. diff --git a/test/merkletreejs/node_modules/@scure/bip39/README.md b/test/merkletreejs/node_modules/@scure/bip39/README.md new file mode 100644 index 0000000..281df3b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/README.md @@ -0,0 +1,97 @@ +# scure-bip39 + +Secure, [audited](#security) & minimal implementation of BIP39 mnemonic phrases. + +Compared to popular `bip39` package, scure-bip39: + +- Supports ESM and common.js +- Supports tree-shaking: only actually used wordlists are bundled +- Is 491KB all-bundled instead of 1.3MB +- Uses 2 dependencies instead of 15 +- Wordlists are 157KB instead of 315KB +- Had an external security [audit](#security) by Cure53 + +Check out [scure-bip32](https://github.com/paulmillr/scure-bip32) if you need +hierarchical deterministic wallets ("HD Wallets"). + +### This library belongs to *scure* + +> **scure** — secure, independently audited packages for every use case. + +- All releases are signed with PGP keys +- As minimal as possible +- Check out all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer) + +## Usage + +> npm install @scure/bip39 + +Or + +> yarn add @scure/bip39 + +```js +import * as bip39 from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; + +// Generate x random words. Uses Cryptographically-Secure Random Number Generator. +const mn = bip39.generateMnemonic(wordlist); +console.log(mn); + +// Reversible: Converts mnemonic string to raw entropy in form of byte array. +const ent = bip39.mnemonicToEntropy(mn, wordlist) + +// Reversible: Converts raw entropy in form of byte array to mnemonic string. +bip39.entropyToMnemonic(ent, wordlist); + +// Validates mnemonic for being 12-24 words contained in `wordlist`. +bip39.validateMnemonic(mn, wordlist); + +// Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. +await bip39.mnemonicToSeed(mn, 'password'); +bip39.mnemonicToSeedSync(mn, 'password'); +``` + +This submodule contains the word lists defined by BIP39 for Czech, English, French, Italian, Japanese, Korean, Simplified and Traditional Chinese, and Spanish. These are not imported by default, as that would increase bundle sizes too much. Instead, you should import and use them explicitly. + +```typescript +function generateMnemonic(wordlist: string[], strength?: number): string; +function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; +function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; +function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise; +function mnemonicToSeedSync(mnemonic: string, passphrase?: string): Uint8Array; +``` + +All wordlists: + +```typescript +import { wordlist as czech } from '@scure/bip39/wordlists/czech'; +import { wordlist as english } from '@scure/bip39/wordlists/english'; +import { wordlist as french } from '@scure/bip39/wordlists/french'; +import { wordlist as italian } from '@scure/bip39/wordlists/italian'; +import { wordlist as japanese } from '@scure/bip39/wordlists/japanese'; +import { wordlist as korean } from '@scure/bip39/wordlists/korean'; +import { wordlist as simp } from '@scure/bip39/wordlists/simplified-chinese'; +import { wordlist as spanish } from '@scure/bip39/wordlists/spanish'; +import { wordlist as trad } from '@scure/bip39/wordlists/traditional-chinese'; +``` + +## Security + +The library has been audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). See [changes since audit](https://github.com/paulmillr/scure-bip39/compare/1.0.0..main). + +1. The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) +2. At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), it + was extracted to a separate package called `micro-bip39` +3. After the audit we've decided to use NPM namespace for security. Since `@micro` namespace was taken, we've renamed the package to `@scure/bip39` + +## License + +[MIT License](./LICENSE) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/index.js b/test/merkletreejs/node_modules/@scure/bip39/esm/index.js new file mode 100644 index 0000000..fd55e60 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/index.js @@ -0,0 +1,69 @@ +import assert from '@noble/hashes/_assert'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +import { sha512 } from '@noble/hashes/sha512'; +import { randomBytes } from '@noble/hashes/utils'; +import { utils as baseUtils } from '@scure/base'; +const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093'; +function nfkd(str) { + if (typeof str !== 'string') + throw new TypeError(`Invalid mnemonic type: ${typeof str}`); + return str.normalize('NFKD'); +} +function normalize(str) { + const norm = nfkd(str); + const words = norm.split(' '); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error('Invalid mnemonic'); + return { nfkd: norm, words }; +} +function assertEntropy(entropy) { + assert.bytes(entropy, 16, 20, 24, 28, 32); +} +export function generateMnemonic(wordlist, strength = 128) { + assert.number(strength); + if (strength % 32 !== 0 || strength > 256) + throw new TypeError('Invalid entropy'); + return entropyToMnemonic(randomBytes(strength / 8), wordlist); +} +const calcChecksum = (entropy) => { + const bitsLeft = 8 - entropy.length / 4; + return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]); +}; +function getCoder(wordlist) { + if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string') + throw new Error('Worlist: expected array of 2048 strings'); + wordlist.forEach((i) => { + if (typeof i !== 'string') + throw new Error(`Wordlist: non-string element: ${i}`); + }); + return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist)); +} +export function mnemonicToEntropy(mnemonic, wordlist) { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist).decode(words); + assertEntropy(entropy); + return entropy; +} +export function entropyToMnemonic(entropy, wordlist) { + assertEntropy(entropy); + const words = getCoder(wordlist).encode(entropy); + return words.join(isJapanese(wordlist) ? '\u3000' : ' '); +} +export function validateMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + } + catch (e) { + return false; + } + return true; +} +const salt = (passphrase) => nfkd(`mnemonic${passphrase}`); +export function mnemonicToSeed(mnemonic, passphrase = '') { + return pbkdf2Async(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +export function mnemonicToSeedSync(mnemonic, passphrase = '') { + return pbkdf2(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/index.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/index.js.map new file mode 100644 index 0000000..a8297d2 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,aAAa,CAAC;AAGjD,MAAM,UAAU,GAAG,CAAC,QAAkB,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,sCAAsC,CAAC;AAKlG,SAAS,IAAI,CAAC,GAAW;IACvB,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,MAAM,IAAI,SAAS,CAAC,0BAA0B,OAAO,GAAG,EAAE,CAAC,CAAC;IACzF,OAAO,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,GAAW;IAC5B,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IACvB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;IACtF,OAAO,EAAE,IA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IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AACjG,CAAC;AAYD,MAAM,UAAU,kBAAkB,CAAC,QAAgB,EAAE,UAAU,GAAG,EAAE;IAClE,OAAO,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5F,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/package.json b/test/merkletreejs/node_modules/@scure/bip39/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/czech.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/czech.js new file mode 100644 index 0000000..cf7b564 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/czech.js @@ -0,0 +1,2049 @@ +export const wordlist = `abdikace +abeceda +adresa +agrese +akce +aktovka +alej +alkohol +amputace +ananas +andulka +anekdota +anketa +antika +anulovat +archa +arogance +asfalt +asistent +aspirace +astma +astronom +atlas +atletika +atol +autobus +azyl +babka +bachor +bacil +baculka +badatel +bageta +bagr +bahno +bakterie +balada +baletka +balkon +balonek +balvan +balza +bambus +bankomat +barbar +baret +barman +baroko +barva +baterka +batoh +bavlna +bazalka +bazilika +bazuka +bedna +beran +beseda +bestie +beton +bezinka +bezmoc +beztak +bicykl +bidlo +biftek +bikiny +bilance +biograf +biolog +bitva +bizon +blahobyt +blatouch +blecha +bledule +blesk +blikat +blizna +blokovat +bloudit +blud +bobek +bobr +bodlina +bodnout +bohatost +bojkot +bojovat +bokorys +bolest +borec +borovice +bota +boubel +bouchat +bouda +boule +bourat +boxer +bradavka +brambora +branka +bratr +brepta +briketa +brko +brloh +bronz +broskev +brunetka +brusinka +brzda +brzy +bublina +bubnovat +buchta +buditel +budka +budova +bufet +bujarost +bukvice +buldok +bulva +bunda +bunkr +burza +butik +buvol +buzola +bydlet +bylina +bytovka +bzukot +capart +carevna +cedr +cedule +cejch +cejn +cela +celer +celkem +celnice +cenina +cennost +cenovka +centrum +cenzor +cestopis +cetka +chalupa +chapadlo +charita +chata +chechtat +chemie +chichot +chirurg +chlad +chleba +chlubit +chmel +chmura +chobot +chochol +chodba +cholera +chomout +chopit +choroba +chov +chrapot +chrlit +chrt +chrup +chtivost +chudina +chutnat +chvat +chvilka +chvost +chyba +chystat +chytit +cibule +cigareta +cihelna +cihla +cinkot +cirkus +cisterna +citace +citrus +cizinec +cizost +clona +cokoliv +couvat +ctitel +ctnost +cudnost +cuketa +cukr +cupot +cvaknout +cval +cvik +cvrkot +cyklista +daleko +dareba +datel +datum +dcera +debata +dechovka +decibel +deficit +deflace +dekl +dekret +demokrat +deprese +derby +deska +detektiv +dikobraz +diktovat +dioda +diplom +disk +displej +divadlo +divoch +dlaha +dlouho +dluhopis +dnes +dobro +dobytek +docent +dochutit +dodnes +dohled +dohoda +dohra +dojem +dojnice +doklad +dokola +doktor +dokument +dolar +doleva +dolina +doma +dominant +domluvit +domov +donutit +dopad +dopis +doplnit +doposud +doprovod +dopustit +dorazit +dorost +dort +dosah +doslov +dostatek +dosud +dosyta +dotaz +dotek +dotknout +doufat +doutnat +dovozce +dozadu +doznat +dozorce +drahota +drak +dramatik +dravec +draze +drdol +drobnost +drogerie +drozd +drsnost +drtit +drzost +duben +duchovno +dudek +duha +duhovka +dusit +dusno +dutost +dvojice +dvorec +dynamit +ekolog +ekonomie +elektron +elipsa +email +emise +emoce +empatie +epizoda +epocha +epopej +epos +esej +esence +eskorta +eskymo +etiketa +euforie +evoluce +exekuce +exkurze +expedice +exploze +export +extrakt +facka +fajfka +fakulta +fanatik +fantazie +farmacie +favorit +fazole +federace +fejeton +fenka +fialka +figurant +filozof +filtr +finance +finta +fixace +fjord +flanel +flirt +flotila +fond +fosfor +fotbal +fotka +foton +frakce +freska +fronta +fukar +funkce +fyzika +galeje +garant +genetika +geolog +gilotina +glazura +glejt +golem +golfista +gotika +graf +gramofon +granule +grep +gril +grog +groteska +guma +hadice +hadr +hala +halenka +hanba +hanopis +harfa +harpuna +havran +hebkost +hejkal +hejno +hejtman +hektar +helma +hematom +herec +herna +heslo +hezky +historik +hladovka +hlasivky +hlava +hledat +hlen +hlodavec +hloh +hloupost +hltat +hlubina +hluchota +hmat +hmota +hmyz +hnis +hnojivo +hnout +hoblina +hoboj +hoch +hodiny +hodlat +hodnota +hodovat +hojnost +hokej +holinka +holka +holub +homole +honitba +honorace +horal +horda +horizont +horko +horlivec +hormon +hornina +horoskop +horstvo +hospoda +hostina +hotovost +houba +houf +houpat +houska +hovor +hradba +hranice +hravost +hrazda +hrbolek +hrdina +hrdlo +hrdost +hrnek +hrobka +hromada +hrot +hrouda +hrozen +hrstka +hrubost +hryzat +hubenost +hubnout +hudba +hukot +humr +husita +hustota +hvozd +hybnost +hydrant +hygiena +hymna +hysterik +idylka +ihned +ikona +iluze +imunita +infekce +inflace +inkaso +inovace +inspekce +internet +invalida +investor +inzerce +ironie +jablko +jachta +jahoda +jakmile +jakost +jalovec +jantar +jarmark +jaro +jasan +jasno +jatka +javor +jazyk +jedinec +jedle +jednatel +jehlan +jekot +jelen +jelito +jemnost +jenom +jepice +jeseter +jevit +jezdec +jezero +jinak +jindy +jinoch +jiskra +jistota +jitrnice +jizva +jmenovat +jogurt +jurta +kabaret +kabel +kabinet +kachna +kadet +kadidlo +kahan +kajak +kajuta +kakao +kaktus +kalamita +kalhoty +kalibr +kalnost +kamera +kamkoliv +kamna +kanibal +kanoe +kantor +kapalina +kapela +kapitola +kapka +kaple +kapota +kapr +kapusta +kapybara +karamel +karotka +karton +kasa +katalog +katedra +kauce +kauza +kavalec +kazajka +kazeta +kazivost +kdekoliv +kdesi +kedluben +kemp +keramika +kino +klacek +kladivo +klam +klapot +klasika +klaun +klec +klenba +klepat +klesnout +klid +klima +klisna +klobouk +klokan +klopa +kloub +klubovna +klusat +kluzkost +kmen +kmitat +kmotr +kniha +knot +koalice +koberec +kobka +kobliha +kobyla +kocour +kohout +kojenec +kokos +koktejl +kolaps +koleda +kolize +kolo +komando +kometa +komik +komnata +komora +kompas +komunita +konat +koncept +kondice +konec +konfese +kongres +konina +konkurs +kontakt +konzerva +kopanec +kopie +kopnout +koprovka +korbel +korektor +kormidlo +koroptev +korpus +koruna +koryto +korzet +kosatec +kostka +kotel +kotleta +kotoul +koukat +koupelna +kousek +kouzlo +kovboj +koza +kozoroh +krabice +krach +krajina +kralovat +krasopis +kravata +kredit +krejcar +kresba +kreveta +kriket +kritik +krize +krkavec +krmelec +krmivo +krocan +krok +kronika +kropit +kroupa +krovka +krtek +kruhadlo +krupice +krutost +krvinka +krychle +krypta +krystal +kryt +kudlanka +kufr +kujnost +kukla +kulajda +kulich +kulka +kulomet +kultura +kuna +kupodivu +kurt +kurzor +kutil +kvalita +kvasinka +kvestor +kynolog +kyselina +kytara +kytice +kytka +kytovec +kyvadlo +labrador +lachtan +ladnost +laik +lakomec +lamela +lampa +lanovka +lasice +laso +lastura +latinka +lavina +lebka +leckdy +leden +lednice +ledovka +ledvina +legenda +legie +legrace +lehce +lehkost +lehnout +lektvar +lenochod +lentilka +lepenka +lepidlo +letadlo +letec +letmo +letokruh +levhart +levitace +levobok +libra +lichotka +lidojed +lidskost +lihovina +lijavec +lilek +limetka +linie +linka +linoleum +listopad +litina +litovat +lobista +lodivod +logika +logoped +lokalita +loket +lomcovat +lopata +lopuch +lord +losos +lotr +loudal +louh +louka +louskat +lovec +lstivost +lucerna +lucifer +lump +lusk +lustrace +lvice +lyra +lyrika +lysina +madam +madlo +magistr +mahagon +majetek +majitel +majorita +makak +makovice +makrela +malba +malina +malovat +malvice +maminka +mandle +manko +marnost +masakr +maskot +masopust +matice +matrika +maturita +mazanec +mazivo +mazlit +mazurka +mdloba +mechanik +meditace +medovina +melasa +meloun +mentolka +metla +metoda +metr +mezera +migrace +mihnout +mihule +mikina +mikrofon +milenec +milimetr +milost +mimika +mincovna +minibar +minomet +minulost +miska +mistr +mixovat +mladost +mlha +mlhovina +mlok +mlsat +mluvit +mnich +mnohem +mobil +mocnost +modelka +modlitba +mohyla +mokro +molekula +momentka +monarcha +monokl +monstrum +montovat +monzun +mosaz +moskyt +most +motivace +motorka +motyka +moucha +moudrost +mozaika +mozek +mozol +mramor +mravenec +mrkev +mrtvola +mrzet +mrzutost +mstitel +mudrc +muflon +mulat +mumie +munice +muset +mutace +muzeum +muzikant +myslivec +mzda +nabourat +nachytat +nadace +nadbytek +nadhoz +nadobro +nadpis +nahlas +nahnat +nahodile +nahradit +naivita +najednou +najisto +najmout +naklonit +nakonec +nakrmit +nalevo +namazat +namluvit +nanometr +naoko +naopak +naostro +napadat +napevno +naplnit +napnout +naposled +naprosto +narodit +naruby +narychlo +nasadit +nasekat +naslepo +nastat +natolik +navenek +navrch +navzdory +nazvat +nebe +nechat +necky +nedaleko +nedbat +neduh +negace +nehet +nehoda +nejen +nejprve +neklid +nelibost +nemilost +nemoc +neochota +neonka +nepokoj +nerost +nerv +nesmysl +nesoulad +netvor +neuron +nevina +nezvykle +nicota +nijak +nikam +nikdy +nikl +nikterak +nitro +nocleh +nohavice +nominace +nora +norek +nositel +nosnost +nouze +noviny +novota +nozdra +nuda +nudle +nuget +nutit +nutnost +nutrie +nymfa +obal +obarvit +obava +obdiv +obec +obehnat +obejmout +obezita +obhajoba +obilnice +objasnit +objekt +obklopit +oblast +oblek +obliba +obloha +obluda +obnos +obohatit +obojek +obout +obrazec +obrna +obruba +obrys +obsah +obsluha +obstarat +obuv +obvaz +obvinit +obvod +obvykle +obyvatel +obzor +ocas +ocel +ocenit +ochladit +ochota +ochrana +ocitnout +odboj +odbyt +odchod +odcizit +odebrat +odeslat +odevzdat +odezva +odhadce +odhodit +odjet +odjinud +odkaz +odkoupit +odliv +odluka +odmlka +odolnost +odpad +odpis +odplout +odpor +odpustit +odpykat +odrazka +odsoudit +odstup +odsun +odtok +odtud +odvaha +odveta +odvolat +odvracet +odznak +ofina +ofsajd +ohlas +ohnisko +ohrada +ohrozit +ohryzek +okap +okenice +oklika +okno +okouzlit +okovy +okrasa +okres +okrsek +okruh +okupant +okurka +okusit +olejnina +olizovat +omak +omeleta +omezit +omladina +omlouvat +omluva +omyl +onehdy +opakovat +opasek +operace +opice +opilost +opisovat +opora +opozice +opravdu +oproti +orbital +orchestr +orgie +orlice +orloj +ortel +osada +oschnout +osika +osivo +oslava +oslepit +oslnit +oslovit +osnova +osoba +osolit +ospalec +osten +ostraha +ostuda +ostych +osvojit +oteplit +otisk +otop +otrhat +otrlost +otrok +otruby +otvor +ovanout +ovar +oves +ovlivnit +ovoce +oxid +ozdoba +pachatel +pacient +padouch +pahorek +pakt +palanda +palec +palivo +paluba +pamflet +pamlsek +panenka +panika +panna +panovat +panstvo +pantofle +paprika +parketa +parodie +parta +paruka +paryba +paseka +pasivita +pastelka +patent +patrona +pavouk +pazneht +pazourek +pecka +pedagog +pejsek +peklo +peloton +penalta +pendrek +penze +periskop +pero +pestrost +petarda +petice +petrolej +pevnina +pexeso +pianista +piha +pijavice +pikle +piknik +pilina +pilnost +pilulka +pinzeta +pipeta +pisatel +pistole +pitevna +pivnice +pivovar +placenta +plakat +plamen +planeta +plastika +platit +plavidlo +plaz +plech +plemeno +plenta +ples +pletivo +plevel +plivat +plnit +plno +plocha +plodina +plomba +plout +pluk +plyn +pobavit +pobyt +pochod +pocit +poctivec +podat +podcenit +podepsat +podhled +podivit +podklad +podmanit +podnik +podoba +podpora +podraz +podstata +podvod +podzim +poezie +pohanka +pohnutka +pohovor +pohroma +pohyb +pointa +pojistka +pojmout +pokazit +pokles +pokoj +pokrok +pokuta +pokyn +poledne +polibek +polknout +poloha +polynom +pomalu +pominout +pomlka +pomoc +pomsta +pomyslet +ponechat +ponorka +ponurost +popadat +popel +popisek +poplach +poprosit +popsat +popud +poradce +porce +porod +porucha +poryv +posadit +posed +posila +poskok +poslanec +posoudit +pospolu +postava +posudek +posyp +potah +potkan +potlesk +potomek +potrava +potupa +potvora +poukaz +pouto +pouzdro +povaha +povidla +povlak +povoz +povrch +povstat +povyk +povzdech +pozdrav +pozemek +poznatek +pozor +pozvat +pracovat +prahory +praktika +prales +praotec +praporek +prase +pravda +princip +prkno +probudit +procento +prodej +profese +prohra +projekt +prolomit +promile +pronikat +propad +prorok +prosba +proton +proutek +provaz +prskavka +prsten +prudkost +prut +prvek +prvohory +psanec +psovod +pstruh +ptactvo +puberta +puch +pudl +pukavec +puklina +pukrle +pult +pumpa +punc +pupen +pusa +pusinka +pustina +putovat +putyka +pyramida +pysk +pytel +racek +rachot +radiace +radnice +radon +raft +ragby +raketa +rakovina +rameno +rampouch +rande +rarach +rarita +rasovna +rastr +ratolest +razance +razidlo +reagovat +reakce +recept +redaktor +referent +reflex +rejnok +reklama +rekord +rekrut +rektor +reputace +revize +revma +revolver +rezerva +riskovat +riziko +robotika +rodokmen +rohovka +rokle +rokoko +romaneto +ropovod +ropucha +rorejs +rosol +rostlina +rotmistr +rotoped +rotunda +roubenka +roucho +roup +roura +rovina +rovnice +rozbor +rozchod +rozdat +rozeznat +rozhodce +rozinka +rozjezd +rozkaz +rozloha +rozmar +rozpad +rozruch +rozsah +roztok +rozum +rozvod +rubrika +ruchadlo +rukavice +rukopis +ryba +rybolov +rychlost +rydlo +rypadlo +rytina +ryzost +sadista +sahat +sako +samec +samizdat +samota +sanitka +sardinka +sasanka +satelit +sazba +sazenice +sbor +schovat +sebranka +secese +sedadlo +sediment +sedlo +sehnat +sejmout +sekera +sekta +sekunda +sekvoje +semeno +seno +servis +sesadit +seshora +seskok +seslat +sestra +sesuv +sesypat +setba +setina +setkat +setnout +setrvat +sever +seznam +shoda +shrnout +sifon +silnice +sirka +sirotek +sirup +situace +skafandr +skalisko +skanzen +skaut +skeptik +skica +skladba +sklenice +sklo +skluz +skoba +skokan +skoro +skripta +skrz +skupina +skvost +skvrna +slabika +sladidlo +slanina +slast +slavnost +sledovat +slepec +sleva +slezina +slib +slina +sliznice +slon +sloupek +slovo +sluch +sluha +slunce +slupka +slza +smaragd +smetana +smilstvo +smlouva +smog +smrad +smrk +smrtka +smutek +smysl +snad +snaha +snob +sobota +socha +sodovka +sokol +sopka +sotva +souboj +soucit +soudce +souhlas +soulad +soumrak +souprava +soused +soutok +souviset +spalovna +spasitel +spis +splav +spodek +spojenec +spolu +sponzor +spornost +spousta +sprcha +spustit +sranda +sraz +srdce +srna +srnec +srovnat +srpen +srst +srub +stanice +starosta +statika +stavba +stehno +stezka +stodola +stolek +stopa +storno +stoupat +strach +stres +strhnout +strom +struna +studna +stupnice +stvol +styk +subjekt +subtropy +suchar +sudost +sukno +sundat +sunout +surikata +surovina +svah +svalstvo +svetr +svatba +svazek +svisle +svitek +svoboda +svodidlo +svorka +svrab +sykavka +sykot +synek +synovec +sypat +sypkost +syrovost +sysel +sytost +tabletka +tabule +tahoun +tajemno +tajfun +tajga +tajit +tajnost +taktika +tamhle +tampon +tancovat +tanec +tanker +tapeta +tavenina +tazatel +technika +tehdy +tekutina +telefon +temnota +tendence +tenista +tenor +teplota +tepna +teprve +terapie +termoska +textil +ticho +tiskopis +titulek +tkadlec +tkanina +tlapka +tleskat +tlukot +tlupa +tmel +toaleta +topinka +topol +torzo +touha +toulec +tradice +traktor +tramp +trasa +traverza +trefit +trest +trezor +trhavina +trhlina +trochu +trojice +troska +trouba +trpce +trpitel +trpkost +trubec +truchlit +truhlice +trus +trvat +tudy +tuhnout +tuhost +tundra +turista +turnaj +tuzemsko +tvaroh +tvorba +tvrdost +tvrz +tygr +tykev +ubohost +uboze +ubrat +ubrousek +ubrus +ubytovna +ucho +uctivost +udivit +uhradit +ujednat +ujistit +ujmout +ukazatel +uklidnit +uklonit +ukotvit +ukrojit +ulice +ulita +ulovit +umyvadlo +unavit +uniforma +uniknout +upadnout +uplatnit +uplynout +upoutat +upravit +uran +urazit +usednout +usilovat +usmrtit +usnadnit +usnout +usoudit +ustlat +ustrnout +utahovat +utkat +utlumit +utonout +utopenec +utrousit +uvalit +uvolnit +uvozovka +uzdravit +uzel +uzenina +uzlina +uznat +vagon +valcha +valoun +vana +vandal +vanilka +varan +varhany +varovat +vcelku +vchod +vdova +vedro +vegetace +vejce +velbloud +veletrh +velitel +velmoc +velryba +venkov +veranda +verze +veselka +veskrze +vesnice +vespodu +vesta +veterina +veverka +vibrace +vichr +videohra +vidina +vidle +vila +vinice +viset +vitalita +vize +vizitka +vjezd +vklad +vkus +vlajka +vlak +vlasec +vlevo +vlhkost +vliv +vlnovka +vloupat +vnucovat +vnuk +voda +vodivost +vodoznak +vodstvo +vojensky +vojna +vojsko +volant +volba +volit +volno +voskovka +vozidlo +vozovna +vpravo +vrabec +vracet +vrah +vrata +vrba +vrcholek +vrhat +vrstva +vrtule +vsadit +vstoupit +vstup +vtip +vybavit +vybrat +vychovat +vydat +vydra +vyfotit +vyhledat +vyhnout +vyhodit +vyhradit +vyhubit +vyjasnit +vyjet +vyjmout +vyklopit +vykonat +vylekat +vymazat +vymezit +vymizet +vymyslet +vynechat +vynikat +vynutit +vypadat +vyplatit +vypravit +vypustit +vyrazit +vyrovnat +vyrvat +vyslovit +vysoko +vystavit +vysunout +vysypat +vytasit +vytesat +vytratit +vyvinout +vyvolat +vyvrhel +vyzdobit +vyznat +vzadu +vzbudit +vzchopit +vzdor +vzduch +vzdychat +vzestup +vzhledem +vzkaz +vzlykat +vznik +vzorek +vzpoura +vztah +vztek +xylofon +zabrat +zabydlet +zachovat +zadarmo +zadusit +zafoukat +zahltit +zahodit +zahrada +zahynout +zajatec +zajet +zajistit +zaklepat +zakoupit +zalepit +zamezit +zamotat +zamyslet +zanechat +zanikat +zaplatit +zapojit +zapsat +zarazit +zastavit +zasunout +zatajit +zatemnit +zatknout +zaujmout +zavalit +zavelet +zavinit +zavolat +zavrtat +zazvonit +zbavit +zbrusu +zbudovat +zbytek +zdaleka +zdarma +zdatnost +zdivo +zdobit +zdroj +zdvih +zdymadlo +zelenina +zeman +zemina +zeptat +zezadu +zezdola +zhatit +zhltnout +zhluboka +zhotovit +zhruba +zima +zimnice +zjemnit +zklamat +zkoumat +zkratka +zkumavka +zlato +zlehka +zloba +zlom +zlost +zlozvyk +zmapovat +zmar +zmatek +zmije +zmizet +zmocnit +zmodrat +zmrzlina +zmutovat +znak +znalost +znamenat +znovu +zobrazit +zotavit +zoubek +zoufale +zplodit +zpomalit +zprava +zprostit +zprudka +zprvu +zrada +zranit +zrcadlo +zrnitost +zrno +zrovna +zrychlit +zrzavost +zticha +ztratit +zubovina +zubr +zvednout +zvenku +zvesela +zvon +zvrat +zvukovod +zvyk`.split('\n'); +//# sourceMappingURL=czech.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/czech.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/czech.js.map new file mode 100644 index 0000000..613dd9f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/czech.js.map @@ -0,0 +1 @@ +{"version":3,"file":"czech.js","sourceRoot":"","sources":["../../src/wordlists/czech.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA+/D7B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/english.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/english.js new file mode 100644 index 0000000..bb8972e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/english.js @@ -0,0 +1,2049 @@ +export const wordlist = `abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split('\n'); +//# sourceMappingURL=english.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/english.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/english.js.map new file mode 100644 index 0000000..927739d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/english.js.map @@ -0,0 +1 @@ +{"version":3,"file":"english.js","sourceRoot":"","sources":["../../src/wordlists/english.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+/D9B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/french.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/french.js new file mode 100644 index 0000000..b599b65 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/french.js @@ -0,0 +1,2049 @@ +export const wordlist = `abaisser +abandon +abdiquer +abeille +abolir +aborder +aboutir +aboyer +abrasif +abreuver +abriter +abroger +abrupt +absence +absolu +absurde +abusif +abyssal +académie +acajou +acarien +accabler +accepter +acclamer +accolade +accroche +accuser +acerbe +achat +acheter +aciduler +acier +acompte +acquérir +acronyme +acteur +actif +actuel +adepte +adéquat +adhésif +adjectif +adjuger +admettre +admirer +adopter +adorer +adoucir +adresse +adroit +adulte +adverbe +aérer +aéronef +affaire +affecter +affiche +affreux +affubler +agacer +agencer +agile +agiter +agrafer +agréable +agrume +aider +aiguille +ailier +aimable +aisance +ajouter +ajuster +alarmer +alchimie +alerte +algèbre +algue +aliéner +aliment +alléger +alliage +allouer +allumer +alourdir +alpaga +altesse +alvéole +amateur +ambigu +ambre +aménager +amertume +amidon +amiral +amorcer +amour +amovible +amphibie +ampleur +amusant +analyse +anaphore +anarchie +anatomie +ancien +anéantir +angle +angoisse +anguleux +animal +annexer +annonce +annuel +anodin +anomalie +anonyme +anormal +antenne +antidote +anxieux +apaiser +apéritif +aplanir +apologie +appareil +appeler +apporter +appuyer +aquarium +aqueduc +arbitre +arbuste +ardeur +ardoise +argent +arlequin +armature +armement +armoire +armure +arpenter +arracher +arriver +arroser +arsenic +artériel +article +aspect +asphalte +aspirer +assaut +asservir +assiette +associer +assurer +asticot +astre +astuce +atelier +atome +atrium +atroce +attaque +attentif +attirer +attraper +aubaine +auberge +audace +audible +augurer +aurore +automne +autruche +avaler +avancer +avarice +avenir +averse +aveugle +aviateur +avide +avion +aviser +avoine +avouer +avril +axial +axiome +badge +bafouer +bagage +baguette +baignade +balancer +balcon +baleine +balisage +bambin +bancaire +bandage +banlieue +bannière +banquier +barbier +baril +baron +barque +barrage +bassin +bastion +bataille +bateau +batterie +baudrier +bavarder +belette +bélier +belote +bénéfice +berceau +berger +berline +bermuda +besace +besogne +bétail +beurre +biberon +bicycle +bidule +bijou +bilan +bilingue +billard +binaire +biologie +biopsie +biotype +biscuit +bison +bistouri +bitume +bizarre +blafard +blague +blanchir +blessant +blinder +blond +bloquer +blouson +bobard +bobine +boire +boiser +bolide +bonbon +bondir +bonheur +bonifier +bonus +bordure +borne +botte +boucle +boueux +bougie +boulon +bouquin +bourse +boussole +boutique +boxeur +branche +brasier +brave +brebis +brèche +breuvage +bricoler +brigade +brillant +brioche +brique +brochure +broder +bronzer +brousse +broyeur +brume +brusque +brutal +bruyant +buffle +buisson +bulletin +bureau +burin +bustier +butiner +butoir +buvable +buvette +cabanon +cabine +cachette +cadeau +cadre +caféine +caillou +caisson +calculer +calepin +calibre +calmer +calomnie +calvaire +camarade +caméra +camion +campagne +canal +caneton +canon +cantine +canular +capable +caporal +caprice +capsule +capter +capuche +carabine +carbone +caresser +caribou +carnage +carotte +carreau +carton +cascade +casier +casque +cassure +causer +caution +cavalier +caverne +caviar +cédille +ceinture +céleste +cellule +cendrier +censurer +central +cercle +cérébral +cerise +cerner +cerveau +cesser +chagrin +chaise +chaleur +chambre +chance +chapitre +charbon +chasseur +chaton +chausson +chavirer +chemise +chenille +chéquier +chercher +cheval +chien +chiffre +chignon +chimère +chiot +chlorure +chocolat +choisir +chose +chouette +chrome +chute +cigare +cigogne +cimenter +cinéma +cintrer +circuler +cirer +cirque +citerne +citoyen +citron +civil +clairon +clameur +claquer +classe +clavier +client +cligner +climat +clivage +cloche +clonage +cloporte +cobalt +cobra +cocasse +cocotier +coder +codifier +coffre +cogner +cohésion +coiffer +coincer +colère +colibri +colline +colmater +colonel +combat +comédie +commande +compact +concert +conduire +confier +congeler +connoter +consonne +contact +convexe +copain +copie +corail +corbeau +cordage +corniche +corpus +correct +cortège +cosmique +costume +coton +coude +coupure +courage +couteau +couvrir +coyote +crabe +crainte +cravate +crayon +créature +créditer +crémeux +creuser +crevette +cribler +crier +cristal +critère +croire +croquer +crotale +crucial +cruel +crypter +cubique +cueillir +cuillère +cuisine +cuivre +culminer +cultiver +cumuler +cupide +curatif +curseur +cyanure +cycle +cylindre +cynique +daigner +damier +danger +danseur +dauphin +débattre +débiter +déborder +débrider +débutant +décaler +décembre +déchirer +décider +déclarer +décorer +décrire +décupler +dédale +déductif +déesse +défensif +défiler +défrayer +dégager +dégivrer +déglutir +dégrafer +déjeuner +délice +déloger +demander +demeurer +démolir +dénicher +dénouer +dentelle +dénuder +départ +dépenser +déphaser +déplacer +déposer +déranger +dérober +désastre +descente +désert +désigner +désobéir +dessiner +destrier +détacher +détester +détourer +détresse +devancer +devenir +deviner +devoir +diable +dialogue +diamant +dicter +différer +digérer +digital +digne +diluer +dimanche +diminuer +dioxyde +directif +diriger +discuter +disposer +dissiper +distance +divertir +diviser +docile +docteur +dogme +doigt +domaine +domicile +dompter +donateur +donjon +donner +dopamine +dortoir +dorure +dosage +doseur +dossier +dotation +douanier +double +douceur +douter +doyen +dragon +draper +dresser +dribbler +droiture +duperie +duplexe +durable +durcir +dynastie +éblouir +écarter +écharpe +échelle +éclairer +éclipse +éclore +écluse +école +économie +écorce +écouter +écraser +écrémer +écrivain +écrou +écume +écureuil +édifier +éduquer +effacer +effectif +effigie +effort +effrayer +effusion +égaliser +égarer +éjecter +élaborer +élargir +électron +élégant +éléphant +élève +éligible +élitisme +éloge +élucider +éluder +emballer +embellir +embryon +émeraude +émission +emmener +émotion +émouvoir +empereur +employer +emporter +emprise +émulsion +encadrer +enchère +enclave +encoche +endiguer +endosser +endroit +enduire +énergie +enfance +enfermer +enfouir +engager +engin +englober +énigme +enjamber +enjeu +enlever +ennemi +ennuyeux +enrichir +enrobage +enseigne +entasser +entendre +entier +entourer +entraver +énumérer +envahir +enviable +envoyer +enzyme +éolien +épaissir +épargne +épatant +épaule +épicerie +épidémie +épier +épilogue +épine +épisode +épitaphe +époque +épreuve +éprouver +épuisant +équerre +équipe +ériger +érosion +erreur +éruption +escalier +espadon +espèce +espiègle +espoir +esprit +esquiver +essayer +essence +essieu +essorer +estime +estomac +estrade +étagère +étaler +étanche +étatique +éteindre +étendoir +éternel +éthanol +éthique +ethnie +étirer +étoffer +étoile +étonnant +étourdir +étrange +étroit +étude +euphorie +évaluer +évasion +éventail +évidence +éviter +évolutif +évoquer +exact +exagérer +exaucer +exceller +excitant +exclusif +excuse +exécuter +exemple +exercer +exhaler +exhorter +exigence +exiler +exister +exotique +expédier +explorer +exposer +exprimer +exquis +extensif +extraire +exulter +fable +fabuleux +facette +facile +facture +faiblir +falaise +fameux +famille +farceur +farfelu +farine +farouche +fasciner +fatal +fatigue +faucon +fautif +faveur +favori +fébrile +féconder +fédérer +félin +femme +fémur +fendoir +féodal +fermer +féroce +ferveur +festival +feuille +feutre +février +fiasco +ficeler +fictif +fidèle +figure +filature +filetage +filière +filleul +filmer +filou +filtrer +financer +finir +fiole +firme +fissure +fixer +flairer +flamme +flasque +flatteur +fléau +flèche +fleur +flexion +flocon +flore +fluctuer +fluide +fluvial +folie +fonderie +fongible +fontaine +forcer +forgeron +formuler +fortune +fossile +foudre +fougère +fouiller +foulure +fourmi +fragile +fraise +franchir +frapper +frayeur +frégate +freiner +frelon +frémir +frénésie +frère +friable +friction +frisson +frivole +froid +fromage +frontal +frotter +fruit +fugitif +fuite +fureur +furieux +furtif +fusion +futur +gagner +galaxie +galerie +gambader +garantir +gardien +garnir +garrigue +gazelle +gazon +géant +gélatine +gélule +gendarme +général +génie +genou +gentil +géologie +géomètre +géranium +germe +gestuel +geyser +gibier +gicler +girafe +givre +glace +glaive +glisser +globe +gloire +glorieux +golfeur +gomme +gonfler +gorge +gorille +goudron +gouffre +goulot +goupille +gourmand +goutte +graduel +graffiti +graine +grand +grappin +gratuit +gravir +grenat +griffure +griller +grimper +grogner +gronder +grotte +groupe +gruger +grutier +gruyère +guépard +guerrier +guide +guimauve +guitare +gustatif +gymnaste +gyrostat +habitude +hachoir +halte +hameau +hangar +hanneton +haricot +harmonie +harpon +hasard +hélium +hématome +herbe +hérisson +hermine +héron +hésiter +heureux +hiberner +hibou +hilarant +histoire +hiver +homard +hommage +homogène +honneur +honorer +honteux +horde +horizon +horloge +hormone +horrible +houleux +housse +hublot +huileux +humain +humble +humide +humour +hurler +hydromel +hygiène +hymne +hypnose +idylle +ignorer +iguane +illicite +illusion +image +imbiber +imiter +immense +immobile +immuable +impact +impérial +implorer +imposer +imprimer +imputer +incarner +incendie +incident +incliner +incolore +indexer +indice +inductif +inédit +ineptie +inexact +infini +infliger +informer +infusion +ingérer +inhaler +inhiber +injecter +injure +innocent +inoculer +inonder +inscrire +insecte +insigne +insolite +inspirer +instinct +insulter +intact +intense +intime +intrigue +intuitif +inutile +invasion +inventer +inviter +invoquer +ironique +irradier +irréel +irriter +isoler +ivoire +ivresse +jaguar +jaillir +jambe +janvier +jardin +jauger +jaune +javelot +jetable +jeton +jeudi +jeunesse +joindre +joncher +jongler +joueur +jouissif +journal +jovial +joyau +joyeux +jubiler +jugement +junior +jupon +juriste +justice +juteux +juvénile +kayak +kimono +kiosque +label +labial +labourer +lacérer +lactose +lagune +laine +laisser +laitier +lambeau +lamelle +lampe +lanceur +langage +lanterne +lapin +largeur +larme +laurier +lavabo +lavoir +lecture +légal +léger +légume +lessive +lettre +levier +lexique +lézard +liasse +libérer +libre +licence +licorne +liège +lièvre +ligature +ligoter +ligue +limer +limite +limonade +limpide +linéaire +lingot +lionceau +liquide +lisière +lister +lithium +litige +littoral +livreur +logique +lointain +loisir +lombric +loterie +louer +lourd +loutre +louve +loyal +lubie +lucide +lucratif +lueur +lugubre +luisant +lumière +lunaire +lundi +luron +lutter +luxueux +machine +magasin +magenta +magique +maigre +maillon +maintien +mairie +maison +majorer +malaxer +maléfice +malheur +malice +mallette +mammouth +mandater +maniable +manquant +manteau +manuel +marathon +marbre +marchand +mardi +maritime +marqueur +marron +marteler +mascotte +massif +matériel +matière +matraque +maudire +maussade +mauve +maximal +méchant +méconnu +médaille +médecin +méditer +méduse +meilleur +mélange +mélodie +membre +mémoire +menacer +mener +menhir +mensonge +mentor +mercredi +mérite +merle +messager +mesure +métal +météore +méthode +métier +meuble +miauler +microbe +miette +mignon +migrer +milieu +million +mimique +mince +minéral +minimal +minorer +minute +miracle +miroiter +missile +mixte +mobile +moderne +moelleux +mondial +moniteur +monnaie +monotone +monstre +montagne +monument +moqueur +morceau +morsure +mortier +moteur +motif +mouche +moufle +moulin +mousson +mouton +mouvant +multiple +munition +muraille +murène +murmure +muscle +muséum +musicien +mutation +muter +mutuel +myriade +myrtille +mystère +mythique +nageur +nappe +narquois +narrer +natation +nation +nature +naufrage +nautique +navire +nébuleux +nectar +néfaste +négation +négliger +négocier +neige +nerveux +nettoyer +neurone +neutron +neveu +niche +nickel +nitrate +niveau +noble +nocif +nocturne +noirceur +noisette +nomade +nombreux +nommer +normatif +notable +notifier +notoire +nourrir +nouveau +novateur +novembre +novice +nuage +nuancer +nuire +nuisible +numéro +nuptial +nuque +nutritif +obéir +objectif +obliger +obscur +observer +obstacle +obtenir +obturer +occasion +occuper +océan +octobre +octroyer +octupler +oculaire +odeur +odorant +offenser +officier +offrir +ogive +oiseau +oisillon +olfactif +olivier +ombrage +omettre +onctueux +onduler +onéreux +onirique +opale +opaque +opérer +opinion +opportun +opprimer +opter +optique +orageux +orange +orbite +ordonner +oreille +organe +orgueil +orifice +ornement +orque +ortie +osciller +osmose +ossature +otarie +ouragan +ourson +outil +outrager +ouvrage +ovation +oxyde +oxygène +ozone +paisible +palace +palmarès +palourde +palper +panache +panda +pangolin +paniquer +panneau +panorama +pantalon +papaye +papier +papoter +papyrus +paradoxe +parcelle +paresse +parfumer +parler +parole +parrain +parsemer +partager +parure +parvenir +passion +pastèque +paternel +patience +patron +pavillon +pavoiser +payer +paysage +peigne +peintre +pelage +pélican +pelle +pelouse +peluche +pendule +pénétrer +pénible +pensif +pénurie +pépite +péplum +perdrix +perforer +période +permuter +perplexe +persil +perte +peser +pétale +petit +pétrir +peuple +pharaon +phobie +phoque +photon +phrase +physique +piano +pictural +pièce +pierre +pieuvre +pilote +pinceau +pipette +piquer +pirogue +piscine +piston +pivoter +pixel +pizza +placard +plafond +plaisir +planer +plaque +plastron +plateau +pleurer +plexus +pliage +plomb +plonger +pluie +plumage +pochette +poésie +poète +pointe +poirier +poisson +poivre +polaire +policier +pollen +polygone +pommade +pompier +ponctuel +pondérer +poney +portique +position +posséder +posture +potager +poteau +potion +pouce +poulain +poumon +pourpre +poussin +pouvoir +prairie +pratique +précieux +prédire +préfixe +prélude +prénom +présence +prétexte +prévoir +primitif +prince +prison +priver +problème +procéder +prodige +profond +progrès +proie +projeter +prologue +promener +propre +prospère +protéger +prouesse +proverbe +prudence +pruneau +psychose +public +puceron +puiser +pulpe +pulsar +punaise +punitif +pupitre +purifier +puzzle +pyramide +quasar +querelle +question +quiétude +quitter +quotient +racine +raconter +radieux +ragondin +raideur +raisin +ralentir +rallonge +ramasser +rapide +rasage +ratisser +ravager +ravin +rayonner +réactif +réagir +réaliser +réanimer +recevoir +réciter +réclamer +récolter +recruter +reculer +recycler +rédiger +redouter +refaire +réflexe +réformer +refrain +refuge +régalien +région +réglage +régulier +réitérer +rejeter +rejouer +relatif +relever +relief +remarque +remède +remise +remonter +remplir +remuer +renard +renfort +renifler +renoncer +rentrer +renvoi +replier +reporter +reprise +reptile +requin +réserve +résineux +résoudre +respect +rester +résultat +rétablir +retenir +réticule +retomber +retracer +réunion +réussir +revanche +revivre +révolte +révulsif +richesse +rideau +rieur +rigide +rigoler +rincer +riposter +risible +risque +rituel +rival +rivière +rocheux +romance +rompre +ronce +rondin +roseau +rosier +rotatif +rotor +rotule +rouge +rouille +rouleau +routine +royaume +ruban +rubis +ruche +ruelle +rugueux +ruiner +ruisseau +ruser +rustique +rythme +sabler +saboter +sabre +sacoche +safari +sagesse +saisir +salade +salive +salon +saluer +samedi +sanction +sanglier +sarcasme +sardine +saturer +saugrenu +saumon +sauter +sauvage +savant +savonner +scalpel +scandale +scélérat +scénario +sceptre +schéma +science +scinder +score +scrutin +sculpter +séance +sécable +sécher +secouer +sécréter +sédatif +séduire +seigneur +séjour +sélectif +semaine +sembler +semence +séminal +sénateur +sensible +sentence +séparer +séquence +serein +sergent +sérieux +serrure +sérum +service +sésame +sévir +sevrage +sextuple +sidéral +siècle +siéger +siffler +sigle +signal +silence +silicium +simple +sincère +sinistre +siphon +sirop +sismique +situer +skier +social +socle +sodium +soigneux +soldat +soleil +solitude +soluble +sombre +sommeil +somnoler +sonde +songeur +sonnette +sonore +sorcier +sortir +sosie +sottise +soucieux +soudure +souffle +soulever +soupape +source +soutirer +souvenir +spacieux +spatial +spécial +sphère +spiral +stable +station +sternum +stimulus +stipuler +strict +studieux +stupeur +styliste +sublime +substrat +subtil +subvenir +succès +sucre +suffixe +suggérer +suiveur +sulfate +superbe +supplier +surface +suricate +surmener +surprise +sursaut +survie +suspect +syllabe +symbole +symétrie +synapse +syntaxe +système +tabac +tablier +tactile +tailler +talent +talisman +talonner +tambour +tamiser +tangible +tapis +taquiner +tarder +tarif +tartine +tasse +tatami +tatouage +taupe +taureau +taxer +témoin +temporel +tenaille +tendre +teneur +tenir +tension +terminer +terne +terrible +tétine +texte +thème +théorie +thérapie +thorax +tibia +tiède +timide +tirelire +tiroir +tissu +titane +titre +tituber +toboggan +tolérant +tomate +tonique +tonneau +toponyme +torche +tordre +tornade +torpille +torrent +torse +tortue +totem +toucher +tournage +tousser +toxine +traction +trafic +tragique +trahir +train +trancher +travail +trèfle +tremper +trésor +treuil +triage +tribunal +tricoter +trilogie +triomphe +tripler +triturer +trivial +trombone +tronc +tropical +troupeau +tuile +tulipe +tumulte +tunnel +turbine +tuteur +tutoyer +tuyau +tympan +typhon +typique +tyran +ubuesque +ultime +ultrason +unanime +unifier +union +unique +unitaire +univers +uranium +urbain +urticant +usage +usine +usuel +usure +utile +utopie +vacarme +vaccin +vagabond +vague +vaillant +vaincre +vaisseau +valable +valise +vallon +valve +vampire +vanille +vapeur +varier +vaseux +vassal +vaste +vecteur +vedette +végétal +véhicule +veinard +véloce +vendredi +vénérer +venger +venimeux +ventouse +verdure +vérin +vernir +verrou +verser +vertu +veston +vétéran +vétuste +vexant +vexer +viaduc +viande +victoire +vidange +vidéo +vignette +vigueur +vilain +village +vinaigre +violon +vipère +virement +virtuose +virus +visage +viseur +vision +visqueux +visuel +vital +vitesse +viticole +vitrine +vivace +vivipare +vocation +voguer +voile +voisin +voiture +volaille +volcan +voltiger +volume +vorace +vortex +voter +vouloir +voyage +voyelle +wagon +xénon +yacht +zèbre +zénith +zeste +zoologie`.split('\n'); +//# sourceMappingURL=french.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/french.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/french.js.map new file mode 100644 index 0000000..9d2bc2e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/french.js.map @@ -0,0 +1 @@ +{"version":3,"file":"french.js","sourceRoot":"","sources":["../../src/wordlists/french.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SA+/DzB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/italian.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/italian.js new file mode 100644 index 0000000..5fd1b4e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/italian.js @@ -0,0 +1,2049 @@ +export const wordlist = `abaco +abbaglio +abbinato +abete +abisso +abolire +abrasivo +abrogato +accadere +accenno +accusato +acetone +achille +acido +acqua +acre +acrilico +acrobata +acuto +adagio +addebito +addome +adeguato +aderire +adipe +adottare +adulare +affabile +affetto +affisso +affranto +aforisma +afoso +africano +agave +agente +agevole +aggancio +agire +agitare +agonismo +agricolo +agrumeto +aguzzo +alabarda +alato +albatro +alberato +albo +albume +alce +alcolico +alettone +alfa +algebra +aliante +alibi +alimento +allagato +allegro +allievo +allodola +allusivo +almeno +alogeno +alpaca +alpestre +altalena +alterno +alticcio +altrove +alunno +alveolo +alzare +amalgama +amanita +amarena +ambito +ambrato +ameba +america +ametista +amico +ammasso +ammenda +ammirare +ammonito +amore +ampio +ampliare +amuleto +anacardo +anagrafe +analista +anarchia +anatra +anca +ancella +ancora +andare +andrea +anello +angelo +angolare +angusto +anima +annegare +annidato +anno +annuncio +anonimo +anticipo +anzi +apatico +apertura +apode +apparire +appetito +appoggio +approdo +appunto +aprile +arabica +arachide +aragosta +araldica +arancio +aratura +arazzo +arbitro +archivio +ardito +arenile +argento +argine +arguto +aria +armonia +arnese +arredato +arringa +arrosto +arsenico +arso +artefice +arzillo +asciutto +ascolto +asepsi +asettico +asfalto +asino +asola +aspirato +aspro +assaggio +asse +assoluto +assurdo +asta +astenuto +astice +astratto +atavico +ateismo +atomico +atono +attesa +attivare +attorno +attrito +attuale +ausilio +austria +autista +autonomo +autunno +avanzato +avere +avvenire +avviso +avvolgere +azione +azoto +azzimo +azzurro +babele +baccano +bacino +baco +badessa +badilata +bagnato +baita +balcone +baldo +balena +ballata +balzano +bambino +bandire +baraonda +barbaro +barca +baritono +barlume +barocco +basilico +basso +batosta +battuto +baule +bava +bavosa +becco +beffa +belgio +belva +benda +benevole +benigno +benzina +bere +berlina +beta +bibita +bici +bidone +bifido +biga +bilancia +bimbo +binocolo +biologo +bipede +bipolare +birbante +birra +biscotto +bisesto +bisnonno +bisonte +bisturi +bizzarro +blando +blatta +bollito +bonifico +bordo +bosco +botanico +bottino +bozzolo +braccio +bradipo +brama +branca +bravura +bretella +brevetto +brezza +briglia +brillante +brindare +broccolo +brodo +bronzina +brullo +bruno +bubbone +buca +budino +buffone +buio +bulbo +buono +burlone +burrasca +bussola +busta +cadetto +caduco +calamaro +calcolo +calesse +calibro +calmo +caloria +cambusa +camerata +camicia +cammino +camola +campale +canapa +candela +cane +canino +canotto +cantina +capace +capello +capitolo +capogiro +cappero +capra +capsula +carapace +carcassa +cardo +carisma +carovana +carretto +cartolina +casaccio +cascata +caserma +caso +cassone +castello +casuale +catasta +catena +catrame +cauto +cavillo +cedibile +cedrata +cefalo +celebre +cellulare +cena +cenone +centesimo +ceramica +cercare +certo +cerume +cervello +cesoia +cespo +ceto +chela +chiaro +chicca +chiedere +chimera +china +chirurgo +chitarra +ciao +ciclismo +cifrare +cigno +cilindro +ciottolo +circa +cirrosi +citrico +cittadino +ciuffo +civetta +civile +classico +clinica +cloro +cocco +codardo +codice +coerente +cognome +collare +colmato +colore +colposo +coltivato +colza +coma +cometa +commando +comodo +computer +comune +conciso +condurre +conferma +congelare +coniuge +connesso +conoscere +consumo +continuo +convegno +coperto +copione +coppia +copricapo +corazza +cordata +coricato +cornice +corolla +corpo +corredo +corsia +cortese +cosmico +costante +cottura +covato +cratere +cravatta +creato +credere +cremoso +crescita +creta +criceto +crinale +crisi +critico +croce +cronaca +crostata +cruciale +crusca +cucire +cuculo +cugino +cullato +cupola +curatore +cursore +curvo +cuscino +custode +dado +daino +dalmata +damerino +daniela +dannoso +danzare +datato +davanti +davvero +debutto +decennio +deciso +declino +decollo +decreto +dedicato +definito +deforme +degno +delegare +delfino +delirio +delta +demenza +denotato +dentro +deposito +derapata +derivare +deroga +descritto +deserto +desiderio +desumere +detersivo +devoto +diametro +dicembre +diedro +difeso +diffuso +digerire +digitale +diluvio +dinamico +dinnanzi +dipinto +diploma +dipolo +diradare +dire +dirotto +dirupo +disagio +discreto +disfare +disgelo +disposto +distanza +disumano +dito +divano +divelto +dividere +divorato +doblone +docente +doganale +dogma +dolce +domato +domenica +dominare +dondolo +dono +dormire +dote +dottore +dovuto +dozzina +drago +druido +dubbio +dubitare +ducale +duna +duomo +duplice +duraturo +ebano +eccesso +ecco +eclissi +economia +edera +edicola +edile +editoria +educare +egemonia +egli +egoismo +egregio +elaborato +elargire +elegante +elencato +eletto +elevare +elfico +elica +elmo +elsa +eluso +emanato +emblema +emesso +emiro +emotivo +emozione +empirico +emulo +endemico +enduro +energia +enfasi +enoteca +entrare +enzima +epatite +epilogo +episodio +epocale +eppure +equatore +erario +erba +erboso +erede +eremita +erigere +ermetico +eroe +erosivo +errante +esagono +esame +esanime +esaudire +esca +esempio +esercito +esibito +esigente +esistere +esito +esofago +esortato +esoso +espanso +espresso +essenza +esso +esteso +estimare +estonia +estroso +esultare +etilico +etnico +etrusco +etto +euclideo +europa +evaso +evidenza +evitato +evoluto +evviva +fabbrica +faccenda +fachiro +falco +famiglia +fanale +fanfara +fango +fantasma +fare +farfalla +farinoso +farmaco +fascia +fastoso +fasullo +faticare +fato +favoloso +febbre +fecola +fede +fegato +felpa +feltro +femmina +fendere +fenomeno +fermento +ferro +fertile +fessura +festivo +fetta +feudo +fiaba +fiducia +fifa +figurato +filo +finanza +finestra +finire +fiore +fiscale +fisico +fiume +flacone +flamenco +flebo +flemma +florido +fluente +fluoro +fobico +focaccia +focoso +foderato +foglio +folata +folclore +folgore +fondente +fonetico +fonia +fontana +forbito +forchetta +foresta +formica +fornaio +foro +fortezza +forzare +fosfato +fosso +fracasso +frana +frassino +fratello +freccetta +frenata +fresco +frigo +frollino +fronde +frugale +frutta +fucilata +fucsia +fuggente +fulmine +fulvo +fumante +fumetto +fumoso +fune +funzione +fuoco +furbo +furgone +furore +fuso +futile +gabbiano +gaffe +galateo +gallina +galoppo +gambero +gamma +garanzia +garbo +garofano +garzone +gasdotto +gasolio +gastrico +gatto +gaudio +gazebo +gazzella +geco +gelatina +gelso +gemello +gemmato +gene +genitore +gennaio +genotipo +gergo +ghepardo +ghiaccio +ghisa +giallo +gilda +ginepro +giocare +gioiello +giorno +giove +girato +girone +gittata +giudizio +giurato +giusto +globulo +glutine +gnomo +gobba +golf +gomito +gommone +gonfio +gonna +governo +gracile +grado +grafico +grammo +grande +grattare +gravoso +grazia +greca +gregge +grifone +grigio +grinza +grotta +gruppo +guadagno +guaio +guanto +guardare +gufo +guidare +ibernato +icona +identico +idillio +idolo +idra +idrico +idrogeno +igiene +ignaro +ignorato +ilare +illeso +illogico +illudere +imballo +imbevuto +imbocco +imbuto +immane +immerso +immolato +impacco +impeto +impiego +importo +impronta +inalare +inarcare +inattivo +incanto +incendio +inchino +incisivo +incluso +incontro +incrocio +incubo +indagine +india +indole +inedito +infatti +infilare +inflitto +ingaggio +ingegno +inglese +ingordo +ingrosso +innesco +inodore +inoltrare +inondato +insano +insetto +insieme +insonnia +insulina +intasato +intero +intonaco +intuito +inumidire +invalido +invece +invito +iperbole +ipnotico +ipotesi +ippica +iride +irlanda +ironico +irrigato +irrorare +isolato +isotopo +isterico +istituto +istrice +italia +iterare +labbro +labirinto +lacca +lacerato +lacrima +lacuna +laddove +lago +lampo +lancetta +lanterna +lardoso +larga +laringe +lastra +latenza +latino +lattuga +lavagna +lavoro +legale +leggero +lembo +lentezza +lenza +leone +lepre +lesivo +lessato +lesto +letterale +leva +levigato +libero +lido +lievito +lilla +limatura +limitare +limpido +lineare +lingua +liquido +lira +lirica +lisca +lite +litigio +livrea +locanda +lode +logica +lombare +londra +longevo +loquace +lorenzo +loto +lotteria +luce +lucidato +lumaca +luminoso +lungo +lupo +luppolo +lusinga +lusso +lutto +macabro +macchina +macero +macinato +madama +magico +maglia +magnete +magro +maiolica +malafede +malgrado +malinteso +malsano +malto +malumore +mana +mancia +mandorla +mangiare +manifesto +mannaro +manovra +mansarda +mantide +manubrio +mappa +maratona +marcire +maretta +marmo +marsupio +maschera +massaia +mastino +materasso +matricola +mattone +maturo +mazurca +meandro +meccanico +mecenate +medesimo +meditare +mega +melassa +melis +melodia +meninge +meno +mensola +mercurio +merenda +merlo +meschino +mese +messere +mestolo +metallo +metodo +mettere +miagolare +mica +micelio +michele +microbo +midollo +miele +migliore +milano +milite +mimosa +minerale +mini +minore +mirino +mirtillo +miscela +missiva +misto +misurare +mitezza +mitigare +mitra +mittente +mnemonico +modello +modifica +modulo +mogano +mogio +mole +molosso +monastero +monco +mondina +monetario +monile +monotono +monsone +montato +monviso +mora +mordere +morsicato +mostro +motivato +motosega +motto +movenza +movimento +mozzo +mucca +mucosa +muffa +mughetto +mugnaio +mulatto +mulinello +multiplo +mummia +munto +muovere +murale +musa +muscolo +musica +mutevole +muto +nababbo +nafta +nanometro +narciso +narice +narrato +nascere +nastrare +naturale +nautica +naviglio +nebulosa +necrosi +negativo +negozio +nemmeno +neofita +neretto +nervo +nessuno +nettuno +neutrale +neve +nevrotico +nicchia +ninfa +nitido +nobile +nocivo +nodo +nome +nomina +nordico +normale +norvegese +nostrano +notare +notizia +notturno +novella +nucleo +nulla +numero +nuovo +nutrire +nuvola +nuziale +oasi +obbedire +obbligo +obelisco +oblio +obolo +obsoleto +occasione +occhio +occidente +occorrere +occultare +ocra +oculato +odierno +odorare +offerta +offrire +offuscato +oggetto +oggi +ognuno +olandese +olfatto +oliato +oliva +ologramma +oltre +omaggio +ombelico +ombra +omega +omissione +ondoso +onere +onice +onnivoro +onorevole +onta +operato +opinione +opposto +oracolo +orafo +ordine +orecchino +orefice +orfano +organico +origine +orizzonte +orma +ormeggio +ornativo +orologio +orrendo +orribile +ortensia +ortica +orzata +orzo +osare +oscurare +osmosi +ospedale +ospite +ossa +ossidare +ostacolo +oste +otite +otre +ottagono +ottimo +ottobre +ovale +ovest +ovino +oviparo +ovocito +ovunque +ovviare +ozio +pacchetto +pace +pacifico +padella +padrone +paese +paga +pagina +palazzina +palesare +pallido +palo +palude +pandoro +pannello +paolo +paonazzo +paprica +parabola +parcella +parere +pargolo +pari +parlato +parola +partire +parvenza +parziale +passivo +pasticca +patacca +patologia +pattume +pavone +peccato +pedalare +pedonale +peggio +peloso +penare +pendice +penisola +pennuto +penombra +pensare +pentola +pepe +pepita +perbene +percorso +perdonato +perforare +pergamena +periodo +permesso +perno +perplesso +persuaso +pertugio +pervaso +pesatore +pesista +peso +pestifero +petalo +pettine +petulante +pezzo +piacere +pianta +piattino +piccino +picozza +piega +pietra +piffero +pigiama +pigolio +pigro +pila +pilifero +pillola +pilota +pimpante +pineta +pinna +pinolo +pioggia +piombo +piramide +piretico +pirite +pirolisi +pitone +pizzico +placebo +planare +plasma +platano +plenario +pochezza +poderoso +podismo +poesia +poggiare +polenta +poligono +pollice +polmonite +polpetta +polso +poltrona +polvere +pomice +pomodoro +ponte +popoloso +porfido +poroso +porpora +porre +portata +posa +positivo +possesso +postulato +potassio +potere +pranzo +prassi +pratica +precluso +predica +prefisso +pregiato +prelievo +premere +prenotare +preparato +presenza +pretesto +prevalso +prima +principe +privato +problema +procura +produrre +profumo +progetto +prolunga +promessa +pronome +proposta +proroga +proteso +prova +prudente +prugna +prurito +psiche +pubblico +pudica +pugilato +pugno +pulce +pulito +pulsante +puntare +pupazzo +pupilla +puro +quadro +qualcosa +quasi +querela +quota +raccolto +raddoppio +radicale +radunato +raffica +ragazzo +ragione +ragno +ramarro +ramingo +ramo +randagio +rantolare +rapato +rapina +rappreso +rasatura +raschiato +rasente +rassegna +rastrello +rata +ravveduto +reale +recepire +recinto +recluta +recondito +recupero +reddito +redimere +regalato +registro +regola +regresso +relazione +remare +remoto +renna +replica +reprimere +reputare +resa +residente +responso +restauro +rete +retina +retorica +rettifica +revocato +riassunto +ribadire +ribelle +ribrezzo +ricarica +ricco +ricevere +riciclato +ricordo +ricreduto +ridicolo +ridurre +rifasare +riflesso +riforma +rifugio +rigare +rigettato +righello +rilassato +rilevato +rimanere +rimbalzo +rimedio +rimorchio +rinascita +rincaro +rinforzo +rinnovo +rinomato +rinsavito +rintocco +rinuncia +rinvenire +riparato +ripetuto +ripieno +riportare +ripresa +ripulire +risata +rischio +riserva +risibile +riso +rispetto +ristoro +risultato +risvolto +ritardo +ritegno +ritmico +ritrovo +riunione +riva +riverso +rivincita +rivolto +rizoma +roba +robotico +robusto +roccia +roco +rodaggio +rodere +roditore +rogito +rollio +romantico +rompere +ronzio +rosolare +rospo +rotante +rotondo +rotula +rovescio +rubizzo +rubrica +ruga +rullino +rumine +rumoroso +ruolo +rupe +russare +rustico +sabato +sabbiare +sabotato +sagoma +salasso +saldatura +salgemma +salivare +salmone +salone +saltare +saluto +salvo +sapere +sapido +saporito +saraceno +sarcasmo +sarto +sassoso +satellite +satira +satollo +saturno +savana +savio +saziato +sbadiglio +sbalzo +sbancato +sbarra +sbattere +sbavare +sbendare +sbirciare +sbloccato +sbocciato +sbrinare +sbruffone +sbuffare +scabroso +scadenza +scala +scambiare +scandalo +scapola +scarso +scatenare +scavato +scelto +scenico +scettro +scheda +schiena +sciarpa +scienza +scindere +scippo +sciroppo +scivolo +sclerare +scodella +scolpito +scomparto +sconforto +scoprire +scorta +scossone +scozzese +scriba +scrollare +scrutinio +scuderia +scultore +scuola +scuro +scusare +sdebitare +sdoganare +seccatura +secondo +sedano +seggiola +segnalato +segregato +seguito +selciato +selettivo +sella +selvaggio +semaforo +sembrare +seme +seminato +sempre +senso +sentire +sepolto +sequenza +serata +serbato +sereno +serio +serpente +serraglio +servire +sestina +setola +settimana +sfacelo +sfaldare +sfamato +sfarzoso +sfaticato +sfera +sfida +sfilato +sfinge +sfocato +sfoderare +sfogo +sfoltire +sforzato +sfratto +sfruttato +sfuggito +sfumare +sfuso +sgabello +sgarbato +sgonfiare +sgorbio +sgrassato +sguardo +sibilo +siccome +sierra +sigla +signore +silenzio +sillaba +simbolo +simpatico +simulato +sinfonia +singolo +sinistro +sino +sintesi +sinusoide +sipario +sisma +sistole +situato +slitta +slogatura +sloveno +smarrito +smemorato +smentito +smeraldo +smilzo +smontare +smottato +smussato +snellire +snervato +snodo +sobbalzo +sobrio +soccorso +sociale +sodale +soffitto +sogno +soldato +solenne +solido +sollazzo +solo +solubile +solvente +somatico +somma +sonda +sonetto +sonnifero +sopire +soppeso +sopra +sorgere +sorpasso +sorriso +sorso +sorteggio +sorvolato +sospiro +sosta +sottile +spada +spalla +spargere +spatola +spavento +spazzola +specie +spedire +spegnere +spelatura +speranza +spessore +spettrale +spezzato +spia +spigoloso +spillato +spinoso +spirale +splendido +sportivo +sposo +spranga +sprecare +spronato +spruzzo +spuntino +squillo +sradicare +srotolato +stabile +stacco +staffa +stagnare +stampato +stantio +starnuto +stasera +statuto +stelo +steppa +sterzo +stiletto +stima +stirpe +stivale +stizzoso +stonato +storico +strappo +stregato +stridulo +strozzare +strutto +stuccare +stufo +stupendo +subentro +succoso +sudore +suggerito +sugo +sultano +suonare +superbo +supporto +surgelato +surrogato +sussurro +sutura +svagare +svedese +sveglio +svelare +svenuto +svezia +sviluppo +svista +svizzera +svolta +svuotare +tabacco +tabulato +tacciare +taciturno +tale +talismano +tampone +tannino +tara +tardivo +targato +tariffa +tarpare +tartaruga +tasto +tattico +taverna +tavolata +tazza +teca +tecnico +telefono +temerario +tempo +temuto +tendone +tenero +tensione +tentacolo +teorema +terme +terrazzo +terzetto +tesi +tesserato +testato +tetro +tettoia +tifare +tigella +timbro +tinto +tipico +tipografo +tiraggio +tiro +titanio +titolo +titubante +tizio +tizzone +toccare +tollerare +tolto +tombola +tomo +tonfo +tonsilla +topazio +topologia +toppa +torba +tornare +torrone +tortora +toscano +tossire +tostatura +totano +trabocco +trachea +trafila +tragedia +tralcio +tramonto +transito +trapano +trarre +trasloco +trattato +trave +treccia +tremolio +trespolo +tributo +tricheco +trifoglio +trillo +trincea +trio +tristezza +triturato +trivella +tromba +trono +troppo +trottola +trovare +truccato +tubatura +tuffato +tulipano +tumulto +tunisia +turbare +turchino +tuta +tutela +ubicato +uccello +uccisore +udire +uditivo +uffa +ufficio +uguale +ulisse +ultimato +umano +umile +umorismo +uncinetto +ungere +ungherese +unicorno +unificato +unisono +unitario +unte +uovo +upupa +uragano +urgenza +urlo +usanza +usato +uscito +usignolo +usuraio +utensile +utilizzo +utopia +vacante +vaccinato +vagabondo +vagliato +valanga +valgo +valico +valletta +valoroso +valutare +valvola +vampata +vangare +vanitoso +vano +vantaggio +vanvera +vapore +varano +varcato +variante +vasca +vedetta +vedova +veduto +vegetale +veicolo +velcro +velina +velluto +veloce +venato +vendemmia +vento +verace +verbale +vergogna +verifica +vero +verruca +verticale +vescica +vessillo +vestale +veterano +vetrina +vetusto +viandante +vibrante +vicenda +vichingo +vicinanza +vidimare +vigilia +vigneto +vigore +vile +villano +vimini +vincitore +viola +vipera +virgola +virologo +virulento +viscoso +visione +vispo +vissuto +visura +vita +vitello +vittima +vivanda +vivido +viziare +voce +voga +volatile +volere +volpe +voragine +vulcano +zampogna +zanna +zappato +zattera +zavorra +zefiro +zelante +zelo +zenzero +zerbino +zibetto +zinco +zircone +zitto +zolla +zotico +zucchero +zufolo +zulu +zuppa`.split('\n'); +//# sourceMappingURL=italian.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/italian.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/italian.js.map new file mode 100644 index 0000000..db9246a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/italian.js.map @@ -0,0 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA+/D5B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/japanese.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/japanese.js new file mode 100644 index 0000000..44c62bf --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/japanese.js @@ -0,0 +1,2049 @@ +export const wordlist = `あいこくしん +あいさつ +あいだ +あおぞら +あかちゃん +あきる +あけがた +あける +あこがれる +あさい +あさひ +あしあと +あじわう +あずかる +あずき +あそぶ +あたえる +あたためる +あたりまえ +あたる +あつい +あつかう +あっしゅく +あつまり +あつめる +あてな +あてはまる +あひる +あぶら +あぶる +あふれる +あまい +あまど +あまやかす +あまり +あみもの +あめりか +あやまる +あゆむ +あらいぐま +あらし +あらすじ +あらためる +あらゆる +あらわす +ありがとう +あわせる +あわてる +あんい +あんがい +あんこ +あんぜん +あんてい +あんない +あんまり +いいだす +いおん +いがい +いがく +いきおい +いきなり +いきもの +いきる +いくじ +いくぶん +いけばな +いけん +いこう +いこく +いこつ +いさましい +いさん +いしき +いじゅう +いじょう +いじわる +いずみ +いずれ +いせい +いせえび +いせかい +いせき +いぜん +いそうろう +いそがしい +いだい +いだく +いたずら +いたみ +いたりあ +いちおう +いちじ +いちど +いちば +いちぶ +いちりゅう +いつか +いっしゅん +いっせい +いっそう +いったん +いっち +いってい +いっぽう +いてざ +いてん +いどう +いとこ +いない +いなか +いねむり +いのち +いのる +いはつ +いばる +いはん +いびき +いひん +いふく +いへん +いほう +いみん +いもうと +いもたれ +いもり +いやがる +いやす +いよかん +いよく +いらい +いらすと +いりぐち +いりょう +いれい +いれもの +いれる +いろえんぴつ +いわい +いわう +いわかん +いわば +いわゆる +いんげんまめ +いんさつ +いんしょう +いんよう +うえき +うえる +うおざ +うがい +うかぶ +うかべる +うきわ +うくらいな +うくれれ +うけたまわる +うけつけ +うけとる +うけもつ +うける +うごかす +うごく +うこん +うさぎ +うしなう +うしろがみ +うすい +うすぎ +うすぐらい +うすめる +うせつ +うちあわせ +うちがわ +うちき +うちゅう +うっかり +うつくしい +うったえる +うつる +うどん +うなぎ +うなじ +うなずく +うなる +うねる +うのう +うぶげ +うぶごえ +うまれる +うめる +うもう +うやまう +うよく +うらがえす +うらぐち +うらない +うりあげ +うりきれ +うるさい +うれしい +うれゆき +うれる +うろこ +うわき +うわさ +うんこう +うんちん +うんてん +うんどう +えいえん +えいが +えいきょう +えいご +えいせい +えいぶん +えいよう +えいわ +えおり +えがお +えがく +えきたい +えくせる +えしゃく +えすて +えつらん +えのぐ +えほうまき +えほん +えまき +えもじ +えもの +えらい +えらぶ +えりあ +えんえん +えんかい +えんぎ +えんげき +えんしゅう +えんぜつ +えんそく +えんちょう +えんとつ +おいかける +おいこす +おいしい +おいつく +おうえん +おうさま +おうじ +おうせつ +おうたい +おうふく +おうべい +おうよう +おえる +おおい +おおう +おおどおり +おおや +おおよそ +おかえり +おかず +おがむ +おかわり +おぎなう +おきる +おくさま +おくじょう +おくりがな +おくる +おくれる +おこす +おこなう +おこる +おさえる +おさない +おさめる +おしいれ +おしえる +おじぎ +おじさん +おしゃれ +おそらく +おそわる +おたがい +おたく +おだやか +おちつく +おっと +おつり +おでかけ +おとしもの +おとなしい +おどり +おどろかす +おばさん +おまいり +おめでとう +おもいで +おもう +おもたい +おもちゃ +おやつ +おやゆび +およぼす +おらんだ +おろす +おんがく +おんけい +おんしゃ +おんせん +おんだん +おんちゅう +おんどけい +かあつ +かいが +がいき +がいけん +がいこう +かいさつ +かいしゃ +かいすいよく +かいぜん +かいぞうど +かいつう +かいてん +かいとう +かいふく +がいへき +かいほう +かいよう +がいらい +かいわ +かえる +かおり +かかえる +かがく +かがし +かがみ +かくご +かくとく +かざる +がぞう +かたい +かたち +がちょう +がっきゅう +がっこう +がっさん +がっしょう +かなざわし +かのう +がはく +かぶか +かほう +かほご +かまう +かまぼこ +かめれおん +かゆい +かようび +からい +かるい +かろう +かわく +かわら +がんか +かんけい +かんこう +かんしゃ +かんそう +かんたん +かんち +がんばる +きあい +きあつ +きいろ +ぎいん +きうい +きうん +きえる +きおう +きおく +きおち +きおん +きかい +きかく +きかんしゃ +ききて +きくばり +きくらげ +きけんせい +きこう +きこえる +きこく +きさい +きさく +きさま +きさらぎ +ぎじかがく +ぎしき +ぎじたいけん +ぎじにってい +ぎじゅつしゃ +きすう +きせい +きせき +きせつ +きそう +きぞく +きぞん +きたえる +きちょう +きつえん +ぎっちり +きつつき +きつね +きてい +きどう +きどく +きない +きなが +きなこ +きぬごし +きねん +きのう +きのした +きはく +きびしい +きひん +きふく +きぶん +きぼう +きほん +きまる +きみつ +きむずかしい +きめる +きもだめし +きもち +きもの +きゃく +きやく +ぎゅうにく +きよう +きょうりゅう +きらい +きらく +きりん +きれい +きれつ +きろく +ぎろん +きわめる +ぎんいろ +きんかくじ +きんじょ +きんようび +ぐあい +くいず +くうかん +くうき +くうぐん +くうこう +ぐうせい +くうそう +ぐうたら +くうふく +くうぼ +くかん +くきょう +くげん +ぐこう +くさい +くさき +くさばな +くさる +くしゃみ +くしょう +くすのき +くすりゆび +くせげ +くせん +ぐたいてき +くださる +くたびれる +くちこみ +くちさき +くつした +ぐっすり +くつろぐ +くとうてん +くどく +くなん +くねくね +くのう +くふう +くみあわせ +くみたてる +くめる +くやくしょ +くらす +くらべる +くるま +くれる +くろう +くわしい +ぐんかん +ぐんしょく +ぐんたい +ぐんて +けあな +けいかく +けいけん +けいこ +けいさつ +げいじゅつ +けいたい +げいのうじん +けいれき +けいろ +けおとす +けおりもの +げきか +げきげん +げきだん +げきちん +げきとつ +げきは +げきやく +げこう +げこくじょう +げざい +けさき +げざん +けしき +けしごむ +けしょう +げすと +けたば +けちゃっぷ +けちらす +けつあつ +けつい +けつえき +けっこん +けつじょ +けっせき +けってい +けつまつ +げつようび +げつれい +けつろん +げどく +けとばす +けとる +けなげ +けなす +けなみ +けぬき +げねつ +けねん +けはい +げひん +けぶかい +げぼく +けまり +けみかる +けむし +けむり +けもの +けらい +けろけろ +けわしい +けんい +けんえつ +けんお +けんか +げんき +けんげん +けんこう +けんさく +けんしゅう +けんすう +げんそう +けんちく +けんてい +けんとう +けんない +けんにん +げんぶつ +けんま +けんみん +けんめい +けんらん +けんり +こあくま +こいぬ +こいびと +ごうい +こうえん +こうおん +こうかん +ごうきゅう +ごうけい +こうこう +こうさい +こうじ +こうすい +ごうせい +こうそく +こうたい +こうちゃ +こうつう +こうてい +こうどう +こうない +こうはい +ごうほう +ごうまん +こうもく +こうりつ +こえる +こおり +ごかい +ごがつ +ごかん +こくご +こくさい +こくとう +こくない +こくはく +こぐま +こけい +こける +ここのか +こころ +こさめ +こしつ +こすう +こせい +こせき +こぜん +こそだて +こたい +こたえる +こたつ +こちょう +こっか +こつこつ +こつばん +こつぶ +こてい +こてん +ことがら +ことし +ことば +ことり +こなごな +こねこね +このまま +このみ +このよ +ごはん +こひつじ +こふう +こふん +こぼれる +ごまあぶら +こまかい +ごますり +こまつな +こまる +こむぎこ +こもじ +こもち +こもの +こもん +こやく +こやま +こゆう +こゆび +こよい +こよう +こりる +これくしょん +ころっけ +こわもて +こわれる +こんいん +こんかい +こんき +こんしゅう +こんすい +こんだて +こんとん +こんなん +こんびに +こんぽん +こんまけ +こんや +こんれい +こんわく +ざいえき +さいかい +さいきん +ざいげん +ざいこ +さいしょ +さいせい +ざいたく +ざいちゅう +さいてき +ざいりょう +さうな +さかいし +さがす +さかな +さかみち +さがる +さぎょう +さくし +さくひん +さくら +さこく +さこつ +さずかる +ざせき +さたん +さつえい +ざつおん +ざっか +ざつがく +さっきょく +ざっし +さつじん +ざっそう +さつたば +さつまいも +さてい +さといも +さとう +さとおや +さとし +さとる +さのう +さばく +さびしい +さべつ +さほう +さほど +さます +さみしい +さみだれ +さむけ +さめる +さやえんどう +さゆう +さよう +さよく +さらだ +ざるそば +さわやか +さわる +さんいん +さんか +さんきゃく +さんこう +さんさい +ざんしょ +さんすう +さんせい +さんそ +さんち +さんま +さんみ +さんらん +しあい +しあげ +しあさって +しあわせ +しいく +しいん +しうち +しえい +しおけ +しかい +しかく +じかん +しごと +しすう +じだい +したうけ +したぎ +したて +したみ +しちょう +しちりん +しっかり +しつじ +しつもん +してい +してき +してつ +じてん +じどう +しなぎれ +しなもの +しなん +しねま +しねん +しのぐ +しのぶ +しはい +しばかり +しはつ +しはらい +しはん +しひょう +しふく +じぶん +しへい +しほう +しほん +しまう +しまる +しみん +しむける +じむしょ +しめい +しめる +しもん +しゃいん +しゃうん +しゃおん +じゃがいも +しやくしょ +しゃくほう +しゃけん +しゃこ +しゃざい +しゃしん +しゃせん +しゃそう +しゃたい +しゃちょう +しゃっきん +じゃま +しゃりん +しゃれい +じゆう +じゅうしょ +しゅくはく +じゅしん +しゅっせき +しゅみ +しゅらば +じゅんばん +しょうかい +しょくたく +しょっけん +しょどう +しょもつ +しらせる +しらべる +しんか +しんこう +じんじゃ +しんせいじ +しんちく +しんりん +すあげ +すあし +すあな +ずあん +すいえい +すいか +すいとう +ずいぶん +すいようび +すうがく +すうじつ +すうせん +すおどり +すきま +すくう +すくない +すける +すごい +すこし +ずさん +すずしい +すすむ +すすめる +すっかり +ずっしり +ずっと +すてき +すてる +すねる +すのこ +すはだ +すばらしい +ずひょう +ずぶぬれ +すぶり +すふれ +すべて +すべる +ずほう +すぼん +すまい +すめし +すもう +すやき +すらすら +するめ +すれちがう +すろっと +すわる +すんぜん +すんぽう +せあぶら +せいかつ +せいげん +せいじ +せいよう +せおう +せかいかん +せきにん +せきむ +せきゆ +せきらんうん +せけん +せこう +せすじ +せたい +せたけ +せっかく +せっきゃく +ぜっく +せっけん +せっこつ +せっさたくま +せつぞく +せつだん +せつでん +せっぱん +せつび +せつぶん +せつめい +せつりつ +せなか +せのび +せはば +せびろ +せぼね +せまい +せまる +せめる +せもたれ +せりふ +ぜんあく +せんい +せんえい +せんか +せんきょ +せんく +せんげん +ぜんご +せんさい +せんしゅ +せんすい +せんせい +せんぞ +せんたく +せんちょう +せんてい +せんとう +せんぬき +せんねん +せんぱい +ぜんぶ +ぜんぽう +せんむ +せんめんじょ +せんもん +せんやく +せんゆう +せんよう +ぜんら +ぜんりゃく +せんれい +せんろ +そあく +そいとげる +そいね +そうがんきょう +そうき +そうご +そうしん +そうだん +そうなん +そうび +そうめん +そうり +そえもの +そえん +そがい +そげき +そこう +そこそこ +そざい +そしな +そせい +そせん +そそぐ +そだてる +そつう +そつえん +そっかん +そつぎょう +そっけつ +そっこう +そっせん +そっと +そとがわ +そとづら +そなえる +そなた +そふぼ +そぼく +そぼろ +そまつ +そまる +そむく +そむりえ +そめる +そもそも +そよかぜ +そらまめ +そろう +そんかい +そんけい +そんざい +そんしつ +そんぞく +そんちょう +ぞんび +ぞんぶん +そんみん +たあい +たいいん +たいうん +たいえき +たいおう +だいがく +たいき +たいぐう +たいけん +たいこ +たいざい +だいじょうぶ +だいすき +たいせつ +たいそう +だいたい +たいちょう +たいてい +だいどころ +たいない +たいねつ +たいのう +たいはん +だいひょう +たいふう +たいへん +たいほ +たいまつばな +たいみんぐ +たいむ +たいめん +たいやき +たいよう +たいら +たいりょく +たいる +たいわん +たうえ +たえる +たおす +たおる +たおれる +たかい +たかね +たきび +たくさん +たこく +たこやき +たさい +たしざん +だじゃれ +たすける +たずさわる +たそがれ +たたかう +たたく +ただしい +たたみ +たちばな +だっかい +だっきゃく +だっこ +だっしゅつ +だったい +たてる +たとえる +たなばた +たにん +たぬき +たのしみ +たはつ +たぶん +たべる +たぼう +たまご +たまる +だむる +ためいき +ためす +ためる +たもつ +たやすい +たよる +たらす +たりきほんがん +たりょう +たりる +たると +たれる +たれんと +たろっと +たわむれる +だんあつ +たんい +たんおん +たんか +たんき +たんけん +たんご +たんさん +たんじょうび +だんせい +たんそく +たんたい +だんち +たんてい +たんとう +だんな +たんにん +だんねつ +たんのう +たんぴん +だんぼう +たんまつ +たんめい +だんれつ +だんろ +だんわ +ちあい +ちあん +ちいき +ちいさい +ちえん +ちかい +ちから +ちきゅう +ちきん +ちけいず +ちけん +ちこく +ちさい +ちしき +ちしりょう +ちせい +ちそう +ちたい +ちたん +ちちおや +ちつじょ +ちてき +ちてん +ちぬき +ちぬり +ちのう +ちひょう +ちへいせん +ちほう +ちまた +ちみつ +ちみどろ +ちめいど +ちゃんこなべ +ちゅうい +ちゆりょく +ちょうし +ちょさくけん +ちらし +ちらみ +ちりがみ +ちりょう +ちるど +ちわわ +ちんたい +ちんもく +ついか +ついたち +つうか +つうじょう +つうはん +つうわ +つかう +つかれる +つくね +つくる +つけね +つける +つごう +つたえる +つづく +つつじ +つつむ +つとめる +つながる +つなみ +つねづね +つのる +つぶす +つまらない +つまる +つみき +つめたい +つもり +つもる +つよい +つるぼ +つるみく +つわもの +つわり +てあし +てあて +てあみ +ていおん +ていか +ていき +ていけい +ていこく +ていさつ +ていし +ていせい +ていたい +ていど +ていねい +ていひょう +ていへん +ていぼう +てうち +ておくれ +てきとう +てくび +でこぼこ +てさぎょう +てさげ +てすり +てそう +てちがい +てちょう +てつがく +てつづき +でっぱ +てつぼう +てつや +でぬかえ +てぬき +てぬぐい +てのひら +てはい +てぶくろ +てふだ +てほどき +てほん +てまえ +てまきずし +てみじか +てみやげ +てらす +てれび +てわけ +てわたし +でんあつ +てんいん +てんかい +てんき +てんぐ +てんけん +てんごく +てんさい +てんし +てんすう +でんち +てんてき +てんとう +てんない +てんぷら +てんぼうだい +てんめつ +てんらんかい +でんりょく +でんわ +どあい +といれ +どうかん +とうきゅう +どうぐ +とうし +とうむぎ +とおい +とおか +とおく +とおす +とおる +とかい +とかす +ときおり +ときどき +とくい +とくしゅう +とくてん +とくに +とくべつ +とけい +とける +とこや +とさか +としょかん +とそう +とたん +とちゅう +とっきゅう +とっくん +とつぜん +とつにゅう +とどける +ととのえる +とない +となえる +となり +とのさま +とばす +どぶがわ +とほう +とまる +とめる +ともだち +ともる +どようび +とらえる +とんかつ +どんぶり +ないかく +ないこう +ないしょ +ないす +ないせん +ないそう +なおす +ながい +なくす +なげる +なこうど +なさけ +なたでここ +なっとう +なつやすみ +ななおし +なにごと +なにもの +なにわ +なのか +なふだ +なまいき +なまえ +なまみ +なみだ +なめらか +なめる +なやむ +ならう +ならび +ならぶ +なれる +なわとび +なわばり +にあう +にいがた +にうけ +におい +にかい +にがて +にきび +にくしみ +にくまん +にげる +にさんかたんそ +にしき +にせもの +にちじょう +にちようび +にっか +にっき +にっけい +にっこう +にっさん +にっしょく +にっすう +にっせき +にってい +になう +にほん +にまめ +にもつ +にやり +にゅういん +にりんしゃ +にわとり +にんい +にんか +にんき +にんげん +にんしき +にんずう +にんそう +にんたい +にんち +にんてい +にんにく +にんぷ +にんまり +にんむ +にんめい +にんよう +ぬいくぎ +ぬかす +ぬぐいとる +ぬぐう +ぬくもり +ぬすむ +ぬまえび +ぬめり +ぬらす +ぬんちゃく +ねあげ +ねいき +ねいる +ねいろ +ねぐせ +ねくたい +ねくら +ねこぜ +ねこむ +ねさげ +ねすごす +ねそべる +ねだん +ねつい +ねっしん +ねつぞう +ねったいぎょ +ねぶそく +ねふだ +ねぼう +ねほりはほり +ねまき +ねまわし +ねみみ +ねむい +ねむたい +ねもと +ねらう +ねわざ +ねんいり +ねんおし +ねんかん +ねんきん +ねんぐ +ねんざ +ねんし +ねんちゃく +ねんど +ねんぴ +ねんぶつ +ねんまつ +ねんりょう +ねんれい +のいず +のおづま +のがす +のきなみ +のこぎり +のこす +のこる +のせる +のぞく +のぞむ +のたまう +のちほど +のっく +のばす +のはら +のべる +のぼる +のみもの +のやま +のらいぬ +のらねこ +のりもの +のりゆき +のれん +のんき +ばあい +はあく +ばあさん +ばいか +ばいく +はいけん +はいご +はいしん +はいすい +はいせん +はいそう +はいち +ばいばい +はいれつ +はえる +はおる +はかい +ばかり +はかる +はくしゅ +はけん +はこぶ +はさみ +はさん +はしご +ばしょ +はしる +はせる +ぱそこん +はそん +はたん +はちみつ +はつおん +はっかく +はづき +はっきり +はっくつ +はっけん +はっこう +はっさん +はっしん +はったつ +はっちゅう +はってん +はっぴょう +はっぽう +はなす +はなび +はにかむ +はぶらし +はみがき +はむかう +はめつ +はやい +はやし +はらう +はろうぃん +はわい +はんい +はんえい +はんおん +はんかく +はんきょう +ばんぐみ +はんこ +はんしゃ +はんすう +はんだん +ぱんち +ぱんつ +はんてい +はんとし +はんのう +はんぱ +はんぶん +はんぺん +はんぼうき +はんめい +はんらん +はんろん +ひいき +ひうん +ひえる +ひかく +ひかり +ひかる +ひかん +ひくい +ひけつ +ひこうき +ひこく +ひさい +ひさしぶり +ひさん +びじゅつかん +ひしょ +ひそか +ひそむ +ひたむき +ひだり +ひたる +ひつぎ +ひっこし +ひっし +ひつじゅひん +ひっす +ひつぜん +ぴったり +ぴっちり +ひつよう +ひてい +ひとごみ +ひなまつり +ひなん +ひねる +ひはん +ひびく +ひひょう +ひほう +ひまわり +ひまん +ひみつ +ひめい +ひめじし +ひやけ +ひやす +ひよう +びょうき +ひらがな +ひらく +ひりつ +ひりょう +ひるま +ひるやすみ +ひれい +ひろい +ひろう +ひろき +ひろゆき +ひんかく +ひんけつ +ひんこん +ひんしゅ +ひんそう +ぴんち +ひんぱん +びんぼう +ふあん +ふいうち +ふうけい +ふうせん +ぷうたろう +ふうとう +ふうふ +ふえる +ふおん +ふかい +ふきん +ふくざつ +ふくぶくろ +ふこう +ふさい +ふしぎ +ふじみ +ふすま +ふせい +ふせぐ +ふそく +ぶたにく +ふたん +ふちょう +ふつう +ふつか +ふっかつ +ふっき +ふっこく +ぶどう +ふとる +ふとん +ふのう +ふはい +ふひょう +ふへん +ふまん +ふみん +ふめつ +ふめん +ふよう +ふりこ +ふりる +ふるい +ふんいき +ぶんがく +ぶんぐ +ふんしつ +ぶんせき +ふんそう +ぶんぽう +へいあん +へいおん +へいがい +へいき +へいげん +へいこう +へいさ +へいしゃ +へいせつ +へいそ +へいたく +へいてん +へいねつ +へいわ +へきが +へこむ +べにいろ +べにしょうが +へらす +へんかん +べんきょう +べんごし +へんさい +へんたい +べんり +ほあん +ほいく +ぼうぎょ +ほうこく +ほうそう +ほうほう +ほうもん +ほうりつ +ほえる +ほおん +ほかん +ほきょう +ぼきん +ほくろ +ほけつ +ほけん +ほこう +ほこる +ほしい +ほしつ +ほしゅ +ほしょう +ほせい +ほそい +ほそく +ほたて +ほたる +ぽちぶくろ +ほっきょく +ほっさ +ほったん +ほとんど +ほめる +ほんい +ほんき +ほんけ +ほんしつ +ほんやく +まいにち +まかい +まかせる +まがる +まける +まこと +まさつ +まじめ +ますく +まぜる +まつり +まとめ +まなぶ +まぬけ +まねく +まほう +まもる +まゆげ +まよう +まろやか +まわす +まわり +まわる +まんが +まんきつ +まんぞく +まんなか +みいら +みうち +みえる +みがく +みかた +みかん +みけん +みこん +みじかい +みすい +みすえる +みせる +みっか +みつかる +みつける +みてい +みとめる +みなと +みなみかさい +みねらる +みのう +みのがす +みほん +みもと +みやげ +みらい +みりょく +みわく +みんか +みんぞく +むいか +むえき +むえん +むかい +むかう +むかえ +むかし +むぎちゃ +むける +むげん +むさぼる +むしあつい +むしば +むじゅん +むしろ +むすう +むすこ +むすぶ +むすめ +むせる +むせん +むちゅう +むなしい +むのう +むやみ +むよう +むらさき +むりょう +むろん +めいあん +めいうん +めいえん +めいかく +めいきょく +めいさい +めいし +めいそう +めいぶつ +めいれい +めいわく +めぐまれる +めざす +めした +めずらしい +めだつ +めまい +めやす +めんきょ +めんせき +めんどう +もうしあげる +もうどうけん +もえる +もくし +もくてき +もくようび +もちろん +もどる +もらう +もんく +もんだい +やおや +やける +やさい +やさしい +やすい +やすたろう +やすみ +やせる +やそう +やたい +やちん +やっと +やっぱり +やぶる +やめる +ややこしい +やよい +やわらかい +ゆうき +ゆうびんきょく +ゆうべ +ゆうめい +ゆけつ +ゆしゅつ +ゆせん +ゆそう +ゆたか +ゆちゃく +ゆでる +ゆにゅう +ゆびわ +ゆらい +ゆれる +ようい +ようか +ようきゅう +ようじ +ようす +ようちえん +よかぜ +よかん +よきん +よくせい +よくぼう +よけい +よごれる +よさん +よしゅう +よそう +よそく +よっか +よてい +よどがわく +よねつ +よやく +よゆう +よろこぶ +よろしい +らいう +らくがき +らくご +らくさつ +らくだ +らしんばん +らせん +らぞく +らたい +らっか +られつ +りえき +りかい +りきさく +りきせつ +りくぐん +りくつ +りけん +りこう +りせい +りそう +りそく +りてん +りねん +りゆう +りゅうがく +りよう +りょうり +りょかん +りょくちゃ +りょこう +りりく +りれき +りろん +りんご +るいけい +るいさい +るいじ +るいせき +るすばん +るりがわら +れいかん +れいぎ +れいせい +れいぞうこ +れいとう +れいぼう +れきし +れきだい +れんあい +れんけい +れんこん +れんさい +れんしゅう +れんぞく +れんらく +ろうか +ろうご +ろうじん +ろうそく +ろくが +ろこつ +ろじうら +ろしゅつ +ろせん +ろてん +ろめん +ろれつ +ろんぎ +ろんぱ +ろんぶん +ろんり +わかす +わかめ +わかやま +わかれる +わしつ +わじまし +わすれもの +わらう +われる`.split('\n'); +//# sourceMappingURL=japanese.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/japanese.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/japanese.js.map new file mode 100644 index 0000000..ee1323c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/japanese.js.map @@ -0,0 +1 @@ +{"version":3,"file":"japanese.js","sourceRoot":"","sources":["../../src/wordlists/japanese.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+/D9B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/korean.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/korean.js new file mode 100644 index 0000000..535ae22 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/korean.js @@ -0,0 +1,2049 @@ +export const wordlist = `가격 +가끔 +가난 +가능 +가득 +가르침 +가뭄 +가방 +가상 +가슴 +가운데 +가을 +가이드 +가입 +가장 +가정 +가족 +가죽 +각오 +각자 +간격 +간부 +간섭 +간장 +간접 +간판 +갈등 +갈비 +갈색 +갈증 +감각 +감기 +감소 +감수성 +감자 +감정 +갑자기 +강남 +강당 +강도 +강력히 +강변 +강북 +강사 +강수량 +강아지 +강원도 +강의 +강제 +강조 +같이 +개구리 +개나리 +개방 +개별 +개선 +개성 +개인 +객관적 +거실 +거액 +거울 +거짓 +거품 +걱정 +건강 +건물 +건설 +건조 +건축 +걸음 +검사 +검토 +게시판 +게임 +겨울 +견해 +결과 +결국 +결론 +결석 +결승 +결심 +결정 +결혼 +경계 +경고 +경기 +경력 +경복궁 +경비 +경상도 +경영 +경우 +경쟁 +경제 +경주 +경찰 +경치 +경향 +경험 +계곡 +계단 +계란 +계산 +계속 +계약 +계절 +계층 +계획 +고객 +고구려 +고궁 +고급 +고등학생 +고무신 +고민 +고양이 +고장 +고전 +고집 +고춧가루 +고통 +고향 +곡식 +골목 +골짜기 +골프 +공간 +공개 +공격 +공군 +공급 +공기 +공동 +공무원 +공부 +공사 +공식 +공업 +공연 +공원 +공장 +공짜 +공책 +공통 +공포 +공항 +공휴일 +과목 +과일 +과장 +과정 +과학 +관객 +관계 +관광 +관념 +관람 +관련 +관리 +관습 +관심 +관점 +관찰 +광경 +광고 +광장 +광주 +괴로움 +굉장히 +교과서 +교문 +교복 +교실 +교양 +교육 +교장 +교직 +교통 +교환 +교훈 +구경 +구름 +구멍 +구별 +구분 +구석 +구성 +구속 +구역 +구입 +구청 +구체적 +국가 +국기 +국내 +국립 +국물 +국민 +국수 +국어 +국왕 +국적 +국제 +국회 +군대 +군사 +군인 +궁극적 +권리 +권위 +권투 +귀국 +귀신 +규정 +규칙 +균형 +그날 +그냥 +그늘 +그러나 +그룹 +그릇 +그림 +그제서야 +그토록 +극복 +극히 +근거 +근교 +근래 +근로 +근무 +근본 +근원 +근육 +근처 +글씨 +글자 +금강산 +금고 +금년 +금메달 +금액 +금연 +금요일 +금지 +긍정적 +기간 +기관 +기념 +기능 +기독교 +기둥 +기록 +기름 +기법 +기본 +기분 +기쁨 +기숙사 +기술 +기억 +기업 +기온 +기운 +기원 +기적 +기준 +기침 +기혼 +기획 +긴급 +긴장 +길이 +김밥 +김치 +김포공항 +깍두기 +깜빡 +깨달음 +깨소금 +껍질 +꼭대기 +꽃잎 +나들이 +나란히 +나머지 +나물 +나침반 +나흘 +낙엽 +난방 +날개 +날씨 +날짜 +남녀 +남대문 +남매 +남산 +남자 +남편 +남학생 +낭비 +낱말 +내년 +내용 +내일 +냄비 +냄새 +냇물 +냉동 +냉면 +냉방 +냉장고 +넥타이 +넷째 +노동 +노란색 +노력 +노인 +녹음 +녹차 +녹화 +논리 +논문 +논쟁 +놀이 +농구 +농담 +농민 +농부 +농업 +농장 +농촌 +높이 +눈동자 +눈물 +눈썹 +뉴욕 +느낌 +늑대 +능동적 +능력 +다방 +다양성 +다음 +다이어트 +다행 +단계 +단골 +단독 +단맛 +단순 +단어 +단위 +단점 +단체 +단추 +단편 +단풍 +달걀 +달러 +달력 +달리 +닭고기 +담당 +담배 +담요 +담임 +답변 +답장 +당근 +당분간 +당연히 +당장 +대규모 +대낮 +대단히 +대답 +대도시 +대략 +대량 +대륙 +대문 +대부분 +대신 +대응 +대장 +대전 +대접 +대중 +대책 +대출 +대충 +대통령 +대학 +대한민국 +대합실 +대형 +덩어리 +데이트 +도대체 +도덕 +도둑 +도망 +도서관 +도심 +도움 +도입 +도자기 +도저히 +도전 +도중 +도착 +독감 +독립 +독서 +독일 +독창적 +동화책 +뒷모습 +뒷산 +딸아이 +마누라 +마늘 +마당 +마라톤 +마련 +마무리 +마사지 +마약 +마요네즈 +마을 +마음 +마이크 +마중 +마지막 +마찬가지 +마찰 +마흔 +막걸리 +막내 +막상 +만남 +만두 +만세 +만약 +만일 +만점 +만족 +만화 +많이 +말기 +말씀 +말투 +맘대로 +망원경 +매년 +매달 +매력 +매번 +매스컴 +매일 +매장 +맥주 +먹이 +먼저 +먼지 +멀리 +메일 +며느리 +며칠 +면담 +멸치 +명단 +명령 +명예 +명의 +명절 +명칭 +명함 +모금 +모니터 +모델 +모든 +모범 +모습 +모양 +모임 +모조리 +모집 +모퉁이 +목걸이 +목록 +목사 +목소리 +목숨 +목적 +목표 +몰래 +몸매 +몸무게 +몸살 +몸속 +몸짓 +몸통 +몹시 +무관심 +무궁화 +무더위 +무덤 +무릎 +무슨 +무엇 +무역 +무용 +무조건 +무지개 +무척 +문구 +문득 +문법 +문서 +문제 +문학 +문화 +물가 +물건 +물결 +물고기 +물론 +물리학 +물음 +물질 +물체 +미국 +미디어 +미사일 +미술 +미역 +미용실 +미움 +미인 +미팅 +미혼 +민간 +민족 +민주 +믿음 +밀가루 +밀리미터 +밑바닥 +바가지 +바구니 +바나나 +바늘 +바닥 +바닷가 +바람 +바이러스 +바탕 +박물관 +박사 +박수 +반대 +반드시 +반말 +반발 +반성 +반응 +반장 +반죽 +반지 +반찬 +받침 +발가락 +발걸음 +발견 +발달 +발레 +발목 +발바닥 +발생 +발음 +발자국 +발전 +발톱 +발표 +밤하늘 +밥그릇 +밥맛 +밥상 +밥솥 +방금 +방면 +방문 +방바닥 +방법 +방송 +방식 +방안 +방울 +방지 +방학 +방해 +방향 +배경 +배꼽 +배달 +배드민턴 +백두산 +백색 +백성 +백인 +백제 +백화점 +버릇 +버섯 +버튼 +번개 +번역 +번지 +번호 +벌금 +벌레 +벌써 +범위 +범인 +범죄 +법률 +법원 +법적 +법칙 +베이징 +벨트 +변경 +변동 +변명 +변신 +변호사 +변화 +별도 +별명 +별일 +병실 +병아리 +병원 +보관 +보너스 +보라색 +보람 +보름 +보상 +보안 +보자기 +보장 +보전 +보존 +보통 +보편적 +보험 +복도 +복사 +복숭아 +복습 +볶음 +본격적 +본래 +본부 +본사 +본성 +본인 +본질 +볼펜 +봉사 +봉지 +봉투 +부근 +부끄러움 +부담 +부동산 +부문 +부분 +부산 +부상 +부엌 +부인 +부작용 +부장 +부정 +부족 +부지런히 +부친 +부탁 +부품 +부회장 +북부 +북한 +분노 +분량 +분리 +분명 +분석 +분야 +분위기 +분필 +분홍색 +불고기 +불과 +불교 +불꽃 +불만 +불법 +불빛 +불안 +불이익 +불행 +브랜드 +비극 +비난 +비닐 +비둘기 +비디오 +비로소 +비만 +비명 +비밀 +비바람 +비빔밥 +비상 +비용 +비율 +비중 +비타민 +비판 +빌딩 +빗물 +빗방울 +빗줄기 +빛깔 +빨간색 +빨래 +빨리 +사건 +사계절 +사나이 +사냥 +사람 +사랑 +사립 +사모님 +사물 +사방 +사상 +사생활 +사설 +사슴 +사실 +사업 +사용 +사월 +사장 +사전 +사진 +사촌 +사춘기 +사탕 +사투리 +사흘 +산길 +산부인과 +산업 +산책 +살림 +살인 +살짝 +삼계탕 +삼국 +삼십 +삼월 +삼촌 +상관 +상금 +상대 +상류 +상반기 +상상 +상식 +상업 +상인 +상자 +상점 +상처 +상추 +상태 +상표 +상품 +상황 +새벽 +색깔 +색연필 +생각 +생명 +생물 +생방송 +생산 +생선 +생신 +생일 +생활 +서랍 +서른 +서명 +서민 +서비스 +서양 +서울 +서적 +서점 +서쪽 +서클 +석사 +석유 +선거 +선물 +선배 +선생 +선수 +선원 +선장 +선전 +선택 +선풍기 +설거지 +설날 +설렁탕 +설명 +설문 +설사 +설악산 +설치 +설탕 +섭씨 +성공 +성당 +성명 +성별 +성인 +성장 +성적 +성질 +성함 +세금 +세미나 +세상 +세월 +세종대왕 +세탁 +센터 +센티미터 +셋째 +소규모 +소극적 +소금 +소나기 +소년 +소득 +소망 +소문 +소설 +소속 +소아과 +소용 +소원 +소음 +소중히 +소지품 +소질 +소풍 +소형 +속담 +속도 +속옷 +손가락 +손길 +손녀 +손님 +손등 +손목 +손뼉 +손실 +손질 +손톱 +손해 +솔직히 +솜씨 +송아지 +송이 +송편 +쇠고기 +쇼핑 +수건 +수년 +수단 +수돗물 +수동적 +수면 +수명 +수박 +수상 +수석 +수술 +수시로 +수업 +수염 +수영 +수입 +수준 +수집 +수출 +수컷 +수필 +수학 +수험생 +수화기 +숙녀 +숙소 +숙제 +순간 +순서 +순수 +순식간 +순위 +숟가락 +술병 +술집 +숫자 +스님 +스물 +스스로 +스승 +스웨터 +스위치 +스케이트 +스튜디오 +스트레스 +스포츠 +슬쩍 +슬픔 +습관 +습기 +승객 +승리 +승부 +승용차 +승진 +시각 +시간 +시골 +시금치 +시나리오 +시댁 +시리즈 +시멘트 +시민 +시부모 +시선 +시설 +시스템 +시아버지 +시어머니 +시월 +시인 +시일 +시작 +시장 +시절 +시점 +시중 +시즌 +시집 +시청 +시합 +시험 +식구 +식기 +식당 +식량 +식료품 +식물 +식빵 +식사 +식생활 +식초 +식탁 +식품 +신고 +신규 +신념 +신문 +신발 +신비 +신사 +신세 +신용 +신제품 +신청 +신체 +신화 +실감 +실내 +실력 +실례 +실망 +실수 +실습 +실시 +실장 +실정 +실질적 +실천 +실체 +실컷 +실태 +실패 +실험 +실현 +심리 +심부름 +심사 +심장 +심정 +심판 +쌍둥이 +씨름 +씨앗 +아가씨 +아나운서 +아드님 +아들 +아쉬움 +아스팔트 +아시아 +아울러 +아저씨 +아줌마 +아직 +아침 +아파트 +아프리카 +아픔 +아홉 +아흔 +악기 +악몽 +악수 +안개 +안경 +안과 +안내 +안녕 +안동 +안방 +안부 +안주 +알루미늄 +알코올 +암시 +암컷 +압력 +앞날 +앞문 +애인 +애정 +액수 +앨범 +야간 +야단 +야옹 +약간 +약국 +약속 +약수 +약점 +약품 +약혼녀 +양념 +양력 +양말 +양배추 +양주 +양파 +어둠 +어려움 +어른 +어젯밤 +어쨌든 +어쩌다가 +어쩐지 +언니 +언덕 +언론 +언어 +얼굴 +얼른 +얼음 +얼핏 +엄마 +업무 +업종 +업체 +엉덩이 +엉망 +엉터리 +엊그제 +에너지 +에어컨 +엔진 +여건 +여고생 +여관 +여군 +여권 +여대생 +여덟 +여동생 +여든 +여론 +여름 +여섯 +여성 +여왕 +여인 +여전히 +여직원 +여학생 +여행 +역사 +역시 +역할 +연결 +연구 +연극 +연기 +연락 +연설 +연세 +연속 +연습 +연애 +연예인 +연인 +연장 +연주 +연출 +연필 +연합 +연휴 +열기 +열매 +열쇠 +열심히 +열정 +열차 +열흘 +염려 +엽서 +영국 +영남 +영상 +영양 +영역 +영웅 +영원히 +영하 +영향 +영혼 +영화 +옆구리 +옆방 +옆집 +예감 +예금 +예방 +예산 +예상 +예선 +예술 +예습 +예식장 +예약 +예전 +예절 +예정 +예컨대 +옛날 +오늘 +오락 +오랫동안 +오렌지 +오로지 +오른발 +오븐 +오십 +오염 +오월 +오전 +오직 +오징어 +오페라 +오피스텔 +오히려 +옥상 +옥수수 +온갖 +온라인 +온몸 +온종일 +온통 +올가을 +올림픽 +올해 +옷차림 +와이셔츠 +와인 +완성 +완전 +왕비 +왕자 +왜냐하면 +왠지 +외갓집 +외국 +외로움 +외삼촌 +외출 +외침 +외할머니 +왼발 +왼손 +왼쪽 +요금 +요일 +요즘 +요청 +용기 +용서 +용어 +우산 +우선 +우승 +우연히 +우정 +우체국 +우편 +운동 +운명 +운반 +운전 +운행 +울산 +울음 +움직임 +웃어른 +웃음 +워낙 +원고 +원래 +원서 +원숭이 +원인 +원장 +원피스 +월급 +월드컵 +월세 +월요일 +웨이터 +위반 +위법 +위성 +위원 +위험 +위협 +윗사람 +유난히 +유럽 +유명 +유물 +유산 +유적 +유치원 +유학 +유행 +유형 +육군 +육상 +육십 +육체 +은행 +음력 +음료 +음반 +음성 +음식 +음악 +음주 +의견 +의논 +의문 +의복 +의식 +의심 +의외로 +의욕 +의원 +의학 +이것 +이곳 +이념 +이놈 +이달 +이대로 +이동 +이렇게 +이력서 +이론적 +이름 +이민 +이발소 +이별 +이불 +이빨 +이상 +이성 +이슬 +이야기 +이용 +이웃 +이월 +이윽고 +이익 +이전 +이중 +이튿날 +이틀 +이혼 +인간 +인격 +인공 +인구 +인근 +인기 +인도 +인류 +인물 +인생 +인쇄 +인연 +인원 +인재 +인종 +인천 +인체 +인터넷 +인하 +인형 +일곱 +일기 +일단 +일대 +일등 +일반 +일본 +일부 +일상 +일생 +일손 +일요일 +일월 +일정 +일종 +일주일 +일찍 +일체 +일치 +일행 +일회용 +임금 +임무 +입대 +입력 +입맛 +입사 +입술 +입시 +입원 +입장 +입학 +자가용 +자격 +자극 +자동 +자랑 +자부심 +자식 +자신 +자연 +자원 +자율 +자전거 +자정 +자존심 +자판 +작가 +작년 +작성 +작업 +작용 +작은딸 +작품 +잔디 +잔뜩 +잔치 +잘못 +잠깐 +잠수함 +잠시 +잠옷 +잠자리 +잡지 +장관 +장군 +장기간 +장래 +장례 +장르 +장마 +장면 +장모 +장미 +장비 +장사 +장소 +장식 +장애인 +장인 +장점 +장차 +장학금 +재능 +재빨리 +재산 +재생 +재작년 +재정 +재채기 +재판 +재학 +재활용 +저것 +저고리 +저곳 +저녁 +저런 +저렇게 +저번 +저울 +저절로 +저축 +적극 +적당히 +적성 +적용 +적응 +전개 +전공 +전기 +전달 +전라도 +전망 +전문 +전반 +전부 +전세 +전시 +전용 +전자 +전쟁 +전주 +전철 +전체 +전통 +전혀 +전후 +절대 +절망 +절반 +절약 +절차 +점검 +점수 +점심 +점원 +점점 +점차 +접근 +접시 +접촉 +젓가락 +정거장 +정도 +정류장 +정리 +정말 +정면 +정문 +정반대 +정보 +정부 +정비 +정상 +정성 +정오 +정원 +정장 +정지 +정치 +정확히 +제공 +제과점 +제대로 +제목 +제발 +제법 +제삿날 +제안 +제일 +제작 +제주도 +제출 +제품 +제한 +조각 +조건 +조금 +조깅 +조명 +조미료 +조상 +조선 +조용히 +조절 +조정 +조직 +존댓말 +존재 +졸업 +졸음 +종교 +종로 +종류 +종소리 +종업원 +종종 +종합 +좌석 +죄인 +주관적 +주름 +주말 +주머니 +주먹 +주문 +주민 +주방 +주변 +주식 +주인 +주일 +주장 +주전자 +주택 +준비 +줄거리 +줄기 +줄무늬 +중간 +중계방송 +중국 +중년 +중단 +중독 +중반 +중부 +중세 +중소기업 +중순 +중앙 +중요 +중학교 +즉석 +즉시 +즐거움 +증가 +증거 +증권 +증상 +증세 +지각 +지갑 +지경 +지극히 +지금 +지급 +지능 +지름길 +지리산 +지방 +지붕 +지식 +지역 +지우개 +지원 +지적 +지점 +지진 +지출 +직선 +직업 +직원 +직장 +진급 +진동 +진로 +진료 +진리 +진짜 +진찰 +진출 +진통 +진행 +질문 +질병 +질서 +짐작 +집단 +집안 +집중 +짜증 +찌꺼기 +차남 +차라리 +차량 +차림 +차별 +차선 +차츰 +착각 +찬물 +찬성 +참가 +참기름 +참새 +참석 +참여 +참외 +참조 +찻잔 +창가 +창고 +창구 +창문 +창밖 +창작 +창조 +채널 +채점 +책가방 +책방 +책상 +책임 +챔피언 +처벌 +처음 +천국 +천둥 +천장 +천재 +천천히 +철도 +철저히 +철학 +첫날 +첫째 +청년 +청바지 +청소 +청춘 +체계 +체력 +체온 +체육 +체중 +체험 +초등학생 +초반 +초밥 +초상화 +초순 +초여름 +초원 +초저녁 +초점 +초청 +초콜릿 +촛불 +총각 +총리 +총장 +촬영 +최근 +최상 +최선 +최신 +최악 +최종 +추석 +추억 +추진 +추천 +추측 +축구 +축소 +축제 +축하 +출근 +출발 +출산 +출신 +출연 +출입 +출장 +출판 +충격 +충고 +충돌 +충분히 +충청도 +취업 +취직 +취향 +치약 +친구 +친척 +칠십 +칠월 +칠판 +침대 +침묵 +침실 +칫솔 +칭찬 +카메라 +카운터 +칼국수 +캐릭터 +캠퍼스 +캠페인 +커튼 +컨디션 +컬러 +컴퓨터 +코끼리 +코미디 +콘서트 +콜라 +콤플렉스 +콩나물 +쾌감 +쿠데타 +크림 +큰길 +큰딸 +큰소리 +큰아들 +큰어머니 +큰일 +큰절 +클래식 +클럽 +킬로 +타입 +타자기 +탁구 +탁자 +탄생 +태권도 +태양 +태풍 +택시 +탤런트 +터널 +터미널 +테니스 +테스트 +테이블 +텔레비전 +토론 +토마토 +토요일 +통계 +통과 +통로 +통신 +통역 +통일 +통장 +통제 +통증 +통합 +통화 +퇴근 +퇴원 +퇴직금 +튀김 +트럭 +특급 +특별 +특성 +특수 +특징 +특히 +튼튼히 +티셔츠 +파란색 +파일 +파출소 +판결 +판단 +판매 +판사 +팔십 +팔월 +팝송 +패션 +팩스 +팩시밀리 +팬티 +퍼센트 +페인트 +편견 +편의 +편지 +편히 +평가 +평균 +평생 +평소 +평양 +평일 +평화 +포스터 +포인트 +포장 +포함 +표면 +표정 +표준 +표현 +품목 +품질 +풍경 +풍속 +풍습 +프랑스 +프린터 +플라스틱 +피곤 +피망 +피아노 +필름 +필수 +필요 +필자 +필통 +핑계 +하느님 +하늘 +하드웨어 +하룻밤 +하반기 +하숙집 +하순 +하여튼 +하지만 +하천 +하품 +하필 +학과 +학교 +학급 +학기 +학년 +학력 +학번 +학부모 +학비 +학생 +학술 +학습 +학용품 +학원 +학위 +학자 +학점 +한계 +한글 +한꺼번에 +한낮 +한눈 +한동안 +한때 +한라산 +한마디 +한문 +한번 +한복 +한식 +한여름 +한쪽 +할머니 +할아버지 +할인 +함께 +함부로 +합격 +합리적 +항공 +항구 +항상 +항의 +해결 +해군 +해답 +해당 +해물 +해석 +해설 +해수욕장 +해안 +핵심 +핸드백 +햄버거 +햇볕 +햇살 +행동 +행복 +행사 +행운 +행위 +향기 +향상 +향수 +허락 +허용 +헬기 +현관 +현금 +현대 +현상 +현실 +현장 +현재 +현지 +혈액 +협력 +형부 +형사 +형수 +형식 +형제 +형태 +형편 +혜택 +호기심 +호남 +호랑이 +호박 +호텔 +호흡 +혹시 +홀로 +홈페이지 +홍보 +홍수 +홍차 +화면 +화분 +화살 +화요일 +화장 +화학 +확보 +확인 +확장 +확정 +환갑 +환경 +환영 +환율 +환자 +활기 +활동 +활발히 +활용 +활짝 +회견 +회관 +회복 +회색 +회원 +회장 +회전 +횟수 +횡단보도 +효율적 +후반 +후춧가루 +훈련 +훨씬 +휴식 +휴일 +흉내 +흐름 +흑백 +흑인 +흔적 +흔히 +흥미 +흥분 +희곡 +희망 +희생 +흰색 +힘껏`.split('\n'); +//# sourceMappingURL=korean.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/korean.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/korean.js.map new file mode 100644 index 0000000..082def0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/korean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"korean.js","sourceRoot":"","sources":["../../src/wordlists/korean.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+/D3B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js new file mode 100644 index 0000000..bb5512d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js @@ -0,0 +1,2049 @@ +export const wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +这 +中 +大 +为 +上 +个 +国 +我 +以 +要 +他 +时 +来 +用 +们 +生 +到 +作 +地 +于 +出 +就 +分 +对 +成 +会 +可 +主 +发 +年 +动 +同 +工 +也 +能 +下 +过 +子 +说 +产 +种 +面 +而 +方 +后 +多 +定 +行 +学 +法 +所 +民 +得 +经 +十 +三 +之 +进 +着 +等 +部 +度 +家 +电 +力 +里 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +现 +实 +加 +量 +都 +两 +体 +制 +机 +当 +使 +点 +从 +业 +本 +去 +把 +性 +好 +应 +开 +它 +合 +还 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +义 +事 +平 +形 +相 +全 +表 +间 +样 +与 +关 +各 +重 +新 +线 +内 +数 +正 +心 +反 +你 +明 +看 +原 +又 +么 +利 +比 +或 +但 +质 +气 +第 +向 +道 +命 +此 +变 +条 +只 +没 +结 +解 +问 +意 +建 +月 +公 +无 +系 +军 +很 +情 +者 +最 +立 +代 +想 +已 +通 +并 +提 +直 +题 +党 +程 +展 +五 +果 +料 +象 +员 +革 +位 +入 +常 +文 +总 +次 +品 +式 +活 +设 +及 +管 +特 +件 +长 +求 +老 +头 +基 +资 +边 +流 +路 +级 +少 +图 +山 +统 +接 +知 +较 +将 +组 +见 +计 +别 +她 +手 +角 +期 +根 +论 +运 +农 +指 +几 +九 +区 +强 +放 +决 +西 +被 +干 +做 +必 +战 +先 +回 +则 +任 +取 +据 +处 +队 +南 +给 +色 +光 +门 +即 +保 +治 +北 +造 +百 +规 +热 +领 +七 +海 +口 +东 +导 +器 +压 +志 +世 +金 +增 +争 +济 +阶 +油 +思 +术 +极 +交 +受 +联 +什 +认 +六 +共 +权 +收 +证 +改 +清 +美 +再 +采 +转 +更 +单 +风 +切 +打 +白 +教 +速 +花 +带 +安 +场 +身 +车 +例 +真 +务 +具 +万 +每 +目 +至 +达 +走 +积 +示 +议 +声 +报 +斗 +完 +类 +八 +离 +华 +名 +确 +才 +科 +张 +信 +马 +节 +话 +米 +整 +空 +元 +况 +今 +集 +温 +传 +土 +许 +步 +群 +广 +石 +记 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +观 +越 +织 +装 +影 +算 +低 +持 +音 +众 +书 +布 +复 +容 +儿 +须 +际 +商 +非 +验 +连 +断 +深 +难 +近 +矿 +千 +周 +委 +素 +技 +备 +半 +办 +青 +省 +列 +习 +响 +约 +支 +般 +史 +感 +劳 +便 +团 +往 +酸 +历 +市 +克 +何 +除 +消 +构 +府 +称 +太 +准 +精 +值 +号 +率 +族 +维 +划 +选 +标 +写 +存 +候 +毛 +亲 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +养 +易 +置 +派 +层 +片 +始 +却 +专 +状 +育 +厂 +京 +识 +适 +属 +圆 +包 +火 +住 +调 +满 +县 +局 +照 +参 +红 +细 +引 +听 +该 +铁 +价 +严 +首 +底 +液 +官 +德 +随 +病 +苏 +失 +尔 +死 +讲 +配 +女 +黄 +推 +显 +谈 +罪 +神 +艺 +呢 +席 +含 +企 +望 +密 +批 +营 +项 +防 +举 +球 +英 +氧 +势 +告 +李 +台 +落 +木 +帮 +轮 +破 +亚 +师 +围 +注 +远 +字 +材 +排 +供 +河 +态 +封 +另 +施 +减 +树 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +叶 +鱼 +波 +视 +仅 +费 +紧 +爱 +左 +章 +早 +朝 +害 +续 +轻 +服 +试 +食 +充 +兵 +源 +判 +护 +司 +足 +某 +练 +差 +致 +板 +田 +降 +黑 +犯 +负 +击 +范 +继 +兴 +似 +余 +坚 +曲 +输 +修 +故 +城 +夫 +够 +送 +笔 +船 +占 +右 +财 +吃 +富 +春 +职 +觉 +汉 +画 +功 +巴 +跟 +虽 +杂 +飞 +检 +吸 +助 +升 +阳 +互 +初 +创 +抗 +考 +投 +坏 +策 +古 +径 +换 +未 +跑 +留 +钢 +曾 +端 +责 +站 +简 +述 +钱 +副 +尽 +帝 +射 +草 +冲 +承 +独 +令 +限 +阿 +宣 +环 +双 +请 +超 +微 +让 +控 +州 +良 +轴 +找 +否 +纪 +益 +依 +优 +顶 +础 +载 +倒 +房 +突 +坐 +粉 +敌 +略 +客 +袁 +冷 +胜 +绝 +析 +块 +剂 +测 +丝 +协 +诉 +念 +陈 +仍 +罗 +盐 +友 +洋 +错 +苦 +夜 +刑 +移 +频 +逐 +靠 +混 +母 +短 +皮 +终 +聚 +汽 +村 +云 +哪 +既 +距 +卫 +停 +烈 +央 +察 +烧 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +游 +久 +菜 +味 +旧 +模 +湖 +货 +损 +预 +阻 +毫 +普 +稳 +乙 +妈 +植 +息 +扩 +银 +语 +挥 +酒 +守 +拿 +序 +纸 +医 +缺 +雨 +吗 +针 +刘 +啊 +急 +唱 +误 +训 +愿 +审 +附 +获 +茶 +鲜 +粮 +斤 +孩 +脱 +硫 +肥 +善 +龙 +演 +父 +渐 +血 +欢 +械 +掌 +歌 +沙 +刚 +攻 +谓 +盾 +讨 +晚 +粒 +乱 +燃 +矛 +乎 +杀 +药 +宁 +鲁 +贵 +钟 +煤 +读 +班 +伯 +香 +介 +迫 +句 +丰 +培 +握 +兰 +担 +弦 +蛋 +沉 +假 +穿 +执 +答 +乐 +谁 +顺 +烟 +缩 +征 +脸 +喜 +松 +脚 +困 +异 +免 +背 +星 +福 +买 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +静 +补 +评 +翻 +肉 +践 +尼 +衣 +宽 +扬 +棉 +希 +伤 +操 +垂 +秋 +宜 +氢 +套 +督 +振 +架 +亮 +末 +宪 +庆 +编 +牛 +触 +映 +雷 +销 +诗 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +绿 +晶 +厚 +盟 +衡 +鸡 +孙 +延 +危 +胶 +屋 +乡 +临 +陆 +顾 +掉 +呀 +灯 +岁 +措 +束 +耐 +剧 +玉 +赵 +跳 +哥 +季 +课 +凯 +胡 +额 +款 +绍 +卷 +齐 +伟 +蒸 +殖 +永 +宗 +苗 +川 +炉 +岩 +弱 +零 +杨 +奏 +沿 +露 +杆 +探 +滑 +镇 +饭 +浓 +航 +怀 +赶 +库 +夺 +伊 +灵 +税 +途 +灭 +赛 +归 +召 +鼓 +播 +盘 +裁 +险 +康 +唯 +录 +菌 +纯 +借 +糖 +盖 +横 +符 +私 +努 +堂 +域 +枪 +润 +幅 +哈 +竟 +熟 +虫 +泽 +脑 +壤 +碳 +欧 +遍 +侧 +寨 +敢 +彻 +虑 +斜 +薄 +庭 +纳 +弹 +饲 +伸 +折 +麦 +湿 +暗 +荷 +瓦 +塞 +床 +筑 +恶 +户 +访 +塔 +奇 +透 +梁 +刀 +旋 +迹 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +摆 +灰 +彩 +卖 +耗 +夏 +择 +忙 +铜 +献 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +阵 +阴 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +楼 +避 +谋 +吨 +野 +猪 +旗 +累 +偏 +典 +馆 +索 +秦 +脂 +潮 +爷 +豆 +忽 +托 +惊 +塑 +遗 +愈 +朱 +替 +纤 +粗 +倾 +尚 +痛 +楚 +谢 +奋 +购 +磨 +君 +池 +旁 +碎 +骨 +监 +捕 +弟 +暴 +割 +贯 +殊 +释 +词 +亡 +壁 +顿 +宝 +午 +尘 +闻 +揭 +炮 +残 +冬 +桥 +妇 +警 +综 +招 +吴 +付 +浮 +遭 +徐 +您 +摇 +谷 +赞 +箱 +隔 +订 +男 +吹 +园 +纷 +唐 +败 +宋 +玻 +巨 +耕 +坦 +荣 +闭 +湾 +键 +凡 +驻 +锅 +救 +恩 +剥 +凝 +碱 +齿 +截 +炼 +麻 +纺 +禁 +废 +盛 +版 +缓 +净 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +庄 +街 +藏 +姑 +贸 +腐 +奴 +啦 +惯 +乘 +伙 +恢 +匀 +纱 +扎 +辩 +耳 +彪 +臣 +亿 +璃 +抵 +脉 +秀 +萨 +俄 +网 +舞 +店 +喷 +纵 +寸 +汗 +挂 +洪 +贺 +闪 +柬 +爆 +烯 +津 +稻 +墙 +软 +勇 +像 +滚 +厘 +蒙 +芳 +肯 +坡 +柱 +荡 +腿 +仪 +旅 +尾 +轧 +冰 +贡 +登 +黎 +削 +钻 +勒 +逃 +障 +氨 +郭 +峰 +币 +港 +伏 +轨 +亩 +毕 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +岛 +甘 +泡 +睡 +童 +铸 +汤 +阀 +休 +汇 +舍 +牧 +绕 +炸 +哲 +磷 +绩 +朋 +淡 +尖 +启 +陷 +柴 +呈 +徒 +颜 +泪 +稍 +忘 +泵 +蓝 +拖 +洞 +授 +镜 +辛 +壮 +锋 +贫 +虚 +弯 +摩 +泰 +幼 +廷 +尊 +窗 +纲 +弄 +隶 +疑 +氏 +宫 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +违 +夹 +腰 +缘 +珠 +穷 +森 +枝 +竹 +沟 +催 +绳 +忆 +邦 +剩 +幸 +浆 +栏 +拥 +牙 +贮 +礼 +滤 +钠 +纹 +罢 +拍 +咱 +喊 +袖 +埃 +勤 +罚 +焦 +潜 +伍 +墨 +欲 +缝 +姓 +刊 +饱 +仿 +奖 +铝 +鬼 +丽 +跨 +默 +挖 +链 +扫 +喝 +袋 +炭 +污 +幕 +诸 +弧 +励 +梅 +奶 +洁 +灾 +舟 +鉴 +苯 +讼 +抱 +毁 +懂 +寒 +智 +埔 +寄 +届 +跃 +渡 +挑 +丹 +艰 +贝 +碰 +拔 +爹 +戴 +码 +梦 +芽 +熔 +赤 +渔 +哭 +敬 +颗 +奔 +铅 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +仓 +魏 +锐 +晓 +氮 +兼 +隐 +碍 +赫 +拨 +忠 +肃 +缸 +牵 +抢 +博 +巧 +壳 +兄 +杜 +讯 +诚 +碧 +祥 +柯 +页 +巡 +矩 +悲 +灌 +龄 +伦 +票 +寻 +桂 +铺 +圣 +恐 +恰 +郑 +趣 +抬 +荒 +腾 +贴 +柔 +滴 +猛 +阔 +辆 +妻 +填 +撤 +储 +签 +闹 +扰 +紫 +砂 +递 +戏 +吊 +陶 +伐 +喂 +疗 +瓶 +婆 +抚 +臂 +摸 +忍 +虾 +蜡 +邻 +胸 +巩 +挤 +偶 +弃 +槽 +劲 +乳 +邓 +吉 +仁 +烂 +砖 +租 +乌 +舰 +伴 +瓜 +浅 +丙 +暂 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +胆 +详 +簧 +踏 +瓷 +谱 +呆 +宾 +糊 +洛 +辉 +愤 +竞 +隙 +怒 +粘 +乃 +绪 +肩 +籍 +敏 +涂 +熙 +皆 +侦 +悬 +掘 +享 +纠 +醒 +狂 +锁 +淀 +恨 +牲 +霸 +爬 +赏 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鸭 +趋 +凤 +晨 +畜 +辈 +秩 +卵 +署 +梯 +炎 +滩 +棋 +驱 +筛 +峡 +冒 +啥 +寿 +译 +浸 +泉 +帽 +迟 +硅 +疆 +贷 +漏 +稿 +冠 +嫩 +胁 +芯 +牢 +叛 +蚀 +奥 +鸣 +岭 +羊 +凭 +串 +塘 +绘 +酵 +融 +盆 +锡 +庙 +筹 +冻 +辅 +摄 +袭 +筋 +拒 +僚 +旱 +钾 +鸟 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韩 +逼 +扭 +侨 +凉 +挺 +碗 +栽 +炒 +杯 +患 +馏 +劝 +豪 +辽 +勃 +鸿 +旦 +吏 +拜 +狗 +埋 +辊 +掩 +饮 +搬 +骂 +辞 +勾 +扣 +估 +蒋 +绒 +雾 +丈 +朵 +姆 +拟 +宇 +辑 +陕 +雕 +偿 +蓄 +崇 +剪 +倡 +厅 +咬 +驶 +薯 +刷 +斥 +番 +赋 +奉 +佛 +浇 +漫 +曼 +扇 +钙 +桃 +扶 +仔 +返 +俗 +亏 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +骗 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +胀 +谐 +抛 +霉 +桑 +岗 +嘛 +衰 +盗 +渗 +脏 +赖 +涌 +甜 +曹 +阅 +肌 +哩 +厉 +烃 +纬 +毅 +昨 +伪 +症 +煮 +叹 +钉 +搭 +茎 +笼 +酷 +偷 +弓 +锥 +恒 +杰 +坑 +鼻 +翼 +纶 +叙 +狱 +逮 +罐 +络 +棚 +抑 +膨 +蔬 +寺 +骤 +穆 +冶 +枯 +册 +尸 +凸 +绅 +坯 +牺 +焰 +轰 +欣 +晋 +瘦 +御 +锭 +锦 +丧 +旬 +锻 +垄 +搜 +扑 +邀 +亭 +酯 +迈 +舒 +脆 +酶 +闲 +忧 +酚 +顽 +羽 +涨 +卸 +仗 +陪 +辟 +惩 +杭 +姚 +肚 +捉 +飘 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +饰 +萧 +雅 +邮 +迁 +燕 +撒 +姻 +赴 +宴 +烦 +债 +帐 +斑 +铃 +旨 +醇 +董 +饼 +雏 +姿 +拌 +傅 +腹 +妥 +揉 +贤 +拆 +歪 +葡 +胺 +丢 +浩 +徽 +昂 +垫 +挡 +览 +贪 +慰 +缴 +汪 +慌 +冯 +诺 +姜 +谊 +凶 +劣 +诬 +耀 +昏 +躺 +盈 +骑 +乔 +溪 +丛 +卢 +抹 +闷 +咨 +刮 +驾 +缆 +悟 +摘 +铒 +掷 +颇 +幻 +柄 +惠 +惨 +佳 +仇 +腊 +窝 +涤 +剑 +瞧 +堡 +泼 +葱 +罩 +霍 +捞 +胎 +苍 +滨 +俩 +捅 +湘 +砍 +霞 +邵 +萄 +疯 +淮 +遂 +熊 +粪 +烘 +宿 +档 +戈 +驳 +嫂 +裕 +徙 +箭 +捐 +肠 +撑 +晒 +辨 +殿 +莲 +摊 +搅 +酱 +屏 +疫 +哀 +蔡 +堵 +沫 +皱 +畅 +叠 +阁 +莱 +敲 +辖 +钩 +痕 +坝 +巷 +饿 +祸 +丘 +玄 +溜 +曰 +逻 +彭 +尝 +卿 +妨 +艇 +吞 +韦 +怨 +矮 +歇`.split('\n'); +//# sourceMappingURL=simplified-chinese.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map new file mode 100644 index 0000000..99ab9ca --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/simplified-chinese.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simplified-chinese.js","sourceRoot":"","sources":["../../src/wordlists/sim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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+/DhC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/spanish.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/spanish.js new file mode 100644 index 0000000..afd6c53 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/spanish.js @@ -0,0 +1,2049 @@ +export const wordlist = `ábaco +abdomen +abeja +abierto +abogado +abono +aborto +abrazo +abrir +abuelo +abuso +acabar +academia +acceso +acción +aceite +acelga +acento +aceptar +ácido +aclarar +acné +acoger +acoso +activo +acto +actriz +actuar +acudir +acuerdo +acusar +adicto +admitir +adoptar +adorno +aduana +adulto +aéreo +afectar +afición +afinar +afirmar +ágil +agitar +agonía +agosto +agotar +agregar +agrio +agua +agudo +águila +aguja +ahogo +ahorro +aire +aislar +ajedrez +ajeno +ajuste +alacrán +alambre +alarma +alba +álbum +alcalde +aldea +alegre +alejar +alerta +aleta +alfiler +alga +algodón +aliado +aliento +alivio +alma +almeja +almíbar +altar +alteza +altivo +alto +altura +alumno +alzar +amable +amante +amapola +amargo +amasar +ámbar +ámbito +ameno +amigo +amistad +amor +amparo +amplio +ancho +anciano +ancla +andar +andén +anemia +ángulo +anillo +ánimo +anís +anotar +antena +antiguo +antojo +anual +anular +anuncio +añadir +añejo +año +apagar +aparato +apetito +apio +aplicar +apodo +aporte +apoyo +aprender +aprobar +apuesta +apuro +arado +araña +arar +árbitro +árbol +arbusto +archivo +arco +arder +ardilla +arduo +área +árido +aries +armonía +arnés +aroma +arpa +arpón +arreglo +arroz +arruga +arte +artista +asa +asado +asalto +ascenso +asegurar +aseo +asesor +asiento +asilo +asistir +asno +asombro +áspero +astilla +astro +astuto +asumir +asunto +atajo +ataque +atar +atento +ateo +ático +atleta +átomo +atraer +atroz +atún +audaz +audio +auge +aula +aumento +ausente +autor +aval +avance +avaro +ave +avellana +avena +avestruz +avión +aviso +ayer +ayuda +ayuno +azafrán +azar +azote +azúcar +azufre +azul +baba +babor +bache +bahía +baile +bajar +balanza +balcón +balde +bambú +banco +banda +baño +barba +barco +barniz +barro +báscula +bastón +basura +batalla +batería +batir +batuta +baúl +bazar +bebé +bebida +bello +besar +beso +bestia +bicho +bien +bingo +blanco +bloque +blusa +boa +bobina +bobo +boca +bocina +boda +bodega +boina +bola +bolero +bolsa +bomba +bondad +bonito +bono +bonsái +borde +borrar +bosque +bote +botín +bóveda +bozal +bravo +brazo +brecha +breve +brillo +brinco +brisa +broca +broma +bronce +brote +bruja +brusco +bruto +buceo +bucle +bueno +buey +bufanda +bufón +búho +buitre +bulto +burbuja +burla +burro +buscar +butaca +buzón +caballo +cabeza +cabina +cabra +cacao +cadáver +cadena +caer +café +caída +caimán +caja +cajón +cal +calamar +calcio +caldo +calidad +calle +calma +calor +calvo +cama +cambio +camello +camino +campo +cáncer +candil +canela +canguro +canica +canto +caña +cañón +caoba +caos +capaz +capitán +capote +captar +capucha +cara +carbón +cárcel +careta +carga +cariño +carne +carpeta +carro +carta +casa +casco +casero +caspa +castor +catorce +catre +caudal +causa +cazo +cebolla +ceder +cedro +celda +célebre +celoso +célula +cemento +ceniza +centro +cerca +cerdo +cereza +cero +cerrar +certeza +césped +cetro +chacal +chaleco +champú +chancla +chapa +charla +chico +chiste +chivo +choque +choza +chuleta +chupar +ciclón +ciego +cielo +cien +cierto +cifra +cigarro +cima +cinco +cine +cinta +ciprés +circo +ciruela +cisne +cita +ciudad +clamor +clan +claro +clase +clave +cliente +clima +clínica +cobre +cocción +cochino +cocina +coco +código +codo +cofre +coger +cohete +cojín +cojo +cola +colcha +colegio +colgar +colina +collar +colmo +columna +combate +comer +comida +cómodo +compra +conde +conejo +conga +conocer +consejo +contar +copa +copia +corazón +corbata +corcho +cordón +corona +correr +coser +cosmos +costa +cráneo +cráter +crear +crecer +creído +crema +cría +crimen +cripta +crisis +cromo +crónica +croqueta +crudo +cruz +cuadro +cuarto +cuatro +cubo +cubrir +cuchara +cuello +cuento +cuerda +cuesta +cueva +cuidar +culebra +culpa +culto +cumbre +cumplir +cuna +cuneta +cuota +cupón +cúpula +curar +curioso +curso +curva +cutis +dama +danza +dar +dardo +dátil +deber +débil +década +decir +dedo +defensa +definir +dejar +delfín +delgado +delito +demora +denso +dental +deporte +derecho +derrota +desayuno +deseo +desfile +desnudo +destino +desvío +detalle +detener +deuda +día +diablo +diadema +diamante +diana +diario +dibujo +dictar +diente +dieta +diez +difícil +digno +dilema +diluir +dinero +directo +dirigir +disco +diseño +disfraz +diva +divino +doble +doce +dolor +domingo +don +donar +dorado +dormir +dorso +dos +dosis +dragón +droga +ducha +duda +duelo +dueño +dulce +dúo +duque +durar +dureza +duro +ébano +ebrio +echar +eco +ecuador +edad +edición +edificio +editor +educar +efecto +eficaz +eje +ejemplo +elefante +elegir +elemento +elevar +elipse +élite +elixir +elogio +eludir +embudo +emitir +emoción +empate +empeño +empleo +empresa +enano +encargo +enchufe +encía +enemigo +enero +enfado +enfermo +engaño +enigma +enlace +enorme +enredo +ensayo +enseñar +entero +entrar +envase +envío +época +equipo +erizo +escala +escena +escolar +escribir +escudo +esencia +esfera +esfuerzo +espada +espejo +espía +esposa +espuma +esquí +estar +este +estilo +estufa +etapa +eterno +ética +etnia +evadir +evaluar +evento +evitar +exacto +examen +exceso +excusa +exento +exigir +exilio +existir +éxito +experto +explicar +exponer +extremo +fábrica +fábula +fachada +fácil +factor +faena +faja +falda +fallo +falso +faltar +fama +familia +famoso +faraón +farmacia +farol +farsa +fase +fatiga +fauna +favor +fax +febrero +fecha +feliz +feo +feria +feroz +fértil +fervor +festín +fiable +fianza +fiar +fibra +ficción +ficha +fideo +fiebre +fiel +fiera +fiesta +figura +fijar +fijo +fila +filete +filial +filtro +fin +finca +fingir +finito +firma +flaco +flauta +flecha +flor +flota +fluir +flujo +flúor +fobia +foca +fogata +fogón +folio +folleto +fondo +forma +forro +fortuna +forzar +fosa +foto +fracaso +frágil +franja +frase +fraude +freír +freno +fresa +frío +frito +fruta +fuego +fuente +fuerza +fuga +fumar +función +funda +furgón +furia +fusil +fútbol +futuro +gacela +gafas +gaita +gajo +gala +galería +gallo +gamba +ganar +gancho +ganga +ganso +garaje +garza +gasolina +gastar +gato +gavilán +gemelo +gemir +gen +género +genio +gente +geranio +gerente +germen +gesto +gigante +gimnasio +girar +giro +glaciar +globo +gloria +gol +golfo +goloso +golpe +goma +gordo +gorila +gorra +gota +goteo +gozar +grada +gráfico +grano +grasa +gratis +grave +grieta +grillo +gripe +gris +grito +grosor +grúa +grueso +grumo +grupo +guante +guapo +guardia +guerra +guía +guiño +guion +guiso +guitarra +gusano +gustar +haber +hábil +hablar +hacer +hacha +hada +hallar +hamaca +harina +haz +hazaña +hebilla +hebra +hecho +helado +helio +hembra +herir +hermano +héroe +hervir +hielo +hierro +hígado +higiene +hijo +himno +historia +hocico +hogar +hoguera +hoja +hombre +hongo +honor +honra +hora +hormiga +horno +hostil +hoyo +hueco +huelga +huerta +hueso +huevo +huida +huir +humano +húmedo +humilde +humo +hundir +huracán +hurto +icono +ideal +idioma +ídolo +iglesia +iglú +igual +ilegal +ilusión +imagen +imán +imitar +impar +imperio +imponer +impulso +incapaz +índice +inerte +infiel +informe +ingenio +inicio +inmenso +inmune +innato +insecto +instante +interés +íntimo +intuir +inútil +invierno +ira +iris +ironía +isla +islote +jabalí +jabón +jamón +jarabe +jardín +jarra +jaula +jazmín +jefe +jeringa +jinete +jornada +joroba +joven +joya +juerga +jueves +juez +jugador +jugo +juguete +juicio +junco +jungla +junio +juntar +júpiter +jurar +justo +juvenil +juzgar +kilo +koala +labio +lacio +lacra +lado +ladrón +lagarto +lágrima +laguna +laico +lamer +lámina +lámpara +lana +lancha +langosta +lanza +lápiz +largo +larva +lástima +lata +látex +latir +laurel +lavar +lazo +leal +lección +leche +lector +leer +legión +legumbre +lejano +lengua +lento +leña +león +leopardo +lesión +letal +letra +leve +leyenda +libertad +libro +licor +líder +lidiar +lienzo +liga +ligero +lima +límite +limón +limpio +lince +lindo +línea +lingote +lino +linterna +líquido +liso +lista +litera +litio +litro +llaga +llama +llanto +llave +llegar +llenar +llevar +llorar +llover +lluvia +lobo +loción +loco +locura +lógica +logro +lombriz +lomo +lonja +lote +lucha +lucir +lugar +lujo +luna +lunes +lupa +lustro +luto +luz +maceta +macho +madera +madre +maduro +maestro +mafia +magia +mago +maíz +maldad +maleta +malla +malo +mamá +mambo +mamut +manco +mando +manejar +manga +maniquí +manjar +mano +manso +manta +mañana +mapa +máquina +mar +marco +marea +marfil +margen +marido +mármol +marrón +martes +marzo +masa +máscara +masivo +matar +materia +matiz +matriz +máximo +mayor +mazorca +mecha +medalla +medio +médula +mejilla +mejor +melena +melón +memoria +menor +mensaje +mente +menú +mercado +merengue +mérito +mes +mesón +meta +meter +método +metro +mezcla +miedo +miel +miembro +miga +mil +milagro +militar +millón +mimo +mina +minero +mínimo +minuto +miope +mirar +misa +miseria +misil +mismo +mitad +mito +mochila +moción +moda +modelo +moho +mojar +molde +moler +molino +momento +momia +monarca +moneda +monja +monto +moño +morada +morder +moreno +morir +morro +morsa +mortal +mosca +mostrar +motivo +mover +móvil +mozo +mucho +mudar +mueble +muela +muerte +muestra +mugre +mujer +mula +muleta +multa +mundo +muñeca +mural +muro +músculo +museo +musgo +música +muslo +nácar +nación +nadar +naipe +naranja +nariz +narrar +nasal +natal +nativo +natural +náusea +naval +nave +navidad +necio +néctar +negar +negocio +negro +neón +nervio +neto +neutro +nevar +nevera +nicho +nido +niebla +nieto +niñez +niño +nítido +nivel +nobleza +noche +nómina +noria +norma +norte +nota +noticia +novato +novela +novio +nube +nuca +núcleo +nudillo +nudo +nuera +nueve +nuez +nulo +número +nutria +oasis +obeso +obispo +objeto +obra +obrero +observar +obtener +obvio +oca +ocaso +océano +ochenta +ocho +ocio +ocre +octavo +octubre +oculto +ocupar +ocurrir +odiar +odio +odisea +oeste +ofensa +oferta +oficio +ofrecer +ogro +oído +oír +ojo +ola +oleada +olfato +olivo +olla +olmo +olor +olvido +ombligo +onda +onza +opaco +opción +ópera +opinar +oponer +optar +óptica +opuesto +oración +orador +oral +órbita +orca +orden +oreja +órgano +orgía +orgullo +oriente +origen +orilla +oro +orquesta +oruga +osadía +oscuro +osezno +oso +ostra +otoño +otro +oveja +óvulo +óxido +oxígeno +oyente +ozono +pacto +padre +paella +página +pago +país +pájaro +palabra +palco +paleta +pálido +palma +paloma +palpar +pan +panal +pánico +pantera +pañuelo +papá +papel +papilla +paquete +parar +parcela +pared +parir +paro +párpado +parque +párrafo +parte +pasar +paseo +pasión +paso +pasta +pata +patio +patria +pausa +pauta +pavo +payaso +peatón +pecado +pecera +pecho +pedal +pedir +pegar +peine +pelar +peldaño +pelea +peligro +pellejo +pelo +peluca +pena +pensar +peñón +peón +peor +pepino +pequeño +pera +percha +perder +pereza +perfil +perico +perla +permiso +perro +persona +pesa +pesca +pésimo +pestaña +pétalo +petróleo +pez +pezuña +picar +pichón +pie +piedra +pierna +pieza +pijama +pilar +piloto +pimienta +pino +pintor +pinza +piña +piojo +pipa +pirata +pisar +piscina +piso +pista +pitón +pizca +placa +plan +plata +playa +plaza +pleito +pleno +plomo +pluma +plural +pobre +poco +poder +podio +poema +poesía +poeta +polen +policía +pollo +polvo +pomada +pomelo +pomo +pompa +poner +porción +portal +posada +poseer +posible +poste +potencia +potro +pozo +prado +precoz +pregunta +premio +prensa +preso +previo +primo +príncipe +prisión +privar +proa +probar +proceso +producto +proeza +profesor +programa +prole +promesa +pronto +propio +próximo +prueba +público +puchero +pudor +pueblo +puerta +puesto +pulga +pulir +pulmón +pulpo +pulso +puma +punto +puñal +puño +pupa +pupila +puré +quedar +queja +quemar +querer +queso +quieto +química +quince +quitar +rábano +rabia +rabo +ración +radical +raíz +rama +rampa +rancho +rango +rapaz +rápido +rapto +rasgo +raspa +rato +rayo +raza +razón +reacción +realidad +rebaño +rebote +recaer +receta +rechazo +recoger +recreo +recto +recurso +red +redondo +reducir +reflejo +reforma +refrán +refugio +regalo +regir +regla +regreso +rehén +reino +reír +reja +relato +relevo +relieve +relleno +reloj +remar +remedio +remo +rencor +rendir +renta +reparto +repetir +reposo +reptil +res +rescate +resina +respeto +resto +resumen +retiro +retorno +retrato +reunir +revés +revista +rey +rezar +rico +riego +rienda +riesgo +rifa +rígido +rigor +rincón +riñón +río +riqueza +risa +ritmo +rito +rizo +roble +roce +rociar +rodar +rodeo +rodilla +roer +rojizo +rojo +romero +romper +ron +ronco +ronda +ropa +ropero +rosa +rosca +rostro +rotar +rubí +rubor +rudo +rueda +rugir +ruido +ruina +ruleta +rulo +rumbo +rumor +ruptura +ruta +rutina +sábado +saber +sabio +sable +sacar +sagaz +sagrado +sala +saldo +salero +salir +salmón +salón +salsa +salto +salud +salvar +samba +sanción +sandía +sanear +sangre +sanidad +sano +santo +sapo +saque +sardina +sartén +sastre +satán +sauna +saxofón +sección +seco +secreto +secta +sed +seguir +seis +sello +selva +semana +semilla +senda +sensor +señal +señor +separar +sepia +sequía +ser +serie +sermón +servir +sesenta +sesión +seta +setenta +severo +sexo +sexto +sidra +siesta +siete +siglo +signo +sílaba +silbar +silencio +silla +símbolo +simio +sirena +sistema +sitio +situar +sobre +socio +sodio +sol +solapa +soldado +soledad +sólido +soltar +solución +sombra +sondeo +sonido +sonoro +sonrisa +sopa +soplar +soporte +sordo +sorpresa +sorteo +sostén +sótano +suave +subir +suceso +sudor +suegra +suelo +sueño +suerte +sufrir +sujeto +sultán +sumar +superar +suplir +suponer +supremo +sur +surco +sureño +surgir +susto +sutil +tabaco +tabique +tabla +tabú +taco +tacto +tajo +talar +talco +talento +talla +talón +tamaño +tambor +tango +tanque +tapa +tapete +tapia +tapón +taquilla +tarde +tarea +tarifa +tarjeta +tarot +tarro +tarta +tatuaje +tauro +taza +tazón +teatro +techo +tecla +técnica +tejado +tejer +tejido +tela +teléfono +tema +temor +templo +tenaz +tender +tener +tenis +tenso +teoría +terapia +terco +término +ternura +terror +tesis +tesoro +testigo +tetera +texto +tez +tibio +tiburón +tiempo +tienda +tierra +tieso +tigre +tijera +tilde +timbre +tímido +timo +tinta +tío +típico +tipo +tira +tirón +titán +títere +título +tiza +toalla +tobillo +tocar +tocino +todo +toga +toldo +tomar +tono +tonto +topar +tope +toque +tórax +torero +tormenta +torneo +toro +torpedo +torre +torso +tortuga +tos +tosco +toser +tóxico +trabajo +tractor +traer +tráfico +trago +traje +tramo +trance +trato +trauma +trazar +trébol +tregua +treinta +tren +trepar +tres +tribu +trigo +tripa +triste +triunfo +trofeo +trompa +tronco +tropa +trote +trozo +truco +trueno +trufa +tubería +tubo +tuerto +tumba +tumor +túnel +túnica +turbina +turismo +turno +tutor +ubicar +úlcera +umbral +unidad +unir +universo +uno +untar +uña +urbano +urbe +urgente +urna +usar +usuario +útil +utopía +uva +vaca +vacío +vacuna +vagar +vago +vaina +vajilla +vale +válido +valle +valor +válvula +vampiro +vara +variar +varón +vaso +vecino +vector +vehículo +veinte +vejez +vela +velero +veloz +vena +vencer +venda +veneno +vengar +venir +venta +venus +ver +verano +verbo +verde +vereda +verja +verso +verter +vía +viaje +vibrar +vicio +víctima +vida +vídeo +vidrio +viejo +viernes +vigor +vil +villa +vinagre +vino +viñedo +violín +viral +virgo +virtud +visor +víspera +vista +vitamina +viudo +vivaz +vivero +vivir +vivo +volcán +volumen +volver +voraz +votar +voto +voz +vuelo +vulgar +yacer +yate +yegua +yema +yerno +yeso +yodo +yoga +yogur +zafiro +zanja +zapato +zarza +zona +zorro +zumo +zurdo`.split('\n'); +//# sourceMappingURL=spanish.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/spanish.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/spanish.js.map new file mode 100644 index 0000000..46c5704 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/spanish.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spanish.js","sourceRoot":"","sources":["../../src/wordlists/sp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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA+/D5B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js new file mode 100644 index 0000000..82ca23c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js @@ -0,0 +1,2049 @@ +export const wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +這 +中 +大 +為 +上 +個 +國 +我 +以 +要 +他 +時 +來 +用 +們 +生 +到 +作 +地 +於 +出 +就 +分 +對 +成 +會 +可 +主 +發 +年 +動 +同 +工 +也 +能 +下 +過 +子 +說 +產 +種 +面 +而 +方 +後 +多 +定 +行 +學 +法 +所 +民 +得 +經 +十 +三 +之 +進 +著 +等 +部 +度 +家 +電 +力 +裡 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +現 +實 +加 +量 +都 +兩 +體 +制 +機 +當 +使 +點 +從 +業 +本 +去 +把 +性 +好 +應 +開 +它 +合 +還 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +義 +事 +平 +形 +相 +全 +表 +間 +樣 +與 +關 +各 +重 +新 +線 +內 +數 +正 +心 +反 +你 +明 +看 +原 +又 +麼 +利 +比 +或 +但 +質 +氣 +第 +向 +道 +命 +此 +變 +條 +只 +沒 +結 +解 +問 +意 +建 +月 +公 +無 +系 +軍 +很 +情 +者 +最 +立 +代 +想 +已 +通 +並 +提 +直 +題 +黨 +程 +展 +五 +果 +料 +象 +員 +革 +位 +入 +常 +文 +總 +次 +品 +式 +活 +設 +及 +管 +特 +件 +長 +求 +老 +頭 +基 +資 +邊 +流 +路 +級 +少 +圖 +山 +統 +接 +知 +較 +將 +組 +見 +計 +別 +她 +手 +角 +期 +根 +論 +運 +農 +指 +幾 +九 +區 +強 +放 +決 +西 +被 +幹 +做 +必 +戰 +先 +回 +則 +任 +取 +據 +處 +隊 +南 +給 +色 +光 +門 +即 +保 +治 +北 +造 +百 +規 +熱 +領 +七 +海 +口 +東 +導 +器 +壓 +志 +世 +金 +增 +爭 +濟 +階 +油 +思 +術 +極 +交 +受 +聯 +什 +認 +六 +共 +權 +收 +證 +改 +清 +美 +再 +採 +轉 +更 +單 +風 +切 +打 +白 +教 +速 +花 +帶 +安 +場 +身 +車 +例 +真 +務 +具 +萬 +每 +目 +至 +達 +走 +積 +示 +議 +聲 +報 +鬥 +完 +類 +八 +離 +華 +名 +確 +才 +科 +張 +信 +馬 +節 +話 +米 +整 +空 +元 +況 +今 +集 +溫 +傳 +土 +許 +步 +群 +廣 +石 +記 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +觀 +越 +織 +裝 +影 +算 +低 +持 +音 +眾 +書 +布 +复 +容 +兒 +須 +際 +商 +非 +驗 +連 +斷 +深 +難 +近 +礦 +千 +週 +委 +素 +技 +備 +半 +辦 +青 +省 +列 +習 +響 +約 +支 +般 +史 +感 +勞 +便 +團 +往 +酸 +歷 +市 +克 +何 +除 +消 +構 +府 +稱 +太 +準 +精 +值 +號 +率 +族 +維 +劃 +選 +標 +寫 +存 +候 +毛 +親 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +養 +易 +置 +派 +層 +片 +始 +卻 +專 +狀 +育 +廠 +京 +識 +適 +屬 +圓 +包 +火 +住 +調 +滿 +縣 +局 +照 +參 +紅 +細 +引 +聽 +該 +鐵 +價 +嚴 +首 +底 +液 +官 +德 +隨 +病 +蘇 +失 +爾 +死 +講 +配 +女 +黃 +推 +顯 +談 +罪 +神 +藝 +呢 +席 +含 +企 +望 +密 +批 +營 +項 +防 +舉 +球 +英 +氧 +勢 +告 +李 +台 +落 +木 +幫 +輪 +破 +亞 +師 +圍 +注 +遠 +字 +材 +排 +供 +河 +態 +封 +另 +施 +減 +樹 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +葉 +魚 +波 +視 +僅 +費 +緊 +愛 +左 +章 +早 +朝 +害 +續 +輕 +服 +試 +食 +充 +兵 +源 +判 +護 +司 +足 +某 +練 +差 +致 +板 +田 +降 +黑 +犯 +負 +擊 +范 +繼 +興 +似 +餘 +堅 +曲 +輸 +修 +故 +城 +夫 +夠 +送 +筆 +船 +佔 +右 +財 +吃 +富 +春 +職 +覺 +漢 +畫 +功 +巴 +跟 +雖 +雜 +飛 +檢 +吸 +助 +昇 +陽 +互 +初 +創 +抗 +考 +投 +壞 +策 +古 +徑 +換 +未 +跑 +留 +鋼 +曾 +端 +責 +站 +簡 +述 +錢 +副 +盡 +帝 +射 +草 +衝 +承 +獨 +令 +限 +阿 +宣 +環 +雙 +請 +超 +微 +讓 +控 +州 +良 +軸 +找 +否 +紀 +益 +依 +優 +頂 +礎 +載 +倒 +房 +突 +坐 +粉 +敵 +略 +客 +袁 +冷 +勝 +絕 +析 +塊 +劑 +測 +絲 +協 +訴 +念 +陳 +仍 +羅 +鹽 +友 +洋 +錯 +苦 +夜 +刑 +移 +頻 +逐 +靠 +混 +母 +短 +皮 +終 +聚 +汽 +村 +雲 +哪 +既 +距 +衛 +停 +烈 +央 +察 +燒 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +遊 +久 +菜 +味 +舊 +模 +湖 +貨 +損 +預 +阻 +毫 +普 +穩 +乙 +媽 +植 +息 +擴 +銀 +語 +揮 +酒 +守 +拿 +序 +紙 +醫 +缺 +雨 +嗎 +針 +劉 +啊 +急 +唱 +誤 +訓 +願 +審 +附 +獲 +茶 +鮮 +糧 +斤 +孩 +脫 +硫 +肥 +善 +龍 +演 +父 +漸 +血 +歡 +械 +掌 +歌 +沙 +剛 +攻 +謂 +盾 +討 +晚 +粒 +亂 +燃 +矛 +乎 +殺 +藥 +寧 +魯 +貴 +鐘 +煤 +讀 +班 +伯 +香 +介 +迫 +句 +豐 +培 +握 +蘭 +擔 +弦 +蛋 +沉 +假 +穿 +執 +答 +樂 +誰 +順 +煙 +縮 +徵 +臉 +喜 +松 +腳 +困 +異 +免 +背 +星 +福 +買 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +靜 +補 +評 +翻 +肉 +踐 +尼 +衣 +寬 +揚 +棉 +希 +傷 +操 +垂 +秋 +宜 +氫 +套 +督 +振 +架 +亮 +末 +憲 +慶 +編 +牛 +觸 +映 +雷 +銷 +詩 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +綠 +晶 +厚 +盟 +衡 +雞 +孫 +延 +危 +膠 +屋 +鄉 +臨 +陸 +顧 +掉 +呀 +燈 +歲 +措 +束 +耐 +劇 +玉 +趙 +跳 +哥 +季 +課 +凱 +胡 +額 +款 +紹 +卷 +齊 +偉 +蒸 +殖 +永 +宗 +苗 +川 +爐 +岩 +弱 +零 +楊 +奏 +沿 +露 +桿 +探 +滑 +鎮 +飯 +濃 +航 +懷 +趕 +庫 +奪 +伊 +靈 +稅 +途 +滅 +賽 +歸 +召 +鼓 +播 +盤 +裁 +險 +康 +唯 +錄 +菌 +純 +借 +糖 +蓋 +橫 +符 +私 +努 +堂 +域 +槍 +潤 +幅 +哈 +竟 +熟 +蟲 +澤 +腦 +壤 +碳 +歐 +遍 +側 +寨 +敢 +徹 +慮 +斜 +薄 +庭 +納 +彈 +飼 +伸 +折 +麥 +濕 +暗 +荷 +瓦 +塞 +床 +築 +惡 +戶 +訪 +塔 +奇 +透 +梁 +刀 +旋 +跡 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +擺 +灰 +彩 +賣 +耗 +夏 +擇 +忙 +銅 +獻 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +陣 +陰 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +樓 +避 +謀 +噸 +野 +豬 +旗 +累 +偏 +典 +館 +索 +秦 +脂 +潮 +爺 +豆 +忽 +托 +驚 +塑 +遺 +愈 +朱 +替 +纖 +粗 +傾 +尚 +痛 +楚 +謝 +奮 +購 +磨 +君 +池 +旁 +碎 +骨 +監 +捕 +弟 +暴 +割 +貫 +殊 +釋 +詞 +亡 +壁 +頓 +寶 +午 +塵 +聞 +揭 +炮 +殘 +冬 +橋 +婦 +警 +綜 +招 +吳 +付 +浮 +遭 +徐 +您 +搖 +谷 +贊 +箱 +隔 +訂 +男 +吹 +園 +紛 +唐 +敗 +宋 +玻 +巨 +耕 +坦 +榮 +閉 +灣 +鍵 +凡 +駐 +鍋 +救 +恩 +剝 +凝 +鹼 +齒 +截 +煉 +麻 +紡 +禁 +廢 +盛 +版 +緩 +淨 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +莊 +街 +藏 +姑 +貿 +腐 +奴 +啦 +慣 +乘 +夥 +恢 +勻 +紗 +扎 +辯 +耳 +彪 +臣 +億 +璃 +抵 +脈 +秀 +薩 +俄 +網 +舞 +店 +噴 +縱 +寸 +汗 +掛 +洪 +賀 +閃 +柬 +爆 +烯 +津 +稻 +牆 +軟 +勇 +像 +滾 +厘 +蒙 +芳 +肯 +坡 +柱 +盪 +腿 +儀 +旅 +尾 +軋 +冰 +貢 +登 +黎 +削 +鑽 +勒 +逃 +障 +氨 +郭 +峰 +幣 +港 +伏 +軌 +畝 +畢 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +島 +甘 +泡 +睡 +童 +鑄 +湯 +閥 +休 +匯 +舍 +牧 +繞 +炸 +哲 +磷 +績 +朋 +淡 +尖 +啟 +陷 +柴 +呈 +徒 +顏 +淚 +稍 +忘 +泵 +藍 +拖 +洞 +授 +鏡 +辛 +壯 +鋒 +貧 +虛 +彎 +摩 +泰 +幼 +廷 +尊 +窗 +綱 +弄 +隸 +疑 +氏 +宮 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +違 +夾 +腰 +緣 +珠 +窮 +森 +枝 +竹 +溝 +催 +繩 +憶 +邦 +剩 +幸 +漿 +欄 +擁 +牙 +貯 +禮 +濾 +鈉 +紋 +罷 +拍 +咱 +喊 +袖 +埃 +勤 +罰 +焦 +潛 +伍 +墨 +欲 +縫 +姓 +刊 +飽 +仿 +獎 +鋁 +鬼 +麗 +跨 +默 +挖 +鏈 +掃 +喝 +袋 +炭 +污 +幕 +諸 +弧 +勵 +梅 +奶 +潔 +災 +舟 +鑑 +苯 +訟 +抱 +毀 +懂 +寒 +智 +埔 +寄 +屆 +躍 +渡 +挑 +丹 +艱 +貝 +碰 +拔 +爹 +戴 +碼 +夢 +芽 +熔 +赤 +漁 +哭 +敬 +顆 +奔 +鉛 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +倉 +魏 +銳 +曉 +氮 +兼 +隱 +礙 +赫 +撥 +忠 +肅 +缸 +牽 +搶 +博 +巧 +殼 +兄 +杜 +訊 +誠 +碧 +祥 +柯 +頁 +巡 +矩 +悲 +灌 +齡 +倫 +票 +尋 +桂 +鋪 +聖 +恐 +恰 +鄭 +趣 +抬 +荒 +騰 +貼 +柔 +滴 +猛 +闊 +輛 +妻 +填 +撤 +儲 +簽 +鬧 +擾 +紫 +砂 +遞 +戲 +吊 +陶 +伐 +餵 +療 +瓶 +婆 +撫 +臂 +摸 +忍 +蝦 +蠟 +鄰 +胸 +鞏 +擠 +偶 +棄 +槽 +勁 +乳 +鄧 +吉 +仁 +爛 +磚 +租 +烏 +艦 +伴 +瓜 +淺 +丙 +暫 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +膽 +詳 +簧 +踏 +瓷 +譜 +呆 +賓 +糊 +洛 +輝 +憤 +競 +隙 +怒 +粘 +乃 +緒 +肩 +籍 +敏 +塗 +熙 +皆 +偵 +懸 +掘 +享 +糾 +醒 +狂 +鎖 +淀 +恨 +牲 +霸 +爬 +賞 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鴨 +趨 +鳳 +晨 +畜 +輩 +秩 +卵 +署 +梯 +炎 +灘 +棋 +驅 +篩 +峽 +冒 +啥 +壽 +譯 +浸 +泉 +帽 +遲 +矽 +疆 +貸 +漏 +稿 +冠 +嫩 +脅 +芯 +牢 +叛 +蝕 +奧 +鳴 +嶺 +羊 +憑 +串 +塘 +繪 +酵 +融 +盆 +錫 +廟 +籌 +凍 +輔 +攝 +襲 +筋 +拒 +僚 +旱 +鉀 +鳥 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韓 +逼 +扭 +僑 +涼 +挺 +碗 +栽 +炒 +杯 +患 +餾 +勸 +豪 +遼 +勃 +鴻 +旦 +吏 +拜 +狗 +埋 +輥 +掩 +飲 +搬 +罵 +辭 +勾 +扣 +估 +蔣 +絨 +霧 +丈 +朵 +姆 +擬 +宇 +輯 +陝 +雕 +償 +蓄 +崇 +剪 +倡 +廳 +咬 +駛 +薯 +刷 +斥 +番 +賦 +奉 +佛 +澆 +漫 +曼 +扇 +鈣 +桃 +扶 +仔 +返 +俗 +虧 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +騙 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +脹 +諧 +拋 +黴 +桑 +崗 +嘛 +衰 +盜 +滲 +臟 +賴 +湧 +甜 +曹 +閱 +肌 +哩 +厲 +烴 +緯 +毅 +昨 +偽 +症 +煮 +嘆 +釘 +搭 +莖 +籠 +酷 +偷 +弓 +錐 +恆 +傑 +坑 +鼻 +翼 +綸 +敘 +獄 +逮 +罐 +絡 +棚 +抑 +膨 +蔬 +寺 +驟 +穆 +冶 +枯 +冊 +屍 +凸 +紳 +坯 +犧 +焰 +轟 +欣 +晉 +瘦 +禦 +錠 +錦 +喪 +旬 +鍛 +壟 +搜 +撲 +邀 +亭 +酯 +邁 +舒 +脆 +酶 +閒 +憂 +酚 +頑 +羽 +漲 +卸 +仗 +陪 +闢 +懲 +杭 +姚 +肚 +捉 +飄 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +飾 +蕭 +雅 +郵 +遷 +燕 +撒 +姻 +赴 +宴 +煩 +債 +帳 +斑 +鈴 +旨 +醇 +董 +餅 +雛 +姿 +拌 +傅 +腹 +妥 +揉 +賢 +拆 +歪 +葡 +胺 +丟 +浩 +徽 +昂 +墊 +擋 +覽 +貪 +慰 +繳 +汪 +慌 +馮 +諾 +姜 +誼 +兇 +劣 +誣 +耀 +昏 +躺 +盈 +騎 +喬 +溪 +叢 +盧 +抹 +悶 +諮 +刮 +駕 +纜 +悟 +摘 +鉺 +擲 +頗 +幻 +柄 +惠 +慘 +佳 +仇 +臘 +窩 +滌 +劍 +瞧 +堡 +潑 +蔥 +罩 +霍 +撈 +胎 +蒼 +濱 +倆 +捅 +湘 +砍 +霞 +邵 +萄 +瘋 +淮 +遂 +熊 +糞 +烘 +宿 +檔 +戈 +駁 +嫂 +裕 +徙 +箭 +捐 +腸 +撐 +曬 +辨 +殿 +蓮 +攤 +攪 +醬 +屏 +疫 +哀 +蔡 +堵 +沫 +皺 +暢 +疊 +閣 +萊 +敲 +轄 +鉤 +痕 +壩 +巷 +餓 +禍 +丘 +玄 +溜 +曰 +邏 +彭 +嘗 +卿 +妨 +艇 +吞 +韋 +怨 +矮 +歇`.split('\n'); +//# sourceMappingURL=traditional-chinese.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map new file mode 100644 index 0000000..efa45e0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/esm/wordlists/traditional-chinese.js.map @@ -0,0 +1 @@ +{"version":3,"file":"traditional-chinese.js","sourceRoot":"","sources":["../../src/wordlists/traditional-chinese.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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scure/bip39/index.d.ts new file mode 100644 index 0000000..85cdb22 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/index.d.ts @@ -0,0 +1,63 @@ +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist imported wordlist for specific language + * @param strength mnemonic strength 128-256 bits + * @example + * generateMnemonic(wordlist, 128) + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +export declare function generateMnemonic(wordlist: string[], strength?: number): string; +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic 12-24 words + * @param wordlist imported wordlist for specific language + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToEntropy(mnem, wordlist) + * // Produces + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + */ +export declare function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy byte array + * @param wordlist imported wordlist for specific language + * @returns 12-24 words + * @example + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +export declare function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + */ +export declare function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * await mnemonicToSeed(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +export declare function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToSeedSync(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +export declare function mnemonicToSeedSync(mnemonic: string, passphrase?: string): Uint8Array; diff --git a/test/merkletreejs/node_modules/@scure/bip39/index.js b/test/merkletreejs/node_modules/@scure/bip39/index.js new file mode 100644 index 0000000..924ae10 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/index.js @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mnemonicToSeedSync = exports.mnemonicToSeed = exports.validateMnemonic = exports.entropyToMnemonic = exports.mnemonicToEntropy = exports.generateMnemonic = void 0; +/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +const _assert_1 = require("@noble/hashes/_assert"); +const pbkdf2_1 = require("@noble/hashes/pbkdf2"); +const sha256_1 = require("@noble/hashes/sha256"); +const sha512_1 = require("@noble/hashes/sha512"); +const utils_1 = require("@noble/hashes/utils"); +const base_1 = require("@scure/base"); +// Japanese wordlist +const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093'; +// Normalization replaces equivalent sequences of characters +// so that any two texts that are equivalent will be reduced +// to the same sequence of code points, called the normal form of the original text. +function nfkd(str) { + if (typeof str !== 'string') + throw new TypeError(`Invalid mnemonic type: ${typeof str}`); + return str.normalize('NFKD'); +} +function normalize(str) { + const norm = nfkd(str); + const words = norm.split(' '); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error('Invalid mnemonic'); + return { nfkd: norm, words }; +} +function assertEntropy(entropy) { + _assert_1.default.bytes(entropy, 16, 20, 24, 28, 32); +} +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist imported wordlist for specific language + * @param strength mnemonic strength 128-256 bits + * @example + * generateMnemonic(wordlist, 128) + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +function generateMnemonic(wordlist, strength = 128) { + _assert_1.default.number(strength); + if (strength % 32 !== 0 || strength > 256) + throw new TypeError('Invalid entropy'); + return entropyToMnemonic((0, utils_1.randomBytes)(strength / 8), wordlist); +} +exports.generateMnemonic = generateMnemonic; +const calcChecksum = (entropy) => { + // Checksum is ent.length/4 bits long + const bitsLeft = 8 - entropy.length / 4; + // Zero rightmost "bitsLeft" bits in byte + // For example: bitsLeft=4 val=10111101 -> 10110000 + return new Uint8Array([((0, sha256_1.sha256)(entropy)[0] >> bitsLeft) << bitsLeft]); +}; +function getCoder(wordlist) { + if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string') + throw new Error('Worlist: expected array of 2048 strings'); + wordlist.forEach((i) => { + if (typeof i !== 'string') + throw new Error(`Wordlist: non-string element: ${i}`); + }); + return base_1.utils.chain(base_1.utils.checksum(1, calcChecksum), base_1.utils.radix2(11, true), base_1.utils.alphabet(wordlist)); +} +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic 12-24 words + * @param wordlist imported wordlist for specific language + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToEntropy(mnem, wordlist) + * // Produces + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + */ +function mnemonicToEntropy(mnemonic, wordlist) { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist).decode(words); + assertEntropy(entropy); + return entropy; +} +exports.mnemonicToEntropy = mnemonicToEntropy; +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy byte array + * @param wordlist imported wordlist for specific language + * @returns 12-24 words + * @example + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + */ +function entropyToMnemonic(entropy, wordlist) { + assertEntropy(entropy); + const words = getCoder(wordlist).encode(entropy); + return words.join(isJapanese(wordlist) ? '\u3000' : ' '); +} +exports.entropyToMnemonic = entropyToMnemonic; +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + */ +function validateMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + } + catch (e) { + return false; + } + return true; +} +exports.validateMnemonic = validateMnemonic; +const salt = (passphrase) => nfkd(`mnemonic${passphrase}`); +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * await mnemonicToSeed(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +function mnemonicToSeed(mnemonic, passphrase = '') { + return (0, pbkdf2_1.pbkdf2Async)(sha512_1.sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +exports.mnemonicToSeed = mnemonicToSeed; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic 12-24 words + * @param passphrase string that will additionally protect the key + * @returns 64 bytes of key data + * @example + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * mnemonicToSeedSync(mnem, 'password'); + * // new Uint8Array([...64 bytes]) + */ +function mnemonicToSeedSync(mnemonic, passphrase = '') { + return (0, pbkdf2_1.pbkdf2)(sha512_1.sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); +} +exports.mnemonicToSeedSync = mnemonicToSeedSync; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/LICENSE b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/README.md b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..6f71600 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/README.md @@ -0,0 +1,534 @@ +# noble-hashes + +Audited & minimal JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2 & Scrypt. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shaking-friendly: use only what's necessary, other code won't be included +- 🏎 Ultra-fast, hand-optimized for caveats of JS engines +- 🔍 Unique tests ensure correctness: chained tests, sliding window tests, DoS tests, fuzzing +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🐢 Scrypt supports `N: 2**22`, while other implementations are limited to `2**20` +- 🦘 SHA3 supports Keccak, TupleHash, KangarooTwelve and MarsupilamiFourteen +- 🪶 Just 3.4k lines / 17KB gzipped. SHA256-only is 240 lines / 3KB gzipped + +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ crypto + +> **noble-crypto** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- No dependencies, protection against supply chain attacks +- Auditable TypeScript / JS code +- Supported on all major platforms +- Releases are signed with PGP keys and built transparently with NPM provenance +- Check out [homepage](https://paulmillr.com/noble/) & all libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + 4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) + +## Usage + +> npm install @noble/hashes + +We support all major platforms and runtimes. +For [Deno](https://deno.land), ensure to use [npm specifier](https://deno.land/manual@v1.28.0/node/npm_specifiers). +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +If you don't like NPM, a standalone [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +```js +// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size +import { sha256 } from '@noble/hashes/sha256'; // ECMAScript modules (ESM) and Common.js +// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha256'; // Deno +console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] +// you could also pass strings that will be UTF8-encoded to Uint8Array +console.log(sha256('abc')); // == sha256(new TextEncoder().encode('abc')) + +// sha384 is here, because it uses same internals as sha512 +import { sha512, sha512_256, sha384 } from '@noble/hashes/sha512'; +// prettier-ignore +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3'; +// prettier-ignore +import { + cshake128, cshake256, kmac128, kmac256, + k12, m14, + tuplehash256, parallelhash256, keccakprg +} from '@noble/hashes/sha3-addons'; +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { blake3 } from '@noble/hashes/blake3'; +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +import { hmac } from '@noble/hashes/hmac'; +import { hkdf } from '@noble/hashes/hkdf'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; + +import { sha1 } from '@noble/hashes/sha1'; // legacy + +// small utility method that converts bytes to hex +import { bytesToHex as toHex } from '@noble/hashes/utils'; +console.log(toHex(sha256('abc'))); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +``` + +## API + +All hash functions: + +- can be called directly, with `Uint8Array`. +- return `Uint8Array` +- can receive `string`, which is automatically converted to `Uint8Array` + via utf8 encoding **(not hex)** +- support hashing 4GB of data per update on 64-bit systems (unlimited with streaming) + +```ts +function hash(message: Uint8Array | string): Uint8Array; +hash(new Uint8Array([1, 3])); +hash('string') == hash(new TextEncoder().encode('string')); +``` + +All hash functions can be constructed via `hash.create()` method: + +- the result is `Hash` subclass instance, which has `update()` and `digest()` methods +- `digest()` finalizes the hash and makes it no longer usable + +```ts +hash + .create() + .update(new Uint8Array([1, 3])) + .digest(); +``` + +_Some_ hash functions can also receive `options` object, which can be either passed as a: + +- second argument to hash function: `blake3('abc', { key: 'd', dkLen: 32 })` +- first argument to class initializer: `blake3.create({ context: 'e', dkLen: 32 })` + +## Modules + +- [SHA2 (sha256, sha384, sha512, sha512_256)](#sha2-sha256-sha384-sha512-sha512_256) +- [SHA3 (FIPS, SHAKE, Keccak)](#sha3-fips-shake-keccak) +- [SHA3 Addons (cSHAKE, KMAC, KangarooTwelve, MarsupilamiFourteen)](#sha3-addons-cshake-kmac-tuplehash-parallelhash-kangarootwelve-marsupilamifourteen) +- [RIPEMD-160](#ripemd-160) +- [BLAKE2b, BLAKE2s](#blake2b-blake2s) +- [BLAKE3](#blake3) +- [SHA1 (legacy)](#sha1-legacy) +- [HMAC](#hmac) +- [HKDF](#hkdf) +- [PBKDF2](#pbkdf2) +- [Scrypt](#scrypt) +- [ESKDF](#eskdf) +- [utils](#utils) + +##### SHA2 (sha256, sha384, sha512, sha512_256) + +```typescript +import { sha256 } from '@noble/hashes/sha256'; +const h1a = sha256('abc'); +const h1b = sha256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +```typescript +import { sha512 } from '@noble/hashes/sha512'; +const h2a = sha512('abc'); +const h2b = sha512 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA512/256 variant +import { sha512_256 } from '@noble/hashes/sha512'; +const h3a = sha512_256('abc'); +const h3b = sha512_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); + +// SHA384 +import { sha384 } from '@noble/hashes/sha512'; +const h4a = sha384('abc'); +const h4b = sha384 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +##### SHA3 (FIPS, SHAKE, Keccak) + +```typescript +import { + sha3_224, + sha3_256, + sha3_384, + sha3_512, + keccak_224, + keccak_256, + keccak_384, + keccak_512, + shake128, + shake256, +} from '@noble/hashes/sha3'; +const h5a = sha3_256('abc'); +const h5b = sha3_256 + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +const h6a = keccak_256('abc'); +const h7a = shake128('abc', { dkLen: 512 }); +const h7b = shake256('abc', { dkLen: 512 }); +``` + +See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +##### SHA3 Addons (cSHAKE, KMAC, TupleHash, ParallelHash, KangarooTwelve, MarsupilamiFourteen) + +```typescript +import { + cshake128, + cshake256, + kmac128, + kmac256, + k12, + m14, + tuplehash128, + tuplehash256, + parallelhash128, + parallelhash256, + keccakprg, +} from '@noble/hashes/sha3-addons'; +const h7c = cshake128('abc', { personalization: 'def' }); +const h7d = cshake256('abc', { personalization: 'def' }); +const h7e = kmac128('key', 'message'); +const h7f = kmac256('key', 'message'); +const h7h = k12('abc'); +const h7g = m14('abc'); +const h7i = tuplehash128(['ab', 'c']); // tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash(['abc']) +// Same as k12/blake3, but without reduced number of rounds. Doesn't speedup anything due lack of SIMD and threading, +// added for compatibility. +const h7j = parallelhash128('abc', { blockLen: 8 }); +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.feed('test'); +const rand1b = p.fetch(1); +``` + +- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): + cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants +- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), + [RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) + and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with + reduced number of rounds (same as Blake3 and ParallelHash). +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak + +##### RIPEMD-160 + +```typescript +import { ripemd160 } from '@noble/hashes/ripemd160'; +// function ripemd160(data: Uint8Array): Uint8Array; +const hash8 = ripemd160('abc'); +const hash9 = ripemd160() + .create() + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), +[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) + +##### BLAKE2b, BLAKE2s + +```typescript +import { blake2b } from '@noble/hashes/blake2b'; +import { blake2s } from '@noble/hashes/blake2s'; +const h10a = blake2s('abc'); +const b2params = { key: new Uint8Array([1]), personalization: t, salt: t, dkLen: 32 }; +const h10b = blake2s('abc', b2params); +const h10c = blake2s + .create(b2params) + .update(Uint8Array.from([1, 2, 3])) + .digest(); +``` + +See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net). + +##### BLAKE3 + +```typescript +import { blake3 } from '@noble/hashes/blake3'; +// All params are optional +const h11 = blake3('abc', { dkLen: 256, key: 'def', context: 'fji' }); +``` + +##### SHA1 (legacy) + +SHA1 was cryptographically broken, however, it was not broken for cases like HMAC. + +See [RFC4226 B.2](https://datatracker.ietf.org/doc/html/rfc4226#appendix-B.2). + +Don't use it for a new protocol. + +```typescript +import { sha1 } from '@noble/hashes/sha1'; +const h12 = sha1('def'); +``` + +##### HMAC + +```typescript +import { hmac } from '@noble/hashes/hmac'; +import { sha256 } from '@noble/hashes/sha256'; +const mac1 = hmac(sha256, 'key', 'message'); +const mac2 = hmac.create(sha256, Uint8Array.from([1, 2, 3])).update(Uint8Array.from([4, 5, 6])).digest(); +``` + +Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +##### HKDF + +```typescript +import { hkdf } from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +import { randomBytes } from '@noble/hashes/utils'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = 'abc'; +const dkLen = 32; +const hk1 = hkdf(sha256, inputKey, salt, info, dkLen); + +// == same as +import * as hkdf from '@noble/hashes/hkdf'; +import { sha256 } from '@noble/hashes/sha256'; +const prk = hkdf.extract(sha256, inputKey, salt); +const hk2 = hkdf.expand(sha256, prk, info, dkLen); +``` + +Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +##### PBKDF2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2'; +import { sha256 } from '@noble/hashes/sha256'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 32, + dkLen: 32, +}); +``` + +Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +##### Scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 22, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). +- `dkLen` is the length of output bytes +- It is common to use N from `2**10` to `2**22` and `{r: 8, p: 1, dkLen: 32}` +- `onProgress` can be used with async version of the function to report progress to a user. + +Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, +which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent +DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to +`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase +`maxmem` using the formula above. + +_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS +libs. Many other implementations don't support it. We cannot support `2**23`, +because there is a limitation in JS engines that makes allocating +arrays bigger than 4GB impossible, but we're looking into other possible solutions. + +##### Argon2 + +Experimental Argon2 RFC 9106 implementation. It may be removed at any time. + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2'; +const result = argon2id('password', 'salt', { t: 2, m: 65536, p: 1 }); +``` + +##### ESKDF + +A tiny stretched KDF for various applications like AES key-gen. Takes >= 2 seconds to execute. + +Takes following params: + +- `username` - username, email, or identifier, min: 8 characters, should have enough entropy +- `password` - min: 8 characters, should have enough entropy + +Produces ESKDF instance that has `deriveChildKey(protocol, accountId[, options])` function. + +- `protocol` - 3-15 character protocol name +- `accountId` - numeric identifier of account +- `options` - `keyLength: 32` with specified key length (default is 32), + or `modulus: 2n ** 221n - 17n` with specified modulus. It will fetch modulus + 64 bits of + data, execute modular division. The result will have negligible bias as per FIPS 186 B.4.1. + Can be used to generate, for example, elliptic curve keys. + +Takes username and password, then takes protocol name and account id. + +```typescript +import { eskdf } from '@noble/hashes/eskdf'; +const kdf = await eskdf('example@university', 'beginning-new-example'); +console.log(kdf.fingerprint); +const key1 = kdf.deriveChildKey('aes', 0); +const key2 = kdf.deriveChildKey('aes', 0, { keyLength: 16 }); +const ecc1 = kdf.deriveChildKey('ecc', 0, { modulus: 2n ** 252n - 27742317777372353535851937790883648493n }) +kdf.expire(); +``` + +##### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +## Security + +Noble is production-ready. + +1. The library has been audited in Jan 2022 by an independent security firm + cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). + No vulnerabilities have been found. The audit has been funded by + [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io). + Modules `blake3`, `sha3-addons`, `sha1` and `argon2` have not been audited. + See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). +2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). + You can run the fuzzer by yourself to check it. +3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: + _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to + achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. + Even statically typed Rust, a language without GC, + [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) + for some cases. If your goal is absolute security, don't use any JS lib — including + bindings to native ones. Use low-level libraries & languages. Nonetheless we're + targetting algorithmic constant time. +4. Memory dump considerations: the library shares state buffers between hash + function calls. The buffers are zeroed-out after each call. However, if an attacker + can read application memory, you are doomed in any case: + - At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings + - Input from a file will stay in file buffers + - Input / output will be re-used multiple times in application which means + it could stay in memory + - `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory + - There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +We consider infrastructure attacks like rogue NPM modules very important; that's +why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. +If your app uses 500 dependencies, any dep could get hacked and you'll be downloading +malware with every `npm install`. Our goal is to minimize this attack vector. + +## Speed + +Benchmarks measured on Apple M1 with macOS 12. +Note that PBKDF2 and Scrypt are tested with extremely high work factor. +To run benchmarks, execute `npm run bench:install` and then `npm run bench` + +``` +SHA256 32B x 1,219,512 ops/sec @ 820ns/op ± 2.58% (min: 625ns, max: 4ms) +SHA384 32B x 512,032 ops/sec @ 1μs/op +SHA512 32B x 509,943 ops/sec @ 1μs/op +SHA3-256, keccak256, shake256 32B x 199,600 ops/sec @ 5μs/op +Kangaroo12 32B x 336,360 ops/sec @ 2μs/op +Marsupilami14 32B x 298,418 ops/sec @ 3μs/op +BLAKE2b 32B x 379,794 ops/sec @ 2μs/op +BLAKE2s 32B x 515,995 ops/sec @ 1μs/op ± 1.07% (min: 1μs, max: 4ms) +BLAKE3 32B x 588,235 ops/sec @ 1μs/op ± 1.36% (min: 1μs, max: 5ms) +RIPEMD160 32B x 1,140,250 ops/sec @ 877ns/op ± 3.12% (min: 708ns, max: 6ms) +HMAC-SHA256 32B x 377,358 ops/sec @ 2μs/op + +HKDF-SHA256 32B x 108,377 ops/sec @ 9μs/op +PBKDF2-HMAC-SHA256 262144 x 3 ops/sec @ 326ms/op +PBKDF2-HMAC-SHA512 262144 x 1 ops/sec @ 970ms/op +Scrypt r: 8, p: 1, n: 262144 x 1 ops/sec @ 616ms/op +``` + +Compare to native node.js implementation that uses C bindings instead of pure-js code: + +``` +SHA256 32B node x 1,302,083 ops/sec @ 768ns/op ± 10.54% (min: 416ns, max: 7ms) +SHA384 32B node x 975,609 ops/sec @ 1μs/op ± 11.32% (min: 625ns, max: 8ms) +SHA512 32B node x 983,284 ops/sec @ 1μs/op ± 11.24% (min: 625ns, max: 8ms) +SHA3-256 32B node x 910,746 ops/sec @ 1μs/op ± 12.19% (min: 666ns, max: 10ms) +keccak, k12, m14 are not implemented +BLAKE2b 32B node x 967,117 ops/sec @ 1μs/op ± 11.26% (min: 625ns, max: 9ms) +BLAKE2s 32B node x 1,055,966 ops/sec @ 947ns/op ± 11.07% (min: 583ns, max: 7ms) +BLAKE3 is not implemented +RIPEMD160 32B node x 1,002,004 ops/sec @ 998ns/op ± 10.66% (min: 625ns, max: 7ms) +HMAC-SHA256 32B node x 919,963 ops/sec @ 1μs/op ± 6.13% (min: 833ns, max: 5ms) +HKDF-SHA256 32 node x 369,276 ops/sec @ 2μs/op ± 13.59% (min: 1μs, max: 9ms) +PBKDF2-HMAC-SHA256 262144 node x 25 ops/sec @ 39ms/op +PBKDF2-HMAC-SHA512 262144 node x 7 ops/sec @ 132ms/op +Scrypt r: 8, p: 1, n: 262144 node x 1 ops/sec @ 523ms/op +``` + +It is possible to [make this library 4x+ faster](./benchmark/README.md) by +_doing code generation of full loop unrolls_. We've decided against it. Reasons: + +- the library must be auditable, with minimum amount of code, and zero dependencies +- most method invocations with the lib are going to be something like hashing 32b to 64kb of data +- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead + +The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run. + +## Contributing & testing + +1. Clone the repository +2. `npm install` to install build dependencies like TypeScript +3. `npm run build` to compile TypeScript code +4. `npm run test` will execute all main tests. See [our approach to testing](./test/README.md) +5. `npm run test:dos` will test against DoS; by measuring function complexity. **Takes ~20 minutes** +6. `npm run test:big` will execute hashing on 4GB inputs, + scrypt with 1024 different `N, r, p` combinations, etc. **Takes several hours**. Using 8-32+ core CPU helps. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.d.ts new file mode 100644 index 0000000..32a720b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.d.ts @@ -0,0 +1,22 @@ +declare function number(n: number): void; +declare function bool(b: boolean): void; +declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +declare function hash(hash: Hash): void; +declare function exists(instance: any, checkFinished?: boolean): void; +declare function output(out: any, instance: any): void; +export { number, bool, bytes, hash, exists, output }; +declare const assert: { + number: typeof number; + bool: typeof bool; + bytes: typeof bytes; + hash: typeof hash; + exists: typeof exists; + output: typeof output; +}; +export default assert; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.js new file mode 100644 index 0000000..920cdd9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { number, bool, bytes, hash, exists, output }; +exports.default = assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_assert.js.map new file mode 100644 index 0000000..f3cc515 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules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,kCAAkC,CAAC,CAAC;IAC5E,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AASmC,wBAAM;AAR1C,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAE2C,wBAAM;AAElD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.d.ts new file mode 100644 index 0000000..352b978 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.d.ts @@ -0,0 +1,27 @@ +import { Hash, Input } from './utils.js'; +export declare const SIGMA: Uint8Array; +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; +export declare abstract class BLAKE2> extends Hash { + readonly blockLen: number; + outputLen: number; + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number; + protected pos: number; + protected finished: boolean; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, opts: BlakeOpts | undefined, keyLen: number, saltLen: number, persLen: number); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.js new file mode 100644 index 0000000..9a5a45d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLAKE2 = exports.SIGMA = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +exports.SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +class BLAKE2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.number)(blockLen); + (0, _assert_js_1.number)(outputLen); + (0, _assert_js_1.number)(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + (0, _assert_js_1.exists)(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = (0, utils_js_1.u32)(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +exports.BLAKE2 = BLAKE2; +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.js.map new file mode 100644 index 0000000..85cf0b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["src/_blake2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAuD;AAEvD,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AACL,QAAA,KAAK,GAAmB,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EA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AC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AAlGD,wBAkGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.d.ts new file mode 100644 index 0000000..883788f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.d.ts @@ -0,0 +1,23 @@ +import { Hash, Input } from './utils.js'; +export declare abstract class SHA2> extends Hash { + readonly blockLen: number; + outputLen: number; + readonly padOffset: number; + readonly isLE: boolean; + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: T): T; +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.js new file mode 100644 index 0000000..7a45349 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + (0, _assert_js_1.exists)(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = (0, utils_js_1.createView)(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.SHA2 = SHA2; +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.js.map new file mode 100644 index 0000000..9c9c8eb --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["src/_sha2.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAC9C,yCAA8D;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc,EAAE,UAAkB,EAAE,KAAa,EAAE,IAAa;IACpF,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/F,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,QAAQ,C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CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC1E,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,EAAO,EAAC;QAC5C,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACpE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,IAAI,MAAM,GAAG,QAAQ;YAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AApGD,oBAoGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..59fd1c2 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,54 @@ +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): Uint32Array[]; +declare const toBig: (h: number, l: number) => bigint; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare const rotlSH: (h: number, l: number, s: number) => number; +declare const rotlSL: (h: number, l: number, s: number) => number; +declare const rotlBH: (h: number, l: number, s: number) => number; +declare const rotlBL: (h: number, l: number, s: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, _l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (_h: number, l: number) => number; + rotr32L: (h: number, _l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..c5080f0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.add = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = exports.split = exports.fromBig = void 0; +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +exports.shrSH = shrSH; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.shrSL = shrSL; +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +exports.rotrSH = rotrSH; +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.rotrSL = rotrSL; +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +exports.rotrBH = rotrBH; +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +exports.rotrBL = rotrBL; +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +exports.rotr32H = rotr32H; +const rotr32L = (h, _l) => h; +exports.rotr32L = rotr32L; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +exports.rotlSH = rotlSH; +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +exports.rotlSL = rotlSL; +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +exports.rotlBH = rotlBH; +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +exports.rotlBL = rotlBL; +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +exports.add3L = add3L; +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +exports.add3H = add3H; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +exports.add4L = add4L; +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +exports.add4H = add4H; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +exports.add5L = add5L; +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +exports.add5H = add5H; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports.default = u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..6116a39 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":";;;AAAA,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAExC,+EAA+E;AAC/E,SAAS,OAAO,CAAC,CAAS,EAAE,EAAE,GAAG,KAAK;IACpC,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,UAAU,CAA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,KAAK,GAAG,CAAC,GAAW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AASpB,sBAAK;AAExC,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kBAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..15b6486 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,16 @@ +import { Input } from './utils.js'; +export type ArgonOpts = { + t: number; + m: number; + p: number; + version?: number; + key?: Input; + personalization?: Input; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +export declare const argon2d: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2i: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; +export declare const argon2id: (password: Input, salt: Input, opts: ArgonOpts) => Uint8Array; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..2754f8c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,303 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argon2id = exports.argon2i = exports.argon2d = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const blake2b_js_1 = require("./blake2b.js"); +const _u64_js_1 = require("./_u64.js"); +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = (0, _u64_js_1.add3L)(Al, Bl, Cl); + return { h: (0, _u64_js_1.add3H)(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotr32H)(Dh, Dl), Dl: (0, _u64_js_1.rotr32L)(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrSH)(Bh, Bl, 24), Bl: (0, _u64_js_1.rotrSL)(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: (0, _u64_js_1.rotrSH)(Dh, Dl, 16), Dl: (0, _u64_js_1.rotrSL)(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: (0, _u64_js_1.rotrBH)(Bh, Bl, 63), Bl: (0, _u64_js_1.rotrBL)(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = (0, utils_js_1.u8)(A); + const T = new Uint32Array(1); + const T8 = (0, utils_js_1.u8)(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b_js_1.blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b_js_1.blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = (0, blake2b_js_1.blake2b)(V)).subarray(0, 32), pos); + // Last block + out.set((0, blake2b_js_1.blake2b)(V, { dkLen: dkLen - pos }), pos); + return (0, utils_js_1.u32)(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = (0, utils_js_1.toBytes)(password); + salt = (0, utils_js_1.toBytes)(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(m); + (0, _assert_js_1.number)(t); + (0, _assert_js_1.number)(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = (0, utils_js_1.toBytes)(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = (0, utils_js_1.toBytes)(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b_js_1.blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = (0, utils_js_1.u8)(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = (0, utils_js_1.u8)(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return (0, utils_js_1.u8)(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +exports.argon2d = argon2d; +const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +exports.argon2i = argon2i; +const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +exports.argon2id = argon2id; +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..a88b252 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAqD;AACrD,6CAAuC;AACvC,uCAA2F;AAS3F,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B,MAAM,eAAe,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjG,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7B,MAAM,GAAG,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,MAAM,CAAC,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F;KACF;IACD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAEM,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,OAAO,WAC2B;AACxC,MAAM,OAAO,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACvE,MAAM,wBAAgB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADjC,QAAA,OAAO,WAC0B;AACvC,MAAM,QAAQ,GAAG,CAAC,QAAe,EAAE,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AADlC,QAAA,QAAQ,YAC0B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.d.ts new file mode 100644 index 0000000..7a78c6b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.d.ts @@ -0,0 +1,53 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +declare class BLAKE2b extends BLAKE2 { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2b: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.js new file mode 100644 index 0000000..9d41df5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotr32H(Dh, Dl), Dl: _u64_js_1.default.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrSH(Bh, Bl, 24), Bl: _u64_js_1.default.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = _u64_js_1.default.add3L(Al, Bl, Xl); + Ah = _u64_js_1.default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: _u64_js_1.default.rotrSH(Dh, Dl, 16), Dl: _u64_js_1.default.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = _u64_js_1.default.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: _u64_js_1.default.rotrBH(Bh, Bl, 63), Bl: _u64_js_1.default.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = _u64_js_1.default.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = _blake2_js_1.SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2b = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2b.js.map new file mode 100644 index 0000000..4e936fb --- /dev/null +++ b/test/merkletreejs/node_mod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C,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAmB,IAAA,kCAAuB,EAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.d.ts new file mode 100644 index 0000000..d9dd59b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.d.ts @@ -0,0 +1,47 @@ +import { BLAKE2, BlakeOpts } from './_blake2.js'; +export declare const IV: Uint32Array; +export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +declare class BLAKE2s extends BLAKE2 { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export declare const blake2s: { + (msg: import("./utils.js").Input, opts?: BlakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: BlakeOpts): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.js new file mode 100644 index 0000000..ace7513 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2s = exports.compress = exports.IV = void 0; +const _blake2_js_1 = require("./_blake2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +exports.IV = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 16); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = (0, utils_js_1.rotr)(d ^ a, 8); + c = (c + d) | 0; + b = (0, utils_js_1.rotr)(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +exports.compress = compress; +class BLAKE2s extends _blake2_js_1.BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = exports.IV[0] | 0; + this.v1 = exports.IV[1] | 0; + this.v2 = exports.IV[2] | 0; + this.v3 = exports.IV[3] | 0; + this.v4 = exports.IV[4] | 0; + this.v5 = exports.IV[5] | 0; + this.v6 = exports.IV[6] | 0; + this.v7 = exports.IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = (0, utils_js_1.u32)((0, utils_js_1.toBytes)(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set((0, utils_js_1.toBytes)(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake2_js_1.SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, exports.IV[0], exports.IV[1], exports.IV[2], exports.IV[3], l ^ exports.IV[4], h ^ exports.IV[5], isLast ? ~exports.IV[6] : exports.IV[6], exports.IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +exports.blake2s = (0, utils_js_1.wrapConstructorWithOpts)((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.js.map new file mode 100644 index 0000000..ac692b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AAAA,6CAAwD;AACxD,uCAAoC;AACpC,yCAAyE;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AACL,QAAA,EAAE,GAAkB,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAEnJ,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAA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ble/hashes/blake3.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..13894cf --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,46 @@ +import { BLAKE2 } from './_blake2.js'; +import { Input, HashXOF } from './utils.js'; +export type Blake3Opts = { + dkLen?: number; + key?: Input; + context?: Input; +}; +declare class BLAKE3 extends BLAKE2 implements HashXOF { + private IV; + private flags; + private state; + private chunkPos; + private chunksDone; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): never[]; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: BLAKE3): BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export declare const blake3: { + (msg: Input, opts?: Blake3Opts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: Blake3Opts): HashXOF; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..3c339f5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,229 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake3 = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const _blake2_js_1 = require("./_blake2.js"); +const blake2s_js_1 = require("./blake2s.js"); +const utils_js_1 = require("./utils.js"); +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends _blake2_js_1.BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + (0, _assert_js_1.number)(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = (0, utils_js_1.toBytes)(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = (0, utils_js_1.u32)(key); + this.flags = flags | 16 /* Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = (0, utils_js_1.u32)(context_key); + this.flags = flags | 64 /* Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = blake2s_js_1.IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.IV[0], blake2s_js_1.IV[1], blake2s_js_1.IV[2], blake2s_js_1.IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* Flags.PARENT */; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* Flags.CHUNK_START */ : 0) | 2 /* Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..7ed8fd6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAC7D,uCAAoC;AACpC,6CAAsC;AACtC,6CAA4C;AAC5C,yCAA0F;AAe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,uCAAuC,CAAC,CAAC;QAC9E,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,GAAG,CAAC,KAAa;QACf,IAAA,mBAAM,EAAC,KAAK,CAAC,CAAC;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,IAAA,mBAAM,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACU,QAAA,MAAM,GAAmB,IAAA,qCAA0B,EAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.js new file mode 100644 index 0000000..8226391 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.js.map new file mode 100644 index 0000000..9f794e2 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAGa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.d.ts new file mode 100644 index 0000000..cebbcd1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.d.ts @@ -0,0 +1 @@ +export declare const crypto: any; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.js new file mode 100644 index 0000000..a88676d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +const nc = require("node:crypto"); +exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.js.map new file mode 100644 index 0000000..9287d27 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..f0fc54d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,46 @@ +export declare function scrypt(password: string, salt: string): Uint8Array; +export declare function pbkdf2(password: string, salt: string): Uint8Array; +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export declare function deriveMainSeed(username: string, password: string): Uint8Array; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +type ESKDF = Promise Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; +}>>; +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export declare function eskdf(username: string, password: string): ESKDF; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..bc622b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.eskdf = exports.deriveMainSeed = exports.pbkdf2 = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const hkdf_js_1 = require("./hkdf.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const scrypt_js_1 = require("./scrypt.js"); +const utils_js_1 = require("./utils.js"); +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +function scrypt(password, salt) { + return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +exports.scrypt = scrypt; +// PBKDF2-HMAC-SHA256 +function pbkdf2(password, salt) { + return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +exports.pbkdf2 = pbkdf2; +// Combines two 32-byte byte arrays +function xor32(a, b) { + (0, _assert_js_1.bytes)(a, 32); + (0, _assert_js_1.bytes)(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +exports.deriveMainSeed = deriveMainSeed; +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = (0, utils_js_1.toBytes)(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + (0, utils_js_1.createView)(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = (0, utils_js_1.toBytes)(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = (0, utils_js_1.hexToBytes)(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + (0, _assert_js_1.bytes)(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +exports.eskdf = eskdf; +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..70c49e9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":";;;AAAA,6CAAoD;AACpD,uCAAiC;AACjC,2CAAqC;AACrC,2CAAgD;AAChD,2CAAgD;AAChD,yCAAyE;AAEzE,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AAE9B,aAAa;AACb,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAFD,wBAEC;AAED,qBAAqB;AACrB,SAAgB,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,IAAA,kBAAO,EAAC,kBAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1E,CAAC;AAFD,wBAEC;AAED,mCAAmC;AACnC,SAAS,KAAK,CAAC,CAAa,EAAE,CAAa;IACzC,IAAA,kBAAW,EAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACnB,IAAA,kBAAW,EAAC,CAAC,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AAO,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC;AAvBD,sBAuBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_assert.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_assert.js new file mode 100644 index 0000000..4259cea --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_assert.js @@ -0,0 +1,37 @@ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +export { number, bool, bytes, hash, exists, output }; +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; +//# sourceMappingURL=_assert.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_assert.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_assert.js.map new file mode 100644 index 0000000..d8f294f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,EAAE,CAAC,CAAC;AACzF,CAAC;AAED,SAAS,IAAI,CAAC,CAAU;IACtB,IAAI,OAAO,CAAC,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,SAAS,KAAK,CAAC,CAAyB,EAAE,GAAG,OAAiB;IAC5D,IAAI,CAAC,CAAC,CAAC,YAAY,UAAU,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,iCAAiC,OAAO,mBAAmB,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;AAC3F,CAAC;AAQD,SAAS,IAAI,CAAC,IAAU;IACtB,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU;QACjE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACvB,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACxB,CAAC;AAED,SAAS,MAAM,CAAC,QAAa,EAAE,aAAa,GAAG,IAAI;IACjD,IAAI,QAAQ,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC5E,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACnG,CAAC;AACD,SAAS,MAAM,CAAC,GAAQ,EAAE,QAAa;IACrC,KAAK,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yDAAyD,GAAG,EAAE,CAAC,CAAC;KACjF;AACH,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAErD,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC7D,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_blake2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_blake2.js new file mode 100644 index 0000000..948e01b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_blake2.js @@ -0,0 +1,108 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, toBytes, u32 } from './utils.js'; +// Blake is based on ChaCha permutation. +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); +export class BLAKE2 extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} +//# sourceMappingURL=_blake2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_blake2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_blake2.js.map new file mode 100644 index 0000000..4222d07 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake2.js","sourceRoot":"","sources":["../src/_blake2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,IAAI,EAAS,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEvD,wCAAwC;AAExC,gGAAgG;AAChG,kBAAkB;AAClB,MAAM,CAAC,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC;IAClD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,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C,EAAE,IAAI,CAAC,CAAC;QACjC,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM;QACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,UAAU,CAAC,EAAM;QACf,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QACrE,EAAE,KAAF,EAAE,GAAK,IAAK,IAAI,CAAC,WAAmB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAM,EAAC;QAChE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtB,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;QACnB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtB,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC;QACb,OAAO,EAAE,CAAC;IACZ,CAAC;CACF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_sha2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_sha2.js new file mode 100644 index 0000000..cd26ea4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_sha2.js @@ -0,0 +1,114 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, toBytes } from './utils.js'; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +export class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +//# sourceMappingURL=_sha2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_sha2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_sha2.js.map new file mode 100644 index 0000000..1675e44 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_sha2.js","sourceRoot":"","sources":["../src/_sha2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,UAAU,EAAS,OAAO,EAAE,MAAM,YAAY,CAAC;AAE9D,yBAAyB;AACzB,SAAS,YAAY,CAAC,IAAc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AC;CACF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js new file mode 100644 index 0000000..66cce47 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js @@ -0,0 +1,62 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +export { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, }; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js.map new file mode 100644 index 0000000..b2339ed --- /dev/null +++ b/test/merkletreejs/node_mod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GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,MAAM,KAAK,GAAG,CAAC,GAAW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE,CACxF,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,OAAO,EACL,OAAO,EAAE,KAAK,EAAE,KAAK,EACrB,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAC9B,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAC9C,CAAC;AACF,kBAAkB;AAClB,MAAM,GAAG,GAAG;IACV,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/argon2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/argon2.js new file mode 100644 index 0000000..1e5a6b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/argon2.js @@ -0,0 +1,297 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; +const ARGON2_SYNC_POINTS = 4; +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +function mul(a, b) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} +function relPos(areaSize, relativePos) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} +function mul2(a, b) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 }; +} +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer +const BUF = new Uint32Array(256); +function G(a, b, c, d) { + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + BUF[i] = x[xPos + i] ^ x[yPos + i]; + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} +// Variable-Length Hash Function H' +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + let area; + if (0 == r) { + if (0 == s) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} +function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) + throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) + throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error(`Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(type, password, salt, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 /* Types.Argon2i */ || (type == 2 /* Types.Argon2id */ && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} +export const argon2d = (password, salt, opts) => argon2(0 /* Types.Argond2d */, password, salt, opts); +export const argon2i = (password, salt, opts) => argon2(1 /* Types.Argon2i */, password, salt, opts); +export const argon2id = (password, salt, opts) => argon2(2 /* Types.Argon2id */, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/argon2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/argon2.js.map new file mode 100644 index 0000000..267eb62 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,K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E,IAAW,EAAE,IAAe,EAAE,EAAE,CACxE,MAAM,yBAAiB,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2b.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2b.js new file mode 100644 index 0000000..29cecc5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2b.js @@ -0,0 +1,189 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +function G2(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} +class BLAKE2b extends BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + // Same as SHA-512, but LE + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2b(opts)); +//# sourceMappingURL=blake2b.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2b.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2b.js.map new file mode 100644 index 0000000..a448786 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["../src/blake2b.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAEnE,yBAAyB;AACzB,kBAAkB;AAClB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,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,GAAG,eAAe,CAAC,uBAAuB,CAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2s.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2s.js new file mode 100644 index 0000000..5c64991 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2s.js @@ -0,0 +1,118 @@ +import { BLAKE2, SIGMA } from './_blake2.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = /* @__PURE__ */ new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); +// Mixing function G splitted in two halfs +function G1(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +function G2(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +class BLAKE2s extends BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + // Internal state, same as SHA-256 + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts((opts) => new BLAKE2s(opts)); +//# sourceMappingURL=blake2s.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2s.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2s.js.map new file mode 100644 index 0000000..44cce78 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake2s.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,KAAK,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEzE,iBAAiB;AACjB,yFAAyF;AACzF,kBAAkB;AAClB,kBAAkB;AAClB,MAAM,CAAC,MAAM,EAAE,GAAG,eAAe,CAAA,IAAI,WAAW,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAEnJ,0CAA0C;AAC1C,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IAC/D,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,SAAS,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;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AAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CACjF,CAAC;QACJ,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IACtB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,eAAe,CAAC,uBAAuB,CAC5D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAC5B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake3.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake3.js new file mode 100644 index 0000000..af92963 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake3.js @@ -0,0 +1,226 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { u8, u32, toBytes, wrapXOFConstructorWithOpts } from './utils.js'; +const SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 { + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.flags = 0 | 0; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + this.stack = []; + // Output + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; // index of output chunk + this.enableXOF = true; + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) + throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | 16 /* Flags.KEYED_HASH */; + } + else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, 32 /* Flags.DERIVE_KEY_CONTEXT */) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | 64 /* Flags.DERIVE_KEY_MATERIAL */; + } + else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() { } + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= 1 /* Flags.CHUNK_START */; + if (this.chunkPos === 15 || isLast) + flags |= 2 /* Flags.CHUNK_END */; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4 /* Flags.PARENT */, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) + i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], IV[0], IV[1], IV[2], IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | 8 /* Flags.ROOT */; + if (this.stack.length) { + flags |= 4 /* Flags.PARENT */; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? 1 /* Flags.CHUNK_START */ : 0) | 2 /* Flags.CHUNK_END */; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts((opts) => new BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake3.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake3.js.map new file mode 100644 index 0000000..50f489b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE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AAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC9E,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,GAAG,CAAC,KAAa;QACf,MAAM,CAAC,KAAK,CAAC,CAAC;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,CAAC;IACD,UAAU,CAAC,GAAe;QACxB,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,OAAO,GAAG,CAAC;IACb,CAAC;IACD,MAAM;QACJ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,0BAA0B,CAC9D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAC3B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/crypto.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/crypto.js new file mode 100644 index 0000000..8d499a0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/crypto.js @@ -0,0 +1,2 @@ +export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/crypto.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/crypto.js.map new file mode 100644 index 0000000..4b4fd3d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js new file mode 100644 index 0000000..241f1da --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; +//# sourceMappingURL=cryptoNode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js.map new file mode 100644 index 0000000..f7ab75e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,4BAA4B;AAC5B,iDAAiD;AACjD,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE,CAAC,CAAC,CAAE,EAAE,CAAC,SAAiB,CAAC,CAAC,CAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/eskdf.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/eskdf.js new file mode 100644 index 0000000..13253eb --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/eskdf.js @@ -0,0 +1,155 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; +// Scrypt KDF +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays +function xor32(a, b) { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/eskdf.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/eskdf.js.map new file mode 100644 index 0000000..f53eebe --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble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AAC,CAAC,CAAC,GAAG,CAAC;IACpF,CAAC;IACD,SAAS,MAAM;QACb,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,kBAAkB;IAClB,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;SACvD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hkdf.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hkdf.js new file mode 100644 index 0000000..8fbdac8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hkdf.js @@ -0,0 +1,72 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { toBytes } from './utils.js'; +import { hmac } from './hmac.js'; +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash, ikm, salt) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash, prk, info, length = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hkdf.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hkdf.js.map new file mode 100644 index 0000000..868bdb5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,kBAAkB;AAClB,qDAAqD;AAErD;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY;IAC3D,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,0DAA0D;IACzH,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,mCAAmC;AACnC,MAAM,YAAY,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzD,MAAM,YAAY,GAAG,eAAe,CAAC,IAAI,UAAU,EAAE,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,IAAW,EAAE,GAAU,EAAE,IAAY,EAAE,SAAiB,EAAE;IAC/E,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,YAAY,CAAC,MAAM,CAAC,CAAC;IACrB,IAAI,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACtF,MAAM,MAAM,GAAG,IAAI,C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,MAAM,IAAI,GAAG,CAClB,IAAW,EACX,GAAU,EACV,IAAuB,EACvB,IAAuB,EACvB,MAAc,EACd,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js new file mode 100644 index 0000000..520f776 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js @@ -0,0 +1,77 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assertExists(this); + assertBytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js.map new file mode 100644 index 0000000..e04539d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAChG,OAAO,EAAE,IAAI,EAAgB,OAAO,EAAE,MAAM,YAAY,CAAC;AACzD,kBAAkB;AAClB,MAAM,OAAO,IAAwB,SAAQ,IAAa;IAQxD,YAAY,IAAW,EAAE,IAAW;QAClC,KAAK,EAAE,CAAC;QAJF,aAAQ,GAAG,KAAK,CAAC;QACjB,cAAS,GAAG,KAAK,CAAC;QAIxB,UAAU,CAAC,IAAI,CAAC,CAAC;QACjB,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MA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EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACpD,IAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/index.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/index.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/index.js.map new file mode 100644 index 0000000..90172aa --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/package.json b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/package.json new file mode 100644 index 0000000..f42e46b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/package.json @@ -0,0 +1,10 @@ +{ + "type": "module", + "sideEffects": false, + "browser": { + "node:crypto": false + }, + "node": { + "./crypto": "./esm/cryptoNode.js" + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js new file mode 100644 index 0000000..3f0c11f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js @@ -0,0 +1,86 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { createView, toBytes, checkOpts, asyncLoop } from './utils.js'; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +export async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js.map new file mode 100644 index 0000000..b404934 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAsB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,UAAU,CAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,YAAY,CAAC,CAAC,CAAC,CAAC;IAChB,YAAY,CAAC,KAAK,CAAC,CAAC;IACpB,YAAY,CAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;I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Y,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/ripemd160.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/ripemd160.js new file mode 100644 index 0000000..1e23958 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/ripemd160.js @@ -0,0 +1,104 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/ripemd160.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/ripemd160.js.map new file mode 100644 index 0000000..7964756 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../src/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAA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/@noble/hashes/esm/scrypt.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/scrypt.js new file mode 100644 index 0000000..37012f5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/scrypt.js @@ -0,0 +1,218 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, u32 } from './utils.js'; +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/scrypt.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/scrypt.js.map new file mode 100644 index 0000000..0fa6c1f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../src/scrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAS,GAAG,EAAE,MAAM,YAAY,CAAC;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAA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AC;QACH,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,SAAS,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACjC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha1.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha1.js new file mode 100644 index 0000000..563bff5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha1.js @@ -0,0 +1,87 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha1.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha1.js.map new file mode 100644 index 0000000..55249de --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChG,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,oDAAoD;AACpD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC;IACzC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC3D,CAAC,CAAC;AAEH,4DAA4D;AAC5D,mDAAmD;AACnD,MAAM,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GAAG,CAAC,CAAC;YACnD,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAChB,CAAC,GAAG,CAAC,CAAC;YACN,CAAC,GAAG,CAAC,CAAC;SACP;QACD,qDAAqD;QACrD,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha256.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha256.js new file mode 100644 index 0000000..e92203c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha256.js @@ -0,0 +1,126 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha256.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha256.js.map new file mode 100644 index 0000000..0236fa8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../src/sha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,gEAAgE;AAChE,0DAA0D;AAE1D,oBAAoB;AACpB,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,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KAAK,EAAE,CAAC;QATV,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3-addons.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3-addons.js new file mode 100644 index 0000000..449b3a3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3-addons.js @@ -0,0 +1,347 @@ +import { number as assertNumber } from './_assert.js'; +import { toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; +import { Keccak } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => wrapConstructorWithOpts((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + constructor(capacity) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3-addons.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3-addons.js.map new file mode 100644 index 0000000..7600a9a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["../src/sha3-addons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAS,OAAO,EAAE,uBAAuB,EAAE,GAAG,EAAiB,MAAM,YAAY,CAAC;AACzF,OAAO,EAAE,MAAM,EAAa,MAAM,WAAW,CAAC;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7C,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,CAAS;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;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C,GAAG,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,oFAAoF;IACpF,MAAM;QACJ,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QACvF,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE;YAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3.js new file mode 100644 index 0000000..0879d36 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3.js @@ -0,0 +1,208 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js'; +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +export class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3.js.map new file mode 100644 index 0000000..32d5b16 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.js","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EACL,IAAI,EACJ,GAAG,EAEH,OAAO,EACP,eAAe,EACf,0BAA0B,GAE3B,MAAM,YAAY,CAAC;AAEpB,oGAAoG;AACpG,iCAAiC;AAEjC,2CAA2C;AAC3C,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAmC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtF,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,C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/sha512.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha512.js new file mode 100644 index 0000000..f938b6d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha512.js @@ -0,0 +1,231 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha512.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha512.js.map new file mode 100644 index 0000000..4c9e3e6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,GAAG,MAAM,WAAW,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC;IAC9D,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,oBAAoB,EAAE,oBA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S,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,MAAM,GAAG,eAAe,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js new file mode 100644 index 0000000..80c0949 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js @@ -0,0 +1,154 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +// For runtime check if class implements interface +export class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +const toStr = {}.toString; +export function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +export function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +export function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +export function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js.map new file mode 100644 index 0000000..19d87a9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAM9C,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AACjE,+BAA+B;AAC/B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAClG,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,GAAe,EAAE,EAAE,CACrC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;AAE9E,qBAAqB;AACrB,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAe,EAAE,EAAE,CAC5C,IAAI,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAE3D,+DAA+D;AAC/D,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,EAAE,GA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AC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,QAAkC;IAElC,MAAM,KAAK,GAAG,CAAC,GAAU,EAAE,IAAQ,EAAc,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjG,MAAM,GAAG,GAAG,QAAQ,CAAC,EAAO,CAAC,CAAC;IAC9B,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;IAChC,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,KAAK,CAAC,MAAM,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAC1D,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..e1d683b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,26 @@ +import { CHash, Input } from './utils.js'; +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export declare function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array; +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export declare function expand(hash: CHash, prk: Input, info?: Input, length?: number): Uint8Array; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export declare const hkdf: (hash: CHash, ikm: Input, salt: Input | undefined, info: Input | undefined, length: number) => Uint8Array; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..021b68e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hkdf = exports.expand = exports.extract = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const hmac_js_1 = require("./hmac.js"); +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +function extract(hash, ikm, salt) { + (0, _assert_js_1.hash)(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm)); +} +exports.extract = extract; +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +function expand(hash, prk, info, length = 32) { + (0, _assert_js_1.hash)(hash); + (0, _assert_js_1.number)(length); + if (length > 255 * hash.outputLen) + throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) + info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac_js_1.hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} +exports.expand = expand; +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +exports.hkdf = hkdf; +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..7790e7c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/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,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAN7C,QAAA,IAAI,QAMyC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..63db656 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,25 @@ +import { Hash, CHash, Input } from './utils.js'; +export declare class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished; + private destroyed; + constructor(hash: CHash, _key: Input); + update(buf: Input): this; + digestInto(out: Uint8Array): void; + digest(): Uint8Array; + _cloneInto(to?: HMAC): HMAC; + destroy(): void; +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export declare const hmac: { + (hash: CHash, key: Input, message: Input): Uint8Array; + create(hash: CHash, key: Input): HMAC; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..0fc2d02 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.hash)(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + (0, _assert_js_1.exists)(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.bytes)(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..798c5fa --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js.map @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AAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACxE,EAAE,GAAG,EAAU,CAAC;QAChB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAnED,oBAmEC;AAED;;;;;GAKG;AACI,MAAM,IAAI,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,OAAc,EAAc,EAAE,CAC1E,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AADvC,QAAA,IAAI,QACmC;AACpD,YAAI,CAAC,MAAM,GAAG,CAAC,IAAW,EAAE,GAAU,EAAE,EAAE,CAAC,IAAI,IAAI,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..2299d7f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.js @@ -0,0 +1,3 @@ +"use strict"; +throw new Error('noble-hashes have no entry-point: consult README for usage'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..b71bae6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/package.json b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..9a668d3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/package.json @@ -0,0 +1,174 @@ +{ + "name": "@noble/hashes", + "version": "1.3.2", + "description": "Audited & minimal 0-dependency JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2, Scrypt", + "files": [ + "/*.js", + "/*.d.ts", + "/*.js.map", + "esm", + "src/*.ts" + ], + "scripts": { + "bench": "node benchmark/index.js noble", + "bench:all": "node benchmark/index.js", + "bench:install": "cd benchmark && npm install && cd ../../", + "build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", + "build:release": "cd build; npm i; npm run build", + "build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null", + "lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.js", + "test:dos": "node test/slow-dos.test.js", + "test:big": "node test/slow-big.test.js" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/noble/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/noble-hashes.git" + }, + "license": "MIT", + "sideEffects": false, + "browser": { + "node:crypto": false, + "./crypto": "./crypto.js" + }, + "devDependencies": { + "micro-bmark": "0.3.1", + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "engines": { + "node": ">= 16" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./crypto": { + "types": "./crypto.d.ts", + "node": { + "import": "./esm/cryptoNode.js", + "default": "./cryptoNode.js" + }, + "import": "./esm/crypto.js", + "default": "./crypto.js" + }, + "./_assert": { + "types": "./_assert.d.ts", + "import": "./esm/_assert.js", + "default": "./_assert.js" + }, + "./_sha2": { + "types": "./_sha2.d.ts", + "import": "./esm/_sha2.js", + "default": "./_sha2.js" + }, + "./argon2": { + "types": "./argon2.d.ts", + "import": "./esm/argon2.js", + "default": "./argon2.js" + }, + "./blake2b": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./blake2s": { + "types": "./blake2s.d.ts", + "import": "./esm/blake2s.js", + "default": "./blake2s.js" + }, + "./blake3": { + "types": "./blake3.d.ts", + "import": "./esm/blake3.js", + "default": "./blake3.js" + }, + "./eskdf": { + "types": "./eskdf.d.ts", + "import": "./esm/eskdf.js", + "default": "./eskdf.js" + }, + "./hkdf": { + "types": "./hkdf.d.ts", + "import": "./esm/hkdf.js", + "default": "./hkdf.js" + }, + "./hmac": { + "types": "./hmac.d.ts", + "import": "./esm/hmac.js", + "default": "./hmac.js" + }, + "./pbkdf2": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./ripemd160": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./sha1": { + "types": "./sha1.d.ts", + "import": "./esm/sha1.js", + "default": "./sha1.js" + }, + "./sha3-addons": { + "types": "./sha3-addons.d.ts", + "import": "./esm/sha3-addons.js", + "default": "./sha3-addons.js" + }, + "./sha3": { + "types": "./sha3.d.ts", + "import": "./esm/sha3.js", + "default": "./sha3.js" + }, + "./sha256": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + } + }, + "keywords": [ + "sha", + "sha2", + "sha3", + "sha256", + "sha512", + "keccak", + "kangarootwelve", + "ripemd160", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..42f691c --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,15 @@ +import { CHash, Input } from './utils.js'; +export type Pbkdf2Opt = { + c: number; + dkLen?: number; + asyncTick?: number; +}; +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export declare function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Uint8Array; +export declare function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt): Promise; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..a667178 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2Async = exports.pbkdf2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const hmac_js_1 = require("./hmac.js"); +const utils_js_1 = require("./utils.js"); +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + (0, _assert_js_1.hash)(hash); + const opts = (0, utils_js_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + (0, _assert_js_1.number)(c); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0, utils_js_1.toBytes)(_password); + const salt = (0, utils_js_1.toBytes)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac_js_1.hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2 = pbkdf2; +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0, utils_js_1.createView)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await (0, utils_js_1.asyncLoop)(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +exports.pbkdf2Async = pbkdf2Async; +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..a8f30b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,6CAA0E;AAC1E,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;IACjB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,IAAA,mBAAY,EAAC,CAAC,CAAC,CAAC;IAChB,IAAA,mBAAY,EAAC,KAAK,CAAC,CAAC;IACpB,IAAA,mBAAY,EAAC,SAAS,CAAC,CAAC;IACxB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,0CAA0C;IAC1C,MAAM,GAAG,GAAG,cAAI,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACxC,MAAM,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39/node_modules/@noble/hashes/ripemd160.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.d.ts new file mode 100644 index 0000000..92e662f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.d.ts @@ -0,0 +1,24 @@ +import { SHA2 } from './_sha2.js'; +export declare class RIPEMD160 extends SHA2 { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export declare const ripemd160: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.js new file mode 100644 index 0000000..7d6e057 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.js.map new file mode 100644 index 0000000..396a517 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["src/ripemd160.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,0DAA0D;AAC1D,6EAA6E;AAC7E,MAAM,GAAG,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACnG,MAAM,EAAE,GAAG,eAAe,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACxE,MAAM,EAAE,GAAG,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC3D,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;AAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;IAAE,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;QAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAExF,MAAM,MAAM,GAAG,eAAe,CAAC;IAC7B,CAAC,EAAE,E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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAhED,8BAgEC;AAED;;;GAGG;AACU,QAAA,SAAS,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..82485b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,29 @@ +import { Input } from './utils.js'; +export type ScryptOpts = { + N: number; + r: number; + p: number; + dkLen?: number; + asyncTick?: number; + maxmem?: number; + onProgress?: (progress: number) => void; +}; +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export declare function scrypt(password: Input, salt: Input, opts: ScryptOpts): Uint8Array; +/** + * Scrypt KDF from RFC 7914. + */ +export declare function scryptAsync(password: Input, salt: Input, opts: ScryptOpts): Promise; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..2f118db --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,223 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptAsync = exports.scrypt = void 0; +const _assert_js_1 = require("./_assert.js"); +const sha256_js_1 = require("./sha256.js"); +const pbkdf2_js_1 = require("./pbkdf2.js"); +const utils_js_1 = require("./utils.js"); +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = (0, utils_js_1.checkOpts)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + (0, _assert_js_1.number)(N); + (0, _assert_js_1.number)(r); + (0, _assert_js_1.number)(p); + (0, _assert_js_1.number)(dkLen); + (0, _assert_js_1.number)(asyncTick); + (0, _assert_js_1.number)(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0, utils_js_1.u32)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N)); + const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scrypt = scrypt; +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await (0, utils_js_1.asyncLoop)(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +exports.scryptAsync = scryptAsync; +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..873dc15 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,2CAAqC;AACrC,2CAAqC;AACrC,yCAA8D;AAE9D,sBAAsB;AAEtB,yBAAyB;AACzB,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAEnE,gDAAgD;AAChD,oEAAoE;AACpE,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAiB,EACjB,EAAU,EACV,KAAkB,EAClB,EAAU,EACV,GAAgB,EAChB,EAAU;IAEV,yCAAyC;IACzC,aAAa;IACb,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACnE,IA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AG,EAAE;YACrC,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,2BAA2B;YACzE,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,uBAAuB;QACvE,UAAU,EAAE,CAAC;QACb,MAAM,IAAA,oBAAS,EAAC,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACjC,kDAAkD;YAClD,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,gCAAgC;YAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,iBAAiB;YACtG,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC;AAzBD,kCAyBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.d.ts new file mode 100644 index 0000000..d9cb132 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.d.ts @@ -0,0 +1,21 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA1 extends SHA2 { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha1: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.js new file mode 100644 index 0000000..10c6953 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.js.map new file mode 100644 index 0000000..4b0ccbd --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,yCAA6C;AAE7C,qCAAqC;AACrC,2EAA2E;AAE3E,WAAW;AACX,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC,IAA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AG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;IACS,UAAU;QAClB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,IAAI,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.d.ts new file mode 100644 index 0000000..3e1491d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.d.ts @@ -0,0 +1,34 @@ +import { SHA2 } from './_sha2.js'; +declare class SHA256 extends SHA2 { + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + G: number; + H: number; + constructor(); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export declare const sha256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.js new file mode 100644 index 0000000..24fe574 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.js.map new file mode 100644 index 0000000..a2fd853 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256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GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;CACF;AACD,4EAA4E;AAC5E,MAAM,MAAO,SAAQ,MAAM;IASzB;QACE,KAAK,EAAE,CAAC;QATV,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QACnB,MAAC,GAAG,UAAU,GAAG,CAAC,CAAC;QAGjB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAED;;;GAGG;AACU,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..cf7c3a0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,138 @@ +import { Input, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +export type cShakeOpts = ShakeOpts & { + personalization?: Input; + NISTfn?: Input; +}; +export declare const cshake128: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +export declare const cshake256: { + (msg: Input, opts?: cShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: cShakeOpts): Hash; +}; +declare class KMAC extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: KMAC): KMAC; + clone(): KMAC; +} +export declare const kmac128: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac128xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +export declare const kmac256xof: { + (key: Input, message: Input, opts?: cShakeOpts): Uint8Array; + create(key: Input, opts?: cShakeOpts): KMAC; +}; +declare class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: cShakeOpts); + protected finish(): void; + _cloneInto(to?: TupleHash): TupleHash; + clone(): TupleHash; +} +export declare const tuplehash128: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash128xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +export declare const tuplehash256xof: { + (messages: Input[], opts?: cShakeOpts): Uint8Array; + create(opts?: cShakeOpts): TupleHash; +}; +type ParallelOpts = cShakeOpts & { + blockLen?: number; +}; +declare class ParallelHash extends Keccak implements HashXOF { + protected leafCons: () => Hash; + private leafHash?; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: ParallelOpts); + protected finish(): void; + _cloneInto(to?: ParallelHash): ParallelHash; + destroy(): void; + clone(): ParallelHash; +} +export declare const parallelhash128: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash128xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export declare const parallelhash256xof: { + (message: Input, opts?: ParallelOpts): Uint8Array; + create(opts?: ParallelOpts): ParallelHash; +}; +export type KangarooOpts = { + dkLen?: number; + personalization?: Input; +}; +declare class KangarooTwelve extends Keccak implements HashXOF { + protected leafLen: number; + readonly chunkLen = 8192; + private leafHash?; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts); + update(data: Input): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: KangarooTwelve): KangarooTwelve; + clone(): KangarooTwelve; +} +export declare const k12: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +export declare const m14: { + (msg: Input, opts?: KangarooOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: KangarooOpts): Hash; +}; +declare class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number); + keccak(): void; + update(data: Input): this; + feed(data: Input): this; + protected finish(): void; + digestInto(_out: Uint8Array): Uint8Array; + fetch(bytes: number): Uint8Array; + forget(): void; + _cloneInto(to?: KeccakPRG): KeccakPRG; + clone(): KeccakPRG; +} +export declare const keccakprg: (capacity?: number) => KeccakPRG; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..e5317b1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,351 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccakprg = exports.m14 = exports.k12 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.cshake256 = exports.cshake128 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +const sha3_js_1 = require("./sha3.js"); +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} +function rightEncode(n) { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const toBytesOptional = (buf) => (buf !== undefined ? (0, utils_js_1.toBytes)(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) + return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) + return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} +const gencShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => cshakePers(new sha3_js_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); +exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); +class KMAC extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = (0, utils_js_1.toBytes)(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = (0, utils_js_1.u32)(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +exports.kmac128 = (() => genKmac(168, 128 / 8))(); +exports.kmac256 = (() => genKmac(136, 256 / 8))(); +exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); +exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + finish() { + if (!this.finished) + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + const tuple = (messages, opts) => { + const h = tuple.create(opts); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +exports.tuplehash128 = (() => genTuple(168, 128 / 8))(); +exports.tuplehash256 = (() => genTuple(136, 256 / 8))(); +exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))(); +exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))(); +class ParallelHash extends sha3_js_1.Keccak { + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + this.leafCons = leafCons; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B || (B = 8); + (0, _assert_js_1.number)(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to) { + to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF)); + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + return parallel; +} +exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))(); +exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))(); +exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))(); +exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))(); +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) + res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} +const EMPTY = new Uint8Array([]); +class KangarooTwelve extends sha3_js_1.Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; // Position of current block in chunk + this.chunksDone = 0; // How many chunks we already have + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = (0, utils_js_1.toBytes)(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new sha3_js_1.Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +exports.k12 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))(); +// MarsupilamiFourteen +exports.m14 = (() => (0, utils_js_1.wrapConstructorWithOpts)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))(); +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends sha3_js_1.Keccak { + constructor(capacity) { + (0, _assert_js_1.number)(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data) { + return this.update(data); + } + finish() { } + digestInto(_out) { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes) { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) + throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to || (to = new KeccakPRG(1600 - rate)); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +const keccakprg = (capacity = 254) => new KeccakPRG(capacity); +exports.keccakprg = keccakprg; +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..7232b4f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":";;;AAAA,6CAAsD;AACtD,yCAAyF;AACzF,uCAA8C;AAC9C,kCAAkC;AAClC,SAAS,UAAU,CAAC,CAAS;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACvB,CAAC,KAAK,CAAC,CAAC;IACR,OAAO,CAAC,GAA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AC;IAClF,CAAC;IACD,KAAK,CAAC,KAAa;QACjB,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,oFAAoF;IACpF,MAAM;QACJ,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QACvF,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE;YAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,UAAU,CAAC,EAAc;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QACtB,EAAE,KAAF,EAAE,GAAK,IAAI,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC,EAAC;QAClC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAEM,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;AAAxD,QAAA,SAAS,aAA+C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..2107cf6 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,97 @@ +import { Hash, Input, HashXOF } from './utils.js'; +export declare function keccakP(s: Uint32Array, rounds?: number): void; +export declare class Keccak extends Hash implements HashXOF { + blockLen: number; + suffix: number; + outputLen: number; + protected enableXOF: boolean; + protected rounds: number; + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + protected keccak(): void; + update(data: Input): this; + protected finish(): void; + protected writeInto(out: Uint8Array): Uint8Array; + xofInto(out: Uint8Array): Uint8Array; + xof(bytes: number): Uint8Array; + digestInto(out: Uint8Array): Uint8Array; + digest(): Uint8Array; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +export declare const sha3_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export declare const sha3_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const sha3_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_224: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export declare const keccak_256: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_384: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare const keccak_512: { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export type ShakeOpts = { + dkLen?: number; +}; +export declare const shake128: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; +export declare const shake256: { + (msg: Input, opts?: ShakeOpts | undefined): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: ShakeOpts): HashXOF>; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..e1b7530 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,213 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = require("./_assert.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0, _assert_js_1.number)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0, _assert_js_1.exists)(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..fd68950 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hash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,QAAA,QAAQ,GAAmB,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACxD,QAAA,QAAQ,GAAmB,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.d.ts new file mode 100644 index 0000000..b8ba9b0 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.d.ts @@ -0,0 +1,66 @@ +import { SHA2 } from './_sha2.js'; +export declare class SHA512 extends SHA2 { + Ah: number; + Al: number; + Bh: number; + Bl: number; + Ch: number; + Cl: number; + Dh: number; + Dl: number; + Eh: number; + El: number; + Fh: number; + Fl: number; + Gh: number; + Gl: number; + Hh: number; + Hl: number; + constructor(); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +export declare const sha512: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_224: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha512_256: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; +export declare const sha384: { + (msg: import("./utils.js").Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): import("./utils.js").Hash; +}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.js new file mode 100644 index 0000000..1d3482a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const _u64_js_1 = require("./_u64.js"); +const utils_js_1 = require("./utils.js"); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js_1.default.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends _sha2_js_1.SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7); + const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6); + const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41); + const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39); + const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl); + Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +exports.SHA512 = SHA512; +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +exports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512()); +exports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224()); +exports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256()); +exports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384()); +//# sourceMappingURL=sha512.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.js.map new file mode 100644 index 0000000..700a8e7 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/sha512.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha512.js","sourceRoot":"","sources":["src/sha512.ts"],"names":[],"mappings":";;;AAAA,yCAAkC;AAClC,uCAA4B;AAC5B,yCAA6C;AAE7C,0GAA0G;AAC1G,kBAAkB;AAClB,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,iBAAG,CAAC,KAAK,CAAC;IAC9D,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,oBAAoB;IACtF,oBAAoB,EAAE,o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AG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QACpB,OAAE,GAAG,UAAU,GAAG,CAAC,CAAC;QAIlB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAEY,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;AAC7D,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,UAAU,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;AACrE,QAAA,MAAM,GAAmB,IAAA,0BAAe,EAAC,GAAG,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_assert.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_assert.ts new file mode 100644 index 0000000..11d28ea --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_assert.ts @@ -0,0 +1,43 @@ +function number(n: number) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); +} + +function bool(b: boolean) { + if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`); +} + +function bytes(b: Uint8Array | undefined, ...lengths: number[]) { + if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} + +type Hash = { + (data: Uint8Array): Uint8Array; + blockLen: number; + outputLen: number; + create: any; +}; +function hash(hash: Hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} + +function exists(instance: any, checkFinished = true) { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} +function output(out: any, instance: any) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +export { number, bool, bytes, hash, exists, output }; + +const assert = { number, bool, bytes, hash, exists, output }; +export default assert; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_blake2.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_blake2.ts new file mode 100644 index 0000000..6aa4a74 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_blake2.ts @@ -0,0 +1,128 @@ +import { number, exists, output } from './_assert.js'; +import { Hash, Input, toBytes, u32 } from './utils.js'; + +// Blake is based on ChaCha permutation. + +// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. +// prettier-ignore +export const SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, +]); + +export type BlakeOpts = { + dkLen?: number; + key?: Input; + salt?: Input; + personalization?: Input; +}; + +export abstract class BLAKE2> extends Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected length: number = 0; + protected pos: number = 0; + protected finished = false; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + opts: BlakeOpts = {}, + keyLen: number, + saltLen: number, + persLen: number + ) { + super(); + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== undefined && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if (opts.personalization !== undefined && opts.personalization.length !== persLen) + throw new Error(`personalization must be ${persLen} byte long or undefined`); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data: Input) { + exists(this); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // full block && aligned to 4 bytes && not last in input + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_sha2.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_sha2.ts new file mode 100644 index 0000000..bd99103 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_sha2.ts @@ -0,0 +1,118 @@ +import { exists, output } from './_assert.js'; +import { Hash, createView, Input, toBytes } from './utils.js'; + +// Polyfill for Safari 14 +function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} + +// Base SHA2 class (RFC 6234) +export abstract class SHA2> extends Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor( + readonly blockLen: number, + public outputLen: number, + readonly padOffset: number, + readonly isLE: boolean + ) { + super(); + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: Input): this { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out: Uint8Array) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_u64.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..efc55b4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,77 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); + +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n: bigint, le = false) { + if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} + +function split(lst: bigint[], le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} + +const toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h: number, _l: number, s: number) => h >>> s; +const shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h: number, l: number) => l; +const rotr32L = (h: number, _l: number) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s)); + +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah: number, Al: number, Bh: number, Bl: number) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low: number, Ah: number, Bh: number, Ch: number) => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al: number, Bl: number, Cl: number, Dl: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +export { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +export default u64; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/argon2.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..d727b0f --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,374 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, u8, u32 } from './utils.js'; +import { blake2b } from './blake2b.js'; +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.js'; + +// Experimental Argon2 RFC 9106 implementation. It may be removed at any time. +const enum Types { + Argond2d = 0, + Argon2i = 1, + Argon2id = 2, +} + +const ARGON2_SYNC_POINTS = 4; + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); + +function mul(a: number, b: number) { + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF = ((ll >>> 16) + (hl & 0xffff) + lh) | 0; + const h = ((hl >>> 16) + (BUF >>> 16) + hh) | 0; + return { h, l: (BUF << 16) | (ll & 0xffff) }; +} + +function relPos(areaSize: number, relativePos: number) { + // areaSize - 1 - ((areaSize * ((relativePos ** 2) >>> 32)) >>> 32) + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; +} + +function mul2(a: number, b: number) { + // 2 * a * b (via shifts) + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer +const BUF = new Uint32Array(256); + +function G(a: number, b: number, c: number, d: number) { + let Al = BUF[2*a], Ah = BUF[2*a + 1]; // prettier-ignore + let Bl = BUF[2*b], Bh = BUF[2*b + 1]; // prettier-ignore + let Cl = BUF[2*c], Ch = BUF[2*c + 1]; // prettier-ignore + let Dl = BUF[2*d], Dh = BUF[2*d + 1]; // prettier-ignore + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: Uint32Array, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) BUF[i] = x[xPos + i] ^ x[yPos + i]; + + // columns + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // rows + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = BUF[i] ^ x[xPos + i] ^ x[yPos + i]; +} + +// Variable-Length Hash Function H' +function Hp(A: Uint32Array, dkLen: number) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // First block + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) out.set((V = blake2b(V)).subarray(0, 32), pos); + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); +} + +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + // NOTE: check about overflows here + // absPos = (startPos + relPos) % laneLength; + return (startPos + rel) % laneLen; +} + +// RFC 9106 +export type ArgonOpts = { + t: number; // Time cost, iterations count + m: number; // Memory cost (in KB) + p: number; // Parallelization parameter + version?: number; // Default: 0x13 (19) + key?: Input; // Optional key + personalization?: Input; // Optional arbitrary extra data + dkLen?: number; // Desired number of returned bytes + asyncTick?: number; // Maximum time in ms for which async function can block execution + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +function argon2Init(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = { + ...opts, + version: opts.version || 0x13, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + // Validation + assertNumber(p); + assertNumber(dkLen); + assertNumber(m); + assertNumber(t); + assertNumber(version); + if (dkLen < 4 || dkLen >= 2 ** 32) throw new Error('Argon2: dkLen should be at least 4 bytes'); + if (p < 1 || p >= 2 ** 32) throw new Error('Argon2: p (parallelism) should be at least 1'); + if (t < 1 || t >= 2 ** 32) throw new Error('Argon2: t (iterations) should be at least 1'); + if (m < 8 * p) throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error('Argon2: password should be less than 4 GB'); + salt = toBytes(salt); + if (salt.length < 8) throw new Error('Argon2: salt should be at least 8 bytes'); + key = toBytesOptional(key); + personalization = toBytesOptional(personalization); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // H0 + const h = blake2b.create({}); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + + // 256 u32 = 1024 (BLOCK_SIZE) + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32` + ); + } + const B = new Uint32Array(memUsed); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock }; +} + +function argon2Output(B: Uint32Array, p: number, laneLen: number, dkLen: number) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); +} + +function processBlock( + B: Uint32Array, + address: Uint32Array, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // address block + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2(type: Types, password: Input, salt: Input, opts: ArgonOpts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + type, + password, + salt, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == Types.Argon2i || (type == Types.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); +} + +export const argon2d = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argond2d, password, salt, opts); +export const argon2i = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2i, password, salt, opts); +export const argon2id = (password: Input, salt: Input, opts: ArgonOpts) => + argon2(Types.Argon2id, password, salt, opts); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake2b.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake2b.ts new file mode 100644 index 0000000..5784742 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake2b.ts @@ -0,0 +1,205 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import u64 from './_u64.js'; +import { toBytes, u32, wrapConstructorWithOpts } from './utils.js'; + +// Same as SHA-512 but LE +// prettier-ignore +const IV = /* @__PURE__ */ new Uint32Array([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19 +]); +// Temporary buffer +const BUF = /* @__PURE__ */ new Uint32Array(32); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +function G2(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BUF[2 * a], Ah = BUF[2 * a + 1]; // prettier-ignore + let Bl = BUF[2 * b], Bh = BUF[2 * b + 1]; // prettier-ignore + let Cl = BUF[2 * c], Ch = BUF[2 * c + 1]; // prettier-ignore + let Dl = BUF[2 * d], Dh = BUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); +} + +class BLAKE2b extends BLAKE2 { + // Same as SHA-512, but LE + private v0l = IV[0] | 0; + private v0h = IV[1] | 0; + private v1l = IV[2] | 0; + private v1h = IV[3] | 0; + private v2l = IV[4] | 0; + private v2h = IV[5] | 0; + private v3l = IV[6] | 0; + private v3h = IV[7] | 0; + private v4l = IV[8] | 0; + private v4h = IV[9] | 0; + private v5l = IV[10] | 0; + private v5h = IV[11] | 0; + private v6l = IV[12] | 0; + private v6h = IV[13] | 0; + private v7l = IV[14] | 0; + private v7h = IV[15] | 0; + + constructor(opts: BlakeOpts = {}) { + super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16); + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let {v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h} = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + this.get().forEach((v, i) => (BUF[i] = v)); // First half from state. + BUF.set(IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; // Low word of the offset. + BUF[25] = IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2b = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2b(opts) +); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake2s.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake2s.ts new file mode 100644 index 0000000..a609886 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake2s.ts @@ -0,0 +1,136 @@ +import { BLAKE2, BlakeOpts, SIGMA } from './_blake2.js'; +import { fromBig } from './_u64.js'; +import { rotr, toBytes, wrapConstructorWithOpts, u32 } from './utils.js'; + +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) +// same as SHA-256 +// prettier-ignore +export const IV = /* @__PURE__ */new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); + +// Mixing function G splitted in two halfs +function G1(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +function G2(a: number, b: number, c: number, d: number, x: number) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +// prettier-ignore +export function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +class BLAKE2s extends BLAKE2 { + // Internal state, same as SHA-256 + private v0 = IV[0] | 0; + private v1 = IV[1] | 0; + private v2 = IV[2] | 0; + private v3 = IV[3] | 0; + private v4 = IV[4] | 0; + private v5 = IV[5] | 0; + private v6 = IV[6] | 0; + private v7 = IV[7] | 0; + + constructor(opts: BlakeOpts = {}) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8); + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean) { + const { h, l } = fromBig(BigInt(this.length)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + IV[0], IV[1], IV[2], IV[3], l ^ IV[4], h ^ IV[5], isLast ? ~IV[6] : IV[6], IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b. + * @param msg - message that would be hashed + * @param opts - dkLen, key, salt, personalization + */ +export const blake2s = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2s(opts) +); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake3.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..01d7d54 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,250 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { fromBig } from './_u64.js'; +import { BLAKE2 } from './_blake2.js'; +import { compress, IV } from './blake2s.js'; +import { Input, u8, u32, toBytes, HashXOF, wrapXOFConstructorWithOpts } from './utils.js'; + +// Blake3 is single-option Blake2 with reduced security (round count). + +// Flag bitset +const enum Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +} + +const SIGMA: Uint8Array = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +// - key: is 256-bit key +// - context: string should be hardcoded, globally unique, and application - specific. +// A good default format for the context string is "[application] [commit timestamp] [purpose]" +// - Only one of 'key' (keyed mode) or 'context' (derive key mode) can be used at same time +export type Blake3Opts = { dkLen?: number; key?: Input; context?: Input }; + +// Why is this so slow? It should be 6x faster than blake2b. +// - There is only 30% reduction in number of rounds from blake2s +// - This function uses tree mode to achive parallelisation via SIMD and threading, +// however in JS we don't have threads and SIMD, so we get only overhead from tree structure +// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more +// complicated, which we are trying to avoid, since this library is intended to be used +// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes), +// which won't really benefit small inputs. +class BLAKE3 extends BLAKE2 implements HashXOF { + private IV: Uint32Array; + private flags = 0 | 0; + private state: Uint32Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + private chunkOut = 0; // index of output chunk + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0); + this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== undefined && opts.context !== undefined) + throw new Error('Blake3: only key or context can be specified at same time'); + else if (opts.key !== undefined) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error('Blake3: key should be 32 byte'); + this.IV = u32(key); + this.flags = flags | Flags.KEYED_HASH; + } else if (opts.context !== undefined) { + const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + protected get() { + return []; + } + protected set() {} + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: BLAKE3): BLAKE3 { + to = super._cloneInto(to) as BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + IV[0], IV[1], IV[2], IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + protected finish() { + if (this.finished) return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | Flags.ROOT; + if (this.stack.length) { + flags |= Flags.PARENT; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: Uint8Array) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } +} + +/** + * BLAKE3 hash function. + * @param msg - message that would be hashed + * @param opts - dkLen, key, context + */ +export const blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts( + (opts) => new BLAKE3(opts) +); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/crypto.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/crypto.ts new file mode 100644 index 0000000..eaea6be --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/crypto.ts @@ -0,0 +1,5 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +declare const globalThis: Record | undefined; +export const crypto = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/cryptoNode.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/cryptoNode.ts new file mode 100644 index 0000000..6fdba9e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/cryptoNode.ts @@ -0,0 +1,7 @@ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +// The file will throw on node.js 14 and earlier. +// @ts-ignore +import * as nc from 'node:crypto'; +export const crypto = + nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/eskdf.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..b4c224b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,183 @@ +import { bytes as assertBytes } from './_assert.js'; +import { hkdf } from './hkdf.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.js'; +import { scrypt as _scrypt } from './scrypt.js'; +import { bytesToHex, createView, hexToBytes, toBytes } from './utils.js'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +const SCRYPT_FACTOR = 2 ** 19; +const PBKDF2_FACTOR = 2 ** 17; + +// Scrypt KDF +export function scrypt(password: string, salt: string): Uint8Array { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +// PBKDF2-HMAC-SHA256 +export function pbkdf2(password: string, salt: string): Uint8Array { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays +function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { + assertBytes(a, 32); + assertBytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} + +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead. + */ +export function deriveMainSeed(username: string, password: string): Uint8Array { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + const scr = scrypt(password + '\u{1}', username + '\u{1}'); + const pbk = pbkdf2(password + '\u{2}', username + '\u{2}'); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF salt & info params. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Allow string account ids for some protocols + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt: Uint8Array; // Extract salt. Default is undefined. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) throw new Error('accountId must be valid string'); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`); + } + const info = toBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186 B.4.1 requires at least 64 more bits + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output. + */ +function modReduceKey(key: Uint8Array, modulus: bigint): Uint8Array { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +// We are not using classes because constructor cannot be async +type ESKDF = Promise< + Readonly<{ + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric identifier of account + * @param options - `keyLength: 64` or `modulus: 41920438n` + * @example deriveChildKey('aes', 0) + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array; + /** + * Deletes the main seed from eskdf instance + */ + expire: () => void; + /** + * Account fingerprint + */ + fingerprint: string; + }> +>; + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @example + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * console.log(kdf.fingerprint); + * kdf.expire(); + */ +export async function eskdf(username: string, password: string): ESKDF { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK(protocol: string, accountId: AccountID = 0, options?: KeyOpts): Uint8Array { + assertBytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + const keyLength = getKeyLength(options); // validate options + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/hkdf.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..6d880d1 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,79 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { CHash, Input, toBytes } from './utils.js'; +import { hmac } from './hmac.js'; + +// HKDF (RFC 5869) +// https://soatok.blog/2021/11/17/understanding-hkdf/ + +/** + * HKDF-Extract(IKM, salt) -> PRK + * Arguments position differs from spec (IKM is first one, since it is not optional) + * @param hash + * @param ikm + * @param salt + * @returns + */ +export function extract(hash: CHash, ikm: Input, salt?: Input) { + assertHash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros + return hmac(hash, toBytes(salt), toBytes(ikm)); +} + +// HKDF-Expand(PRK, info, L) -> OKM +const HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); +const EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); + +/** + * HKDF-expand from the spec. + * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in octets + */ +export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) { + assertHash(hash); + assertNumber(length); + if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen'); + const blocks = Math.ceil(length / hash.outputLen); + if (info === undefined) info = EMPTY_BUFFER; + // first L(ength) octets of T + const okm = new Uint8Array(blocks * hash.outputLen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash.outputLen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); +} + +/** + * HKDF (RFC 5869): extract + expand in one step. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information + * @param length - length of output keying material in octets + */ +export const hkdf = ( + hash: CHash, + ikm: Input, + salt: Input | undefined, + info: Input | undefined, + length: number +) => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/hmac.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..bebf4b3 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,81 @@ +import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js'; +import { Hash, CHash, Input, toBytes } from './utils.js'; +// HMAC (RFC 2104) +export class HMAC> extends Hash> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + private finished = false; + private destroyed = false; + + constructor(hash: CHash, _key: Input) { + super(); + assertHash(hash); + const key = toBytes(_key); + this.iHash = hash.create() as T; + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf: Input) { + assertExists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: Uint8Array) { + assertExists(this); + assertBytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to?: HMAC): HMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} + +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +export const hmac = (hash: CHash, key: Input, message: Input): Uint8Array => + new HMAC(hash, key).update(message).digest(); +hmac.create = (hash: CHash, key: Input) => new HMAC(hash, key); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/index.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..1505776 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1 @@ +throw new Error('noble-hashes have no entry-point: consult README for usage'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/pbkdf2.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..b5f7e6a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,97 @@ +import { hash as assertHash, number as assertNumber } from './_assert.js'; +import { hmac } from './hmac.js'; +import { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js'; + +// PBKDF (RFC 2898) +export type Pbkdf2Opt = { + c: number; // Iterations + dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key + asyncTick?: number; // Maximum time in ms for which async function can block execution +}; +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) { + assertHash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assertNumber(c); + assertNumber(dkLen); + assertNumber(asyncTick); + if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} + +function pbkdf2Output>( + PRF: Hash, + PRFSalt: Hash, + DK: Uint8Array, + prfW: Hash, + u: Uint8Array +) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; +} + +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +export function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +export async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/ripemd160.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/ripemd160.ts new file mode 100644 index 0000000..5f32380 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/ripemd160.ts @@ -0,0 +1,110 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word: number, shift: number) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +export class RIPEMD160 extends SHA2 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, + bl = this.h1 | 0, br = bl, + cl = this.h2 | 0, cr = cl, + dl = this.h3 | 0, dr = dl, + el = this.h4 | 0, er = el; + + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0 + ); + } + protected roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +export const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/scrypt.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..85b68d8 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,240 @@ +import { number as assertNumber } from './_assert.js'; +import { sha256 } from './sha256.js'; +import { pbkdf2 } from './pbkdf2.js'; +import { asyncLoop, checkOpts, Input, u32 } from './utils.js'; + +// RFC 7914 Scrypt KDF + +// Left rotate for uint32 +const rotl = (a: number, b: number) => (a << b) | (a >>> (32 - b)); + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa( + prev: Uint32Array, + pi: number, + input: Uint32Array, + ii: number, + out: Uint32Array, + oi: number +) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, + x04 = y04, x05 = y05, x06 = y06, x07 = y07, + x08 = y08, x09 = y09, x10 = y10, x11 = y11, + x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} + +export type ScryptOpts = { + N: number; // cost factor + r: number; // block size + p: number; // parallelization + dkLen?: number; // key length + asyncTick?: number; // block execution max time + maxmem?: number; + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assertNumber(N); + assertNumber(r); + assertNumber(p); + assertNumber(dkLen); + assertNumber(asyncTick); + assertNumber(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error( + 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32' + ); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error( + 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)' + ); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error( + 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32' + ); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error( + `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)` + ); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} + +function scryptOutput( + password: Input, + dkLen: number, + B: Uint8Array, + V: Uint32Array, + tmp: Uint32Array +) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} + +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +export function scrypt(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. + */ +export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha1.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha1.ts new file mode 100644 index 0000000..1fec224 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha1.ts @@ -0,0 +1,88 @@ +import { SHA2 } from './_sha2.js'; +import { wrapConstructor } from './utils.js'; + +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. + +// RFC 3174 +const rotl = (word: number, shift: number) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Initial state +const IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends SHA2 { + private A = IV[0] | 0; + private B = IV[1] | 0; + private C = IV[2] | 0; + private D = IV[3] | 0; + private E = IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + protected roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} + +export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha256.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha256.ts new file mode 100644 index 0000000..6f88b9a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha256.ts @@ -0,0 +1,133 @@ +import { SHA2 } from './_sha2.js'; +import { rotr, wrapConstructor } from './utils.js'; + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. + +// Choice: a ? b : c +const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c); + +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = /* @__PURE__ */new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends SHA2 { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = IV[0] | 0; + B = IV[1] | 0; + C = IV[2] | 0; + D = IV[3] | 0; + E = IV[4] | 0; + F = IV[5] | 0; + G = IV[6] | 0; + H = IV[7] | 0; + + constructor() { + super(64, 32, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + protected roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + A = 0xc1059ed8 | 0; + B = 0x367cd507 | 0; + C = 0x3070dd17 | 0; + D = 0xf70e5939 | 0; + E = 0xffc00b31 | 0; + F = 0x68581511 | 0; + G = 0x64f98fa7 | 0; + H = 0xbefa4fa4 | 0; + constructor() { + super(); + this.outputLen = 28; + } +} + +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +export const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +export const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha3-addons.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..1d5fbf9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,398 @@ +import { number as assertNumber } from './_assert.js'; +import { Input, toBytes, wrapConstructorWithOpts, u32, Hash, HashXOF } from './utils.js'; +import { Keccak, ShakeOpts } from './sha3.js'; +// cSHAKE && KMAC (NIST SP800-185) +function leftEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.unshift(res.length); + return new Uint8Array(res); +} + +function rightEncode(n: number): Uint8Array { + const res = [n & 0xff]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); +// NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; + +// Personalization +function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; + // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) + // bytepad(encode_string(N) || encode_string(S), 168) + const blockLenBytes = leftEncode(hash.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); // length in bits + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); // length in bits + if (!fn.length && !pers.length) return hash; + hash.suffix = 0x04; + hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + hash.update(getPadding(totalLen, hash.blockLen)); + return hash; +} + +const gencShake = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructorWithOpts((opts: cShakeOpts = {}) => + cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) + ); + +export const cshake128 = /* @__PURE__ */ (() => gencShake(0x1f, 168, 128 / 8))(); +export const cshake256 = /* @__PURE__ */ (() => gencShake(0x1f, 136, 256 / 8))(); + +class KMAC extends Keccak implements HashXOF { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: Input, + opts: cShakeOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); + key = toBytes(key); + // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish() { + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: KMAC): KMAC { + // Create new instance without calling constructor since key already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as KMAC; + } + clone(): KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false) { + const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key: Input, opts: cShakeOpts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} + +export const kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); +export const kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); +export const kmac128xof = /* @__PURE__ */ (() => genKmac(168, 128 / 8, true))(); +export const kmac256xof = /* @__PURE__ */ (() => genKmac(136, 256 / 8, true))(); + +// TupleHash +// Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) +class TupleHash extends Keccak implements HashXOF { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + super.update(leftEncode(data.length * 8)); + super.update(data); + return this; + }; + } + protected finish() { + if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: TupleHash): TupleHash { + to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as TupleHash; + } + clone(): TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false) { + const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { + const h = tuple.create(opts); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: cShakeOpts = {}) => + new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} + +export const tuplehash128 = /* @__PURE__ */ (() => genTuple(168, 128 / 8))(); +export const tuplehash256 = /* @__PURE__ */ (() => genTuple(136, 256 / 8))(); +export const tuplehash128xof = /* @__PURE__ */ (() => genTuple(168, 128 / 8, true))(); +export const tuplehash256xof = /* @__PURE__ */ (() => genTuple(136, 256 / 8, true))(); + +// ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) +type ParallelOpts = cShakeOpts & { blockLen?: number }; + +class ParallelHash extends Keccak implements HashXOF { + private leafHash?: Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + protected leafCons: () => Hash, + enableXOF: boolean, + opts: ParallelOpts = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); + let { blockLen: B } = opts; + B ||= 8; + assertNumber(B); + this.chunkLen = B; + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: Input) => { + data = toBytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish() { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + super.update(rightEncode(this.chunksDone)); + super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits + super.finish(); + } + _cloneInto(to?: ParallelHash): ParallelHash { + to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as ParallelHash; + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +) { + const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: ParallelOpts = {}) => + new ParallelHash( + blockLen, + chooseLen(opts, outputLen), + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + return parallel; +} + +export const parallelhash128 = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128))(); +export const parallelhash256 = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256))(); +export const parallelhash128xof = /* @__PURE__ */ (() => genPrl(168, 128 / 8, cshake128, true))(); +export const parallelhash256xof = /* @__PURE__ */ (() => genPrl(136, 256 / 8, cshake256, true))(); + +// Kangaroo +// Same as NIST rightEncode, but returns [0] for zero string +function rightEncodeK12(n: number): Uint8Array { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 0xff); + res.push(res.length); + return new Uint8Array(res); +} + +export type KangarooOpts = { dkLen?: number; personalization?: Input }; +const EMPTY = new Uint8Array([]); + +class KangarooTwelve extends Keccak implements HashXOF { + readonly chunkLen = 8192; + private leafHash?: Keccak; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + protected leafLen: number, + outputLen: number, + rounds: number, + opts: KangarooOpts + ) { + super(blockLen, 0x07, outputLen, true, rounds); + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data: Input) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input + this.personalization = EMPTY; + } + _cloneInto(to?: KangarooTwelve): KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): KangarooTwelve { + return this._cloneInto(); + } +} +// Default to 32 bytes, so it can be used without opts +export const k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) + ))(); +// MarsupilamiFourteen +export const m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) + ))(); + +// https://keccak.team/files/CSF-0.1.pdf +// + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG +class KeccakPRG extends Keccak { + protected rate: number; + constructor(capacity: number) { + assertNumber(capacity); + // Rho should be full bytes + if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) + throw new Error('KeccakPRG: Invalid capacity'); + // blockLen = rho in bytes + super((1600 - capacity - 2) / 8, 0, 0, true); + this.rate = 1600 - capacity; + this.posOut = Math.floor((this.rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: Input) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + feed(data: Input) { + return this.update(data); + } + protected finish() {} + digestInto(_out: Uint8Array): Uint8Array { + throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); + } + fetch(bytes: number): Uint8Array { + return this.xof(bytes); + } + // Ensure irreversibility (even if state leaked previous outputs cannot be computed) + forget() { + if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: KeccakPRG): KeccakPRG { + const { rate } = this; + to ||= new KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): KeccakPRG { + return this._cloneInto(); + } +} + +export const keccakprg = (capacity = 254) => new KeccakPRG(capacity); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha3.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..c730b06 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,223 @@ +import { bytes, exists, number, output } from './_assert.js'; +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js'; +import { + Hash, + u32, + Input, + toBytes, + wrapConstructor, + wrapXOFConstructorWithOpts, + HashXOF, +} from './utils.js'; + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + +// Same as keccakf1600, but allows to skip some rounds +export function keccakP(s: Uint32Array, rounds: number = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} + +export class Keccak extends Hash implements HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + public blockLen: number, + public suffix: number, + public outputLen: number, + protected enableXOF = false, + protected rounds: number = 24 + ) { + super(); + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + protected keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data: Input) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: Uint8Array): Uint8Array { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out: Uint8Array): Uint8Array { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): Uint8Array { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: Uint8Array) { + output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const gen = (suffix: number, blockLen: number, outputLen: number) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + +export const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +export const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +export const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8); +export const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +export const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +export const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +export const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8); +export const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8); + +export type ShakeOpts = { dkLen?: number }; + +const genShake = (suffix: number, blockLen: number, outputLen: number) => + wrapXOFConstructorWithOpts, ShakeOpts>( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true) + ); + +export const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8); +export const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha512.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha512.ts new file mode 100644 index 0000000..27b7ac5 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/sha512.ts @@ -0,0 +1,246 @@ +import { SHA2 } from './_sha2.js'; +import u64 from './_u64.js'; +import { wrapConstructor } from './utils.js'; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); + +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +export class SHA512 extends SHA2 { + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + Ah = 0x6a09e667 | 0; + Al = 0xf3bcc908 | 0; + Bh = 0xbb67ae85 | 0; + Bl = 0x84caa73b | 0; + Ch = 0x3c6ef372 | 0; + Cl = 0xfe94f82b | 0; + Dh = 0xa54ff53a | 0; + Dl = 0x5f1d36f1 | 0; + Eh = 0x510e527f | 0; + El = 0xade682d1 | 0; + Fh = 0x9b05688c | 0; + Fl = 0x2b3e6c1f | 0; + Gh = 0x1f83d9ab | 0; + Gl = 0xfb41bd6b | 0; + Hh = 0x5be0cd19 | 0; + Hl = 0x137e2179 | 0; + + constructor() { + super(128, 64, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + protected process(view: DataView, offset: number) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + protected roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +class SHA512_224 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x8c3d37c8 | 0; + Al = 0x19544da2 | 0; + Bh = 0x73e19966 | 0; + Bl = 0x89dcd4d6 | 0; + Ch = 0x1dfab7ae | 0; + Cl = 0x32ff9c82 | 0; + Dh = 0x679dd514 | 0; + Dl = 0x582f9fcf | 0; + Eh = 0x0f6d2b69 | 0; + El = 0x7bd44da8 | 0; + Fh = 0x77e36f73 | 0; + Fl = 0x04c48942 | 0; + Gh = 0x3f9d85a8 | 0; + Gl = 0x6a1d36c8 | 0; + Hh = 0x1112e6ad | 0; + Hl = 0x91d692a1 | 0; + + constructor() { + super(); + this.outputLen = 28; + } +} + +class SHA512_256 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0x22312194 | 0; + Al = 0xfc2bf72c | 0; + Bh = 0x9f555fa3 | 0; + Bl = 0xc84c64c2 | 0; + Ch = 0x2393b86b | 0; + Cl = 0x6f53b151 | 0; + Dh = 0x96387719 | 0; + Dl = 0x5940eabd | 0; + Eh = 0x96283ee2 | 0; + El = 0xa88effe3 | 0; + Fh = 0xbe5e1e25 | 0; + Fl = 0x53863992 | 0; + Gh = 0x2b0199fc | 0; + Gl = 0x2c85b8aa | 0; + Hh = 0x0eb72ddc | 0; + Hl = 0x81c52ca2 | 0; + + constructor() { + super(); + this.outputLen = 32; + } +} + +class SHA384 extends SHA512 { + // h -- high 32 bits, l -- low 32 bits + Ah = 0xcbbb9d5d | 0; + Al = 0xc1059ed8 | 0; + Bh = 0x629a292a | 0; + Bl = 0x367cd507 | 0; + Ch = 0x9159015a | 0; + Cl = 0x3070dd17 | 0; + Dh = 0x152fecd8 | 0; + Dl = 0xf70e5939 | 0; + Eh = 0x67332667 | 0; + El = 0xffc00b31 | 0; + Fh = 0x8eb44a87 | 0; + Fl = 0x68581511 | 0; + Gh = 0xdb0c2e0d | 0; + Gl = 0x64f98fa7 | 0; + Hh = 0x47b5481d | 0; + Hl = 0xbefa4fa4 | 0; + + constructor() { + super(); + this.outputLen = 48; + } +} + +export const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +export const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224()); +export const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256()); +export const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/utils.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..81e5256 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,215 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +import { crypto } from '@noble/hashes/crypto'; + +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array; +// Cast array to different type +export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +export const u32 = (arr: TypedArray) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +// Cast array to view +export const createView = (arr: TypedArray) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + +// The rotate right (circular right shift) operation for uint32 +export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift); + +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); + +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export function bytesToHex(bytes: Uint8Array): string { + if (!u8a(bytes)) throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export function hexToBytes(hex: string): Uint8Array { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} + +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +export const nextTick = async () => {}; + +// Returns control to thread each 'tick' ms to avoid blocking +export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols in both browsers and Node.js since v11 +// See https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export function utf8ToBytes(str: string): Uint8Array { + if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export function toBytes(data: Input): Uint8Array { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} + +/** + * Copies several Uint8Arrays into one. + */ +export function concatBytes(...arrays: Uint8Array[]): Uint8Array { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} + +// For runtime check if class implements interface +export abstract class Hash> { + abstract blockLen: number; // Bytes per block + abstract outputLen: number; // Bytes in output + abstract update(buf: Input): this; + // Writes digest into buf + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + // Safe version that clones internal state + clone(): T { + return this._cloneInto(); + } +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream + xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf +}; + +const toStr = {}.toString; +type EmptyObj = {}; +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +export type CHash = ReturnType; + +export function wrapConstructor>(hashCons: () => Hash) { + const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +export function wrapConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => Hash +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +export function wrapXOFConstructorWithOpts, T extends Object>( + hashCons: (opts?: T) => HashXOF +) { + const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({} as T); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts: T) => hashCons(opts); + return hashC; +} + +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export function randomBytes(bytesLength = 32): Uint8Array { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.d.ts b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..a0017e4 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,90 @@ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +export declare const u8: (arr: TypedArray) => Uint8Array; +export declare const u32: (arr: TypedArray) => Uint32Array; +export declare const createView: (arr: TypedArray) => DataView; +export declare const rotr: (word: number, shift: number) => number; +export declare const isLE: boolean; +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +export declare function bytesToHex(bytes: Uint8Array): string; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +export declare function hexToBytes(hex: string): Uint8Array; +export declare const nextTick: () => Promise; +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +export declare function utf8ToBytes(str: string): Uint8Array; +export type Input = Uint8Array | string; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +export declare function toBytes(data: Input): Uint8Array; +/** + * Copies several Uint8Arrays into one. + */ +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare abstract class Hash> { + abstract blockLen: number; + abstract outputLen: number; + abstract update(buf: Input): this; + abstract digestInto(buf: Uint8Array): void; + abstract digest(): Uint8Array; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + abstract destroy(): void; + /** + * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` + * when no options are passed. + * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal + * buffers are overwritten => causes buffer overwrite which is used for digest in some cases. + * There are no guarantees for clean-up because it's impossible in JS. + */ + abstract _cloneInto(to?: T): T; + clone(): T; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + xof(bytes: number): Uint8Array; + xofInto(buf: Uint8Array): Uint8Array; +}; +type EmptyObj = {}; +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +export type CHash = ReturnType; +export declare function wrapConstructor>(hashCons: () => Hash): { + (msg: Input): Uint8Array; + outputLen: number; + blockLen: number; + create(): Hash; +}; +export declare function wrapConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => Hash): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): Hash; +}; +export declare function wrapXOFConstructorWithOpts, T extends Object>(hashCons: (opts?: T) => HashXOF): { + (msg: Input, opts?: T): Uint8Array; + outputLen: number; + blockLen: number; + create(opts: T): HashXOF; +}; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +export declare function randomBytes(bytesLength?: number): Uint8Array; +export {}; diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..2ffcbbe --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js @@ -0,0 +1,174 @@ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +const crypto_1 = require("@noble/hashes/crypto"); +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js.map b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..4fc2171 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AAEtE,oFAAoF;AACpF,sEAAsE;AACtE,kEAAkE;AAClE,8DAA8D;AAC9D,+DAA+D;AAC/D,8DAA8D;AAC9D,iDAA8C;AAM9C,MAAM,GAAG,GAAG,CAAC,CAAM,EAAmB,EAAE,CAAC,CAAC,YAAY,UAAU,CAAC;AACjE,+BAA+B;AACxB,MAAM,EAAE,GAAG,CAAC,GAAe,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;AAArF,QAAA,EAAE,MAAmF;AAC3F,MAAM,GAAG,GAAG,CAAC,GAAe,EAAE,EAAE,CACrC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,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AC,WAAW,CAAC,CAAC,CAAC;KAC5D;IACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC5D,CAAC;AALD,kCAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@scure/bip39/package.json b/test/merkletreejs/node_modules/@scure/bip39/package.json new file mode 100644 index 0000000..51102a9 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/package.json @@ -0,0 +1,116 @@ +{ + "name": "@scure/bip39", + "version": "1.2.1", + "description": "Secure, audited & minimal implementation of BIP39 mnemonic phrases", + "main": "index.js", + "files": [ + "index.js", + "index.d.ts", + "wordlists/*.js", + "wordlists/*.d.ts", + "esm" + ], + "types": "index.d.ts", + "dependencies": { + "@noble/hashes": "~1.3.0", + "@scure/base": "~1.1.0" + }, + "devDependencies": { + "micro-should": "0.4.0", + "prettier": "2.8.4", + "typescript": "5.0.2" + }, + "author": "Paul Miller (https://paulmillr.com)", + "homepage": "https://paulmillr.com/", + "repository": { + "type": "git", + "url": "https://github.com/paulmillr/scure-bip39.git" + }, + "contributors": [ + { + "name": "Patricio Palladino", + "email": "patricio@nomiclabs.io" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "license": "MIT", + "scripts": { + "build": "tsc && tsc -p tsconfig.esm.json", + "lint": "prettier --check 'src/**/*.ts' 'test/*.test.ts'", + "format": "prettier --write 'src/**/*.ts' 'test/*.test.ts'", + "test": "cd test && tsc && node bip39.test.js" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./wordlists/czech": { + "types": "./wordlists/czech.d.ts", + "import": "./esm/wordlists/czech.js", + "default": "./wordlists/czech.js" + }, + "./wordlists/english": { + "types": "./wordlists/english.d.ts", + "import": "./esm/wordlists/english.js", + "default": "./wordlists/english.js" + }, + "./wordlists/french": { + "types": "./wordlists/french.d.ts", + "import": "./esm/wordlists/french.js", + "default": "./wordlists/french.js" + }, + "./wordlists/italian": { + "types": "./wordlists/italian.d.ts", + "import": "./esm/wordlists/italian.js", + "default": "./wordlists/italian.js" + }, + "./wordlists/japanese": { + "types": "./wordlists/japanese.d.ts", + "import": "./esm/wordlists/japanese.js", + "default": "./wordlists/japanese.js" + }, + "./wordlists/korean": { + "types": "./wordlists/korean.d.ts", + "import": "./esm/wordlists/korean.js", + "default": "./wordlists/korean.js" + }, + "./wordlists/simplified-chinese": { + "types": "./wordlists/simplified-chinese.d.ts", + "import": "./esm/wordlists/simplified-chinese.js", + "default": "./wordlists/simplified-chinese.js" + }, + "./wordlists/spanish": { + "types": "./wordlists/spanish.d.ts", + "import": "./esm/wordlists/spanish.js", + "default": "./wordlists/spanish.js" + }, + "./wordlists/traditional-chinese": { + "types": "./wordlists/traditional-chinese.d.ts", + "import": "./esm/wordlists/traditional-chinese.js", + "default": "./wordlists/traditional-chinese.js" + } + }, + "keywords": [ + "bip39", + "mnemonic", + "phrase", + "code", + "bip0039", + "bip-39", + "micro", + "scure", + "wordlist", + "noble" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/czech.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/czech.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/czech.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/czech.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/czech.js new file mode 100644 index 0000000..0295622 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/czech.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abdikace +abeceda +adresa +agrese +akce +aktovka +alej +alkohol +amputace +ananas +andulka +anekdota +anketa +antika +anulovat +archa +arogance +asfalt +asistent +aspirace +astma +astronom +atlas +atletika +atol +autobus +azyl +babka +bachor +bacil +baculka +badatel +bageta +bagr +bahno +bakterie +balada +baletka +balkon +balonek +balvan +balza +bambus +bankomat +barbar +baret +barman +baroko +barva +baterka +batoh +bavlna +bazalka +bazilika +bazuka +bedna +beran +beseda +bestie +beton +bezinka +bezmoc +beztak +bicykl +bidlo +biftek +bikiny +bilance +biograf +biolog +bitva +bizon +blahobyt +blatouch +blecha +bledule +blesk +blikat +blizna +blokovat +bloudit +blud +bobek +bobr +bodlina +bodnout +bohatost +bojkot +bojovat +bokorys +bolest +borec +borovice +bota +boubel +bouchat +bouda +boule +bourat +boxer +bradavka +brambora +branka +bratr +brepta +briketa +brko +brloh +bronz +broskev +brunetka +brusinka +brzda +brzy +bublina +bubnovat +buchta +buditel +budka +budova +bufet +bujarost +bukvice +buldok +bulva +bunda +bunkr +burza +butik +buvol +buzola +bydlet +bylina +bytovka +bzukot +capart +carevna +cedr +cedule +cejch +cejn +cela +celer +celkem +celnice +cenina +cennost +cenovka +centrum +cenzor +cestopis +cetka +chalupa +chapadlo +charita +chata +chechtat +chemie +chichot +chirurg +chlad +chleba +chlubit +chmel +chmura +chobot +chochol +chodba +cholera +chomout +chopit +choroba +chov +chrapot +chrlit +chrt +chrup +chtivost +chudina +chutnat +chvat +chvilka +chvost +chyba +chystat +chytit +cibule +cigareta +cihelna +cihla +cinkot +cirkus +cisterna +citace +citrus +cizinec +cizost +clona +cokoliv +couvat +ctitel +ctnost +cudnost +cuketa +cukr +cupot +cvaknout +cval +cvik +cvrkot +cyklista +daleko +dareba +datel +datum +dcera +debata +dechovka +decibel +deficit +deflace +dekl +dekret +demokrat +deprese +derby +deska +detektiv +dikobraz +diktovat +dioda +diplom +disk +displej +divadlo +divoch +dlaha +dlouho +dluhopis +dnes +dobro +dobytek +docent +dochutit +dodnes +dohled +dohoda +dohra +dojem +dojnice +doklad +dokola +doktor +dokument +dolar +doleva +dolina +doma +dominant +domluvit +domov +donutit +dopad +dopis +doplnit +doposud +doprovod +dopustit +dorazit +dorost +dort +dosah +doslov +dostatek +dosud +dosyta +dotaz +dotek +dotknout +doufat +doutnat +dovozce +dozadu +doznat +dozorce +drahota +drak +dramatik +dravec +draze +drdol +drobnost +drogerie +drozd +drsnost +drtit +drzost +duben +duchovno +dudek +duha +duhovka +dusit +dusno +dutost +dvojice +dvorec +dynamit +ekolog +ekonomie +elektron +elipsa +email +emise +emoce +empatie +epizoda +epocha +epopej +epos +esej +esence +eskorta +eskymo +etiketa +euforie +evoluce +exekuce +exkurze +expedice +exploze +export +extrakt +facka +fajfka +fakulta +fanatik +fantazie +farmacie +favorit +fazole +federace +fejeton +fenka +fialka +figurant +filozof +filtr +finance +finta +fixace +fjord +flanel +flirt +flotila +fond +fosfor +fotbal +fotka +foton +frakce +freska +fronta +fukar +funkce +fyzika +galeje +garant +genetika +geolog +gilotina +glazura +glejt +golem +golfista +gotika +graf +gramofon +granule +grep +gril +grog +groteska +guma +hadice +hadr +hala +halenka +hanba +hanopis +harfa +harpuna +havran +hebkost +hejkal +hejno +hejtman +hektar +helma +hematom +herec +herna +heslo +hezky +historik +hladovka +hlasivky +hlava +hledat +hlen +hlodavec +hloh +hloupost +hltat +hlubina +hluchota +hmat +hmota +hmyz +hnis +hnojivo +hnout +hoblina +hoboj +hoch +hodiny +hodlat +hodnota +hodovat +hojnost +hokej +holinka +holka +holub +homole +honitba +honorace +horal +horda +horizont +horko +horlivec +hormon +hornina +horoskop +horstvo +hospoda +hostina +hotovost +houba +houf +houpat +houska +hovor +hradba +hranice +hravost +hrazda +hrbolek +hrdina +hrdlo +hrdost +hrnek +hrobka +hromada +hrot +hrouda +hrozen +hrstka +hrubost +hryzat +hubenost +hubnout +hudba +hukot +humr +husita +hustota +hvozd +hybnost +hydrant +hygiena +hymna +hysterik +idylka +ihned +ikona +iluze +imunita +infekce +inflace +inkaso +inovace +inspekce +internet +invalida +investor +inzerce +ironie +jablko +jachta +jahoda +jakmile +jakost +jalovec +jantar +jarmark +jaro +jasan +jasno +jatka +javor +jazyk +jedinec +jedle +jednatel +jehlan +jekot +jelen +jelito +jemnost +jenom +jepice +jeseter +jevit +jezdec +jezero +jinak +jindy +jinoch +jiskra +jistota +jitrnice +jizva +jmenovat +jogurt +jurta +kabaret +kabel +kabinet +kachna +kadet +kadidlo +kahan +kajak +kajuta +kakao +kaktus +kalamita +kalhoty +kalibr +kalnost +kamera +kamkoliv +kamna +kanibal +kanoe +kantor +kapalina +kapela +kapitola +kapka +kaple +kapota +kapr +kapusta +kapybara +karamel +karotka +karton +kasa +katalog +katedra +kauce +kauza +kavalec +kazajka +kazeta +kazivost +kdekoliv +kdesi +kedluben +kemp +keramika +kino +klacek +kladivo +klam +klapot +klasika +klaun +klec +klenba +klepat +klesnout +klid +klima +klisna +klobouk +klokan +klopa +kloub +klubovna +klusat +kluzkost +kmen +kmitat +kmotr +kniha +knot +koalice +koberec +kobka +kobliha +kobyla +kocour +kohout +kojenec +kokos +koktejl +kolaps +koleda +kolize +kolo +komando +kometa +komik +komnata +komora +kompas +komunita +konat +koncept +kondice +konec +konfese +kongres +konina +konkurs +kontakt +konzerva +kopanec +kopie +kopnout +koprovka +korbel +korektor +kormidlo +koroptev +korpus +koruna +koryto +korzet +kosatec +kostka +kotel +kotleta +kotoul +koukat +koupelna +kousek +kouzlo +kovboj +koza +kozoroh +krabice +krach +krajina +kralovat +krasopis +kravata +kredit +krejcar +kresba +kreveta +kriket +kritik +krize +krkavec +krmelec +krmivo +krocan +krok +kronika +kropit +kroupa +krovka +krtek +kruhadlo +krupice +krutost +krvinka +krychle +krypta +krystal +kryt +kudlanka +kufr +kujnost +kukla +kulajda +kulich +kulka +kulomet +kultura +kuna +kupodivu +kurt +kurzor +kutil +kvalita +kvasinka +kvestor +kynolog +kyselina +kytara +kytice +kytka +kytovec +kyvadlo +labrador +lachtan +ladnost +laik +lakomec +lamela +lampa +lanovka +lasice +laso +lastura +latinka +lavina +lebka +leckdy +leden +lednice +ledovka +ledvina +legenda +legie +legrace +lehce +lehkost +lehnout +lektvar +lenochod +lentilka +lepenka +lepidlo +letadlo +letec +letmo +letokruh +levhart +levitace +levobok +libra +lichotka +lidojed +lidskost +lihovina +lijavec +lilek +limetka +linie +linka +linoleum +listopad +litina +litovat +lobista +lodivod +logika +logoped +lokalita +loket +lomcovat +lopata +lopuch +lord +losos +lotr +loudal +louh +louka +louskat +lovec +lstivost +lucerna +lucifer +lump +lusk +lustrace +lvice +lyra +lyrika +lysina +madam +madlo +magistr +mahagon +majetek +majitel +majorita +makak +makovice +makrela +malba +malina +malovat +malvice +maminka +mandle +manko +marnost +masakr +maskot +masopust +matice +matrika +maturita +mazanec +mazivo +mazlit +mazurka +mdloba +mechanik +meditace +medovina +melasa +meloun +mentolka +metla +metoda +metr +mezera +migrace +mihnout +mihule +mikina +mikrofon +milenec +milimetr +milost +mimika +mincovna +minibar +minomet +minulost +miska +mistr +mixovat +mladost +mlha +mlhovina +mlok +mlsat +mluvit +mnich +mnohem +mobil +mocnost +modelka +modlitba +mohyla +mokro +molekula +momentka +monarcha +monokl +monstrum +montovat +monzun +mosaz +moskyt +most +motivace +motorka +motyka +moucha +moudrost +mozaika +mozek +mozol +mramor +mravenec +mrkev +mrtvola +mrzet +mrzutost +mstitel +mudrc +muflon +mulat +mumie +munice +muset +mutace +muzeum +muzikant +myslivec +mzda +nabourat +nachytat +nadace +nadbytek +nadhoz +nadobro +nadpis +nahlas +nahnat +nahodile +nahradit +naivita +najednou +najisto +najmout +naklonit +nakonec +nakrmit +nalevo +namazat +namluvit +nanometr +naoko +naopak +naostro +napadat +napevno +naplnit +napnout +naposled +naprosto +narodit +naruby +narychlo +nasadit +nasekat +naslepo +nastat +natolik +navenek +navrch +navzdory +nazvat +nebe +nechat +necky +nedaleko +nedbat +neduh +negace +nehet +nehoda +nejen +nejprve +neklid +nelibost +nemilost +nemoc +neochota +neonka +nepokoj +nerost +nerv +nesmysl +nesoulad +netvor +neuron +nevina +nezvykle +nicota +nijak +nikam +nikdy +nikl +nikterak +nitro +nocleh +nohavice +nominace +nora +norek +nositel +nosnost +nouze +noviny +novota +nozdra +nuda +nudle +nuget +nutit +nutnost +nutrie +nymfa +obal +obarvit +obava +obdiv +obec +obehnat +obejmout +obezita +obhajoba +obilnice +objasnit +objekt +obklopit +oblast +oblek +obliba +obloha +obluda +obnos +obohatit +obojek +obout +obrazec +obrna +obruba +obrys +obsah +obsluha +obstarat +obuv +obvaz +obvinit +obvod +obvykle +obyvatel +obzor +ocas +ocel +ocenit +ochladit +ochota +ochrana +ocitnout +odboj +odbyt +odchod +odcizit +odebrat +odeslat +odevzdat +odezva +odhadce +odhodit +odjet +odjinud +odkaz +odkoupit +odliv +odluka +odmlka +odolnost +odpad +odpis +odplout +odpor +odpustit +odpykat +odrazka +odsoudit +odstup +odsun +odtok +odtud +odvaha +odveta +odvolat +odvracet +odznak +ofina +ofsajd +ohlas +ohnisko +ohrada +ohrozit +ohryzek +okap +okenice +oklika +okno +okouzlit +okovy +okrasa +okres +okrsek +okruh +okupant +okurka +okusit +olejnina +olizovat +omak +omeleta +omezit +omladina +omlouvat +omluva +omyl +onehdy +opakovat +opasek +operace +opice +opilost +opisovat +opora +opozice +opravdu +oproti +orbital +orchestr +orgie +orlice +orloj +ortel +osada +oschnout +osika +osivo +oslava +oslepit +oslnit +oslovit +osnova +osoba +osolit +ospalec +osten +ostraha +ostuda +ostych +osvojit +oteplit +otisk +otop +otrhat +otrlost +otrok +otruby +otvor +ovanout +ovar +oves +ovlivnit +ovoce +oxid +ozdoba +pachatel +pacient +padouch +pahorek +pakt +palanda +palec +palivo +paluba +pamflet +pamlsek +panenka +panika +panna +panovat +panstvo +pantofle +paprika +parketa +parodie +parta +paruka +paryba +paseka +pasivita +pastelka +patent +patrona +pavouk +pazneht +pazourek +pecka +pedagog +pejsek +peklo +peloton +penalta +pendrek +penze +periskop +pero +pestrost +petarda +petice +petrolej +pevnina +pexeso +pianista +piha +pijavice +pikle +piknik +pilina +pilnost +pilulka +pinzeta +pipeta +pisatel +pistole +pitevna +pivnice +pivovar +placenta +plakat +plamen +planeta +plastika +platit +plavidlo +plaz +plech +plemeno +plenta +ples +pletivo +plevel +plivat +plnit +plno +plocha +plodina +plomba +plout +pluk +plyn +pobavit +pobyt +pochod +pocit +poctivec +podat +podcenit +podepsat +podhled +podivit +podklad +podmanit +podnik +podoba +podpora +podraz +podstata +podvod +podzim +poezie +pohanka +pohnutka +pohovor +pohroma +pohyb +pointa +pojistka +pojmout +pokazit +pokles +pokoj +pokrok +pokuta +pokyn +poledne +polibek +polknout +poloha +polynom +pomalu +pominout +pomlka +pomoc +pomsta +pomyslet +ponechat +ponorka +ponurost +popadat +popel +popisek +poplach +poprosit +popsat +popud +poradce +porce +porod +porucha +poryv +posadit +posed +posila +poskok +poslanec +posoudit +pospolu +postava +posudek +posyp +potah +potkan +potlesk +potomek +potrava +potupa +potvora +poukaz +pouto +pouzdro +povaha +povidla +povlak +povoz +povrch +povstat +povyk +povzdech +pozdrav +pozemek +poznatek +pozor +pozvat +pracovat +prahory +praktika +prales +praotec +praporek +prase +pravda +princip +prkno +probudit +procento +prodej +profese +prohra +projekt +prolomit +promile +pronikat +propad +prorok +prosba +proton +proutek +provaz +prskavka +prsten +prudkost +prut +prvek +prvohory +psanec +psovod +pstruh +ptactvo +puberta +puch +pudl +pukavec +puklina +pukrle +pult +pumpa +punc +pupen +pusa +pusinka +pustina +putovat +putyka +pyramida +pysk +pytel +racek +rachot +radiace +radnice +radon +raft +ragby +raketa +rakovina +rameno +rampouch +rande +rarach +rarita +rasovna +rastr +ratolest +razance +razidlo +reagovat +reakce +recept +redaktor +referent +reflex +rejnok +reklama +rekord +rekrut +rektor +reputace +revize +revma +revolver +rezerva +riskovat +riziko +robotika +rodokmen +rohovka +rokle +rokoko +romaneto +ropovod +ropucha +rorejs +rosol +rostlina +rotmistr +rotoped +rotunda +roubenka +roucho +roup +roura +rovina +rovnice +rozbor +rozchod +rozdat +rozeznat +rozhodce +rozinka +rozjezd +rozkaz +rozloha +rozmar +rozpad +rozruch +rozsah +roztok +rozum +rozvod +rubrika +ruchadlo +rukavice +rukopis +ryba +rybolov +rychlost +rydlo +rypadlo +rytina +ryzost +sadista +sahat +sako +samec +samizdat +samota +sanitka +sardinka +sasanka +satelit +sazba +sazenice +sbor +schovat +sebranka +secese +sedadlo +sediment +sedlo +sehnat +sejmout +sekera +sekta +sekunda +sekvoje +semeno +seno +servis +sesadit +seshora +seskok +seslat +sestra +sesuv +sesypat +setba +setina +setkat +setnout +setrvat +sever +seznam +shoda +shrnout +sifon +silnice +sirka +sirotek +sirup +situace +skafandr +skalisko +skanzen +skaut +skeptik +skica +skladba +sklenice +sklo +skluz +skoba +skokan +skoro +skripta +skrz +skupina +skvost +skvrna +slabika +sladidlo +slanina +slast +slavnost +sledovat +slepec +sleva +slezina +slib +slina +sliznice +slon +sloupek +slovo +sluch +sluha +slunce +slupka +slza +smaragd +smetana +smilstvo +smlouva +smog +smrad +smrk +smrtka +smutek +smysl +snad +snaha +snob +sobota +socha +sodovka +sokol +sopka +sotva +souboj +soucit +soudce +souhlas +soulad +soumrak +souprava +soused +soutok +souviset +spalovna +spasitel +spis +splav +spodek +spojenec +spolu +sponzor +spornost +spousta +sprcha +spustit +sranda +sraz +srdce +srna +srnec +srovnat +srpen +srst +srub +stanice +starosta +statika +stavba +stehno +stezka +stodola +stolek +stopa +storno +stoupat +strach +stres +strhnout +strom +struna +studna +stupnice +stvol +styk +subjekt +subtropy +suchar +sudost +sukno +sundat +sunout +surikata +surovina +svah +svalstvo +svetr +svatba +svazek +svisle +svitek +svoboda +svodidlo +svorka +svrab +sykavka +sykot +synek +synovec +sypat +sypkost +syrovost +sysel +sytost +tabletka +tabule +tahoun +tajemno +tajfun +tajga +tajit +tajnost +taktika +tamhle +tampon +tancovat +tanec +tanker +tapeta +tavenina +tazatel +technika +tehdy +tekutina +telefon +temnota +tendence +tenista +tenor +teplota +tepna +teprve +terapie +termoska +textil +ticho +tiskopis +titulek +tkadlec +tkanina +tlapka +tleskat +tlukot +tlupa +tmel +toaleta +topinka +topol +torzo +touha +toulec +tradice +traktor +tramp +trasa +traverza +trefit +trest +trezor +trhavina +trhlina +trochu +trojice +troska +trouba +trpce +trpitel +trpkost +trubec +truchlit +truhlice +trus +trvat +tudy +tuhnout +tuhost +tundra +turista +turnaj +tuzemsko +tvaroh +tvorba +tvrdost +tvrz +tygr +tykev +ubohost +uboze +ubrat +ubrousek +ubrus +ubytovna +ucho +uctivost +udivit +uhradit +ujednat +ujistit +ujmout +ukazatel +uklidnit +uklonit +ukotvit +ukrojit +ulice +ulita +ulovit +umyvadlo +unavit +uniforma +uniknout +upadnout +uplatnit +uplynout +upoutat +upravit +uran +urazit +usednout +usilovat +usmrtit +usnadnit +usnout +usoudit +ustlat +ustrnout +utahovat +utkat +utlumit +utonout +utopenec +utrousit +uvalit +uvolnit +uvozovka +uzdravit +uzel +uzenina +uzlina +uznat +vagon +valcha +valoun +vana +vandal +vanilka +varan +varhany +varovat +vcelku +vchod +vdova +vedro +vegetace +vejce +velbloud +veletrh +velitel +velmoc +velryba +venkov +veranda +verze +veselka +veskrze +vesnice +vespodu +vesta +veterina +veverka +vibrace +vichr +videohra +vidina +vidle +vila +vinice +viset +vitalita +vize +vizitka +vjezd +vklad +vkus +vlajka +vlak +vlasec +vlevo +vlhkost +vliv +vlnovka +vloupat +vnucovat +vnuk +voda +vodivost +vodoznak +vodstvo +vojensky +vojna +vojsko +volant +volba +volit +volno +voskovka +vozidlo +vozovna +vpravo +vrabec +vracet +vrah +vrata +vrba +vrcholek +vrhat +vrstva +vrtule +vsadit +vstoupit +vstup +vtip +vybavit +vybrat +vychovat +vydat +vydra +vyfotit +vyhledat +vyhnout +vyhodit +vyhradit +vyhubit +vyjasnit +vyjet +vyjmout +vyklopit +vykonat +vylekat +vymazat +vymezit +vymizet +vymyslet +vynechat +vynikat +vynutit +vypadat +vyplatit +vypravit +vypustit +vyrazit +vyrovnat +vyrvat +vyslovit +vysoko +vystavit +vysunout +vysypat +vytasit +vytesat +vytratit +vyvinout +vyvolat +vyvrhel +vyzdobit +vyznat +vzadu +vzbudit +vzchopit +vzdor +vzduch +vzdychat +vzestup +vzhledem +vzkaz +vzlykat +vznik +vzorek +vzpoura +vztah +vztek +xylofon +zabrat +zabydlet +zachovat +zadarmo +zadusit +zafoukat +zahltit +zahodit +zahrada +zahynout +zajatec +zajet +zajistit +zaklepat +zakoupit +zalepit +zamezit +zamotat +zamyslet +zanechat +zanikat +zaplatit +zapojit +zapsat +zarazit +zastavit +zasunout +zatajit +zatemnit +zatknout +zaujmout +zavalit +zavelet +zavinit +zavolat +zavrtat +zazvonit +zbavit +zbrusu +zbudovat +zbytek +zdaleka +zdarma +zdatnost +zdivo +zdobit +zdroj +zdvih +zdymadlo +zelenina +zeman +zemina +zeptat +zezadu +zezdola +zhatit +zhltnout +zhluboka +zhotovit +zhruba +zima +zimnice +zjemnit +zklamat +zkoumat +zkratka +zkumavka +zlato +zlehka +zloba +zlom +zlost +zlozvyk +zmapovat +zmar +zmatek +zmije +zmizet +zmocnit +zmodrat +zmrzlina +zmutovat +znak +znalost +znamenat +znovu +zobrazit +zotavit +zoubek +zoufale +zplodit +zpomalit +zprava +zprostit +zprudka +zprvu +zrada +zranit +zrcadlo +zrnitost +zrno +zrovna +zrychlit +zrzavost +zticha +ztratit +zubovina +zubr +zvednout +zvenku +zvesela +zvon +zvrat +zvukovod +zvyk`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/english.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/english.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/english.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/english.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/english.js new file mode 100644 index 0000000..10c9c19 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/english.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/french.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/french.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/french.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/french.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/french.js new file mode 100644 index 0000000..6010582 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/french.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abaisser +abandon +abdiquer +abeille +abolir +aborder +aboutir +aboyer +abrasif +abreuver +abriter +abroger +abrupt +absence +absolu +absurde +abusif +abyssal +académie +acajou +acarien +accabler +accepter +acclamer +accolade +accroche +accuser +acerbe +achat +acheter +aciduler +acier +acompte +acquérir +acronyme +acteur +actif +actuel +adepte +adéquat +adhésif +adjectif +adjuger +admettre +admirer +adopter +adorer +adoucir +adresse +adroit +adulte +adverbe +aérer +aéronef +affaire +affecter +affiche +affreux +affubler +agacer +agencer +agile +agiter +agrafer +agréable +agrume +aider +aiguille +ailier +aimable +aisance +ajouter +ajuster +alarmer +alchimie +alerte +algèbre +algue +aliéner +aliment +alléger +alliage +allouer +allumer +alourdir +alpaga +altesse +alvéole +amateur +ambigu +ambre +aménager +amertume +amidon +amiral +amorcer +amour +amovible +amphibie +ampleur +amusant +analyse +anaphore +anarchie +anatomie +ancien +anéantir +angle +angoisse +anguleux +animal +annexer +annonce +annuel +anodin +anomalie +anonyme +anormal +antenne +antidote +anxieux +apaiser +apéritif +aplanir +apologie +appareil +appeler +apporter +appuyer +aquarium +aqueduc +arbitre +arbuste +ardeur +ardoise +argent +arlequin +armature +armement +armoire +armure +arpenter +arracher +arriver +arroser +arsenic +artériel +article +aspect +asphalte +aspirer +assaut +asservir +assiette +associer +assurer +asticot +astre +astuce +atelier +atome +atrium +atroce +attaque +attentif +attirer +attraper +aubaine +auberge +audace +audible +augurer +aurore +automne +autruche +avaler +avancer +avarice +avenir +averse +aveugle +aviateur +avide +avion +aviser +avoine +avouer +avril +axial +axiome +badge +bafouer +bagage +baguette +baignade +balancer +balcon +baleine +balisage +bambin +bancaire +bandage +banlieue +bannière +banquier +barbier +baril +baron +barque +barrage +bassin +bastion +bataille +bateau +batterie +baudrier +bavarder +belette +bélier +belote +bénéfice +berceau +berger +berline +bermuda +besace +besogne +bétail +beurre +biberon +bicycle +bidule +bijou +bilan +bilingue +billard +binaire +biologie +biopsie +biotype +biscuit +bison +bistouri +bitume +bizarre +blafard +blague +blanchir +blessant +blinder +blond +bloquer +blouson +bobard +bobine +boire +boiser +bolide +bonbon +bondir +bonheur +bonifier +bonus +bordure +borne +botte +boucle +boueux +bougie +boulon +bouquin +bourse +boussole +boutique +boxeur +branche +brasier +brave +brebis +brèche +breuvage +bricoler +brigade +brillant +brioche +brique +brochure +broder +bronzer +brousse +broyeur +brume +brusque +brutal +bruyant +buffle +buisson +bulletin +bureau +burin +bustier +butiner +butoir +buvable +buvette +cabanon +cabine +cachette +cadeau +cadre +caféine +caillou +caisson +calculer +calepin +calibre +calmer +calomnie +calvaire +camarade +caméra +camion +campagne +canal +caneton +canon +cantine +canular +capable +caporal +caprice +capsule +capter +capuche +carabine +carbone +caresser +caribou +carnage +carotte +carreau +carton +cascade +casier +casque +cassure +causer +caution +cavalier +caverne +caviar +cédille +ceinture +céleste +cellule +cendrier +censurer +central +cercle +cérébral +cerise +cerner +cerveau +cesser +chagrin +chaise +chaleur +chambre +chance +chapitre +charbon +chasseur +chaton +chausson +chavirer +chemise +chenille +chéquier +chercher +cheval +chien +chiffre +chignon +chimère +chiot +chlorure +chocolat +choisir +chose +chouette +chrome +chute +cigare +cigogne +cimenter +cinéma +cintrer +circuler +cirer +cirque +citerne +citoyen +citron +civil +clairon +clameur +claquer +classe +clavier +client +cligner +climat +clivage +cloche +clonage +cloporte +cobalt +cobra +cocasse +cocotier +coder +codifier +coffre +cogner +cohésion +coiffer +coincer +colère +colibri +colline +colmater +colonel +combat +comédie +commande +compact +concert +conduire +confier +congeler +connoter +consonne +contact +convexe +copain +copie +corail +corbeau +cordage +corniche +corpus +correct +cortège +cosmique +costume +coton +coude +coupure +courage +couteau +couvrir +coyote +crabe +crainte +cravate +crayon +créature +créditer +crémeux +creuser +crevette +cribler +crier +cristal +critère +croire +croquer +crotale +crucial +cruel +crypter +cubique +cueillir +cuillère +cuisine +cuivre +culminer +cultiver +cumuler +cupide +curatif +curseur +cyanure +cycle +cylindre +cynique +daigner +damier +danger +danseur +dauphin +débattre +débiter +déborder +débrider +débutant +décaler +décembre +déchirer +décider +déclarer +décorer +décrire +décupler +dédale +déductif +déesse +défensif +défiler +défrayer +dégager +dégivrer +déglutir +dégrafer +déjeuner +délice +déloger +demander +demeurer +démolir +dénicher +dénouer +dentelle +dénuder +départ +dépenser +déphaser +déplacer +déposer +déranger +dérober +désastre +descente +désert +désigner +désobéir +dessiner +destrier +détacher +détester +détourer +détresse +devancer +devenir +deviner +devoir +diable +dialogue +diamant +dicter +différer +digérer +digital +digne +diluer +dimanche +diminuer +dioxyde +directif +diriger +discuter +disposer +dissiper +distance +divertir +diviser +docile +docteur +dogme +doigt +domaine +domicile +dompter +donateur +donjon +donner +dopamine +dortoir +dorure +dosage +doseur +dossier +dotation +douanier +double +douceur +douter +doyen +dragon +draper +dresser +dribbler +droiture +duperie +duplexe +durable +durcir +dynastie +éblouir +écarter +écharpe +échelle +éclairer +éclipse +éclore +écluse +école +économie +écorce +écouter +écraser +écrémer +écrivain +écrou +écume +écureuil +édifier +éduquer +effacer +effectif +effigie +effort +effrayer +effusion +égaliser +égarer +éjecter +élaborer +élargir +électron +élégant +éléphant +élève +éligible +élitisme +éloge +élucider +éluder +emballer +embellir +embryon +émeraude +émission +emmener +émotion +émouvoir +empereur +employer +emporter +emprise +émulsion +encadrer +enchère +enclave +encoche +endiguer +endosser +endroit +enduire +énergie +enfance +enfermer +enfouir +engager +engin +englober +énigme +enjamber +enjeu +enlever +ennemi +ennuyeux +enrichir +enrobage +enseigne +entasser +entendre +entier +entourer +entraver +énumérer +envahir +enviable +envoyer +enzyme +éolien +épaissir +épargne +épatant +épaule +épicerie +épidémie +épier +épilogue +épine +épisode +épitaphe +époque +épreuve +éprouver +épuisant +équerre +équipe +ériger +érosion +erreur +éruption +escalier +espadon +espèce +espiègle +espoir +esprit +esquiver +essayer +essence +essieu +essorer +estime +estomac +estrade +étagère +étaler +étanche +étatique +éteindre +étendoir +éternel +éthanol +éthique +ethnie +étirer +étoffer +étoile +étonnant +étourdir +étrange +étroit +étude +euphorie +évaluer +évasion +éventail +évidence +éviter +évolutif +évoquer +exact +exagérer +exaucer +exceller +excitant +exclusif +excuse +exécuter +exemple +exercer +exhaler +exhorter +exigence +exiler +exister +exotique +expédier +explorer +exposer +exprimer +exquis +extensif +extraire +exulter +fable +fabuleux +facette +facile +facture +faiblir +falaise +fameux +famille +farceur +farfelu +farine +farouche +fasciner +fatal +fatigue +faucon +fautif +faveur +favori +fébrile +féconder +fédérer +félin +femme +fémur +fendoir +féodal +fermer +féroce +ferveur +festival +feuille +feutre +février +fiasco +ficeler +fictif +fidèle +figure +filature +filetage +filière +filleul +filmer +filou +filtrer +financer +finir +fiole +firme +fissure +fixer +flairer +flamme +flasque +flatteur +fléau +flèche +fleur +flexion +flocon +flore +fluctuer +fluide +fluvial +folie +fonderie +fongible +fontaine +forcer +forgeron +formuler +fortune +fossile +foudre +fougère +fouiller +foulure +fourmi +fragile +fraise +franchir +frapper +frayeur +frégate +freiner +frelon +frémir +frénésie +frère +friable +friction +frisson +frivole +froid +fromage +frontal +frotter +fruit +fugitif +fuite +fureur +furieux +furtif +fusion +futur +gagner +galaxie +galerie +gambader +garantir +gardien +garnir +garrigue +gazelle +gazon +géant +gélatine +gélule +gendarme +général +génie +genou +gentil +géologie +géomètre +géranium +germe +gestuel +geyser +gibier +gicler +girafe +givre +glace +glaive +glisser +globe +gloire +glorieux +golfeur +gomme +gonfler +gorge +gorille +goudron +gouffre +goulot +goupille +gourmand +goutte +graduel +graffiti +graine +grand +grappin +gratuit +gravir +grenat +griffure +griller +grimper +grogner +gronder +grotte +groupe +gruger +grutier +gruyère +guépard +guerrier +guide +guimauve +guitare +gustatif +gymnaste +gyrostat +habitude +hachoir +halte +hameau +hangar +hanneton +haricot +harmonie +harpon +hasard +hélium +hématome +herbe +hérisson +hermine +héron +hésiter +heureux +hiberner +hibou +hilarant +histoire +hiver +homard +hommage +homogène +honneur +honorer +honteux +horde +horizon +horloge +hormone +horrible +houleux +housse +hublot +huileux +humain +humble +humide +humour +hurler +hydromel +hygiène +hymne +hypnose +idylle +ignorer +iguane +illicite +illusion +image +imbiber +imiter +immense +immobile +immuable +impact +impérial +implorer +imposer +imprimer +imputer +incarner +incendie +incident +incliner +incolore +indexer +indice +inductif +inédit +ineptie +inexact +infini +infliger +informer +infusion +ingérer +inhaler +inhiber +injecter +injure +innocent +inoculer +inonder +inscrire +insecte +insigne +insolite +inspirer +instinct +insulter +intact +intense +intime +intrigue +intuitif +inutile +invasion +inventer +inviter +invoquer +ironique +irradier +irréel +irriter +isoler +ivoire +ivresse +jaguar +jaillir +jambe +janvier +jardin +jauger +jaune +javelot +jetable +jeton +jeudi +jeunesse +joindre +joncher +jongler +joueur +jouissif +journal +jovial +joyau +joyeux +jubiler +jugement +junior +jupon +juriste +justice +juteux +juvénile +kayak +kimono +kiosque +label +labial +labourer +lacérer +lactose +lagune +laine +laisser +laitier +lambeau +lamelle +lampe +lanceur +langage +lanterne +lapin +largeur +larme +laurier +lavabo +lavoir +lecture +légal +léger +légume +lessive +lettre +levier +lexique +lézard +liasse +libérer +libre +licence +licorne +liège +lièvre +ligature +ligoter +ligue +limer +limite +limonade +limpide +linéaire +lingot +lionceau +liquide +lisière +lister +lithium +litige +littoral +livreur +logique +lointain +loisir +lombric +loterie +louer +lourd +loutre +louve +loyal +lubie +lucide +lucratif +lueur +lugubre +luisant +lumière +lunaire +lundi +luron +lutter +luxueux +machine +magasin +magenta +magique +maigre +maillon +maintien +mairie +maison +majorer +malaxer +maléfice +malheur +malice +mallette +mammouth +mandater +maniable +manquant +manteau +manuel +marathon +marbre +marchand +mardi +maritime +marqueur +marron +marteler +mascotte +massif +matériel +matière +matraque +maudire +maussade +mauve +maximal +méchant +méconnu +médaille +médecin +méditer +méduse +meilleur +mélange +mélodie +membre +mémoire +menacer +mener +menhir +mensonge +mentor +mercredi +mérite +merle +messager +mesure +métal +météore +méthode +métier +meuble +miauler +microbe +miette +mignon +migrer +milieu +million +mimique +mince +minéral +minimal +minorer +minute +miracle +miroiter +missile +mixte +mobile +moderne +moelleux +mondial +moniteur +monnaie +monotone +monstre +montagne +monument +moqueur +morceau +morsure +mortier +moteur +motif +mouche +moufle +moulin +mousson +mouton +mouvant +multiple +munition +muraille +murène +murmure +muscle +muséum +musicien +mutation +muter +mutuel +myriade +myrtille +mystère +mythique +nageur +nappe +narquois +narrer +natation +nation +nature +naufrage +nautique +navire +nébuleux +nectar +néfaste +négation +négliger +négocier +neige +nerveux +nettoyer +neurone +neutron +neveu +niche +nickel +nitrate +niveau +noble +nocif +nocturne +noirceur +noisette +nomade +nombreux +nommer +normatif +notable +notifier +notoire +nourrir +nouveau +novateur +novembre +novice +nuage +nuancer +nuire +nuisible +numéro +nuptial +nuque +nutritif +obéir +objectif +obliger +obscur +observer +obstacle +obtenir +obturer +occasion +occuper +océan +octobre +octroyer +octupler +oculaire +odeur +odorant +offenser +officier +offrir +ogive +oiseau +oisillon +olfactif +olivier +ombrage +omettre +onctueux +onduler +onéreux +onirique +opale +opaque +opérer +opinion +opportun +opprimer +opter +optique +orageux +orange +orbite +ordonner +oreille +organe +orgueil +orifice +ornement +orque +ortie +osciller +osmose +ossature +otarie +ouragan +ourson +outil +outrager +ouvrage +ovation +oxyde +oxygène +ozone +paisible +palace +palmarès +palourde +palper +panache +panda +pangolin +paniquer +panneau +panorama +pantalon +papaye +papier +papoter +papyrus +paradoxe +parcelle +paresse +parfumer +parler +parole +parrain +parsemer +partager +parure +parvenir +passion +pastèque +paternel +patience +patron +pavillon +pavoiser +payer +paysage +peigne +peintre +pelage +pélican +pelle +pelouse +peluche +pendule +pénétrer +pénible +pensif +pénurie +pépite +péplum +perdrix +perforer +période +permuter +perplexe +persil +perte +peser +pétale +petit +pétrir +peuple +pharaon +phobie +phoque +photon +phrase +physique +piano +pictural +pièce +pierre +pieuvre +pilote +pinceau +pipette +piquer +pirogue +piscine +piston +pivoter +pixel +pizza +placard +plafond +plaisir +planer +plaque +plastron +plateau +pleurer +plexus +pliage +plomb +plonger +pluie +plumage +pochette +poésie +poète +pointe +poirier +poisson +poivre +polaire +policier +pollen +polygone +pommade +pompier +ponctuel +pondérer +poney +portique +position +posséder +posture +potager +poteau +potion +pouce +poulain +poumon +pourpre +poussin +pouvoir +prairie +pratique +précieux +prédire +préfixe +prélude +prénom +présence +prétexte +prévoir +primitif +prince +prison +priver +problème +procéder +prodige +profond +progrès +proie +projeter +prologue +promener +propre +prospère +protéger +prouesse +proverbe +prudence +pruneau +psychose +public +puceron +puiser +pulpe +pulsar +punaise +punitif +pupitre +purifier +puzzle +pyramide +quasar +querelle +question +quiétude +quitter +quotient +racine +raconter +radieux +ragondin +raideur +raisin +ralentir +rallonge +ramasser +rapide +rasage +ratisser +ravager +ravin +rayonner +réactif +réagir +réaliser +réanimer +recevoir +réciter +réclamer +récolter +recruter +reculer +recycler +rédiger +redouter +refaire +réflexe +réformer +refrain +refuge +régalien +région +réglage +régulier +réitérer +rejeter +rejouer +relatif +relever +relief +remarque +remède +remise +remonter +remplir +remuer +renard +renfort +renifler +renoncer +rentrer +renvoi +replier +reporter +reprise +reptile +requin +réserve +résineux +résoudre +respect +rester +résultat +rétablir +retenir +réticule +retomber +retracer +réunion +réussir +revanche +revivre +révolte +révulsif +richesse +rideau +rieur +rigide +rigoler +rincer +riposter +risible +risque +rituel +rival +rivière +rocheux +romance +rompre +ronce +rondin +roseau +rosier +rotatif +rotor +rotule +rouge +rouille +rouleau +routine +royaume +ruban +rubis +ruche +ruelle +rugueux +ruiner +ruisseau +ruser +rustique +rythme +sabler +saboter +sabre +sacoche +safari +sagesse +saisir +salade +salive +salon +saluer +samedi +sanction +sanglier +sarcasme +sardine +saturer +saugrenu +saumon +sauter +sauvage +savant +savonner +scalpel +scandale +scélérat +scénario +sceptre +schéma +science +scinder +score +scrutin +sculpter +séance +sécable +sécher +secouer +sécréter +sédatif +séduire +seigneur +séjour +sélectif +semaine +sembler +semence +séminal +sénateur +sensible +sentence +séparer +séquence +serein +sergent +sérieux +serrure +sérum +service +sésame +sévir +sevrage +sextuple +sidéral +siècle +siéger +siffler +sigle +signal +silence +silicium +simple +sincère +sinistre +siphon +sirop +sismique +situer +skier +social +socle +sodium +soigneux +soldat +soleil +solitude +soluble +sombre +sommeil +somnoler +sonde +songeur +sonnette +sonore +sorcier +sortir +sosie +sottise +soucieux +soudure +souffle +soulever +soupape +source +soutirer +souvenir +spacieux +spatial +spécial +sphère +spiral +stable +station +sternum +stimulus +stipuler +strict +studieux +stupeur +styliste +sublime +substrat +subtil +subvenir +succès +sucre +suffixe +suggérer +suiveur +sulfate +superbe +supplier +surface +suricate +surmener +surprise +sursaut +survie +suspect +syllabe +symbole +symétrie +synapse +syntaxe +système +tabac +tablier +tactile +tailler +talent +talisman +talonner +tambour +tamiser +tangible +tapis +taquiner +tarder +tarif +tartine +tasse +tatami +tatouage +taupe +taureau +taxer +témoin +temporel +tenaille +tendre +teneur +tenir +tension +terminer +terne +terrible +tétine +texte +thème +théorie +thérapie +thorax +tibia +tiède +timide +tirelire +tiroir +tissu +titane +titre +tituber +toboggan +tolérant +tomate +tonique +tonneau +toponyme +torche +tordre +tornade +torpille +torrent +torse +tortue +totem +toucher +tournage +tousser +toxine +traction +trafic +tragique +trahir +train +trancher +travail +trèfle +tremper +trésor +treuil +triage +tribunal +tricoter +trilogie +triomphe +tripler +triturer +trivial +trombone +tronc +tropical +troupeau +tuile +tulipe +tumulte +tunnel +turbine +tuteur +tutoyer +tuyau +tympan +typhon +typique +tyran +ubuesque +ultime +ultrason +unanime +unifier +union +unique +unitaire +univers +uranium +urbain +urticant +usage +usine +usuel +usure +utile +utopie +vacarme +vaccin +vagabond +vague +vaillant +vaincre +vaisseau +valable +valise +vallon +valve +vampire +vanille +vapeur +varier +vaseux +vassal +vaste +vecteur +vedette +végétal +véhicule +veinard +véloce +vendredi +vénérer +venger +venimeux +ventouse +verdure +vérin +vernir +verrou +verser +vertu +veston +vétéran +vétuste +vexant +vexer +viaduc +viande +victoire +vidange +vidéo +vignette +vigueur +vilain +village +vinaigre +violon +vipère +virement +virtuose +virus +visage +viseur +vision +visqueux +visuel +vital +vitesse +viticole +vitrine +vivace +vivipare +vocation +voguer +voile +voisin +voiture +volaille +volcan +voltiger +volume +vorace +vortex +voter +vouloir +voyage +voyelle +wagon +xénon +yacht +zèbre +zénith +zeste +zoologie`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/italian.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/italian.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/italian.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/italian.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/italian.js new file mode 100644 index 0000000..7eabb0e --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/italian.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `abaco +abbaglio +abbinato +abete +abisso +abolire +abrasivo +abrogato +accadere +accenno +accusato +acetone +achille +acido +acqua +acre +acrilico +acrobata +acuto +adagio +addebito +addome +adeguato +aderire +adipe +adottare +adulare +affabile +affetto +affisso +affranto +aforisma +afoso +africano +agave +agente +agevole +aggancio +agire +agitare +agonismo +agricolo +agrumeto +aguzzo +alabarda +alato +albatro +alberato +albo +albume +alce +alcolico +alettone +alfa +algebra +aliante +alibi +alimento +allagato +allegro +allievo +allodola +allusivo +almeno +alogeno +alpaca +alpestre +altalena +alterno +alticcio +altrove +alunno +alveolo +alzare +amalgama +amanita +amarena +ambito +ambrato +ameba +america +ametista +amico +ammasso +ammenda +ammirare +ammonito +amore +ampio +ampliare +amuleto +anacardo +anagrafe +analista +anarchia +anatra +anca +ancella +ancora +andare +andrea +anello +angelo +angolare +angusto +anima +annegare +annidato +anno +annuncio +anonimo +anticipo +anzi +apatico +apertura +apode +apparire +appetito +appoggio +approdo +appunto +aprile +arabica +arachide +aragosta +araldica +arancio +aratura +arazzo +arbitro +archivio +ardito +arenile +argento +argine +arguto +aria +armonia +arnese +arredato +arringa +arrosto +arsenico +arso +artefice +arzillo +asciutto +ascolto +asepsi +asettico +asfalto +asino +asola +aspirato +aspro +assaggio +asse +assoluto +assurdo +asta +astenuto +astice +astratto +atavico +ateismo +atomico +atono +attesa +attivare +attorno +attrito +attuale +ausilio +austria +autista +autonomo +autunno +avanzato +avere +avvenire +avviso +avvolgere +azione +azoto +azzimo +azzurro +babele +baccano +bacino +baco +badessa +badilata +bagnato +baita +balcone +baldo +balena +ballata +balzano +bambino +bandire +baraonda +barbaro +barca +baritono +barlume +barocco +basilico +basso +batosta +battuto +baule +bava +bavosa +becco +beffa +belgio +belva +benda +benevole +benigno +benzina +bere +berlina +beta +bibita +bici +bidone +bifido +biga +bilancia +bimbo +binocolo +biologo +bipede +bipolare +birbante +birra +biscotto +bisesto +bisnonno +bisonte +bisturi +bizzarro +blando +blatta +bollito +bonifico +bordo +bosco +botanico +bottino +bozzolo +braccio +bradipo +brama +branca +bravura +bretella +brevetto +brezza +briglia +brillante +brindare +broccolo +brodo +bronzina +brullo +bruno +bubbone +buca +budino +buffone +buio +bulbo +buono +burlone +burrasca +bussola +busta +cadetto +caduco +calamaro +calcolo +calesse +calibro +calmo +caloria +cambusa +camerata +camicia +cammino +camola +campale +canapa +candela +cane +canino +canotto +cantina +capace +capello +capitolo +capogiro +cappero +capra +capsula +carapace +carcassa +cardo +carisma +carovana +carretto +cartolina +casaccio +cascata +caserma +caso +cassone +castello +casuale +catasta +catena +catrame +cauto +cavillo +cedibile +cedrata +cefalo +celebre +cellulare +cena +cenone +centesimo +ceramica +cercare +certo +cerume +cervello +cesoia +cespo +ceto +chela +chiaro +chicca +chiedere +chimera +china +chirurgo +chitarra +ciao +ciclismo +cifrare +cigno +cilindro +ciottolo +circa +cirrosi +citrico +cittadino +ciuffo +civetta +civile +classico +clinica +cloro +cocco +codardo +codice +coerente +cognome +collare +colmato +colore +colposo +coltivato +colza +coma +cometa +commando +comodo +computer +comune +conciso +condurre +conferma +congelare +coniuge +connesso +conoscere +consumo +continuo +convegno +coperto +copione +coppia +copricapo +corazza +cordata +coricato +cornice +corolla +corpo +corredo +corsia +cortese +cosmico +costante +cottura +covato +cratere +cravatta +creato +credere +cremoso +crescita +creta +criceto +crinale +crisi +critico +croce +cronaca +crostata +cruciale +crusca +cucire +cuculo +cugino +cullato +cupola +curatore +cursore +curvo +cuscino +custode +dado +daino +dalmata +damerino +daniela +dannoso +danzare +datato +davanti +davvero +debutto +decennio +deciso +declino +decollo +decreto +dedicato +definito +deforme +degno +delegare +delfino +delirio +delta +demenza +denotato +dentro +deposito +derapata +derivare +deroga +descritto +deserto +desiderio +desumere +detersivo +devoto +diametro +dicembre +diedro +difeso +diffuso +digerire +digitale +diluvio +dinamico +dinnanzi +dipinto +diploma +dipolo +diradare +dire +dirotto +dirupo +disagio +discreto +disfare +disgelo +disposto +distanza +disumano +dito +divano +divelto +dividere +divorato +doblone +docente +doganale +dogma +dolce +domato +domenica +dominare +dondolo +dono +dormire +dote +dottore +dovuto +dozzina +drago +druido +dubbio +dubitare +ducale +duna +duomo +duplice +duraturo +ebano +eccesso +ecco +eclissi +economia +edera +edicola +edile +editoria +educare +egemonia +egli +egoismo +egregio +elaborato +elargire +elegante +elencato +eletto +elevare +elfico +elica +elmo +elsa +eluso +emanato +emblema +emesso +emiro +emotivo +emozione +empirico +emulo +endemico +enduro +energia +enfasi +enoteca +entrare +enzima +epatite +epilogo +episodio +epocale +eppure +equatore +erario +erba +erboso +erede +eremita +erigere +ermetico +eroe +erosivo +errante +esagono +esame +esanime +esaudire +esca +esempio +esercito +esibito +esigente +esistere +esito +esofago +esortato +esoso +espanso +espresso +essenza +esso +esteso +estimare +estonia +estroso +esultare +etilico +etnico +etrusco +etto +euclideo +europa +evaso +evidenza +evitato +evoluto +evviva +fabbrica +faccenda +fachiro +falco +famiglia +fanale +fanfara +fango +fantasma +fare +farfalla +farinoso +farmaco +fascia +fastoso +fasullo +faticare +fato +favoloso +febbre +fecola +fede +fegato +felpa +feltro +femmina +fendere +fenomeno +fermento +ferro +fertile +fessura +festivo +fetta +feudo +fiaba +fiducia +fifa +figurato +filo +finanza +finestra +finire +fiore +fiscale +fisico +fiume +flacone +flamenco +flebo +flemma +florido +fluente +fluoro +fobico +focaccia +focoso +foderato +foglio +folata +folclore +folgore +fondente +fonetico +fonia +fontana +forbito +forchetta +foresta +formica +fornaio +foro +fortezza +forzare +fosfato +fosso +fracasso +frana +frassino +fratello +freccetta +frenata +fresco +frigo +frollino +fronde +frugale +frutta +fucilata +fucsia +fuggente +fulmine +fulvo +fumante +fumetto +fumoso +fune +funzione +fuoco +furbo +furgone +furore +fuso +futile +gabbiano +gaffe +galateo +gallina +galoppo +gambero +gamma +garanzia +garbo +garofano +garzone +gasdotto +gasolio +gastrico +gatto +gaudio +gazebo +gazzella +geco +gelatina +gelso +gemello +gemmato +gene +genitore +gennaio +genotipo +gergo +ghepardo +ghiaccio +ghisa +giallo +gilda +ginepro +giocare +gioiello +giorno +giove +girato +girone +gittata +giudizio +giurato +giusto +globulo +glutine +gnomo +gobba +golf +gomito +gommone +gonfio +gonna +governo +gracile +grado +grafico +grammo +grande +grattare +gravoso +grazia +greca +gregge +grifone +grigio +grinza +grotta +gruppo +guadagno +guaio +guanto +guardare +gufo +guidare +ibernato +icona +identico +idillio +idolo +idra +idrico +idrogeno +igiene +ignaro +ignorato +ilare +illeso +illogico +illudere +imballo +imbevuto +imbocco +imbuto +immane +immerso +immolato +impacco +impeto +impiego +importo +impronta +inalare +inarcare +inattivo +incanto +incendio +inchino +incisivo +incluso +incontro +incrocio +incubo +indagine +india +indole +inedito +infatti +infilare +inflitto +ingaggio +ingegno +inglese +ingordo +ingrosso +innesco +inodore +inoltrare +inondato +insano +insetto +insieme +insonnia +insulina +intasato +intero +intonaco +intuito +inumidire +invalido +invece +invito +iperbole +ipnotico +ipotesi +ippica +iride +irlanda +ironico +irrigato +irrorare +isolato +isotopo +isterico +istituto +istrice +italia +iterare +labbro +labirinto +lacca +lacerato +lacrima +lacuna +laddove +lago +lampo +lancetta +lanterna +lardoso +larga +laringe +lastra +latenza +latino +lattuga +lavagna +lavoro +legale +leggero +lembo +lentezza +lenza +leone +lepre +lesivo +lessato +lesto +letterale +leva +levigato +libero +lido +lievito +lilla +limatura +limitare +limpido +lineare +lingua +liquido +lira +lirica +lisca +lite +litigio +livrea +locanda +lode +logica +lombare +londra +longevo +loquace +lorenzo +loto +lotteria +luce +lucidato +lumaca +luminoso +lungo +lupo +luppolo +lusinga +lusso +lutto +macabro +macchina +macero +macinato +madama +magico +maglia +magnete +magro +maiolica +malafede +malgrado +malinteso +malsano +malto +malumore +mana +mancia +mandorla +mangiare +manifesto +mannaro +manovra +mansarda +mantide +manubrio +mappa +maratona +marcire +maretta +marmo +marsupio +maschera +massaia +mastino +materasso +matricola +mattone +maturo +mazurca +meandro +meccanico +mecenate +medesimo +meditare +mega +melassa +melis +melodia +meninge +meno +mensola +mercurio +merenda +merlo +meschino +mese +messere +mestolo +metallo +metodo +mettere +miagolare +mica +micelio +michele +microbo +midollo +miele +migliore +milano +milite +mimosa +minerale +mini +minore +mirino +mirtillo +miscela +missiva +misto +misurare +mitezza +mitigare +mitra +mittente +mnemonico +modello +modifica +modulo +mogano +mogio +mole +molosso +monastero +monco +mondina +monetario +monile +monotono +monsone +montato +monviso +mora +mordere +morsicato +mostro +motivato +motosega +motto +movenza +movimento +mozzo +mucca +mucosa +muffa +mughetto +mugnaio +mulatto +mulinello +multiplo +mummia +munto +muovere +murale +musa +muscolo +musica +mutevole +muto +nababbo +nafta +nanometro +narciso +narice +narrato +nascere +nastrare +naturale +nautica +naviglio +nebulosa +necrosi +negativo +negozio +nemmeno +neofita +neretto +nervo +nessuno +nettuno +neutrale +neve +nevrotico +nicchia +ninfa +nitido +nobile +nocivo +nodo +nome +nomina +nordico +normale +norvegese +nostrano +notare +notizia +notturno +novella +nucleo +nulla +numero +nuovo +nutrire +nuvola +nuziale +oasi +obbedire +obbligo +obelisco +oblio +obolo +obsoleto +occasione +occhio +occidente +occorrere +occultare +ocra +oculato +odierno +odorare +offerta +offrire +offuscato +oggetto +oggi +ognuno +olandese +olfatto +oliato +oliva +ologramma +oltre +omaggio +ombelico +ombra +omega +omissione +ondoso +onere +onice +onnivoro +onorevole +onta +operato +opinione +opposto +oracolo +orafo +ordine +orecchino +orefice +orfano +organico +origine +orizzonte +orma +ormeggio +ornativo +orologio +orrendo +orribile +ortensia +ortica +orzata +orzo +osare +oscurare +osmosi +ospedale +ospite +ossa +ossidare +ostacolo +oste +otite +otre +ottagono +ottimo +ottobre +ovale +ovest +ovino +oviparo +ovocito +ovunque +ovviare +ozio +pacchetto +pace +pacifico +padella +padrone +paese +paga +pagina +palazzina +palesare +pallido +palo +palude +pandoro +pannello +paolo +paonazzo +paprica +parabola +parcella +parere +pargolo +pari +parlato +parola +partire +parvenza +parziale +passivo +pasticca +patacca +patologia +pattume +pavone +peccato +pedalare +pedonale +peggio +peloso +penare +pendice +penisola +pennuto +penombra +pensare +pentola +pepe +pepita +perbene +percorso +perdonato +perforare +pergamena +periodo +permesso +perno +perplesso +persuaso +pertugio +pervaso +pesatore +pesista +peso +pestifero +petalo +pettine +petulante +pezzo +piacere +pianta +piattino +piccino +picozza +piega +pietra +piffero +pigiama +pigolio +pigro +pila +pilifero +pillola +pilota +pimpante +pineta +pinna +pinolo +pioggia +piombo +piramide +piretico +pirite +pirolisi +pitone +pizzico +placebo +planare +plasma +platano +plenario +pochezza +poderoso +podismo +poesia +poggiare +polenta +poligono +pollice +polmonite +polpetta +polso +poltrona +polvere +pomice +pomodoro +ponte +popoloso +porfido +poroso +porpora +porre +portata +posa +positivo +possesso +postulato +potassio +potere +pranzo +prassi +pratica +precluso +predica +prefisso +pregiato +prelievo +premere +prenotare +preparato +presenza +pretesto +prevalso +prima +principe +privato +problema +procura +produrre +profumo +progetto +prolunga +promessa +pronome +proposta +proroga +proteso +prova +prudente +prugna +prurito +psiche +pubblico +pudica +pugilato +pugno +pulce +pulito +pulsante +puntare +pupazzo +pupilla +puro +quadro +qualcosa +quasi +querela +quota +raccolto +raddoppio +radicale +radunato +raffica +ragazzo +ragione +ragno +ramarro +ramingo +ramo +randagio +rantolare +rapato +rapina +rappreso +rasatura +raschiato +rasente +rassegna +rastrello +rata +ravveduto +reale +recepire +recinto +recluta +recondito +recupero +reddito +redimere +regalato +registro +regola +regresso +relazione +remare +remoto +renna +replica +reprimere +reputare +resa +residente +responso +restauro +rete +retina +retorica +rettifica +revocato +riassunto +ribadire +ribelle +ribrezzo +ricarica +ricco +ricevere +riciclato +ricordo +ricreduto +ridicolo +ridurre +rifasare +riflesso +riforma +rifugio +rigare +rigettato +righello +rilassato +rilevato +rimanere +rimbalzo +rimedio +rimorchio +rinascita +rincaro +rinforzo +rinnovo +rinomato +rinsavito +rintocco +rinuncia +rinvenire +riparato +ripetuto +ripieno +riportare +ripresa +ripulire +risata +rischio +riserva +risibile +riso +rispetto +ristoro +risultato +risvolto +ritardo +ritegno +ritmico +ritrovo +riunione +riva +riverso +rivincita +rivolto +rizoma +roba +robotico +robusto +roccia +roco +rodaggio +rodere +roditore +rogito +rollio +romantico +rompere +ronzio +rosolare +rospo +rotante +rotondo +rotula +rovescio +rubizzo +rubrica +ruga +rullino +rumine +rumoroso +ruolo +rupe +russare +rustico +sabato +sabbiare +sabotato +sagoma +salasso +saldatura +salgemma +salivare +salmone +salone +saltare +saluto +salvo +sapere +sapido +saporito +saraceno +sarcasmo +sarto +sassoso +satellite +satira +satollo +saturno +savana +savio +saziato +sbadiglio +sbalzo +sbancato +sbarra +sbattere +sbavare +sbendare +sbirciare +sbloccato +sbocciato +sbrinare +sbruffone +sbuffare +scabroso +scadenza +scala +scambiare +scandalo +scapola +scarso +scatenare +scavato +scelto +scenico +scettro +scheda +schiena +sciarpa +scienza +scindere +scippo +sciroppo +scivolo +sclerare +scodella +scolpito +scomparto +sconforto +scoprire +scorta +scossone +scozzese +scriba +scrollare +scrutinio +scuderia +scultore +scuola +scuro +scusare +sdebitare +sdoganare +seccatura +secondo +sedano +seggiola +segnalato +segregato +seguito +selciato +selettivo +sella +selvaggio +semaforo +sembrare +seme +seminato +sempre +senso +sentire +sepolto +sequenza +serata +serbato +sereno +serio +serpente +serraglio +servire +sestina +setola +settimana +sfacelo +sfaldare +sfamato +sfarzoso +sfaticato +sfera +sfida +sfilato +sfinge +sfocato +sfoderare +sfogo +sfoltire +sforzato +sfratto +sfruttato +sfuggito +sfumare +sfuso +sgabello +sgarbato +sgonfiare +sgorbio +sgrassato +sguardo +sibilo +siccome +sierra +sigla +signore +silenzio +sillaba +simbolo +simpatico +simulato +sinfonia +singolo +sinistro +sino +sintesi +sinusoide +sipario +sisma +sistole +situato +slitta +slogatura +sloveno +smarrito +smemorato +smentito +smeraldo +smilzo +smontare +smottato +smussato +snellire +snervato +snodo +sobbalzo +sobrio +soccorso +sociale +sodale +soffitto +sogno +soldato +solenne +solido +sollazzo +solo +solubile +solvente +somatico +somma +sonda +sonetto +sonnifero +sopire +soppeso +sopra +sorgere +sorpasso +sorriso +sorso +sorteggio +sorvolato +sospiro +sosta +sottile +spada +spalla +spargere +spatola +spavento +spazzola +specie +spedire +spegnere +spelatura +speranza +spessore +spettrale +spezzato +spia +spigoloso +spillato +spinoso +spirale +splendido +sportivo +sposo +spranga +sprecare +spronato +spruzzo +spuntino +squillo +sradicare +srotolato +stabile +stacco +staffa +stagnare +stampato +stantio +starnuto +stasera +statuto +stelo +steppa +sterzo +stiletto +stima +stirpe +stivale +stizzoso +stonato +storico +strappo +stregato +stridulo +strozzare +strutto +stuccare +stufo +stupendo +subentro +succoso +sudore +suggerito +sugo +sultano +suonare +superbo +supporto +surgelato +surrogato +sussurro +sutura +svagare +svedese +sveglio +svelare +svenuto +svezia +sviluppo +svista +svizzera +svolta +svuotare +tabacco +tabulato +tacciare +taciturno +tale +talismano +tampone +tannino +tara +tardivo +targato +tariffa +tarpare +tartaruga +tasto +tattico +taverna +tavolata +tazza +teca +tecnico +telefono +temerario +tempo +temuto +tendone +tenero +tensione +tentacolo +teorema +terme +terrazzo +terzetto +tesi +tesserato +testato +tetro +tettoia +tifare +tigella +timbro +tinto +tipico +tipografo +tiraggio +tiro +titanio +titolo +titubante +tizio +tizzone +toccare +tollerare +tolto +tombola +tomo +tonfo +tonsilla +topazio +topologia +toppa +torba +tornare +torrone +tortora +toscano +tossire +tostatura +totano +trabocco +trachea +trafila +tragedia +tralcio +tramonto +transito +trapano +trarre +trasloco +trattato +trave +treccia +tremolio +trespolo +tributo +tricheco +trifoglio +trillo +trincea +trio +tristezza +triturato +trivella +tromba +trono +troppo +trottola +trovare +truccato +tubatura +tuffato +tulipano +tumulto +tunisia +turbare +turchino +tuta +tutela +ubicato +uccello +uccisore +udire +uditivo +uffa +ufficio +uguale +ulisse +ultimato +umano +umile +umorismo +uncinetto +ungere +ungherese +unicorno +unificato +unisono +unitario +unte +uovo +upupa +uragano +urgenza +urlo +usanza +usato +uscito +usignolo +usuraio +utensile +utilizzo +utopia +vacante +vaccinato +vagabondo +vagliato +valanga +valgo +valico +valletta +valoroso +valutare +valvola +vampata +vangare +vanitoso +vano +vantaggio +vanvera +vapore +varano +varcato +variante +vasca +vedetta +vedova +veduto +vegetale +veicolo +velcro +velina +velluto +veloce +venato +vendemmia +vento +verace +verbale +vergogna +verifica +vero +verruca +verticale +vescica +vessillo +vestale +veterano +vetrina +vetusto +viandante +vibrante +vicenda +vichingo +vicinanza +vidimare +vigilia +vigneto +vigore +vile +villano +vimini +vincitore +viola +vipera +virgola +virologo +virulento +viscoso +visione +vispo +vissuto +visura +vita +vitello +vittima +vivanda +vivido +viziare +voce +voga +volatile +volere +volpe +voragine +vulcano +zampogna +zanna +zappato +zattera +zavorra +zefiro +zelante +zelo +zenzero +zerbino +zibetto +zinco +zircone +zitto +zolla +zotico +zucchero +zufolo +zulu +zuppa`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/japanese.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/japanese.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/japanese.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/japanese.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/japanese.js new file mode 100644 index 0000000..82eda6b --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/japanese.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `あいこくしん +あいさつ +あいだ +あおぞら +あかちゃん +あきる +あけがた +あける +あこがれる +あさい +あさひ +あしあと +あじわう +あずかる +あずき +あそぶ +あたえる +あたためる +あたりまえ +あたる +あつい +あつかう +あっしゅく +あつまり +あつめる +あてな +あてはまる +あひる +あぶら +あぶる +あふれる +あまい +あまど +あまやかす +あまり +あみもの +あめりか +あやまる +あゆむ +あらいぐま +あらし +あらすじ +あらためる +あらゆる +あらわす +ありがとう +あわせる +あわてる +あんい +あんがい +あんこ +あんぜん +あんてい +あんない +あんまり +いいだす +いおん +いがい +いがく +いきおい +いきなり +いきもの +いきる +いくじ +いくぶん +いけばな +いけん +いこう +いこく +いこつ +いさましい +いさん +いしき +いじゅう +いじょう +いじわる +いずみ +いずれ +いせい +いせえび +いせかい +いせき +いぜん +いそうろう +いそがしい +いだい +いだく +いたずら +いたみ +いたりあ +いちおう +いちじ +いちど +いちば +いちぶ +いちりゅう +いつか +いっしゅん +いっせい +いっそう +いったん +いっち +いってい +いっぽう +いてざ +いてん +いどう +いとこ +いない +いなか +いねむり +いのち +いのる +いはつ +いばる +いはん +いびき +いひん +いふく +いへん +いほう +いみん +いもうと +いもたれ +いもり +いやがる +いやす +いよかん +いよく +いらい +いらすと +いりぐち +いりょう +いれい +いれもの +いれる +いろえんぴつ +いわい +いわう +いわかん +いわば +いわゆる +いんげんまめ +いんさつ +いんしょう +いんよう +うえき +うえる +うおざ +うがい +うかぶ +うかべる +うきわ +うくらいな +うくれれ +うけたまわる +うけつけ +うけとる +うけもつ +うける +うごかす +うごく +うこん +うさぎ +うしなう +うしろがみ +うすい +うすぎ +うすぐらい +うすめる +うせつ +うちあわせ +うちがわ +うちき +うちゅう +うっかり +うつくしい +うったえる +うつる +うどん +うなぎ +うなじ +うなずく +うなる +うねる +うのう +うぶげ +うぶごえ +うまれる +うめる +うもう +うやまう +うよく +うらがえす +うらぐち +うらない +うりあげ +うりきれ +うるさい +うれしい +うれゆき +うれる +うろこ +うわき +うわさ +うんこう +うんちん +うんてん +うんどう +えいえん +えいが +えいきょう +えいご +えいせい +えいぶん +えいよう +えいわ +えおり +えがお +えがく +えきたい +えくせる +えしゃく +えすて +えつらん +えのぐ +えほうまき +えほん +えまき +えもじ +えもの +えらい +えらぶ +えりあ +えんえん +えんかい +えんぎ +えんげき +えんしゅう +えんぜつ +えんそく +えんちょう +えんとつ +おいかける +おいこす +おいしい +おいつく +おうえん +おうさま +おうじ +おうせつ +おうたい +おうふく +おうべい +おうよう +おえる +おおい +おおう +おおどおり +おおや +おおよそ +おかえり +おかず +おがむ +おかわり +おぎなう +おきる +おくさま +おくじょう +おくりがな +おくる +おくれる +おこす +おこなう +おこる +おさえる +おさない +おさめる +おしいれ +おしえる +おじぎ +おじさん +おしゃれ +おそらく +おそわる +おたがい +おたく +おだやか +おちつく +おっと +おつり +おでかけ +おとしもの +おとなしい +おどり +おどろかす +おばさん +おまいり +おめでとう +おもいで +おもう +おもたい +おもちゃ +おやつ +おやゆび +およぼす +おらんだ +おろす +おんがく +おんけい +おんしゃ +おんせん +おんだん +おんちゅう +おんどけい +かあつ +かいが +がいき +がいけん +がいこう +かいさつ +かいしゃ +かいすいよく +かいぜん +かいぞうど +かいつう +かいてん +かいとう +かいふく +がいへき +かいほう +かいよう +がいらい +かいわ +かえる +かおり +かかえる +かがく +かがし +かがみ +かくご +かくとく +かざる +がぞう +かたい +かたち +がちょう +がっきゅう +がっこう +がっさん +がっしょう +かなざわし +かのう +がはく +かぶか +かほう +かほご +かまう +かまぼこ +かめれおん +かゆい +かようび +からい +かるい +かろう +かわく +かわら +がんか +かんけい +かんこう +かんしゃ +かんそう +かんたん +かんち +がんばる +きあい +きあつ +きいろ +ぎいん +きうい +きうん +きえる +きおう +きおく +きおち +きおん +きかい +きかく +きかんしゃ +ききて +きくばり +きくらげ +きけんせい +きこう +きこえる +きこく +きさい +きさく +きさま +きさらぎ +ぎじかがく +ぎしき +ぎじたいけん +ぎじにってい +ぎじゅつしゃ +きすう +きせい +きせき +きせつ +きそう +きぞく +きぞん +きたえる +きちょう +きつえん +ぎっちり +きつつき +きつね +きてい +きどう +きどく +きない +きなが +きなこ +きぬごし +きねん +きのう +きのした +きはく +きびしい +きひん +きふく +きぶん +きぼう +きほん +きまる +きみつ +きむずかしい +きめる +きもだめし +きもち +きもの +きゃく +きやく +ぎゅうにく +きよう +きょうりゅう +きらい +きらく +きりん +きれい +きれつ +きろく +ぎろん +きわめる +ぎんいろ +きんかくじ +きんじょ +きんようび +ぐあい +くいず +くうかん +くうき +くうぐん +くうこう +ぐうせい +くうそう +ぐうたら +くうふく +くうぼ +くかん +くきょう +くげん +ぐこう +くさい +くさき +くさばな +くさる +くしゃみ +くしょう +くすのき +くすりゆび +くせげ +くせん +ぐたいてき +くださる +くたびれる +くちこみ +くちさき +くつした +ぐっすり +くつろぐ +くとうてん +くどく +くなん +くねくね +くのう +くふう +くみあわせ +くみたてる +くめる +くやくしょ +くらす +くらべる +くるま +くれる +くろう +くわしい +ぐんかん +ぐんしょく +ぐんたい +ぐんて +けあな +けいかく +けいけん +けいこ +けいさつ +げいじゅつ +けいたい +げいのうじん +けいれき +けいろ +けおとす +けおりもの +げきか +げきげん +げきだん +げきちん +げきとつ +げきは +げきやく +げこう +げこくじょう +げざい +けさき +げざん +けしき +けしごむ +けしょう +げすと +けたば +けちゃっぷ +けちらす +けつあつ +けつい +けつえき +けっこん +けつじょ +けっせき +けってい +けつまつ +げつようび +げつれい +けつろん +げどく +けとばす +けとる +けなげ +けなす +けなみ +けぬき +げねつ +けねん +けはい +げひん +けぶかい +げぼく +けまり +けみかる +けむし +けむり +けもの +けらい +けろけろ +けわしい +けんい +けんえつ +けんお +けんか +げんき +けんげん +けんこう +けんさく +けんしゅう +けんすう +げんそう +けんちく +けんてい +けんとう +けんない +けんにん +げんぶつ +けんま +けんみん +けんめい +けんらん +けんり +こあくま +こいぬ +こいびと +ごうい +こうえん +こうおん +こうかん +ごうきゅう +ごうけい +こうこう +こうさい +こうじ +こうすい +ごうせい +こうそく +こうたい +こうちゃ +こうつう +こうてい +こうどう +こうない +こうはい +ごうほう +ごうまん +こうもく +こうりつ +こえる +こおり +ごかい +ごがつ +ごかん +こくご +こくさい +こくとう +こくない +こくはく +こぐま +こけい +こける +ここのか +こころ +こさめ +こしつ +こすう +こせい +こせき +こぜん +こそだて +こたい +こたえる +こたつ +こちょう +こっか +こつこつ +こつばん +こつぶ +こてい +こてん +ことがら +ことし +ことば +ことり +こなごな +こねこね +このまま +このみ +このよ +ごはん +こひつじ +こふう +こふん +こぼれる +ごまあぶら +こまかい +ごますり +こまつな +こまる +こむぎこ +こもじ +こもち +こもの +こもん +こやく +こやま +こゆう +こゆび +こよい +こよう +こりる +これくしょん +ころっけ +こわもて +こわれる +こんいん +こんかい +こんき +こんしゅう +こんすい +こんだて +こんとん +こんなん +こんびに +こんぽん +こんまけ +こんや +こんれい +こんわく +ざいえき +さいかい +さいきん +ざいげん +ざいこ +さいしょ +さいせい +ざいたく +ざいちゅう +さいてき +ざいりょう +さうな +さかいし +さがす +さかな +さかみち +さがる +さぎょう +さくし +さくひん +さくら +さこく +さこつ +さずかる +ざせき +さたん +さつえい +ざつおん +ざっか +ざつがく +さっきょく +ざっし +さつじん +ざっそう +さつたば +さつまいも +さてい +さといも +さとう +さとおや +さとし +さとる +さのう +さばく +さびしい +さべつ +さほう +さほど +さます +さみしい +さみだれ +さむけ +さめる +さやえんどう +さゆう +さよう +さよく +さらだ +ざるそば +さわやか +さわる +さんいん +さんか +さんきゃく +さんこう +さんさい +ざんしょ +さんすう +さんせい +さんそ +さんち +さんま +さんみ +さんらん +しあい +しあげ +しあさって +しあわせ +しいく +しいん +しうち +しえい +しおけ +しかい +しかく +じかん +しごと +しすう +じだい +したうけ +したぎ +したて +したみ +しちょう +しちりん +しっかり +しつじ +しつもん +してい +してき +してつ +じてん +じどう +しなぎれ +しなもの +しなん +しねま +しねん +しのぐ +しのぶ +しはい +しばかり +しはつ +しはらい +しはん +しひょう +しふく +じぶん +しへい +しほう +しほん +しまう +しまる +しみん +しむける +じむしょ +しめい +しめる +しもん +しゃいん +しゃうん +しゃおん +じゃがいも +しやくしょ +しゃくほう +しゃけん +しゃこ +しゃざい +しゃしん +しゃせん +しゃそう +しゃたい +しゃちょう +しゃっきん +じゃま +しゃりん +しゃれい +じゆう +じゅうしょ +しゅくはく +じゅしん +しゅっせき +しゅみ +しゅらば +じゅんばん +しょうかい +しょくたく +しょっけん +しょどう +しょもつ +しらせる +しらべる +しんか +しんこう +じんじゃ +しんせいじ +しんちく +しんりん +すあげ +すあし +すあな +ずあん +すいえい +すいか +すいとう +ずいぶん +すいようび +すうがく +すうじつ +すうせん +すおどり +すきま +すくう +すくない +すける +すごい +すこし +ずさん +すずしい +すすむ +すすめる +すっかり +ずっしり +ずっと +すてき +すてる +すねる +すのこ +すはだ +すばらしい +ずひょう +ずぶぬれ +すぶり +すふれ +すべて +すべる +ずほう +すぼん +すまい +すめし +すもう +すやき +すらすら +するめ +すれちがう +すろっと +すわる +すんぜん +すんぽう +せあぶら +せいかつ +せいげん +せいじ +せいよう +せおう +せかいかん +せきにん +せきむ +せきゆ +せきらんうん +せけん +せこう +せすじ +せたい +せたけ +せっかく +せっきゃく +ぜっく +せっけん +せっこつ +せっさたくま +せつぞく +せつだん +せつでん +せっぱん +せつび +せつぶん +せつめい +せつりつ +せなか +せのび +せはば +せびろ +せぼね +せまい +せまる +せめる +せもたれ +せりふ +ぜんあく +せんい +せんえい +せんか +せんきょ +せんく +せんげん +ぜんご +せんさい +せんしゅ +せんすい +せんせい +せんぞ +せんたく +せんちょう +せんてい +せんとう +せんぬき +せんねん +せんぱい +ぜんぶ +ぜんぽう +せんむ +せんめんじょ +せんもん +せんやく +せんゆう +せんよう +ぜんら +ぜんりゃく +せんれい +せんろ +そあく +そいとげる +そいね +そうがんきょう +そうき +そうご +そうしん +そうだん +そうなん +そうび +そうめん +そうり +そえもの +そえん +そがい +そげき +そこう +そこそこ +そざい +そしな +そせい +そせん +そそぐ +そだてる +そつう +そつえん +そっかん +そつぎょう +そっけつ +そっこう +そっせん +そっと +そとがわ +そとづら +そなえる +そなた +そふぼ +そぼく +そぼろ +そまつ +そまる +そむく +そむりえ +そめる +そもそも +そよかぜ +そらまめ +そろう +そんかい +そんけい +そんざい +そんしつ +そんぞく +そんちょう +ぞんび +ぞんぶん +そんみん +たあい +たいいん +たいうん +たいえき +たいおう +だいがく +たいき +たいぐう +たいけん +たいこ +たいざい +だいじょうぶ +だいすき +たいせつ +たいそう +だいたい +たいちょう +たいてい +だいどころ +たいない +たいねつ +たいのう +たいはん +だいひょう +たいふう +たいへん +たいほ +たいまつばな +たいみんぐ +たいむ +たいめん +たいやき +たいよう +たいら +たいりょく +たいる +たいわん +たうえ +たえる +たおす +たおる +たおれる +たかい +たかね +たきび +たくさん +たこく +たこやき +たさい +たしざん +だじゃれ +たすける +たずさわる +たそがれ +たたかう +たたく +ただしい +たたみ +たちばな +だっかい +だっきゃく +だっこ +だっしゅつ +だったい +たてる +たとえる +たなばた +たにん +たぬき +たのしみ +たはつ +たぶん +たべる +たぼう +たまご +たまる +だむる +ためいき +ためす +ためる +たもつ +たやすい +たよる +たらす +たりきほんがん +たりょう +たりる +たると +たれる +たれんと +たろっと +たわむれる +だんあつ +たんい +たんおん +たんか +たんき +たんけん +たんご +たんさん +たんじょうび +だんせい +たんそく +たんたい +だんち +たんてい +たんとう +だんな +たんにん +だんねつ +たんのう +たんぴん +だんぼう +たんまつ +たんめい +だんれつ +だんろ +だんわ +ちあい +ちあん +ちいき +ちいさい +ちえん +ちかい +ちから +ちきゅう +ちきん +ちけいず +ちけん +ちこく +ちさい +ちしき +ちしりょう +ちせい +ちそう +ちたい +ちたん +ちちおや +ちつじょ +ちてき +ちてん +ちぬき +ちぬり +ちのう +ちひょう +ちへいせん +ちほう +ちまた +ちみつ +ちみどろ +ちめいど +ちゃんこなべ +ちゅうい +ちゆりょく +ちょうし +ちょさくけん +ちらし +ちらみ +ちりがみ +ちりょう +ちるど +ちわわ +ちんたい +ちんもく +ついか +ついたち +つうか +つうじょう +つうはん +つうわ +つかう +つかれる +つくね +つくる +つけね +つける +つごう +つたえる +つづく +つつじ +つつむ +つとめる +つながる +つなみ +つねづね +つのる +つぶす +つまらない +つまる +つみき +つめたい +つもり +つもる +つよい +つるぼ +つるみく +つわもの +つわり +てあし +てあて +てあみ +ていおん +ていか +ていき +ていけい +ていこく +ていさつ +ていし +ていせい +ていたい +ていど +ていねい +ていひょう +ていへん +ていぼう +てうち +ておくれ +てきとう +てくび +でこぼこ +てさぎょう +てさげ +てすり +てそう +てちがい +てちょう +てつがく +てつづき +でっぱ +てつぼう +てつや +でぬかえ +てぬき +てぬぐい +てのひら +てはい +てぶくろ +てふだ +てほどき +てほん +てまえ +てまきずし +てみじか +てみやげ +てらす +てれび +てわけ +てわたし +でんあつ +てんいん +てんかい +てんき +てんぐ +てんけん +てんごく +てんさい +てんし +てんすう +でんち +てんてき +てんとう +てんない +てんぷら +てんぼうだい +てんめつ +てんらんかい +でんりょく +でんわ +どあい +といれ +どうかん +とうきゅう +どうぐ +とうし +とうむぎ +とおい +とおか +とおく +とおす +とおる +とかい +とかす +ときおり +ときどき +とくい +とくしゅう +とくてん +とくに +とくべつ +とけい +とける +とこや +とさか +としょかん +とそう +とたん +とちゅう +とっきゅう +とっくん +とつぜん +とつにゅう +とどける +ととのえる +とない +となえる +となり +とのさま +とばす +どぶがわ +とほう +とまる +とめる +ともだち +ともる +どようび +とらえる +とんかつ +どんぶり +ないかく +ないこう +ないしょ +ないす +ないせん +ないそう +なおす +ながい +なくす +なげる +なこうど +なさけ +なたでここ +なっとう +なつやすみ +ななおし +なにごと +なにもの +なにわ +なのか +なふだ +なまいき +なまえ +なまみ +なみだ +なめらか +なめる +なやむ +ならう +ならび +ならぶ +なれる +なわとび +なわばり +にあう +にいがた +にうけ +におい +にかい +にがて +にきび +にくしみ +にくまん +にげる +にさんかたんそ +にしき +にせもの +にちじょう +にちようび +にっか +にっき +にっけい +にっこう +にっさん +にっしょく +にっすう +にっせき +にってい +になう +にほん +にまめ +にもつ +にやり +にゅういん +にりんしゃ +にわとり +にんい +にんか +にんき +にんげん +にんしき +にんずう +にんそう +にんたい +にんち +にんてい +にんにく +にんぷ +にんまり +にんむ +にんめい +にんよう +ぬいくぎ +ぬかす +ぬぐいとる +ぬぐう +ぬくもり +ぬすむ +ぬまえび +ぬめり +ぬらす +ぬんちゃく +ねあげ +ねいき +ねいる +ねいろ +ねぐせ +ねくたい +ねくら +ねこぜ +ねこむ +ねさげ +ねすごす +ねそべる +ねだん +ねつい +ねっしん +ねつぞう +ねったいぎょ +ねぶそく +ねふだ +ねぼう +ねほりはほり +ねまき +ねまわし +ねみみ +ねむい +ねむたい +ねもと +ねらう +ねわざ +ねんいり +ねんおし +ねんかん +ねんきん +ねんぐ +ねんざ +ねんし +ねんちゃく +ねんど +ねんぴ +ねんぶつ +ねんまつ +ねんりょう +ねんれい +のいず +のおづま +のがす +のきなみ +のこぎり +のこす +のこる +のせる +のぞく +のぞむ +のたまう +のちほど +のっく +のばす +のはら +のべる +のぼる +のみもの +のやま +のらいぬ +のらねこ +のりもの +のりゆき +のれん +のんき +ばあい +はあく +ばあさん +ばいか +ばいく +はいけん +はいご +はいしん +はいすい +はいせん +はいそう +はいち +ばいばい +はいれつ +はえる +はおる +はかい +ばかり +はかる +はくしゅ +はけん +はこぶ +はさみ +はさん +はしご +ばしょ +はしる +はせる +ぱそこん +はそん +はたん +はちみつ +はつおん +はっかく +はづき +はっきり +はっくつ +はっけん +はっこう +はっさん +はっしん +はったつ +はっちゅう +はってん +はっぴょう +はっぽう +はなす +はなび +はにかむ +はぶらし +はみがき +はむかう +はめつ +はやい +はやし +はらう +はろうぃん +はわい +はんい +はんえい +はんおん +はんかく +はんきょう +ばんぐみ +はんこ +はんしゃ +はんすう +はんだん +ぱんち +ぱんつ +はんてい +はんとし +はんのう +はんぱ +はんぶん +はんぺん +はんぼうき +はんめい +はんらん +はんろん +ひいき +ひうん +ひえる +ひかく +ひかり +ひかる +ひかん +ひくい +ひけつ +ひこうき +ひこく +ひさい +ひさしぶり +ひさん +びじゅつかん +ひしょ +ひそか +ひそむ +ひたむき +ひだり +ひたる +ひつぎ +ひっこし +ひっし +ひつじゅひん +ひっす +ひつぜん +ぴったり +ぴっちり +ひつよう +ひてい +ひとごみ +ひなまつり +ひなん +ひねる +ひはん +ひびく +ひひょう +ひほう +ひまわり +ひまん +ひみつ +ひめい +ひめじし +ひやけ +ひやす +ひよう +びょうき +ひらがな +ひらく +ひりつ +ひりょう +ひるま +ひるやすみ +ひれい +ひろい +ひろう +ひろき +ひろゆき +ひんかく +ひんけつ +ひんこん +ひんしゅ +ひんそう +ぴんち +ひんぱん +びんぼう +ふあん +ふいうち +ふうけい +ふうせん +ぷうたろう +ふうとう +ふうふ +ふえる +ふおん +ふかい +ふきん +ふくざつ +ふくぶくろ +ふこう +ふさい +ふしぎ +ふじみ +ふすま +ふせい +ふせぐ +ふそく +ぶたにく +ふたん +ふちょう +ふつう +ふつか +ふっかつ +ふっき +ふっこく +ぶどう +ふとる +ふとん +ふのう +ふはい +ふひょう +ふへん +ふまん +ふみん +ふめつ +ふめん +ふよう +ふりこ +ふりる +ふるい +ふんいき +ぶんがく +ぶんぐ +ふんしつ +ぶんせき +ふんそう +ぶんぽう +へいあん +へいおん +へいがい +へいき +へいげん +へいこう +へいさ +へいしゃ +へいせつ +へいそ +へいたく +へいてん +へいねつ +へいわ +へきが +へこむ +べにいろ +べにしょうが +へらす +へんかん +べんきょう +べんごし +へんさい +へんたい +べんり +ほあん +ほいく +ぼうぎょ +ほうこく +ほうそう +ほうほう +ほうもん +ほうりつ +ほえる +ほおん +ほかん +ほきょう +ぼきん +ほくろ +ほけつ +ほけん +ほこう +ほこる +ほしい +ほしつ +ほしゅ +ほしょう +ほせい +ほそい +ほそく +ほたて +ほたる +ぽちぶくろ +ほっきょく +ほっさ +ほったん +ほとんど +ほめる +ほんい +ほんき +ほんけ +ほんしつ +ほんやく +まいにち +まかい +まかせる +まがる +まける +まこと +まさつ +まじめ +ますく +まぜる +まつり +まとめ +まなぶ +まぬけ +まねく +まほう +まもる +まゆげ +まよう +まろやか +まわす +まわり +まわる +まんが +まんきつ +まんぞく +まんなか +みいら +みうち +みえる +みがく +みかた +みかん +みけん +みこん +みじかい +みすい +みすえる +みせる +みっか +みつかる +みつける +みてい +みとめる +みなと +みなみかさい +みねらる +みのう +みのがす +みほん +みもと +みやげ +みらい +みりょく +みわく +みんか +みんぞく +むいか +むえき +むえん +むかい +むかう +むかえ +むかし +むぎちゃ +むける +むげん +むさぼる +むしあつい +むしば +むじゅん +むしろ +むすう +むすこ +むすぶ +むすめ +むせる +むせん +むちゅう +むなしい +むのう +むやみ +むよう +むらさき +むりょう +むろん +めいあん +めいうん +めいえん +めいかく +めいきょく +めいさい +めいし +めいそう +めいぶつ +めいれい +めいわく +めぐまれる +めざす +めした +めずらしい +めだつ +めまい +めやす +めんきょ +めんせき +めんどう +もうしあげる +もうどうけん +もえる +もくし +もくてき +もくようび +もちろん +もどる +もらう +もんく +もんだい +やおや +やける +やさい +やさしい +やすい +やすたろう +やすみ +やせる +やそう +やたい +やちん +やっと +やっぱり +やぶる +やめる +ややこしい +やよい +やわらかい +ゆうき +ゆうびんきょく +ゆうべ +ゆうめい +ゆけつ +ゆしゅつ +ゆせん +ゆそう +ゆたか +ゆちゃく +ゆでる +ゆにゅう +ゆびわ +ゆらい +ゆれる +ようい +ようか +ようきゅう +ようじ +ようす +ようちえん +よかぜ +よかん +よきん +よくせい +よくぼう +よけい +よごれる +よさん +よしゅう +よそう +よそく +よっか +よてい +よどがわく +よねつ +よやく +よゆう +よろこぶ +よろしい +らいう +らくがき +らくご +らくさつ +らくだ +らしんばん +らせん +らぞく +らたい +らっか +られつ +りえき +りかい +りきさく +りきせつ +りくぐん +りくつ +りけん +りこう +りせい +りそう +りそく +りてん +りねん +りゆう +りゅうがく +りよう +りょうり +りょかん +りょくちゃ +りょこう +りりく +りれき +りろん +りんご +るいけい +るいさい +るいじ +るいせき +るすばん +るりがわら +れいかん +れいぎ +れいせい +れいぞうこ +れいとう +れいぼう +れきし +れきだい +れんあい +れんけい +れんこん +れんさい +れんしゅう +れんぞく +れんらく +ろうか +ろうご +ろうじん +ろうそく +ろくが +ろこつ +ろじうら +ろしゅつ +ろせん +ろてん +ろめん +ろれつ +ろんぎ +ろんぱ +ろんぶん +ろんり +わかす +わかめ +わかやま +わかれる +わしつ +わじまし +わすれもの +わらう +われる`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/korean.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/korean.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/korean.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/korean.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/korean.js new file mode 100644 index 0000000..15ba442 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/korean.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `가격 +가끔 +가난 +가능 +가득 +가르침 +가뭄 +가방 +가상 +가슴 +가운데 +가을 +가이드 +가입 +가장 +가정 +가족 +가죽 +각오 +각자 +간격 +간부 +간섭 +간장 +간접 +간판 +갈등 +갈비 +갈색 +갈증 +감각 +감기 +감소 +감수성 +감자 +감정 +갑자기 +강남 +강당 +강도 +강력히 +강변 +강북 +강사 +강수량 +강아지 +강원도 +강의 +강제 +강조 +같이 +개구리 +개나리 +개방 +개별 +개선 +개성 +개인 +객관적 +거실 +거액 +거울 +거짓 +거품 +걱정 +건강 +건물 +건설 +건조 +건축 +걸음 +검사 +검토 +게시판 +게임 +겨울 +견해 +결과 +결국 +결론 +결석 +결승 +결심 +결정 +결혼 +경계 +경고 +경기 +경력 +경복궁 +경비 +경상도 +경영 +경우 +경쟁 +경제 +경주 +경찰 +경치 +경향 +경험 +계곡 +계단 +계란 +계산 +계속 +계약 +계절 +계층 +계획 +고객 +고구려 +고궁 +고급 +고등학생 +고무신 +고민 +고양이 +고장 +고전 +고집 +고춧가루 +고통 +고향 +곡식 +골목 +골짜기 +골프 +공간 +공개 +공격 +공군 +공급 +공기 +공동 +공무원 +공부 +공사 +공식 +공업 +공연 +공원 +공장 +공짜 +공책 +공통 +공포 +공항 +공휴일 +과목 +과일 +과장 +과정 +과학 +관객 +관계 +관광 +관념 +관람 +관련 +관리 +관습 +관심 +관점 +관찰 +광경 +광고 +광장 +광주 +괴로움 +굉장히 +교과서 +교문 +교복 +교실 +교양 +교육 +교장 +교직 +교통 +교환 +교훈 +구경 +구름 +구멍 +구별 +구분 +구석 +구성 +구속 +구역 +구입 +구청 +구체적 +국가 +국기 +국내 +국립 +국물 +국민 +국수 +국어 +국왕 +국적 +국제 +국회 +군대 +군사 +군인 +궁극적 +권리 +권위 +권투 +귀국 +귀신 +규정 +규칙 +균형 +그날 +그냥 +그늘 +그러나 +그룹 +그릇 +그림 +그제서야 +그토록 +극복 +극히 +근거 +근교 +근래 +근로 +근무 +근본 +근원 +근육 +근처 +글씨 +글자 +금강산 +금고 +금년 +금메달 +금액 +금연 +금요일 +금지 +긍정적 +기간 +기관 +기념 +기능 +기독교 +기둥 +기록 +기름 +기법 +기본 +기분 +기쁨 +기숙사 +기술 +기억 +기업 +기온 +기운 +기원 +기적 +기준 +기침 +기혼 +기획 +긴급 +긴장 +길이 +김밥 +김치 +김포공항 +깍두기 +깜빡 +깨달음 +깨소금 +껍질 +꼭대기 +꽃잎 +나들이 +나란히 +나머지 +나물 +나침반 +나흘 +낙엽 +난방 +날개 +날씨 +날짜 +남녀 +남대문 +남매 +남산 +남자 +남편 +남학생 +낭비 +낱말 +내년 +내용 +내일 +냄비 +냄새 +냇물 +냉동 +냉면 +냉방 +냉장고 +넥타이 +넷째 +노동 +노란색 +노력 +노인 +녹음 +녹차 +녹화 +논리 +논문 +논쟁 +놀이 +농구 +농담 +농민 +농부 +농업 +농장 +농촌 +높이 +눈동자 +눈물 +눈썹 +뉴욕 +느낌 +늑대 +능동적 +능력 +다방 +다양성 +다음 +다이어트 +다행 +단계 +단골 +단독 +단맛 +단순 +단어 +단위 +단점 +단체 +단추 +단편 +단풍 +달걀 +달러 +달력 +달리 +닭고기 +담당 +담배 +담요 +담임 +답변 +답장 +당근 +당분간 +당연히 +당장 +대규모 +대낮 +대단히 +대답 +대도시 +대략 +대량 +대륙 +대문 +대부분 +대신 +대응 +대장 +대전 +대접 +대중 +대책 +대출 +대충 +대통령 +대학 +대한민국 +대합실 +대형 +덩어리 +데이트 +도대체 +도덕 +도둑 +도망 +도서관 +도심 +도움 +도입 +도자기 +도저히 +도전 +도중 +도착 +독감 +독립 +독서 +독일 +독창적 +동화책 +뒷모습 +뒷산 +딸아이 +마누라 +마늘 +마당 +마라톤 +마련 +마무리 +마사지 +마약 +마요네즈 +마을 +마음 +마이크 +마중 +마지막 +마찬가지 +마찰 +마흔 +막걸리 +막내 +막상 +만남 +만두 +만세 +만약 +만일 +만점 +만족 +만화 +많이 +말기 +말씀 +말투 +맘대로 +망원경 +매년 +매달 +매력 +매번 +매스컴 +매일 +매장 +맥주 +먹이 +먼저 +먼지 +멀리 +메일 +며느리 +며칠 +면담 +멸치 +명단 +명령 +명예 +명의 +명절 +명칭 +명함 +모금 +모니터 +모델 +모든 +모범 +모습 +모양 +모임 +모조리 +모집 +모퉁이 +목걸이 +목록 +목사 +목소리 +목숨 +목적 +목표 +몰래 +몸매 +몸무게 +몸살 +몸속 +몸짓 +몸통 +몹시 +무관심 +무궁화 +무더위 +무덤 +무릎 +무슨 +무엇 +무역 +무용 +무조건 +무지개 +무척 +문구 +문득 +문법 +문서 +문제 +문학 +문화 +물가 +물건 +물결 +물고기 +물론 +물리학 +물음 +물질 +물체 +미국 +미디어 +미사일 +미술 +미역 +미용실 +미움 +미인 +미팅 +미혼 +민간 +민족 +민주 +믿음 +밀가루 +밀리미터 +밑바닥 +바가지 +바구니 +바나나 +바늘 +바닥 +바닷가 +바람 +바이러스 +바탕 +박물관 +박사 +박수 +반대 +반드시 +반말 +반발 +반성 +반응 +반장 +반죽 +반지 +반찬 +받침 +발가락 +발걸음 +발견 +발달 +발레 +발목 +발바닥 +발생 +발음 +발자국 +발전 +발톱 +발표 +밤하늘 +밥그릇 +밥맛 +밥상 +밥솥 +방금 +방면 +방문 +방바닥 +방법 +방송 +방식 +방안 +방울 +방지 +방학 +방해 +방향 +배경 +배꼽 +배달 +배드민턴 +백두산 +백색 +백성 +백인 +백제 +백화점 +버릇 +버섯 +버튼 +번개 +번역 +번지 +번호 +벌금 +벌레 +벌써 +범위 +범인 +범죄 +법률 +법원 +법적 +법칙 +베이징 +벨트 +변경 +변동 +변명 +변신 +변호사 +변화 +별도 +별명 +별일 +병실 +병아리 +병원 +보관 +보너스 +보라색 +보람 +보름 +보상 +보안 +보자기 +보장 +보전 +보존 +보통 +보편적 +보험 +복도 +복사 +복숭아 +복습 +볶음 +본격적 +본래 +본부 +본사 +본성 +본인 +본질 +볼펜 +봉사 +봉지 +봉투 +부근 +부끄러움 +부담 +부동산 +부문 +부분 +부산 +부상 +부엌 +부인 +부작용 +부장 +부정 +부족 +부지런히 +부친 +부탁 +부품 +부회장 +북부 +북한 +분노 +분량 +분리 +분명 +분석 +분야 +분위기 +분필 +분홍색 +불고기 +불과 +불교 +불꽃 +불만 +불법 +불빛 +불안 +불이익 +불행 +브랜드 +비극 +비난 +비닐 +비둘기 +비디오 +비로소 +비만 +비명 +비밀 +비바람 +비빔밥 +비상 +비용 +비율 +비중 +비타민 +비판 +빌딩 +빗물 +빗방울 +빗줄기 +빛깔 +빨간색 +빨래 +빨리 +사건 +사계절 +사나이 +사냥 +사람 +사랑 +사립 +사모님 +사물 +사방 +사상 +사생활 +사설 +사슴 +사실 +사업 +사용 +사월 +사장 +사전 +사진 +사촌 +사춘기 +사탕 +사투리 +사흘 +산길 +산부인과 +산업 +산책 +살림 +살인 +살짝 +삼계탕 +삼국 +삼십 +삼월 +삼촌 +상관 +상금 +상대 +상류 +상반기 +상상 +상식 +상업 +상인 +상자 +상점 +상처 +상추 +상태 +상표 +상품 +상황 +새벽 +색깔 +색연필 +생각 +생명 +생물 +생방송 +생산 +생선 +생신 +생일 +생활 +서랍 +서른 +서명 +서민 +서비스 +서양 +서울 +서적 +서점 +서쪽 +서클 +석사 +석유 +선거 +선물 +선배 +선생 +선수 +선원 +선장 +선전 +선택 +선풍기 +설거지 +설날 +설렁탕 +설명 +설문 +설사 +설악산 +설치 +설탕 +섭씨 +성공 +성당 +성명 +성별 +성인 +성장 +성적 +성질 +성함 +세금 +세미나 +세상 +세월 +세종대왕 +세탁 +센터 +센티미터 +셋째 +소규모 +소극적 +소금 +소나기 +소년 +소득 +소망 +소문 +소설 +소속 +소아과 +소용 +소원 +소음 +소중히 +소지품 +소질 +소풍 +소형 +속담 +속도 +속옷 +손가락 +손길 +손녀 +손님 +손등 +손목 +손뼉 +손실 +손질 +손톱 +손해 +솔직히 +솜씨 +송아지 +송이 +송편 +쇠고기 +쇼핑 +수건 +수년 +수단 +수돗물 +수동적 +수면 +수명 +수박 +수상 +수석 +수술 +수시로 +수업 +수염 +수영 +수입 +수준 +수집 +수출 +수컷 +수필 +수학 +수험생 +수화기 +숙녀 +숙소 +숙제 +순간 +순서 +순수 +순식간 +순위 +숟가락 +술병 +술집 +숫자 +스님 +스물 +스스로 +스승 +스웨터 +스위치 +스케이트 +스튜디오 +스트레스 +스포츠 +슬쩍 +슬픔 +습관 +습기 +승객 +승리 +승부 +승용차 +승진 +시각 +시간 +시골 +시금치 +시나리오 +시댁 +시리즈 +시멘트 +시민 +시부모 +시선 +시설 +시스템 +시아버지 +시어머니 +시월 +시인 +시일 +시작 +시장 +시절 +시점 +시중 +시즌 +시집 +시청 +시합 +시험 +식구 +식기 +식당 +식량 +식료품 +식물 +식빵 +식사 +식생활 +식초 +식탁 +식품 +신고 +신규 +신념 +신문 +신발 +신비 +신사 +신세 +신용 +신제품 +신청 +신체 +신화 +실감 +실내 +실력 +실례 +실망 +실수 +실습 +실시 +실장 +실정 +실질적 +실천 +실체 +실컷 +실태 +실패 +실험 +실현 +심리 +심부름 +심사 +심장 +심정 +심판 +쌍둥이 +씨름 +씨앗 +아가씨 +아나운서 +아드님 +아들 +아쉬움 +아스팔트 +아시아 +아울러 +아저씨 +아줌마 +아직 +아침 +아파트 +아프리카 +아픔 +아홉 +아흔 +악기 +악몽 +악수 +안개 +안경 +안과 +안내 +안녕 +안동 +안방 +안부 +안주 +알루미늄 +알코올 +암시 +암컷 +압력 +앞날 +앞문 +애인 +애정 +액수 +앨범 +야간 +야단 +야옹 +약간 +약국 +약속 +약수 +약점 +약품 +약혼녀 +양념 +양력 +양말 +양배추 +양주 +양파 +어둠 +어려움 +어른 +어젯밤 +어쨌든 +어쩌다가 +어쩐지 +언니 +언덕 +언론 +언어 +얼굴 +얼른 +얼음 +얼핏 +엄마 +업무 +업종 +업체 +엉덩이 +엉망 +엉터리 +엊그제 +에너지 +에어컨 +엔진 +여건 +여고생 +여관 +여군 +여권 +여대생 +여덟 +여동생 +여든 +여론 +여름 +여섯 +여성 +여왕 +여인 +여전히 +여직원 +여학생 +여행 +역사 +역시 +역할 +연결 +연구 +연극 +연기 +연락 +연설 +연세 +연속 +연습 +연애 +연예인 +연인 +연장 +연주 +연출 +연필 +연합 +연휴 +열기 +열매 +열쇠 +열심히 +열정 +열차 +열흘 +염려 +엽서 +영국 +영남 +영상 +영양 +영역 +영웅 +영원히 +영하 +영향 +영혼 +영화 +옆구리 +옆방 +옆집 +예감 +예금 +예방 +예산 +예상 +예선 +예술 +예습 +예식장 +예약 +예전 +예절 +예정 +예컨대 +옛날 +오늘 +오락 +오랫동안 +오렌지 +오로지 +오른발 +오븐 +오십 +오염 +오월 +오전 +오직 +오징어 +오페라 +오피스텔 +오히려 +옥상 +옥수수 +온갖 +온라인 +온몸 +온종일 +온통 +올가을 +올림픽 +올해 +옷차림 +와이셔츠 +와인 +완성 +완전 +왕비 +왕자 +왜냐하면 +왠지 +외갓집 +외국 +외로움 +외삼촌 +외출 +외침 +외할머니 +왼발 +왼손 +왼쪽 +요금 +요일 +요즘 +요청 +용기 +용서 +용어 +우산 +우선 +우승 +우연히 +우정 +우체국 +우편 +운동 +운명 +운반 +운전 +운행 +울산 +울음 +움직임 +웃어른 +웃음 +워낙 +원고 +원래 +원서 +원숭이 +원인 +원장 +원피스 +월급 +월드컵 +월세 +월요일 +웨이터 +위반 +위법 +위성 +위원 +위험 +위협 +윗사람 +유난히 +유럽 +유명 +유물 +유산 +유적 +유치원 +유학 +유행 +유형 +육군 +육상 +육십 +육체 +은행 +음력 +음료 +음반 +음성 +음식 +음악 +음주 +의견 +의논 +의문 +의복 +의식 +의심 +의외로 +의욕 +의원 +의학 +이것 +이곳 +이념 +이놈 +이달 +이대로 +이동 +이렇게 +이력서 +이론적 +이름 +이민 +이발소 +이별 +이불 +이빨 +이상 +이성 +이슬 +이야기 +이용 +이웃 +이월 +이윽고 +이익 +이전 +이중 +이튿날 +이틀 +이혼 +인간 +인격 +인공 +인구 +인근 +인기 +인도 +인류 +인물 +인생 +인쇄 +인연 +인원 +인재 +인종 +인천 +인체 +인터넷 +인하 +인형 +일곱 +일기 +일단 +일대 +일등 +일반 +일본 +일부 +일상 +일생 +일손 +일요일 +일월 +일정 +일종 +일주일 +일찍 +일체 +일치 +일행 +일회용 +임금 +임무 +입대 +입력 +입맛 +입사 +입술 +입시 +입원 +입장 +입학 +자가용 +자격 +자극 +자동 +자랑 +자부심 +자식 +자신 +자연 +자원 +자율 +자전거 +자정 +자존심 +자판 +작가 +작년 +작성 +작업 +작용 +작은딸 +작품 +잔디 +잔뜩 +잔치 +잘못 +잠깐 +잠수함 +잠시 +잠옷 +잠자리 +잡지 +장관 +장군 +장기간 +장래 +장례 +장르 +장마 +장면 +장모 +장미 +장비 +장사 +장소 +장식 +장애인 +장인 +장점 +장차 +장학금 +재능 +재빨리 +재산 +재생 +재작년 +재정 +재채기 +재판 +재학 +재활용 +저것 +저고리 +저곳 +저녁 +저런 +저렇게 +저번 +저울 +저절로 +저축 +적극 +적당히 +적성 +적용 +적응 +전개 +전공 +전기 +전달 +전라도 +전망 +전문 +전반 +전부 +전세 +전시 +전용 +전자 +전쟁 +전주 +전철 +전체 +전통 +전혀 +전후 +절대 +절망 +절반 +절약 +절차 +점검 +점수 +점심 +점원 +점점 +점차 +접근 +접시 +접촉 +젓가락 +정거장 +정도 +정류장 +정리 +정말 +정면 +정문 +정반대 +정보 +정부 +정비 +정상 +정성 +정오 +정원 +정장 +정지 +정치 +정확히 +제공 +제과점 +제대로 +제목 +제발 +제법 +제삿날 +제안 +제일 +제작 +제주도 +제출 +제품 +제한 +조각 +조건 +조금 +조깅 +조명 +조미료 +조상 +조선 +조용히 +조절 +조정 +조직 +존댓말 +존재 +졸업 +졸음 +종교 +종로 +종류 +종소리 +종업원 +종종 +종합 +좌석 +죄인 +주관적 +주름 +주말 +주머니 +주먹 +주문 +주민 +주방 +주변 +주식 +주인 +주일 +주장 +주전자 +주택 +준비 +줄거리 +줄기 +줄무늬 +중간 +중계방송 +중국 +중년 +중단 +중독 +중반 +중부 +중세 +중소기업 +중순 +중앙 +중요 +중학교 +즉석 +즉시 +즐거움 +증가 +증거 +증권 +증상 +증세 +지각 +지갑 +지경 +지극히 +지금 +지급 +지능 +지름길 +지리산 +지방 +지붕 +지식 +지역 +지우개 +지원 +지적 +지점 +지진 +지출 +직선 +직업 +직원 +직장 +진급 +진동 +진로 +진료 +진리 +진짜 +진찰 +진출 +진통 +진행 +질문 +질병 +질서 +짐작 +집단 +집안 +집중 +짜증 +찌꺼기 +차남 +차라리 +차량 +차림 +차별 +차선 +차츰 +착각 +찬물 +찬성 +참가 +참기름 +참새 +참석 +참여 +참외 +참조 +찻잔 +창가 +창고 +창구 +창문 +창밖 +창작 +창조 +채널 +채점 +책가방 +책방 +책상 +책임 +챔피언 +처벌 +처음 +천국 +천둥 +천장 +천재 +천천히 +철도 +철저히 +철학 +첫날 +첫째 +청년 +청바지 +청소 +청춘 +체계 +체력 +체온 +체육 +체중 +체험 +초등학생 +초반 +초밥 +초상화 +초순 +초여름 +초원 +초저녁 +초점 +초청 +초콜릿 +촛불 +총각 +총리 +총장 +촬영 +최근 +최상 +최선 +최신 +최악 +최종 +추석 +추억 +추진 +추천 +추측 +축구 +축소 +축제 +축하 +출근 +출발 +출산 +출신 +출연 +출입 +출장 +출판 +충격 +충고 +충돌 +충분히 +충청도 +취업 +취직 +취향 +치약 +친구 +친척 +칠십 +칠월 +칠판 +침대 +침묵 +침실 +칫솔 +칭찬 +카메라 +카운터 +칼국수 +캐릭터 +캠퍼스 +캠페인 +커튼 +컨디션 +컬러 +컴퓨터 +코끼리 +코미디 +콘서트 +콜라 +콤플렉스 +콩나물 +쾌감 +쿠데타 +크림 +큰길 +큰딸 +큰소리 +큰아들 +큰어머니 +큰일 +큰절 +클래식 +클럽 +킬로 +타입 +타자기 +탁구 +탁자 +탄생 +태권도 +태양 +태풍 +택시 +탤런트 +터널 +터미널 +테니스 +테스트 +테이블 +텔레비전 +토론 +토마토 +토요일 +통계 +통과 +통로 +통신 +통역 +통일 +통장 +통제 +통증 +통합 +통화 +퇴근 +퇴원 +퇴직금 +튀김 +트럭 +특급 +특별 +특성 +특수 +특징 +특히 +튼튼히 +티셔츠 +파란색 +파일 +파출소 +판결 +판단 +판매 +판사 +팔십 +팔월 +팝송 +패션 +팩스 +팩시밀리 +팬티 +퍼센트 +페인트 +편견 +편의 +편지 +편히 +평가 +평균 +평생 +평소 +평양 +평일 +평화 +포스터 +포인트 +포장 +포함 +표면 +표정 +표준 +표현 +품목 +품질 +풍경 +풍속 +풍습 +프랑스 +프린터 +플라스틱 +피곤 +피망 +피아노 +필름 +필수 +필요 +필자 +필통 +핑계 +하느님 +하늘 +하드웨어 +하룻밤 +하반기 +하숙집 +하순 +하여튼 +하지만 +하천 +하품 +하필 +학과 +학교 +학급 +학기 +학년 +학력 +학번 +학부모 +학비 +학생 +학술 +학습 +학용품 +학원 +학위 +학자 +학점 +한계 +한글 +한꺼번에 +한낮 +한눈 +한동안 +한때 +한라산 +한마디 +한문 +한번 +한복 +한식 +한여름 +한쪽 +할머니 +할아버지 +할인 +함께 +함부로 +합격 +합리적 +항공 +항구 +항상 +항의 +해결 +해군 +해답 +해당 +해물 +해석 +해설 +해수욕장 +해안 +핵심 +핸드백 +햄버거 +햇볕 +햇살 +행동 +행복 +행사 +행운 +행위 +향기 +향상 +향수 +허락 +허용 +헬기 +현관 +현금 +현대 +현상 +현실 +현장 +현재 +현지 +혈액 +협력 +형부 +형사 +형수 +형식 +형제 +형태 +형편 +혜택 +호기심 +호남 +호랑이 +호박 +호텔 +호흡 +혹시 +홀로 +홈페이지 +홍보 +홍수 +홍차 +화면 +화분 +화살 +화요일 +화장 +화학 +확보 +확인 +확장 +확정 +환갑 +환경 +환영 +환율 +환자 +활기 +활동 +활발히 +활용 +활짝 +회견 +회관 +회복 +회색 +회원 +회장 +회전 +횟수 +횡단보도 +효율적 +후반 +후춧가루 +훈련 +훨씬 +휴식 +휴일 +흉내 +흐름 +흑백 +흑인 +흔적 +흔히 +흥미 +흥분 +희곡 +희망 +희생 +흰색 +힘껏`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/simplified-chinese.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/simplified-chinese.js new file mode 100644 index 0000000..43ac9d2 --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/simplified-chinese.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +这 +中 +大 +为 +上 +个 +国 +我 +以 +要 +他 +时 +来 +用 +们 +生 +到 +作 +地 +于 +出 +就 +分 +对 +成 +会 +可 +主 +发 +年 +动 +同 +工 +也 +能 +下 +过 +子 +说 +产 +种 +面 +而 +方 +后 +多 +定 +行 +学 +法 +所 +民 +得 +经 +十 +三 +之 +进 +着 +等 +部 +度 +家 +电 +力 +里 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +现 +实 +加 +量 +都 +两 +体 +制 +机 +当 +使 +点 +从 +业 +本 +去 +把 +性 +好 +应 +开 +它 +合 +还 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +义 +事 +平 +形 +相 +全 +表 +间 +样 +与 +关 +各 +重 +新 +线 +内 +数 +正 +心 +反 +你 +明 +看 +原 +又 +么 +利 +比 +或 +但 +质 +气 +第 +向 +道 +命 +此 +变 +条 +只 +没 +结 +解 +问 +意 +建 +月 +公 +无 +系 +军 +很 +情 +者 +最 +立 +代 +想 +已 +通 +并 +提 +直 +题 +党 +程 +展 +五 +果 +料 +象 +员 +革 +位 +入 +常 +文 +总 +次 +品 +式 +活 +设 +及 +管 +特 +件 +长 +求 +老 +头 +基 +资 +边 +流 +路 +级 +少 +图 +山 +统 +接 +知 +较 +将 +组 +见 +计 +别 +她 +手 +角 +期 +根 +论 +运 +农 +指 +几 +九 +区 +强 +放 +决 +西 +被 +干 +做 +必 +战 +先 +回 +则 +任 +取 +据 +处 +队 +南 +给 +色 +光 +门 +即 +保 +治 +北 +造 +百 +规 +热 +领 +七 +海 +口 +东 +导 +器 +压 +志 +世 +金 +增 +争 +济 +阶 +油 +思 +术 +极 +交 +受 +联 +什 +认 +六 +共 +权 +收 +证 +改 +清 +美 +再 +采 +转 +更 +单 +风 +切 +打 +白 +教 +速 +花 +带 +安 +场 +身 +车 +例 +真 +务 +具 +万 +每 +目 +至 +达 +走 +积 +示 +议 +声 +报 +斗 +完 +类 +八 +离 +华 +名 +确 +才 +科 +张 +信 +马 +节 +话 +米 +整 +空 +元 +况 +今 +集 +温 +传 +土 +许 +步 +群 +广 +石 +记 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +观 +越 +织 +装 +影 +算 +低 +持 +音 +众 +书 +布 +复 +容 +儿 +须 +际 +商 +非 +验 +连 +断 +深 +难 +近 +矿 +千 +周 +委 +素 +技 +备 +半 +办 +青 +省 +列 +习 +响 +约 +支 +般 +史 +感 +劳 +便 +团 +往 +酸 +历 +市 +克 +何 +除 +消 +构 +府 +称 +太 +准 +精 +值 +号 +率 +族 +维 +划 +选 +标 +写 +存 +候 +毛 +亲 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +养 +易 +置 +派 +层 +片 +始 +却 +专 +状 +育 +厂 +京 +识 +适 +属 +圆 +包 +火 +住 +调 +满 +县 +局 +照 +参 +红 +细 +引 +听 +该 +铁 +价 +严 +首 +底 +液 +官 +德 +随 +病 +苏 +失 +尔 +死 +讲 +配 +女 +黄 +推 +显 +谈 +罪 +神 +艺 +呢 +席 +含 +企 +望 +密 +批 +营 +项 +防 +举 +球 +英 +氧 +势 +告 +李 +台 +落 +木 +帮 +轮 +破 +亚 +师 +围 +注 +远 +字 +材 +排 +供 +河 +态 +封 +另 +施 +减 +树 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +叶 +鱼 +波 +视 +仅 +费 +紧 +爱 +左 +章 +早 +朝 +害 +续 +轻 +服 +试 +食 +充 +兵 +源 +判 +护 +司 +足 +某 +练 +差 +致 +板 +田 +降 +黑 +犯 +负 +击 +范 +继 +兴 +似 +余 +坚 +曲 +输 +修 +故 +城 +夫 +够 +送 +笔 +船 +占 +右 +财 +吃 +富 +春 +职 +觉 +汉 +画 +功 +巴 +跟 +虽 +杂 +飞 +检 +吸 +助 +升 +阳 +互 +初 +创 +抗 +考 +投 +坏 +策 +古 +径 +换 +未 +跑 +留 +钢 +曾 +端 +责 +站 +简 +述 +钱 +副 +尽 +帝 +射 +草 +冲 +承 +独 +令 +限 +阿 +宣 +环 +双 +请 +超 +微 +让 +控 +州 +良 +轴 +找 +否 +纪 +益 +依 +优 +顶 +础 +载 +倒 +房 +突 +坐 +粉 +敌 +略 +客 +袁 +冷 +胜 +绝 +析 +块 +剂 +测 +丝 +协 +诉 +念 +陈 +仍 +罗 +盐 +友 +洋 +错 +苦 +夜 +刑 +移 +频 +逐 +靠 +混 +母 +短 +皮 +终 +聚 +汽 +村 +云 +哪 +既 +距 +卫 +停 +烈 +央 +察 +烧 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +游 +久 +菜 +味 +旧 +模 +湖 +货 +损 +预 +阻 +毫 +普 +稳 +乙 +妈 +植 +息 +扩 +银 +语 +挥 +酒 +守 +拿 +序 +纸 +医 +缺 +雨 +吗 +针 +刘 +啊 +急 +唱 +误 +训 +愿 +审 +附 +获 +茶 +鲜 +粮 +斤 +孩 +脱 +硫 +肥 +善 +龙 +演 +父 +渐 +血 +欢 +械 +掌 +歌 +沙 +刚 +攻 +谓 +盾 +讨 +晚 +粒 +乱 +燃 +矛 +乎 +杀 +药 +宁 +鲁 +贵 +钟 +煤 +读 +班 +伯 +香 +介 +迫 +句 +丰 +培 +握 +兰 +担 +弦 +蛋 +沉 +假 +穿 +执 +答 +乐 +谁 +顺 +烟 +缩 +征 +脸 +喜 +松 +脚 +困 +异 +免 +背 +星 +福 +买 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +静 +补 +评 +翻 +肉 +践 +尼 +衣 +宽 +扬 +棉 +希 +伤 +操 +垂 +秋 +宜 +氢 +套 +督 +振 +架 +亮 +末 +宪 +庆 +编 +牛 +触 +映 +雷 +销 +诗 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +绿 +晶 +厚 +盟 +衡 +鸡 +孙 +延 +危 +胶 +屋 +乡 +临 +陆 +顾 +掉 +呀 +灯 +岁 +措 +束 +耐 +剧 +玉 +赵 +跳 +哥 +季 +课 +凯 +胡 +额 +款 +绍 +卷 +齐 +伟 +蒸 +殖 +永 +宗 +苗 +川 +炉 +岩 +弱 +零 +杨 +奏 +沿 +露 +杆 +探 +滑 +镇 +饭 +浓 +航 +怀 +赶 +库 +夺 +伊 +灵 +税 +途 +灭 +赛 +归 +召 +鼓 +播 +盘 +裁 +险 +康 +唯 +录 +菌 +纯 +借 +糖 +盖 +横 +符 +私 +努 +堂 +域 +枪 +润 +幅 +哈 +竟 +熟 +虫 +泽 +脑 +壤 +碳 +欧 +遍 +侧 +寨 +敢 +彻 +虑 +斜 +薄 +庭 +纳 +弹 +饲 +伸 +折 +麦 +湿 +暗 +荷 +瓦 +塞 +床 +筑 +恶 +户 +访 +塔 +奇 +透 +梁 +刀 +旋 +迹 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +摆 +灰 +彩 +卖 +耗 +夏 +择 +忙 +铜 +献 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +阵 +阴 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +楼 +避 +谋 +吨 +野 +猪 +旗 +累 +偏 +典 +馆 +索 +秦 +脂 +潮 +爷 +豆 +忽 +托 +惊 +塑 +遗 +愈 +朱 +替 +纤 +粗 +倾 +尚 +痛 +楚 +谢 +奋 +购 +磨 +君 +池 +旁 +碎 +骨 +监 +捕 +弟 +暴 +割 +贯 +殊 +释 +词 +亡 +壁 +顿 +宝 +午 +尘 +闻 +揭 +炮 +残 +冬 +桥 +妇 +警 +综 +招 +吴 +付 +浮 +遭 +徐 +您 +摇 +谷 +赞 +箱 +隔 +订 +男 +吹 +园 +纷 +唐 +败 +宋 +玻 +巨 +耕 +坦 +荣 +闭 +湾 +键 +凡 +驻 +锅 +救 +恩 +剥 +凝 +碱 +齿 +截 +炼 +麻 +纺 +禁 +废 +盛 +版 +缓 +净 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +庄 +街 +藏 +姑 +贸 +腐 +奴 +啦 +惯 +乘 +伙 +恢 +匀 +纱 +扎 +辩 +耳 +彪 +臣 +亿 +璃 +抵 +脉 +秀 +萨 +俄 +网 +舞 +店 +喷 +纵 +寸 +汗 +挂 +洪 +贺 +闪 +柬 +爆 +烯 +津 +稻 +墙 +软 +勇 +像 +滚 +厘 +蒙 +芳 +肯 +坡 +柱 +荡 +腿 +仪 +旅 +尾 +轧 +冰 +贡 +登 +黎 +削 +钻 +勒 +逃 +障 +氨 +郭 +峰 +币 +港 +伏 +轨 +亩 +毕 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +岛 +甘 +泡 +睡 +童 +铸 +汤 +阀 +休 +汇 +舍 +牧 +绕 +炸 +哲 +磷 +绩 +朋 +淡 +尖 +启 +陷 +柴 +呈 +徒 +颜 +泪 +稍 +忘 +泵 +蓝 +拖 +洞 +授 +镜 +辛 +壮 +锋 +贫 +虚 +弯 +摩 +泰 +幼 +廷 +尊 +窗 +纲 +弄 +隶 +疑 +氏 +宫 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +违 +夹 +腰 +缘 +珠 +穷 +森 +枝 +竹 +沟 +催 +绳 +忆 +邦 +剩 +幸 +浆 +栏 +拥 +牙 +贮 +礼 +滤 +钠 +纹 +罢 +拍 +咱 +喊 +袖 +埃 +勤 +罚 +焦 +潜 +伍 +墨 +欲 +缝 +姓 +刊 +饱 +仿 +奖 +铝 +鬼 +丽 +跨 +默 +挖 +链 +扫 +喝 +袋 +炭 +污 +幕 +诸 +弧 +励 +梅 +奶 +洁 +灾 +舟 +鉴 +苯 +讼 +抱 +毁 +懂 +寒 +智 +埔 +寄 +届 +跃 +渡 +挑 +丹 +艰 +贝 +碰 +拔 +爹 +戴 +码 +梦 +芽 +熔 +赤 +渔 +哭 +敬 +颗 +奔 +铅 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +仓 +魏 +锐 +晓 +氮 +兼 +隐 +碍 +赫 +拨 +忠 +肃 +缸 +牵 +抢 +博 +巧 +壳 +兄 +杜 +讯 +诚 +碧 +祥 +柯 +页 +巡 +矩 +悲 +灌 +龄 +伦 +票 +寻 +桂 +铺 +圣 +恐 +恰 +郑 +趣 +抬 +荒 +腾 +贴 +柔 +滴 +猛 +阔 +辆 +妻 +填 +撤 +储 +签 +闹 +扰 +紫 +砂 +递 +戏 +吊 +陶 +伐 +喂 +疗 +瓶 +婆 +抚 +臂 +摸 +忍 +虾 +蜡 +邻 +胸 +巩 +挤 +偶 +弃 +槽 +劲 +乳 +邓 +吉 +仁 +烂 +砖 +租 +乌 +舰 +伴 +瓜 +浅 +丙 +暂 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +胆 +详 +簧 +踏 +瓷 +谱 +呆 +宾 +糊 +洛 +辉 +愤 +竞 +隙 +怒 +粘 +乃 +绪 +肩 +籍 +敏 +涂 +熙 +皆 +侦 +悬 +掘 +享 +纠 +醒 +狂 +锁 +淀 +恨 +牲 +霸 +爬 +赏 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鸭 +趋 +凤 +晨 +畜 +辈 +秩 +卵 +署 +梯 +炎 +滩 +棋 +驱 +筛 +峡 +冒 +啥 +寿 +译 +浸 +泉 +帽 +迟 +硅 +疆 +贷 +漏 +稿 +冠 +嫩 +胁 +芯 +牢 +叛 +蚀 +奥 +鸣 +岭 +羊 +凭 +串 +塘 +绘 +酵 +融 +盆 +锡 +庙 +筹 +冻 +辅 +摄 +袭 +筋 +拒 +僚 +旱 +钾 +鸟 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韩 +逼 +扭 +侨 +凉 +挺 +碗 +栽 +炒 +杯 +患 +馏 +劝 +豪 +辽 +勃 +鸿 +旦 +吏 +拜 +狗 +埋 +辊 +掩 +饮 +搬 +骂 +辞 +勾 +扣 +估 +蒋 +绒 +雾 +丈 +朵 +姆 +拟 +宇 +辑 +陕 +雕 +偿 +蓄 +崇 +剪 +倡 +厅 +咬 +驶 +薯 +刷 +斥 +番 +赋 +奉 +佛 +浇 +漫 +曼 +扇 +钙 +桃 +扶 +仔 +返 +俗 +亏 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +骗 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +胀 +谐 +抛 +霉 +桑 +岗 +嘛 +衰 +盗 +渗 +脏 +赖 +涌 +甜 +曹 +阅 +肌 +哩 +厉 +烃 +纬 +毅 +昨 +伪 +症 +煮 +叹 +钉 +搭 +茎 +笼 +酷 +偷 +弓 +锥 +恒 +杰 +坑 +鼻 +翼 +纶 +叙 +狱 +逮 +罐 +络 +棚 +抑 +膨 +蔬 +寺 +骤 +穆 +冶 +枯 +册 +尸 +凸 +绅 +坯 +牺 +焰 +轰 +欣 +晋 +瘦 +御 +锭 +锦 +丧 +旬 +锻 +垄 +搜 +扑 +邀 +亭 +酯 +迈 +舒 +脆 +酶 +闲 +忧 +酚 +顽 +羽 +涨 +卸 +仗 +陪 +辟 +惩 +杭 +姚 +肚 +捉 +飘 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +饰 +萧 +雅 +邮 +迁 +燕 +撒 +姻 +赴 +宴 +烦 +债 +帐 +斑 +铃 +旨 +醇 +董 +饼 +雏 +姿 +拌 +傅 +腹 +妥 +揉 +贤 +拆 +歪 +葡 +胺 +丢 +浩 +徽 +昂 +垫 +挡 +览 +贪 +慰 +缴 +汪 +慌 +冯 +诺 +姜 +谊 +凶 +劣 +诬 +耀 +昏 +躺 +盈 +骑 +乔 +溪 +丛 +卢 +抹 +闷 +咨 +刮 +驾 +缆 +悟 +摘 +铒 +掷 +颇 +幻 +柄 +惠 +惨 +佳 +仇 +腊 +窝 +涤 +剑 +瞧 +堡 +泼 +葱 +罩 +霍 +捞 +胎 +苍 +滨 +俩 +捅 +湘 +砍 +霞 +邵 +萄 +疯 +淮 +遂 +熊 +粪 +烘 +宿 +档 +戈 +驳 +嫂 +裕 +徙 +箭 +捐 +肠 +撑 +晒 +辨 +殿 +莲 +摊 +搅 +酱 +屏 +疫 +哀 +蔡 +堵 +沫 +皱 +畅 +叠 +阁 +莱 +敲 +辖 +钩 +痕 +坝 +巷 +饿 +祸 +丘 +玄 +溜 +曰 +逻 +彭 +尝 +卿 +妨 +艇 +吞 +韦 +怨 +矮 +歇`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/spanish.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/spanish.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/spanish.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/spanish.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/spanish.js new file mode 100644 index 0000000..0a8328a --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/spanish.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `ábaco +abdomen +abeja +abierto +abogado +abono +aborto +abrazo +abrir +abuelo +abuso +acabar +academia +acceso +acción +aceite +acelga +acento +aceptar +ácido +aclarar +acné +acoger +acoso +activo +acto +actriz +actuar +acudir +acuerdo +acusar +adicto +admitir +adoptar +adorno +aduana +adulto +aéreo +afectar +afición +afinar +afirmar +ágil +agitar +agonía +agosto +agotar +agregar +agrio +agua +agudo +águila +aguja +ahogo +ahorro +aire +aislar +ajedrez +ajeno +ajuste +alacrán +alambre +alarma +alba +álbum +alcalde +aldea +alegre +alejar +alerta +aleta +alfiler +alga +algodón +aliado +aliento +alivio +alma +almeja +almíbar +altar +alteza +altivo +alto +altura +alumno +alzar +amable +amante +amapola +amargo +amasar +ámbar +ámbito +ameno +amigo +amistad +amor +amparo +amplio +ancho +anciano +ancla +andar +andén +anemia +ángulo +anillo +ánimo +anís +anotar +antena +antiguo +antojo +anual +anular +anuncio +añadir +añejo +año +apagar +aparato +apetito +apio +aplicar +apodo +aporte +apoyo +aprender +aprobar +apuesta +apuro +arado +araña +arar +árbitro +árbol +arbusto +archivo +arco +arder +ardilla +arduo +área +árido +aries +armonía +arnés +aroma +arpa +arpón +arreglo +arroz +arruga +arte +artista +asa +asado +asalto +ascenso +asegurar +aseo +asesor +asiento +asilo +asistir +asno +asombro +áspero +astilla +astro +astuto +asumir +asunto +atajo +ataque +atar +atento +ateo +ático +atleta +átomo +atraer +atroz +atún +audaz +audio +auge +aula +aumento +ausente +autor +aval +avance +avaro +ave +avellana +avena +avestruz +avión +aviso +ayer +ayuda +ayuno +azafrán +azar +azote +azúcar +azufre +azul +baba +babor +bache +bahía +baile +bajar +balanza +balcón +balde +bambú +banco +banda +baño +barba +barco +barniz +barro +báscula +bastón +basura +batalla +batería +batir +batuta +baúl +bazar +bebé +bebida +bello +besar +beso +bestia +bicho +bien +bingo +blanco +bloque +blusa +boa +bobina +bobo +boca +bocina +boda +bodega +boina +bola +bolero +bolsa +bomba +bondad +bonito +bono +bonsái +borde +borrar +bosque +bote +botín +bóveda +bozal +bravo +brazo +brecha +breve +brillo +brinco +brisa +broca +broma +bronce +brote +bruja +brusco +bruto +buceo +bucle +bueno +buey +bufanda +bufón +búho +buitre +bulto +burbuja +burla +burro +buscar +butaca +buzón +caballo +cabeza +cabina +cabra +cacao +cadáver +cadena +caer +café +caída +caimán +caja +cajón +cal +calamar +calcio +caldo +calidad +calle +calma +calor +calvo +cama +cambio +camello +camino +campo +cáncer +candil +canela +canguro +canica +canto +caña +cañón +caoba +caos +capaz +capitán +capote +captar +capucha +cara +carbón +cárcel +careta +carga +cariño +carne +carpeta +carro +carta +casa +casco +casero +caspa +castor +catorce +catre +caudal +causa +cazo +cebolla +ceder +cedro +celda +célebre +celoso +célula +cemento +ceniza +centro +cerca +cerdo +cereza +cero +cerrar +certeza +césped +cetro +chacal +chaleco +champú +chancla +chapa +charla +chico +chiste +chivo +choque +choza +chuleta +chupar +ciclón +ciego +cielo +cien +cierto +cifra +cigarro +cima +cinco +cine +cinta +ciprés +circo +ciruela +cisne +cita +ciudad +clamor +clan +claro +clase +clave +cliente +clima +clínica +cobre +cocción +cochino +cocina +coco +código +codo +cofre +coger +cohete +cojín +cojo +cola +colcha +colegio +colgar +colina +collar +colmo +columna +combate +comer +comida +cómodo +compra +conde +conejo +conga +conocer +consejo +contar +copa +copia +corazón +corbata +corcho +cordón +corona +correr +coser +cosmos +costa +cráneo +cráter +crear +crecer +creído +crema +cría +crimen +cripta +crisis +cromo +crónica +croqueta +crudo +cruz +cuadro +cuarto +cuatro +cubo +cubrir +cuchara +cuello +cuento +cuerda +cuesta +cueva +cuidar +culebra +culpa +culto +cumbre +cumplir +cuna +cuneta +cuota +cupón +cúpula +curar +curioso +curso +curva +cutis +dama +danza +dar +dardo +dátil +deber +débil +década +decir +dedo +defensa +definir +dejar +delfín +delgado +delito +demora +denso +dental +deporte +derecho +derrota +desayuno +deseo +desfile +desnudo +destino +desvío +detalle +detener +deuda +día +diablo +diadema +diamante +diana +diario +dibujo +dictar +diente +dieta +diez +difícil +digno +dilema +diluir +dinero +directo +dirigir +disco +diseño +disfraz +diva +divino +doble +doce +dolor +domingo +don +donar +dorado +dormir +dorso +dos +dosis +dragón +droga +ducha +duda +duelo +dueño +dulce +dúo +duque +durar +dureza +duro +ébano +ebrio +echar +eco +ecuador +edad +edición +edificio +editor +educar +efecto +eficaz +eje +ejemplo +elefante +elegir +elemento +elevar +elipse +élite +elixir +elogio +eludir +embudo +emitir +emoción +empate +empeño +empleo +empresa +enano +encargo +enchufe +encía +enemigo +enero +enfado +enfermo +engaño +enigma +enlace +enorme +enredo +ensayo +enseñar +entero +entrar +envase +envío +época +equipo +erizo +escala +escena +escolar +escribir +escudo +esencia +esfera +esfuerzo +espada +espejo +espía +esposa +espuma +esquí +estar +este +estilo +estufa +etapa +eterno +ética +etnia +evadir +evaluar +evento +evitar +exacto +examen +exceso +excusa +exento +exigir +exilio +existir +éxito +experto +explicar +exponer +extremo +fábrica +fábula +fachada +fácil +factor +faena +faja +falda +fallo +falso +faltar +fama +familia +famoso +faraón +farmacia +farol +farsa +fase +fatiga +fauna +favor +fax +febrero +fecha +feliz +feo +feria +feroz +fértil +fervor +festín +fiable +fianza +fiar +fibra +ficción +ficha +fideo +fiebre +fiel +fiera +fiesta +figura +fijar +fijo +fila +filete +filial +filtro +fin +finca +fingir +finito +firma +flaco +flauta +flecha +flor +flota +fluir +flujo +flúor +fobia +foca +fogata +fogón +folio +folleto +fondo +forma +forro +fortuna +forzar +fosa +foto +fracaso +frágil +franja +frase +fraude +freír +freno +fresa +frío +frito +fruta +fuego +fuente +fuerza +fuga +fumar +función +funda +furgón +furia +fusil +fútbol +futuro +gacela +gafas +gaita +gajo +gala +galería +gallo +gamba +ganar +gancho +ganga +ganso +garaje +garza +gasolina +gastar +gato +gavilán +gemelo +gemir +gen +género +genio +gente +geranio +gerente +germen +gesto +gigante +gimnasio +girar +giro +glaciar +globo +gloria +gol +golfo +goloso +golpe +goma +gordo +gorila +gorra +gota +goteo +gozar +grada +gráfico +grano +grasa +gratis +grave +grieta +grillo +gripe +gris +grito +grosor +grúa +grueso +grumo +grupo +guante +guapo +guardia +guerra +guía +guiño +guion +guiso +guitarra +gusano +gustar +haber +hábil +hablar +hacer +hacha +hada +hallar +hamaca +harina +haz +hazaña +hebilla +hebra +hecho +helado +helio +hembra +herir +hermano +héroe +hervir +hielo +hierro +hígado +higiene +hijo +himno +historia +hocico +hogar +hoguera +hoja +hombre +hongo +honor +honra +hora +hormiga +horno +hostil +hoyo +hueco +huelga +huerta +hueso +huevo +huida +huir +humano +húmedo +humilde +humo +hundir +huracán +hurto +icono +ideal +idioma +ídolo +iglesia +iglú +igual +ilegal +ilusión +imagen +imán +imitar +impar +imperio +imponer +impulso +incapaz +índice +inerte +infiel +informe +ingenio +inicio +inmenso +inmune +innato +insecto +instante +interés +íntimo +intuir +inútil +invierno +ira +iris +ironía +isla +islote +jabalí +jabón +jamón +jarabe +jardín +jarra +jaula +jazmín +jefe +jeringa +jinete +jornada +joroba +joven +joya +juerga +jueves +juez +jugador +jugo +juguete +juicio +junco +jungla +junio +juntar +júpiter +jurar +justo +juvenil +juzgar +kilo +koala +labio +lacio +lacra +lado +ladrón +lagarto +lágrima +laguna +laico +lamer +lámina +lámpara +lana +lancha +langosta +lanza +lápiz +largo +larva +lástima +lata +látex +latir +laurel +lavar +lazo +leal +lección +leche +lector +leer +legión +legumbre +lejano +lengua +lento +leña +león +leopardo +lesión +letal +letra +leve +leyenda +libertad +libro +licor +líder +lidiar +lienzo +liga +ligero +lima +límite +limón +limpio +lince +lindo +línea +lingote +lino +linterna +líquido +liso +lista +litera +litio +litro +llaga +llama +llanto +llave +llegar +llenar +llevar +llorar +llover +lluvia +lobo +loción +loco +locura +lógica +logro +lombriz +lomo +lonja +lote +lucha +lucir +lugar +lujo +luna +lunes +lupa +lustro +luto +luz +maceta +macho +madera +madre +maduro +maestro +mafia +magia +mago +maíz +maldad +maleta +malla +malo +mamá +mambo +mamut +manco +mando +manejar +manga +maniquí +manjar +mano +manso +manta +mañana +mapa +máquina +mar +marco +marea +marfil +margen +marido +mármol +marrón +martes +marzo +masa +máscara +masivo +matar +materia +matiz +matriz +máximo +mayor +mazorca +mecha +medalla +medio +médula +mejilla +mejor +melena +melón +memoria +menor +mensaje +mente +menú +mercado +merengue +mérito +mes +mesón +meta +meter +método +metro +mezcla +miedo +miel +miembro +miga +mil +milagro +militar +millón +mimo +mina +minero +mínimo +minuto +miope +mirar +misa +miseria +misil +mismo +mitad +mito +mochila +moción +moda +modelo +moho +mojar +molde +moler +molino +momento +momia +monarca +moneda +monja +monto +moño +morada +morder +moreno +morir +morro +morsa +mortal +mosca +mostrar +motivo +mover +móvil +mozo +mucho +mudar +mueble +muela +muerte +muestra +mugre +mujer +mula +muleta +multa +mundo +muñeca +mural +muro +músculo +museo +musgo +música +muslo +nácar +nación +nadar +naipe +naranja +nariz +narrar +nasal +natal +nativo +natural +náusea +naval +nave +navidad +necio +néctar +negar +negocio +negro +neón +nervio +neto +neutro +nevar +nevera +nicho +nido +niebla +nieto +niñez +niño +nítido +nivel +nobleza +noche +nómina +noria +norma +norte +nota +noticia +novato +novela +novio +nube +nuca +núcleo +nudillo +nudo +nuera +nueve +nuez +nulo +número +nutria +oasis +obeso +obispo +objeto +obra +obrero +observar +obtener +obvio +oca +ocaso +océano +ochenta +ocho +ocio +ocre +octavo +octubre +oculto +ocupar +ocurrir +odiar +odio +odisea +oeste +ofensa +oferta +oficio +ofrecer +ogro +oído +oír +ojo +ola +oleada +olfato +olivo +olla +olmo +olor +olvido +ombligo +onda +onza +opaco +opción +ópera +opinar +oponer +optar +óptica +opuesto +oración +orador +oral +órbita +orca +orden +oreja +órgano +orgía +orgullo +oriente +origen +orilla +oro +orquesta +oruga +osadía +oscuro +osezno +oso +ostra +otoño +otro +oveja +óvulo +óxido +oxígeno +oyente +ozono +pacto +padre +paella +página +pago +país +pájaro +palabra +palco +paleta +pálido +palma +paloma +palpar +pan +panal +pánico +pantera +pañuelo +papá +papel +papilla +paquete +parar +parcela +pared +parir +paro +párpado +parque +párrafo +parte +pasar +paseo +pasión +paso +pasta +pata +patio +patria +pausa +pauta +pavo +payaso +peatón +pecado +pecera +pecho +pedal +pedir +pegar +peine +pelar +peldaño +pelea +peligro +pellejo +pelo +peluca +pena +pensar +peñón +peón +peor +pepino +pequeño +pera +percha +perder +pereza +perfil +perico +perla +permiso +perro +persona +pesa +pesca +pésimo +pestaña +pétalo +petróleo +pez +pezuña +picar +pichón +pie +piedra +pierna +pieza +pijama +pilar +piloto +pimienta +pino +pintor +pinza +piña +piojo +pipa +pirata +pisar +piscina +piso +pista +pitón +pizca +placa +plan +plata +playa +plaza +pleito +pleno +plomo +pluma +plural +pobre +poco +poder +podio +poema +poesía +poeta +polen +policía +pollo +polvo +pomada +pomelo +pomo +pompa +poner +porción +portal +posada +poseer +posible +poste +potencia +potro +pozo +prado +precoz +pregunta +premio +prensa +preso +previo +primo +príncipe +prisión +privar +proa +probar +proceso +producto +proeza +profesor +programa +prole +promesa +pronto +propio +próximo +prueba +público +puchero +pudor +pueblo +puerta +puesto +pulga +pulir +pulmón +pulpo +pulso +puma +punto +puñal +puño +pupa +pupila +puré +quedar +queja +quemar +querer +queso +quieto +química +quince +quitar +rábano +rabia +rabo +ración +radical +raíz +rama +rampa +rancho +rango +rapaz +rápido +rapto +rasgo +raspa +rato +rayo +raza +razón +reacción +realidad +rebaño +rebote +recaer +receta +rechazo +recoger +recreo +recto +recurso +red +redondo +reducir +reflejo +reforma +refrán +refugio +regalo +regir +regla +regreso +rehén +reino +reír +reja +relato +relevo +relieve +relleno +reloj +remar +remedio +remo +rencor +rendir +renta +reparto +repetir +reposo +reptil +res +rescate +resina +respeto +resto +resumen +retiro +retorno +retrato +reunir +revés +revista +rey +rezar +rico +riego +rienda +riesgo +rifa +rígido +rigor +rincón +riñón +río +riqueza +risa +ritmo +rito +rizo +roble +roce +rociar +rodar +rodeo +rodilla +roer +rojizo +rojo +romero +romper +ron +ronco +ronda +ropa +ropero +rosa +rosca +rostro +rotar +rubí +rubor +rudo +rueda +rugir +ruido +ruina +ruleta +rulo +rumbo +rumor +ruptura +ruta +rutina +sábado +saber +sabio +sable +sacar +sagaz +sagrado +sala +saldo +salero +salir +salmón +salón +salsa +salto +salud +salvar +samba +sanción +sandía +sanear +sangre +sanidad +sano +santo +sapo +saque +sardina +sartén +sastre +satán +sauna +saxofón +sección +seco +secreto +secta +sed +seguir +seis +sello +selva +semana +semilla +senda +sensor +señal +señor +separar +sepia +sequía +ser +serie +sermón +servir +sesenta +sesión +seta +setenta +severo +sexo +sexto +sidra +siesta +siete +siglo +signo +sílaba +silbar +silencio +silla +símbolo +simio +sirena +sistema +sitio +situar +sobre +socio +sodio +sol +solapa +soldado +soledad +sólido +soltar +solución +sombra +sondeo +sonido +sonoro +sonrisa +sopa +soplar +soporte +sordo +sorpresa +sorteo +sostén +sótano +suave +subir +suceso +sudor +suegra +suelo +sueño +suerte +sufrir +sujeto +sultán +sumar +superar +suplir +suponer +supremo +sur +surco +sureño +surgir +susto +sutil +tabaco +tabique +tabla +tabú +taco +tacto +tajo +talar +talco +talento +talla +talón +tamaño +tambor +tango +tanque +tapa +tapete +tapia +tapón +taquilla +tarde +tarea +tarifa +tarjeta +tarot +tarro +tarta +tatuaje +tauro +taza +tazón +teatro +techo +tecla +técnica +tejado +tejer +tejido +tela +teléfono +tema +temor +templo +tenaz +tender +tener +tenis +tenso +teoría +terapia +terco +término +ternura +terror +tesis +tesoro +testigo +tetera +texto +tez +tibio +tiburón +tiempo +tienda +tierra +tieso +tigre +tijera +tilde +timbre +tímido +timo +tinta +tío +típico +tipo +tira +tirón +titán +títere +título +tiza +toalla +tobillo +tocar +tocino +todo +toga +toldo +tomar +tono +tonto +topar +tope +toque +tórax +torero +tormenta +torneo +toro +torpedo +torre +torso +tortuga +tos +tosco +toser +tóxico +trabajo +tractor +traer +tráfico +trago +traje +tramo +trance +trato +trauma +trazar +trébol +tregua +treinta +tren +trepar +tres +tribu +trigo +tripa +triste +triunfo +trofeo +trompa +tronco +tropa +trote +trozo +truco +trueno +trufa +tubería +tubo +tuerto +tumba +tumor +túnel +túnica +turbina +turismo +turno +tutor +ubicar +úlcera +umbral +unidad +unir +universo +uno +untar +uña +urbano +urbe +urgente +urna +usar +usuario +útil +utopía +uva +vaca +vacío +vacuna +vagar +vago +vaina +vajilla +vale +válido +valle +valor +válvula +vampiro +vara +variar +varón +vaso +vecino +vector +vehículo +veinte +vejez +vela +velero +veloz +vena +vencer +venda +veneno +vengar +venir +venta +venus +ver +verano +verbo +verde +vereda +verja +verso +verter +vía +viaje +vibrar +vicio +víctima +vida +vídeo +vidrio +viejo +viernes +vigor +vil +villa +vinagre +vino +viñedo +violín +viral +virgo +virtud +visor +víspera +vista +vitamina +viudo +vivaz +vivero +vivir +vivo +volcán +volumen +volver +voraz +votar +voto +voz +vuelo +vulgar +yacer +yate +yegua +yema +yerno +yeso +yodo +yoga +yogur +zafiro +zanja +zapato +zarza +zona +zorro +zumo +zurdo`.split('\n'); diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts b/test/merkletreejs/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts new file mode 100644 index 0000000..b566a1d --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts @@ -0,0 +1 @@ +export declare const wordlist: string[]; diff --git a/test/merkletreejs/node_modules/@scure/bip39/wordlists/traditional-chinese.js b/test/merkletreejs/node_modules/@scure/bip39/wordlists/traditional-chinese.js new file mode 100644 index 0000000..789a0bc --- /dev/null +++ b/test/merkletreejs/node_modules/@scure/bip39/wordlists/traditional-chinese.js @@ -0,0 +1,2051 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +exports.wordlist = `的 +一 +是 +在 +不 +了 +有 +和 +人 +這 +中 +大 +為 +上 +個 +國 +我 +以 +要 +他 +時 +來 +用 +們 +生 +到 +作 +地 +於 +出 +就 +分 +對 +成 +會 +可 +主 +發 +年 +動 +同 +工 +也 +能 +下 +過 +子 +說 +產 +種 +面 +而 +方 +後 +多 +定 +行 +學 +法 +所 +民 +得 +經 +十 +三 +之 +進 +著 +等 +部 +度 +家 +電 +力 +裡 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +現 +實 +加 +量 +都 +兩 +體 +制 +機 +當 +使 +點 +從 +業 +本 +去 +把 +性 +好 +應 +開 +它 +合 +還 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +義 +事 +平 +形 +相 +全 +表 +間 +樣 +與 +關 +各 +重 +新 +線 +內 +數 +正 +心 +反 +你 +明 +看 +原 +又 +麼 +利 +比 +或 +但 +質 +氣 +第 +向 +道 +命 +此 +變 +條 +只 +沒 +結 +解 +問 +意 +建 +月 +公 +無 +系 +軍 +很 +情 +者 +最 +立 +代 +想 +已 +通 +並 +提 +直 +題 +黨 +程 +展 +五 +果 +料 +象 +員 +革 +位 +入 +常 +文 +總 +次 +品 +式 +活 +設 +及 +管 +特 +件 +長 +求 +老 +頭 +基 +資 +邊 +流 +路 +級 +少 +圖 +山 +統 +接 +知 +較 +將 +組 +見 +計 +別 +她 +手 +角 +期 +根 +論 +運 +農 +指 +幾 +九 +區 +強 +放 +決 +西 +被 +幹 +做 +必 +戰 +先 +回 +則 +任 +取 +據 +處 +隊 +南 +給 +色 +光 +門 +即 +保 +治 +北 +造 +百 +規 +熱 +領 +七 +海 +口 +東 +導 +器 +壓 +志 +世 +金 +增 +爭 +濟 +階 +油 +思 +術 +極 +交 +受 +聯 +什 +認 +六 +共 +權 +收 +證 +改 +清 +美 +再 +採 +轉 +更 +單 +風 +切 +打 +白 +教 +速 +花 +帶 +安 +場 +身 +車 +例 +真 +務 +具 +萬 +每 +目 +至 +達 +走 +積 +示 +議 +聲 +報 +鬥 +完 +類 +八 +離 +華 +名 +確 +才 +科 +張 +信 +馬 +節 +話 +米 +整 +空 +元 +況 +今 +集 +溫 +傳 +土 +許 +步 +群 +廣 +石 +記 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +觀 +越 +織 +裝 +影 +算 +低 +持 +音 +眾 +書 +布 +复 +容 +兒 +須 +際 +商 +非 +驗 +連 +斷 +深 +難 +近 +礦 +千 +週 +委 +素 +技 +備 +半 +辦 +青 +省 +列 +習 +響 +約 +支 +般 +史 +感 +勞 +便 +團 +往 +酸 +歷 +市 +克 +何 +除 +消 +構 +府 +稱 +太 +準 +精 +值 +號 +率 +族 +維 +劃 +選 +標 +寫 +存 +候 +毛 +親 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +養 +易 +置 +派 +層 +片 +始 +卻 +專 +狀 +育 +廠 +京 +識 +適 +屬 +圓 +包 +火 +住 +調 +滿 +縣 +局 +照 +參 +紅 +細 +引 +聽 +該 +鐵 +價 +嚴 +首 +底 +液 +官 +德 +隨 +病 +蘇 +失 +爾 +死 +講 +配 +女 +黃 +推 +顯 +談 +罪 +神 +藝 +呢 +席 +含 +企 +望 +密 +批 +營 +項 +防 +舉 +球 +英 +氧 +勢 +告 +李 +台 +落 +木 +幫 +輪 +破 +亞 +師 +圍 +注 +遠 +字 +材 +排 +供 +河 +態 +封 +另 +施 +減 +樹 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +葉 +魚 +波 +視 +僅 +費 +緊 +愛 +左 +章 +早 +朝 +害 +續 +輕 +服 +試 +食 +充 +兵 +源 +判 +護 +司 +足 +某 +練 +差 +致 +板 +田 +降 +黑 +犯 +負 +擊 +范 +繼 +興 +似 +餘 +堅 +曲 +輸 +修 +故 +城 +夫 +夠 +送 +筆 +船 +佔 +右 +財 +吃 +富 +春 +職 +覺 +漢 +畫 +功 +巴 +跟 +雖 +雜 +飛 +檢 +吸 +助 +昇 +陽 +互 +初 +創 +抗 +考 +投 +壞 +策 +古 +徑 +換 +未 +跑 +留 +鋼 +曾 +端 +責 +站 +簡 +述 +錢 +副 +盡 +帝 +射 +草 +衝 +承 +獨 +令 +限 +阿 +宣 +環 +雙 +請 +超 +微 +讓 +控 +州 +良 +軸 +找 +否 +紀 +益 +依 +優 +頂 +礎 +載 +倒 +房 +突 +坐 +粉 +敵 +略 +客 +袁 +冷 +勝 +絕 +析 +塊 +劑 +測 +絲 +協 +訴 +念 +陳 +仍 +羅 +鹽 +友 +洋 +錯 +苦 +夜 +刑 +移 +頻 +逐 +靠 +混 +母 +短 +皮 +終 +聚 +汽 +村 +雲 +哪 +既 +距 +衛 +停 +烈 +央 +察 +燒 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +遊 +久 +菜 +味 +舊 +模 +湖 +貨 +損 +預 +阻 +毫 +普 +穩 +乙 +媽 +植 +息 +擴 +銀 +語 +揮 +酒 +守 +拿 +序 +紙 +醫 +缺 +雨 +嗎 +針 +劉 +啊 +急 +唱 +誤 +訓 +願 +審 +附 +獲 +茶 +鮮 +糧 +斤 +孩 +脫 +硫 +肥 +善 +龍 +演 +父 +漸 +血 +歡 +械 +掌 +歌 +沙 +剛 +攻 +謂 +盾 +討 +晚 +粒 +亂 +燃 +矛 +乎 +殺 +藥 +寧 +魯 +貴 +鐘 +煤 +讀 +班 +伯 +香 +介 +迫 +句 +豐 +培 +握 +蘭 +擔 +弦 +蛋 +沉 +假 +穿 +執 +答 +樂 +誰 +順 +煙 +縮 +徵 +臉 +喜 +松 +腳 +困 +異 +免 +背 +星 +福 +買 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +靜 +補 +評 +翻 +肉 +踐 +尼 +衣 +寬 +揚 +棉 +希 +傷 +操 +垂 +秋 +宜 +氫 +套 +督 +振 +架 +亮 +末 +憲 +慶 +編 +牛 +觸 +映 +雷 +銷 +詩 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +綠 +晶 +厚 +盟 +衡 +雞 +孫 +延 +危 +膠 +屋 +鄉 +臨 +陸 +顧 +掉 +呀 +燈 +歲 +措 +束 +耐 +劇 +玉 +趙 +跳 +哥 +季 +課 +凱 +胡 +額 +款 +紹 +卷 +齊 +偉 +蒸 +殖 +永 +宗 +苗 +川 +爐 +岩 +弱 +零 +楊 +奏 +沿 +露 +桿 +探 +滑 +鎮 +飯 +濃 +航 +懷 +趕 +庫 +奪 +伊 +靈 +稅 +途 +滅 +賽 +歸 +召 +鼓 +播 +盤 +裁 +險 +康 +唯 +錄 +菌 +純 +借 +糖 +蓋 +橫 +符 +私 +努 +堂 +域 +槍 +潤 +幅 +哈 +竟 +熟 +蟲 +澤 +腦 +壤 +碳 +歐 +遍 +側 +寨 +敢 +徹 +慮 +斜 +薄 +庭 +納 +彈 +飼 +伸 +折 +麥 +濕 +暗 +荷 +瓦 +塞 +床 +築 +惡 +戶 +訪 +塔 +奇 +透 +梁 +刀 +旋 +跡 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +擺 +灰 +彩 +賣 +耗 +夏 +擇 +忙 +銅 +獻 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +陣 +陰 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +樓 +避 +謀 +噸 +野 +豬 +旗 +累 +偏 +典 +館 +索 +秦 +脂 +潮 +爺 +豆 +忽 +托 +驚 +塑 +遺 +愈 +朱 +替 +纖 +粗 +傾 +尚 +痛 +楚 +謝 +奮 +購 +磨 +君 +池 +旁 +碎 +骨 +監 +捕 +弟 +暴 +割 +貫 +殊 +釋 +詞 +亡 +壁 +頓 +寶 +午 +塵 +聞 +揭 +炮 +殘 +冬 +橋 +婦 +警 +綜 +招 +吳 +付 +浮 +遭 +徐 +您 +搖 +谷 +贊 +箱 +隔 +訂 +男 +吹 +園 +紛 +唐 +敗 +宋 +玻 +巨 +耕 +坦 +榮 +閉 +灣 +鍵 +凡 +駐 +鍋 +救 +恩 +剝 +凝 +鹼 +齒 +截 +煉 +麻 +紡 +禁 +廢 +盛 +版 +緩 +淨 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +莊 +街 +藏 +姑 +貿 +腐 +奴 +啦 +慣 +乘 +夥 +恢 +勻 +紗 +扎 +辯 +耳 +彪 +臣 +億 +璃 +抵 +脈 +秀 +薩 +俄 +網 +舞 +店 +噴 +縱 +寸 +汗 +掛 +洪 +賀 +閃 +柬 +爆 +烯 +津 +稻 +牆 +軟 +勇 +像 +滾 +厘 +蒙 +芳 +肯 +坡 +柱 +盪 +腿 +儀 +旅 +尾 +軋 +冰 +貢 +登 +黎 +削 +鑽 +勒 +逃 +障 +氨 +郭 +峰 +幣 +港 +伏 +軌 +畝 +畢 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +島 +甘 +泡 +睡 +童 +鑄 +湯 +閥 +休 +匯 +舍 +牧 +繞 +炸 +哲 +磷 +績 +朋 +淡 +尖 +啟 +陷 +柴 +呈 +徒 +顏 +淚 +稍 +忘 +泵 +藍 +拖 +洞 +授 +鏡 +辛 +壯 +鋒 +貧 +虛 +彎 +摩 +泰 +幼 +廷 +尊 +窗 +綱 +弄 +隸 +疑 +氏 +宮 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +違 +夾 +腰 +緣 +珠 +窮 +森 +枝 +竹 +溝 +催 +繩 +憶 +邦 +剩 +幸 +漿 +欄 +擁 +牙 +貯 +禮 +濾 +鈉 +紋 +罷 +拍 +咱 +喊 +袖 +埃 +勤 +罰 +焦 +潛 +伍 +墨 +欲 +縫 +姓 +刊 +飽 +仿 +獎 +鋁 +鬼 +麗 +跨 +默 +挖 +鏈 +掃 +喝 +袋 +炭 +污 +幕 +諸 +弧 +勵 +梅 +奶 +潔 +災 +舟 +鑑 +苯 +訟 +抱 +毀 +懂 +寒 +智 +埔 +寄 +屆 +躍 +渡 +挑 +丹 +艱 +貝 +碰 +拔 +爹 +戴 +碼 +夢 +芽 +熔 +赤 +漁 +哭 +敬 +顆 +奔 +鉛 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +倉 +魏 +銳 +曉 +氮 +兼 +隱 +礙 +赫 +撥 +忠 +肅 +缸 +牽 +搶 +博 +巧 +殼 +兄 +杜 +訊 +誠 +碧 +祥 +柯 +頁 +巡 +矩 +悲 +灌 +齡 +倫 +票 +尋 +桂 +鋪 +聖 +恐 +恰 +鄭 +趣 +抬 +荒 +騰 +貼 +柔 +滴 +猛 +闊 +輛 +妻 +填 +撤 +儲 +簽 +鬧 +擾 +紫 +砂 +遞 +戲 +吊 +陶 +伐 +餵 +療 +瓶 +婆 +撫 +臂 +摸 +忍 +蝦 +蠟 +鄰 +胸 +鞏 +擠 +偶 +棄 +槽 +勁 +乳 +鄧 +吉 +仁 +爛 +磚 +租 +烏 +艦 +伴 +瓜 +淺 +丙 +暫 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +膽 +詳 +簧 +踏 +瓷 +譜 +呆 +賓 +糊 +洛 +輝 +憤 +競 +隙 +怒 +粘 +乃 +緒 +肩 +籍 +敏 +塗 +熙 +皆 +偵 +懸 +掘 +享 +糾 +醒 +狂 +鎖 +淀 +恨 +牲 +霸 +爬 +賞 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鴨 +趨 +鳳 +晨 +畜 +輩 +秩 +卵 +署 +梯 +炎 +灘 +棋 +驅 +篩 +峽 +冒 +啥 +壽 +譯 +浸 +泉 +帽 +遲 +矽 +疆 +貸 +漏 +稿 +冠 +嫩 +脅 +芯 +牢 +叛 +蝕 +奧 +鳴 +嶺 +羊 +憑 +串 +塘 +繪 +酵 +融 +盆 +錫 +廟 +籌 +凍 +輔 +攝 +襲 +筋 +拒 +僚 +旱 +鉀 +鳥 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韓 +逼 +扭 +僑 +涼 +挺 +碗 +栽 +炒 +杯 +患 +餾 +勸 +豪 +遼 +勃 +鴻 +旦 +吏 +拜 +狗 +埋 +輥 +掩 +飲 +搬 +罵 +辭 +勾 +扣 +估 +蔣 +絨 +霧 +丈 +朵 +姆 +擬 +宇 +輯 +陝 +雕 +償 +蓄 +崇 +剪 +倡 +廳 +咬 +駛 +薯 +刷 +斥 +番 +賦 +奉 +佛 +澆 +漫 +曼 +扇 +鈣 +桃 +扶 +仔 +返 +俗 +虧 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +騙 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +脹 +諧 +拋 +黴 +桑 +崗 +嘛 +衰 +盜 +滲 +臟 +賴 +湧 +甜 +曹 +閱 +肌 +哩 +厲 +烴 +緯 +毅 +昨 +偽 +症 +煮 +嘆 +釘 +搭 +莖 +籠 +酷 +偷 +弓 +錐 +恆 +傑 +坑 +鼻 +翼 +綸 +敘 +獄 +逮 +罐 +絡 +棚 +抑 +膨 +蔬 +寺 +驟 +穆 +冶 +枯 +冊 +屍 +凸 +紳 +坯 +犧 +焰 +轟 +欣 +晉 +瘦 +禦 +錠 +錦 +喪 +旬 +鍛 +壟 +搜 +撲 +邀 +亭 +酯 +邁 +舒 +脆 +酶 +閒 +憂 +酚 +頑 +羽 +漲 +卸 +仗 +陪 +闢 +懲 +杭 +姚 +肚 +捉 +飄 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +飾 +蕭 +雅 +郵 +遷 +燕 +撒 +姻 +赴 +宴 +煩 +債 +帳 +斑 +鈴 +旨 +醇 +董 +餅 +雛 +姿 +拌 +傅 +腹 +妥 +揉 +賢 +拆 +歪 +葡 +胺 +丟 +浩 +徽 +昂 +墊 +擋 +覽 +貪 +慰 +繳 +汪 +慌 +馮 +諾 +姜 +誼 +兇 +劣 +誣 +耀 +昏 +躺 +盈 +騎 +喬 +溪 +叢 +盧 +抹 +悶 +諮 +刮 +駕 +纜 +悟 +摘 +鉺 +擲 +頗 +幻 +柄 +惠 +慘 +佳 +仇 +臘 +窩 +滌 +劍 +瞧 +堡 +潑 +蔥 +罩 +霍 +撈 +胎 +蒼 +濱 +倆 +捅 +湘 +砍 +霞 +邵 +萄 +瘋 +淮 +遂 +熊 +糞 +烘 +宿 +檔 +戈 +駁 +嫂 +裕 +徙 +箭 +捐 +腸 +撐 +曬 +辨 +殿 +蓮 +攤 +攪 +醬 +屏 +疫 +哀 +蔡 +堵 +沫 +皺 +暢 +疊 +閣 +萊 +敲 +轄 +鉤 +痕 +壩 +巷 +餓 +禍 +丘 +玄 +溜 +曰 +邏 +彭 +嘗 +卿 +妨 +艇 +吞 +韋 +怨 +矮 +歇`.split('\n'); diff --git a/test/merkletreejs/node_modules/@types/node/LICENSE b/test/merkletreejs/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/test/merkletreejs/node_modules/@types/node/README.md b/test/merkletreejs/node_modules/@types/node/README.md new file mode 100644 index 0000000..07a7e55 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Sun, 03 Dec 2023 18:07:12 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). diff --git a/test/merkletreejs/node_modules/@types/node/assert.d.ts b/test/merkletreejs/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..cd82143 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/assert.d.ts @@ -0,0 +1,996 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn + * @return An Array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An Array of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. + * If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/test/merkletreejs/node_modules/@types/node/assert/strict.d.ts b/test/merkletreejs/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/test/merkletreejs/node_modules/@types/node/async_hooks.d.ts b/test/merkletreejs/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..0667a61 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,539 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * `AsyncLocalStorage` tracks async context + * * `process.getActiveResourcesInfo()` tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/test/merkletreejs/node_modules/@types/node/buffer.d.ts b/test/merkletreejs/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..1ee5c01 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2362 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + import { Blob as NodeBlob } from "buffer"; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: readonly any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`\-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | readonly number[]): Buffer; + from(data: WithImplicitCoercion): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=': 0'] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than or equal to`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends __Blob {} + /** + * `Blob` class is a global reference for `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } ? T + : typeof NodeBlob; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/test/merkletreejs/node_modules/@types/node/child_process.d.ts b/test/merkletreejs/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..a97532b --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1540 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('node:child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) + */ +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('node:assert'); + * const fs = require('node:fs'); + * const child_process = require('node:child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('node:child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('node:child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('node:child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('node:child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('node:net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('node:child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('node:net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('node:child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('node:child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('node:child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve + * it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('node:child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('node:child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('node:util'); + * const exec = util.promisify(require('node:child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('node:child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('node:util'); + * const execFile = util.promisify(require('node:child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile(file: string, args?: readonly string[] | null): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/test/merkletreejs/node_modules/@types/node/cluster.d.ts b/test/merkletreejs/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..39cd56a --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,432 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process + * isolation is not needed, use the `worker_threads` module instead, which + * allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + serialization?: SerializationType | undefined; + cwd?: string | undefined; + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker, this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('node:net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/test/merkletreejs/node_modules/@types/node/console.d.ts b/test/merkletreejs/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..bcc3450 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/console.d.ts @@ -0,0 +1,415 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | "auto" | undefined; + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/test/merkletreejs/node_modules/@types/node/constants.d.ts b/test/merkletreejs/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/constants.d.ts @@ -0,0 +1,19 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + import { constants as osConstants, SignalConstants } from "node:os"; + import { constants as cryptoConstants } from "node:crypto"; + import { constants as fsConstants } from "node:fs"; + + const exp: + & typeof osConstants.errno + & typeof osConstants.priority + & SignalConstants + & typeof cryptoConstants + & typeof fsConstants; + export = exp; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/test/merkletreejs/node_modules/@types/node/crypto.d.ts b/test/merkletreejs/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..2f2038e --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4456 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; + deriveBits( + algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/test/merkletreejs/node_modules/@types/node/dgram.d.ts b/test/merkletreejs/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..692e547 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,586 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | Uint8Array | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/test/merkletreejs/node_modules/@types/node/diagnostics_channel.d.ts b/test/merkletreejs/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..b02f591 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,191 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/test/merkletreejs/node_modules/@types/node/dns.d.ts b/test/merkletreejs/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..380cf7d --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/dns.d.ts @@ -0,0 +1,809 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('node:dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('node:dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('node:dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "AAAA", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CNAME", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NS", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default + * dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/test/merkletreejs/node_modules/@types/node/dns/promises.d.ts b/test/merkletreejs/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..ef9b222 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,425 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('node:dns').promises` or `require('node:dns/promises')`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('node:dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve( + hostname: string, + rrtype: string, + ): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the + * default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns').promises; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/dom-events.d.ts b/test/merkletreejs/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000..147a7b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/dom-events.d.ts @@ -0,0 +1,122 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from "events"; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: __Event; + new(type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: __EventTarget; + new(): __EventTarget; + }; +} diff --git a/test/merkletreejs/node_modules/@types/node/domain.d.ts b/test/merkletreejs/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..72f17bd --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('node:domain'); + * const fs = require('node:fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/test/merkletreejs/node_modules/@types/node/events.d.ts b/test/merkletreejs/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..6ed47c5 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/events.d.ts @@ -0,0 +1,879 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + interface _DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + }, + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: _NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @experimental + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_`EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: string | symbol, listener?: Function): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/test/merkletreejs/node_modules/@types/node/fs.d.ts b/test/merkletreejs/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..f98453a --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4291 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v20.1.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "close", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "close", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "close", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('node:path').sep`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | Buffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: WatchOptions | string, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + * @experimental + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/test/merkletreejs/node_modules/@types/node/fs/promises.d.ts b/test/merkletreejs/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..88a9fc3 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1239 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v20.0.0 + */ + type?: "bytes" | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + * @experimental + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & Abortable & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * An alias for {@link FileHandle.close()}. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('node:path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('node:fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/globals.d.ts b/test/merkletreejs/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..72d1860 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/globals.d.ts @@ -0,0 +1,385 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib-dom is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File; +// #endregion Fetch and friends + +declare global { + // Declare "static" methods in Error + interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; + } + + /*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + + // For backwards compability + interface NodeRequire extends NodeJS.Require {} + interface RequireResolve extends NodeJS.RequireResolve {} + interface NodeModule extends NodeJS.Module {} + + var process: NodeJS.Process; + var console: Console; + + var __filename: string; + var __dirname: string; + + var require: NodeRequire; + var module: NodeModule; + + // Same as module.exports + var exports: any; + + /** + * Only available if `--expose-gc` is passed to the process. + */ + var gc: undefined | (() => void); + + // #region borrowed + // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib + /** A controller object that allows you to abort one or more DOM requests as and when desired. */ + interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(reason?: any): void; + } + + /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ + interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; + } + + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion borrowed + + // #region Disposable + interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; + } + + interface Disposable { + [Symbol.dispose](): void; + } + + interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; + } + // #endregion Disposable + + // #region ArrayLike.at() + interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; + } + interface String extends RelativeIndexable {} + interface Array extends RelativeIndexable {} + interface ReadonlyArray extends RelativeIndexable {} + interface Int8Array extends RelativeIndexable {} + interface Uint8Array extends RelativeIndexable {} + interface Uint8ClampedArray extends RelativeIndexable {} + interface Int16Array extends RelativeIndexable {} + interface Uint16Array extends RelativeIndexable {} + interface Int32Array extends RelativeIndexable {} + interface Uint32Array extends RelativeIndexable {} + interface Float32Array extends RelativeIndexable {} + interface Float64Array extends RelativeIndexable {} + interface BigInt64Array extends RelativeIndexable {} + interface BigUint64Array extends RelativeIndexable {} + // #endregion ArrayLike.at() end + + /** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ + function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, + ): T; + + /*----------------------------------------------* + * * + * GLOBAL INTERFACES * + * * + *-----------------------------------------------*/ + namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | undefined; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + ".js": (m: Module, filename: string) => any; + ".json": (m: Module, filename: string) => any; + ".node": (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + } + + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | globalThis.Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; + + interface File extends _File {} + var File: typeof globalThis extends { + onmessage: any; + File: infer T; + } ? T + : typeof import("node:buffer").File; +} diff --git a/test/merkletreejs/node_modules/@types/node/globals.global.d.ts b/test/merkletreejs/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/test/merkletreejs/node_modules/@types/node/http.d.ts b/test/merkletreejs/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..9b2c3c2 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/http.d.ts @@ -0,0 +1,1888 @@ +/** + * To use the HTTP server and client one must `require('node:http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'example.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + prgama?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple + * times. + * + * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()`automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * Examples: + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module "node:http" { + export * from "http"; +} diff --git a/test/merkletreejs/node_modules/@types/node/http2.d.ts b/test/merkletreejs/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..c3b3e8e --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2382 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * const http2 = require('node:http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('node:http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('node:http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('node:http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/test/merkletreejs/node_modules/@types/node/https.d.ts b/test/merkletreejs/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..36ae5b2 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/https.d.ts @@ -0,0 +1,550 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('node:https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('node:https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/test/merkletreejs/node_modules/@types/node/index.d.ts b/test/merkletreejs/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..a596cad --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/index.d.ts @@ -0,0 +1,88 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 4.9+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/test/merkletreejs/node_modules/@types/node/inspector.d.ts b/test/merkletreejs/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..3927b81 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2747 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * + * It can be accessed using: + * + * ```js + * import * as inspector from 'node:inspector/promises'; + * ``` + * + * or + * + * ```js + * import * as inspector from 'node:inspector'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} diff --git a/test/merkletreejs/node_modules/@types/node/module.d.ts b/test/merkletreejs/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..68d59c7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/module.d.ts @@ -0,0 +1,301 @@ +/** + * @since v0.3.7 + * @experimental + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name?: string; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + /** @deprecated Use `ImportAttributes` instead */ + interface ImportAssertions extends ImportAttributes {} + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * The `initialize` hook provides a way to define a custom function that runs in the hooks thread + * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable objects. + * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored) + */ + format?: ModuleFormat | null | undefined; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions?: ImportAttributes | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. + * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); + * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource; + } + /** + * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. + * It is also in charge of validating the import assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` + * command flag enabled. + * + * @since v20.6.0 + * + * @param specifier The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. + * @returns The absolute (`file:`) URL string for the resolved module. + */ + resolve(specifier: string, parent?: string | URL | undefined): string; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/test/merkletreejs/node_modules/@types/node/net.d.ts b/test/merkletreejs/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..70789e1 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/net.d.ts @@ -0,0 +1,949 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('node:net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. ready + * 9. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('node:net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250`. + * @since v19.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @since v19.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/test/merkletreejs/node_modules/@types/node/os.d.ts b/test/merkletreejs/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..39a33f7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/os.d.ts @@ -0,0 +1,478 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('node:os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/test/merkletreejs/node_modules/@types/node/package.json b/test/merkletreejs/node_modules/@types/node/package.json new file mode 100644 index 0000000..8e61e9f --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/package.json @@ -0,0 +1,230 @@ +{ + "name": "@types/node", + "version": "20.10.3", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "githubUsername": "alvis", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "githubUsername": "smac89", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "githubUsername": "DeividasBakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "githubUsername": "eyqs", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "githubUsername": "Hannes-Magnusson-CK", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "githubUsername": "hoo29", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "githubUsername": "kjin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "githubUsername": "ajafff", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "githubUsername": "islishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "githubUsername": "mwiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "githubUsername": "n-e", + "url": "https://github.com/n-e" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "githubUsername": "parambirs", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Thomas den Hollander", + "githubUsername": "ThomasdenH", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "githubUsername": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "githubUsername": "samuela", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "githubUsername": "kuehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "githubUsername": "bhongy", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "githubUsername": "ZYSzys", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=4.8": { + "*": [ + "ts4.8/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~5.26.4" + }, + "typesPublisherContentHash": "23bf5e20c3e989ac01a5ead7a9bd16b7752ee61c6293df790619aa6185433385", + "typeScriptVersion": "4.6", + "nonNpm": true +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/@types/node/path.d.ts b/test/merkletreejs/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..6f07681 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/path.d.ts @@ -0,0 +1,191 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * const path = require('node:path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/test/merkletreejs/node_modules/@types/node/perf_hooks.d.ts b/test/merkletreejs/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..b369bb6 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,639 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * const { PerformanceObserver, performance } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only the named measure. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { performance as _performance } from "perf_hooks"; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/test/merkletreejs/node_modules/@types/node/process.d.ts b/test/merkletreejs/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..0e27473 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/process.d.ts @@ -0,0 +1,1539 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information', + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of`process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the Source Map v3 support for stack traces. + * It provides same features as launching Node.js process with commandline options --enable-source-maps. + * @since v16.6.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `undefined` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number | undefined; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/test/merkletreejs/node_modules/@types/node/punycode.d.ts b/test/merkletreejs/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..d2fc9f9 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/test/merkletreejs/node_modules/@types/node/querystring.d.ts b/test/merkletreejs/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..54ecc96 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,141 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('node:querystring'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/test/merkletreejs/node_modules/@types/node/readline.d.ts b/test/merkletreejs/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..b06d58b --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/readline.d.ts @@ -0,0 +1,539 @@ +/** + * The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline`module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/test/merkletreejs/node_modules/@types/node/readline/promises.d.ts b/test/merkletreejs/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..73fb111 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,150 @@ +/** + * @since v17.0.0 + * @experimental + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the`readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated`stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/repl.d.ts b/test/merkletreejs/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..6c5f81b --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * const repl = require('node:repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('node:repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('node:repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('node:repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/test/merkletreejs/node_modules/@types/node/stream.d.ts b/test/merkletreejs/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..15c633f --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1701 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `node:stream` module: + * + * ```js + * const stream = require('node:stream'); + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + interface ArrayOptions { + /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */ + concurrency?: number; + /** allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('node:fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('node:string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('node:stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('node:fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends ReadableBase { + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends WritableBase { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends ReadableBase implements WritableBase { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new + * AbortError())` for webstreams. + * + * ```js + * const fs = require('node:fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `16384` (16 KiB), or `16` for `objectMode`. + * @since v19.9.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param objectMode + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides `promise version`. + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a `promise version`. + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + * @experimental + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @experimental + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/test/merkletreejs/node_modules/@types/node/stream/consumers.d.ts b/test/merkletreejs/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/test/merkletreejs/node_modules/@types/node/stream/promises.d.ts b/test/merkletreejs/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/stream/web.d.ts b/test/merkletreejs/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..0d91613 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,350 @@ +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read(view: T): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/test/merkletreejs/node_modules/@types/node/string_decoder.d.ts b/test/merkletreejs/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..b8691e1 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/test/merkletreejs/node_modules/@types/node/test.d.ts b/test/merkletreejs/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..44b6a96 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/test.d.ts @@ -0,0 +1,1382 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the`test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.4.0/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import { AsyncResource } from "node:async_hooks"; + /** + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. The following properties are supported: + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a `describe()` block, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param [name='The name'] The name of the test, which is displayed when reporting test results. + * @param options Configuration options for the test. The following properties are supported: + * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the + * second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within {@link describe}. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; + } + /** + * The `describe()` function imported from the `node:test` module. Each + * invocation of this function results in the creation of a Subtest. + * After invocation of top level `describe` functions, + * all top level tests and suites will execute. + * @param [name='The name'] The name of the suite, which is displayed when reporting test results. + * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for `test()`. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + } + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a function under Suite. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run tests whose name matches the provided pattern. + * Test name patterns are interpreted as JavaScript regular expressions. + * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean; + /** + * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. + */ + setup?: (root: Test) => void | Promise; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + } + class Test extends AsyncResource { + concurrency: number; + nesting: number; + only: boolean; + reporter: TestsStream; + runOnlySubtests: boolean; + testNumber: number; + timeout: number | null; + } + /** + * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the + * order of the tests definition + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + class TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v20.1.0 + */ + before: typeof before; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + class SuiteContext { + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + } + /** + * This function is used to create a hook running before running a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after running a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running + * before each subtest of the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running + * after each subtest of the current test. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (s: SuiteContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's`mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param [original='A no-op function'] An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. The following properties are supported: + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. The following properties are supported: + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: Function, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + type Timer = "setInterval" | "clearInterval" | "setTimeout" | "clearTimeout"; + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + class MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * Example usage: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable(['setInterval']); + * ``` + * + * The above example enables mocking for the `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `setInterval`and `clearInterval` functions from `node:timers`,`node:timers/promises`, and`globalThis` will be mocked. + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout`functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * @since v20.4.0 + */ + enable(timers?: Timer[]): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable(['setTimeout']); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable(['setTimeout']); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable(['setTimeout']); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * + * assert.deepStrictEqual(results, [3, 2, 1]); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + Mock, + mock, + only, + run, + skip, + test, + test as default, + todo, + }; +} + +interface TestLocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test is not ran through a file. + */ + file?: string; + /** + * The line number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPass extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPlan extends TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr extends TestLocationInfo { + /** + * The message written to `stderr` + */ + message: string; +} +interface TestStdout extends TestLocationInfo { + /** + * The message written to `stdout` + */ + message: string; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform } from "node:stream"; + + type TestEvent = + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:watch:drained" }; + type TestEventGenerator = AsyncGenerator; + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + */ + class Spec extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format + */ + function junit(source: TestEventGenerator): AsyncGenerator; + export { dot, junit, Spec as spec, tap, TestEvent }; +} diff --git a/test/merkletreejs/node_modules/@types/node/timers.d.ts b/test/merkletreejs/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..039f31f --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/timers.d.ts @@ -0,0 +1,240 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('node:timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/test/merkletreejs/node_modules/@types/node/timers/promises.d.ts b/test/merkletreejs/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..5a54dc7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/tls.d.ts b/test/merkletreejs/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..b289e84 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1210 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('node:tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom`options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.createSecureContext(). + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of crypto.constants.defaultCoreCipherList, unless + * changed using CLI options using --tls-default-ciphers. + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/test/merkletreejs/node_modules/@types/node/trace_events.d.ts b/test/merkletreejs/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..3361359 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,182 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing + * information generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `node:trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool + * synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool + * asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync + * directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async + * directory methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * const trace_events = require('node:trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('node:trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/assert.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/assert.d.ts new file mode 100644 index 0000000..cd82143 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/assert.d.ts @@ -0,0 +1,996 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn + * @return An Array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An Array of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. + * If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/assert/strict.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/async_hooks.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/async_hooks.d.ts new file mode 100644 index 0000000..0667a61 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/async_hooks.d.ts @@ -0,0 +1,539 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * `AsyncLocalStorage` tracks async context + * * `process.getActiveResourcesInfo()` tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/buffer.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/buffer.d.ts new file mode 100644 index 0000000..1ee5c01 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/buffer.d.ts @@ -0,0 +1,2362 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + import { Blob as NodeBlob } from "buffer"; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: readonly any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`\-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | readonly number[]): Buffer; + from(data: WithImplicitCoercion): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=': 0'] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than or equal to`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends __Blob {} + /** + * `Blob` class is a global reference for `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } ? T + : typeof NodeBlob; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/child_process.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/child_process.d.ts new file mode 100644 index 0000000..a97532b --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/child_process.d.ts @@ -0,0 +1,1540 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('node:child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) + */ +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('node:assert'); + * const fs = require('node:fs'); + * const child_process = require('node:child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('node:child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('node:child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('node:child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('node:child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('node:net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('node:child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('node:net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('node:child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('node:child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('node:child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve + * it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('node:child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('node:child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('node:util'); + * const exec = util.promisify(require('node:child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('node:child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('node:util'); + * const execFile = util.promisify(require('node:child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile(file: string, args?: readonly string[] | null): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/cluster.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/cluster.d.ts new file mode 100644 index 0000000..39cd56a --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/cluster.d.ts @@ -0,0 +1,432 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process + * isolation is not needed, use the `worker_threads` module instead, which + * allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + serialization?: SerializationType | undefined; + cwd?: string | undefined; + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker, this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('node:net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/console.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/console.d.ts new file mode 100644 index 0000000..bcc3450 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/console.d.ts @@ -0,0 +1,415 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | "auto" | undefined; + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/constants.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/constants.d.ts @@ -0,0 +1,19 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + import { constants as osConstants, SignalConstants } from "node:os"; + import { constants as cryptoConstants } from "node:crypto"; + import { constants as fsConstants } from "node:fs"; + + const exp: + & typeof osConstants.errno + & typeof osConstants.priority + & SignalConstants + & typeof cryptoConstants + & typeof fsConstants; + export = exp; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/crypto.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/crypto.d.ts new file mode 100644 index 0000000..a540d91 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/crypto.d.ts @@ -0,0 +1,4455 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): string; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; + deriveBits( + algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/dgram.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/dgram.d.ts new file mode 100644 index 0000000..692e547 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/dgram.d.ts @@ -0,0 +1,586 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | Uint8Array | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts new file mode 100644 index 0000000..b02f591 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts @@ -0,0 +1,191 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/dns.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/dns.d.ts new file mode 100644 index 0000000..380cf7d --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/dns.d.ts @@ -0,0 +1,809 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('node:dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('node:dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('node:dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "AAAA", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CNAME", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NS", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default + * dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/dns/promises.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/dns/promises.d.ts new file mode 100644 index 0000000..ef9b222 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/dns/promises.d.ts @@ -0,0 +1,425 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('node:dns').promises` or `require('node:dns/promises')`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('node:dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve( + hostname: string, + rrtype: string, + ): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the + * default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns').promises; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/dom-events.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/dom-events.d.ts new file mode 100644 index 0000000..147a7b6 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/dom-events.d.ts @@ -0,0 +1,122 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from "events"; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: __Event; + new(type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: __EventTarget; + new(): __EventTarget; + }; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/domain.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/domain.d.ts new file mode 100644 index 0000000..72f17bd --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('node:domain'); + * const fs = require('node:fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/events.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/events.d.ts new file mode 100644 index 0000000..6ed47c5 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/events.d.ts @@ -0,0 +1,879 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + interface _DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + }, + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: _NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @experimental + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_`EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: string | symbol, listener?: Function): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/fs.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/fs.d.ts new file mode 100644 index 0000000..f98453a --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/fs.d.ts @@ -0,0 +1,4291 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v20.1.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "close", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "close", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "close", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('node:path').sep`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | Buffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: WatchOptions | string, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + * @experimental + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/fs/promises.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/fs/promises.d.ts new file mode 100644 index 0000000..88a9fc3 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/fs/promises.d.ts @@ -0,0 +1,1239 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v20.0.0 + */ + type?: "bytes" | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + * @experimental + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & Abortable & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * An alias for {@link FileHandle.close()}. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('node:path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('node:fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/globals.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/globals.d.ts new file mode 100644 index 0000000..72d1860 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/globals.d.ts @@ -0,0 +1,385 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib-dom is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File; +// #endregion Fetch and friends + +declare global { + // Declare "static" methods in Error + interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; + } + + /*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + + // For backwards compability + interface NodeRequire extends NodeJS.Require {} + interface RequireResolve extends NodeJS.RequireResolve {} + interface NodeModule extends NodeJS.Module {} + + var process: NodeJS.Process; + var console: Console; + + var __filename: string; + var __dirname: string; + + var require: NodeRequire; + var module: NodeModule; + + // Same as module.exports + var exports: any; + + /** + * Only available if `--expose-gc` is passed to the process. + */ + var gc: undefined | (() => void); + + // #region borrowed + // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib + /** A controller object that allows you to abort one or more DOM requests as and when desired. */ + interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(reason?: any): void; + } + + /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ + interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; + } + + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion borrowed + + // #region Disposable + interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; + } + + interface Disposable { + [Symbol.dispose](): void; + } + + interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; + } + // #endregion Disposable + + // #region ArrayLike.at() + interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; + } + interface String extends RelativeIndexable {} + interface Array extends RelativeIndexable {} + interface ReadonlyArray extends RelativeIndexable {} + interface Int8Array extends RelativeIndexable {} + interface Uint8Array extends RelativeIndexable {} + interface Uint8ClampedArray extends RelativeIndexable {} + interface Int16Array extends RelativeIndexable {} + interface Uint16Array extends RelativeIndexable {} + interface Int32Array extends RelativeIndexable {} + interface Uint32Array extends RelativeIndexable {} + interface Float32Array extends RelativeIndexable {} + interface Float64Array extends RelativeIndexable {} + interface BigInt64Array extends RelativeIndexable {} + interface BigUint64Array extends RelativeIndexable {} + // #endregion ArrayLike.at() end + + /** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ + function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, + ): T; + + /*----------------------------------------------* + * * + * GLOBAL INTERFACES * + * * + *-----------------------------------------------*/ + namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | undefined; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + ".js": (m: Module, filename: string) => any; + ".json": (m: Module, filename: string) => any; + ".node": (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + } + + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | globalThis.Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; + + interface File extends _File {} + var File: typeof globalThis extends { + onmessage: any; + File: infer T; + } ? T + : typeof import("node:buffer").File; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/globals.global.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/http.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/http.d.ts new file mode 100644 index 0000000..9b2c3c2 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/http.d.ts @@ -0,0 +1,1888 @@ +/** + * To use the HTTP server and client one must `require('node:http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'example.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + prgama?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple + * times. + * + * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()`automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * Examples: + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module "node:http" { + export * from "http"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/http2.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/http2.d.ts new file mode 100644 index 0000000..c3b3e8e --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/http2.d.ts @@ -0,0 +1,2382 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * const http2 = require('node:http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('node:http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('node:http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('node:http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/https.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/https.d.ts new file mode 100644 index 0000000..36ae5b2 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/https.d.ts @@ -0,0 +1,550 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('node:https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('node:https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/index.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/index.d.ts new file mode 100644 index 0000000..7c8b38c --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/index.d.ts @@ -0,0 +1,88 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 4.8 and earlier. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/inspector.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/inspector.d.ts new file mode 100644 index 0000000..3927b81 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/inspector.d.ts @@ -0,0 +1,2747 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * + * It can be accessed using: + * + * ```js + * import * as inspector from 'node:inspector/promises'; + * ``` + * + * or + * + * ```js + * import * as inspector from 'node:inspector'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/module.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/module.d.ts new file mode 100644 index 0000000..68d59c7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/module.d.ts @@ -0,0 +1,301 @@ +/** + * @since v0.3.7 + * @experimental + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name?: string; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + /** @deprecated Use `ImportAttributes` instead */ + interface ImportAssertions extends ImportAttributes {} + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * The `initialize` hook provides a way to define a custom function that runs in the hooks thread + * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable objects. + * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored) + */ + format?: ModuleFormat | null | undefined; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions?: ImportAttributes | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. + * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); + * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource; + } + /** + * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. + * It is also in charge of validating the import assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` + * command flag enabled. + * + * @since v20.6.0 + * + * @param specifier The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. + * @returns The absolute (`file:`) URL string for the resolved module. + */ + resolve(specifier: string, parent?: string | URL | undefined): string; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/net.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/net.d.ts new file mode 100644 index 0000000..70789e1 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/net.d.ts @@ -0,0 +1,949 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('node:net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. ready + * 9. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('node:net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250`. + * @since v19.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @since v19.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/os.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/os.d.ts new file mode 100644 index 0000000..39a33f7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/os.d.ts @@ -0,0 +1,478 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('node:os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/path.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/path.d.ts new file mode 100644 index 0000000..6f07681 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/path.d.ts @@ -0,0 +1,191 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * const path = require('node:path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/perf_hooks.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/perf_hooks.d.ts new file mode 100644 index 0000000..0e16e58 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/perf_hooks.d.ts @@ -0,0 +1,639 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * const { PerformanceObserver, performance } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http"; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only the named measure. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { performance as _performance } from "perf_hooks"; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/process.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/process.d.ts new file mode 100644 index 0000000..0e27473 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/process.d.ts @@ -0,0 +1,1539 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information', + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of`process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the Source Map v3 support for stack traces. + * It provides same features as launching Node.js process with commandline options --enable-source-maps. + * @since v16.6.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `undefined` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number | undefined; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/punycode.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/punycode.d.ts new file mode 100644 index 0000000..d2fc9f9 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/querystring.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/querystring.d.ts new file mode 100644 index 0000000..54ecc96 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/querystring.d.ts @@ -0,0 +1,141 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('node:querystring'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/readline.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/readline.d.ts new file mode 100644 index 0000000..b06d58b --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/readline.d.ts @@ -0,0 +1,539 @@ +/** + * The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline`module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/readline/promises.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/readline/promises.d.ts new file mode 100644 index 0000000..73fb111 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/readline/promises.d.ts @@ -0,0 +1,150 @@ +/** + * @since v17.0.0 + * @experimental + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the`readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated`stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/repl.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/repl.d.ts new file mode 100644 index 0000000..6c5f81b --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * const repl = require('node:repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('node:repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('node:repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('node:repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/stream.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/stream.d.ts new file mode 100644 index 0000000..15c633f --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/stream.d.ts @@ -0,0 +1,1701 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `node:stream` module: + * + * ```js + * const stream = require('node:stream'); + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + interface ArrayOptions { + /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */ + concurrency?: number; + /** allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('node:fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('node:string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('node:stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('node:fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends ReadableBase { + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends WritableBase { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends ReadableBase implements WritableBase { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new + * AbortError())` for webstreams. + * + * ```js + * const fs = require('node:fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `16384` (16 KiB), or `16` for `objectMode`. + * @since v19.9.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param objectMode + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides `promise version`. + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a `promise version`. + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + * @experimental + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @experimental + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/stream/consumers.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/stream/promises.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/stream/web.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/stream/web.d.ts new file mode 100644 index 0000000..0d91613 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/stream/web.d.ts @@ -0,0 +1,350 @@ +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read(view: T): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/string_decoder.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/string_decoder.d.ts new file mode 100644 index 0000000..b8691e1 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/test.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/test.d.ts new file mode 100644 index 0000000..44b6a96 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/test.d.ts @@ -0,0 +1,1382 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the`test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.4.0/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import { AsyncResource } from "node:async_hooks"; + /** + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. The following properties are supported: + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a `describe()` block, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param [name='The name'] The name of the test, which is displayed when reporting test results. + * @param options Configuration options for the test. The following properties are supported: + * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the + * second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within {@link describe}. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; + } + /** + * The `describe()` function imported from the `node:test` module. Each + * invocation of this function results in the creation of a Subtest. + * After invocation of top level `describe` functions, + * all top level tests and suites will execute. + * @param [name='The name'] The name of the suite, which is displayed when reporting test results. + * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for `test()`. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + } + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a function under Suite. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run tests whose name matches the provided pattern. + * Test name patterns are interpreted as JavaScript regular expressions. + * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean; + /** + * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. + */ + setup?: (root: Test) => void | Promise; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + } + class Test extends AsyncResource { + concurrency: number; + nesting: number; + only: boolean; + reporter: TestsStream; + runOnlySubtests: boolean; + testNumber: number; + timeout: number | null; + } + /** + * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the + * order of the tests definition + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + class TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v20.1.0 + */ + before: typeof before; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + class SuiteContext { + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + } + /** + * This function is used to create a hook running before running a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after running a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running + * before each subtest of the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running + * after each subtest of the current test. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (s: SuiteContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's`mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param [original='A no-op function'] An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. The following properties are supported: + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. The following properties are supported: + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: Function, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + type Timer = "setInterval" | "clearInterval" | "setTimeout" | "clearTimeout"; + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + class MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * Example usage: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable(['setInterval']); + * ``` + * + * The above example enables mocking for the `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `setInterval`and `clearInterval` functions from `node:timers`,`node:timers/promises`, and`globalThis` will be mocked. + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout`functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * @since v20.4.0 + */ + enable(timers?: Timer[]): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable(['setTimeout']); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable(['setTimeout']); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable(['setTimeout']); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * + * assert.deepStrictEqual(results, [3, 2, 1]); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + Mock, + mock, + only, + run, + skip, + test, + test as default, + todo, + }; +} + +interface TestLocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test is not ran through a file. + */ + file?: string; + /** + * The line number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPass extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPlan extends TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr extends TestLocationInfo { + /** + * The message written to `stderr` + */ + message: string; +} +interface TestStdout extends TestLocationInfo { + /** + * The message written to `stdout` + */ + message: string; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform } from "node:stream"; + + type TestEvent = + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:watch:drained" }; + type TestEventGenerator = AsyncGenerator; + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + */ + class Spec extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format + */ + function junit(source: TestEventGenerator): AsyncGenerator; + export { dot, junit, Spec as spec, tap, TestEvent }; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/timers.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/timers.d.ts new file mode 100644 index 0000000..039f31f --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/timers.d.ts @@ -0,0 +1,240 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('node:timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/timers/promises.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/timers/promises.d.ts new file mode 100644 index 0000000..5a54dc7 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/tls.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/tls.d.ts new file mode 100644 index 0000000..b289e84 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/tls.d.ts @@ -0,0 +1,1210 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('node:tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom`options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.createSecureContext(). + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of crypto.constants.defaultCoreCipherList, unless + * changed using CLI options using --tls-default-ciphers. + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/trace_events.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/trace_events.d.ts new file mode 100644 index 0000000..3361359 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/trace_events.d.ts @@ -0,0 +1,182 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing + * information generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `node:trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool + * synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool + * asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync + * directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async + * directory methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * const trace_events = require('node:trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('node:trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/tty.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/tty.d.ts new file mode 100644 index 0000000..1c0dafd --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * const tty = require('node:tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to`setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/url.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/url.d.ts new file mode 100644 index 0000000..20a5d85 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/url.d.ts @@ -0,0 +1,927 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('node:url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject` s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('node:buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + constructor(input: string, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`.. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on`name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/util.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/util.d.ts new file mode 100644 index 0000000..ac269ec --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/util.d.ts @@ -0,0 +1,2183 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('node:util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('node:util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @experimental + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @experimental + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and + * returns a promise that is fulfilled when the `signal` is + * aborted. If the passed `resource` is garbage collected before the `signal` is + * aborted, the returned promise shall remain pending indefinitely. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('node:util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('node:util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('node:util'); + * const assert = require('node:assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('node:util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('node:util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('node:events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('node:util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('node:util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('node:util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('node:util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('node:util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `require('util').TextDecoder` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `require('util').TextEncoder` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: "string" | "boolean"; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? { + -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a`MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()`returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false`for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/v8.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/v8.d.ts new file mode 100644 index 0000000..6790e76 --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/v8.d.ts @@ -0,0 +1,635 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('node:v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('node:v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('node:v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('node:v8'); + * const { + * Worker, + * isMainThread, + * parentPort, + * } = require('node:worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8[`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object.The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/test/merkletreejs/node_modules/@types/node/ts4.8/vm.d.ts b/test/merkletreejs/node_modules/@types/node/ts4.8/vm.d.ts new file mode 100644 index 0000000..3a310cc --- /dev/null +++ b/test/merkletreejs/node_modules/@types/node/ts4.8/vm.d.ts @@ -0,0 +1,903 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('node:vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Called during evaluation of this module when `import()` is called. + * If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions["name"]; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions["origin"]; + contextCodeGeneration?: CreateContextOptions["codeGeneration"]; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: CreateContextOptions["microtaskMode"]; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: "afterEvaluate" | undefined; + } + type MeasureMemoryMode = "summary" | "detailed"; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + /** + * @default 'default' + */ + execution?: "default" | "eager" | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions | string); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('node:vm'); + * + * const context = { + * animal: 'cat', + * count: 2, + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('node:vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. + * + * script.runInThisContext(); + * + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8\. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic + * comment, this property will be set to the URL of the source map. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + sourceMapURL?: string | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` +``` + +> ES module + +```html + +``` + +### [Node.js](http://nodejs.org) + +```bash +npm install bignumber.js +``` + +```javascript +const BigNumber = require('bignumber.js'); +``` + +> ES module + +```javascript +import BigNumber from "bignumber.js"; +import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs"; +``` + +### [Deno](https://deno.land/) + +```javascript +import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.1.2/bignumber.mjs'; +import BigNumber from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs'; +``` + +## Use + +The library exports a single constructor function, [`BigNumber`](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber, + +```javascript +let x = new BigNumber(123.4567); +let y = BigNumber('123456.7e-3'); +let z = new BigNumber(x); +x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true +``` + +To get the string value of a BigNumber use [`toString()`](http://mikemcl.github.io/bignumber.js/#toS) or [`toFixed()`](http://mikemcl.github.io/bignumber.js/#toFix). Using `toFixed()` prevents exponential notation being returned, no matter how large or small the value. + +```javascript +let x = new BigNumber('1111222233334444555566'); +x.toString(); // "1.111222233334444555566e+21" +x.toFixed(); // "1111222233334444555566" +``` + +If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision. + +*In all further examples below, `let`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +```javascript +// Precision loss from using numeric literals with more than 15 significant digits. +new BigNumber(1.0000000000000001) // '1' +new BigNumber(88259496234518.57) // '88259496234518.56' +new BigNumber(99999999999999999999) // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new BigNumber(2e+308) // 'Infinity' +new BigNumber(1e-324) // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new BigNumber(0.7 + 0.1) // '0.7999999999999999' +``` + +When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2. + +```javascript +new BigNumber(Number.MAX_VALUE.toString(2), 2) +``` + +BigNumbers can be created from values in bases from 2 to 36. See [`ALPHABET`](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range. + +```javascript +a = new BigNumber(1011, 2) // "11" +b = new BigNumber('zz.9', 36) // "1295.25" +c = a.plus(b) // "1306.25" +``` + +*Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when you want to limit the number of decimal places of the input value to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9) +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue() +``` + +Some of the longer method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3)) // true +x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true +``` + +As with JavaScript's Number type, there are [`toExponential`](http://mikemcl.github.io/bignumber.js/#toE), [`toFixed`](http://mikemcl.github.io/bignumber.js/#toFix) and [`toPrecision`](http://mikemcl.github.io/bignumber.js/#toP) methods. + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + A base can be specified for [`toString`](http://mikemcl.github.io/bignumber.js/#toS). + +*Performance is better if base 10 is NOT specified, i.e. use `toString()` not `toString(10)`. Only specify base 10 when you want to limit the number of decimal places of the string to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is a [`toFormat`](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation. + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `set` or `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2) +y = new BigNumber(3) +z = x.dividedBy(y) // "0.6666666667" +z.squareRoot() // "0.8164965809" +z.exponentiatedBy(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.multipliedBy(z) // "0.44444444448888888889" +z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" +``` + +There is a [`toFraction`](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and [`isNaN`](http://mikemcl.github.io/bignumber.js/#isNaN) and [`isFinite`](http://mikemcl.github.io/bignumber.js/#isF) methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + +For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.set({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +To avoid having to call `toString` or `valueOf` on a BigNumber to get its value in the Node.js REPL or when using `console.log` use + +```javascript +BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf; +``` + +For further information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test/modules* directory contains the test scripts for each method. + +The tests can be run with Node.js or a browser. For Node.js use + +```bash +npm test +``` + +or + +```bash +node test/test +``` + +To test a single method, use, for example + +```bash +node test/methods/toFraction +``` + +For the browser, open *test/test.html*. + +## Minify + +To minify using, for example, [terser](https://github.com/terser/terser) + +```bash +npm install -g terser +``` + +```bash +terser big.js -c -m -o big.min.js +``` + +## Licence + +The MIT Licence. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE). diff --git a/test/merkletreejs/node_modules/bignumber.js/bignumber.d.ts b/test/merkletreejs/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 0000000..f75f8bf --- /dev/null +++ b/test/merkletreejs/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,1831 @@ +// Type definitions for bignumber.js >=8.1.0 +// Project: https://github.com/MikeMcl/bignumber.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/bignumber.js + +// Documentation: http://mikemcl.github.io/bignumber.js/ +// +// Exports: +// +// class BigNumber (default export) +// type BigNumber.Constructor +// type BigNumber.ModuloMode +// type BigNumber.RoundingMode +// type BigNumber.Value +// interface BigNumber.Config +// interface BigNumber.Format +// interface BigNumber.Instance +// +// Example: +// +// import {BigNumber} from "bignumber.js" +// //import BigNumber from "bignumber.js" +// +// let rm: BigNumber.RoundingMode = BigNumber.ROUND_UP; +// let f: BigNumber.Format = { decimalSeparator: ',' }; +// let c: BigNumber.Config = { DECIMAL_PLACES: 4, ROUNDING_MODE: rm, FORMAT: f }; +// BigNumber.config(c); +// +// let v: BigNumber.Value = '12345.6789'; +// let b: BigNumber = new BigNumber(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +export default BigNumber; + +export namespace BigNumber { + + /** See `BigNumber.config` (alias `BigNumber.set`) and `BigNumber.clone`. */ + interface Config { + + /** + * An integer, 0 to 1e+9. Default value: 20. + * + * The maximum number of decimal places of the result of operations involving division, i.e. + * division, square root and base conversion operations, and exponentiation when the exponent is + * negative. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.set({ DECIMAL_PLACES: 5 }) + * ``` + */ + DECIMAL_PLACES?: number; + + /** + * An integer, 0 to 8. Default value: `BigNumber.ROUND_HALF_UP` (4). + * + * The rounding mode used in operations that involve division (see `DECIMAL_PLACES`) and the + * default rounding mode of the `decimalPlaces`, `precision`, `toExponential`, `toFixed`, + * `toFormat` and `toPrecision` methods. + * + * The modes are available as enumerated properties of the BigNumber constructor. + * + * ```ts + * BigNumber.config({ ROUNDING_MODE: 0 }) + * BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) + * ``` + */ + ROUNDING_MODE?: BigNumber.RoundingMode; + + /** + * An integer, 0 to 1e+9, or an array, [-1e+9 to 0, 0 to 1e+9]. + * Default value: `[-7, 20]`. + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at + * and beneath which exponential notation is used, and the second number is the positive exponent + * value at and above which exponential notation is used. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they begin + * to use exponential notation, use `[-7, 20]`. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in + * normal notation and the `toExponential` method will always return a value in exponential form. + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal + * notation. + */ + EXPONENTIAL_AT?: number | [number, number]; + + /** + * An integer, magnitude 1 to 1e+9, or an array, [-1e+9 to -1, 1 to 1e+9]. + * Default value: `[-1e+9, 1e+9]`. + * + * The exponent value(s) beyond which overflow to Infinity and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: values wth a positive + * exponent of greater magnitude become Infinity and those with a negative exponent of greater + * magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and + * the second number is the positive exponent limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they + * become zero and Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * The largest possible magnitude of a finite BigNumber is 9.999...e+1000000000. + * The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. + */ + RANGE?: number | [number, number]; + + /** + * A boolean: `true` or `false`. Default value: `false`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is + * used. If `CRYPTO` is set to true then the random method will generate random digits using + * `crypto.getRandomValues` in browsers that support it, or `crypto.randomBytes` if using a + * version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to + * `true` will fail and an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is + * assumed to generate at least 30 bits of randomness). + * + * See `BigNumber.random`. + * + * ```ts + * // Node.js + * global.crypto = require('crypto') + * + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + */ + CRYPTO?: boolean; + + /** + * An integer, 0, 1, 3, 6 or 9. Default value: `BigNumber.ROUND_DOWN` (1). + * + * The modulo mode used when calculating the modulus: `a mod n`. + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to + * the chosen `MODULO_MODE`. + * The remainder, `r`, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the + * following table. Although the other rounding modes can be used, they may not give useful + * results. + * + * Property | Value | Description + * :------------------|:------|:------------------------------------------------------------------ + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. + * | | Uses 'truncating division' and matches JavaScript's `%` operator . + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's `%` operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. + * | | Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See `modulo`. + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.set({ MODULO_MODE: 9 }) // equivalent + * ``` + */ + MODULO_MODE?: BigNumber.ModuloMode; + + /** + * An integer, 0 to 1e+9. Default value: 0. + * + * The maximum precision, i.e. number of significant digits, of the result of the power operation + * - unless a modulus is specified. + * + * If set to 0, the number of significant digits will not be limited. + * + * See `exponentiatedBy`. + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + */ + POW_PRECISION?: number; + + /** + * An object including any number of the properties shown below. + * + * The object configures the format of the string returned by the `toFormat` method. + * The example below shows the properties of the object that are recognised, and + * their default values. + * + * Unlike the other configuration properties, the values of the properties of the `FORMAT` object + * will not be checked for validity - the existing object will simply be replaced by the object + * that is passed in. + * + * See `toFormat`. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // string to prepend + * prefix: '', + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0, + * // string to append + * suffix: '' + * } + * }) + * ``` + */ + FORMAT?: BigNumber.Format; + + /** + * The alphabet used for base conversion. The length of the alphabet corresponds to the maximum + * value of the base argument that can be passed to the BigNumber constructor or `toString`. + * + * Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. + * + * There is no maximum length for the alphabet, but it must be at least 2 characters long, + * and it must not contain whitespace or a repeated character, or the sign indicators '+' and + * '-', or the decimal separator '.'. + * + * ```ts + * // duodecimal (base 12) + * BigNumber.config({ ALPHABET: '0123456789TE' }) + * x = new BigNumber('T', 12) + * x.toString() // '10' + * x.toString(12) // 'T' + * ``` + */ + ALPHABET?: string; + } + + /** See `FORMAT` and `toFormat`. */ + interface Format { + + /** The string to prepend. */ + prefix?: string; + + /** The decimal separator. */ + decimalSeparator?: string; + + /** The grouping separator of the integer part. */ + groupSeparator?: string; + + /** The primary grouping size of the integer part. */ + groupSize?: number; + + /** The secondary grouping size of the integer part. */ + secondaryGroupSize?: number; + + /** The grouping separator of the fraction part. */ + fractionGroupSeparator?: string; + + /** The grouping size of the fraction part. */ + fractionGroupSize?: number; + + /** The string to append. */ + suffix?: string; + } + + interface Instance { + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + [key: string]: any; + } + + type Constructor = typeof BigNumber; + type ModuloMode = 0 | 1 | 3 | 6 | 9; + type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + type Value = string | number | Instance; +} + +export declare class BigNumber implements BigNumber.Instance { + + /** Used internally to identify a BigNumber instance. */ + private readonly _isBigNumber: true; + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + /** + * Returns a new instance of a BigNumber object with value `n`, where `n` is a numeric value in + * the specified `base`, or base 10 if `base` is omitted or is `null` or `undefined`. + * + * ```ts + * x = new BigNumber(123.4567) // '123.4567' + * // 'new' is optional + * y = BigNumber(x) // '123.4567' + * ``` + * + * If `n` is a base 10 value it can be in normal (fixed-point) or exponential notation. + * Values in other bases must be in normal notation. Values in any base can have fraction digits, + * i.e. digits after the decimal point. + * + * ```ts + * new BigNumber(43210) // '43210' + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * ``` + * + * Signed `0`, signed `Infinity` and `NaN` are supported. + * + * ```ts + * new BigNumber('-Infinity') // '-Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber(-0) // '0' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * ``` + * + * String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values with + * the octal and binary prefixs `'0o'` and `'0b'`. String values in octal literal form without the + * prefix will be interpreted as decimals, e.g. `'011'` is interpreted as 11, not 9. + * + * ```ts + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber('-0b10110100.1') // '-180.5' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * If a base is specified, `n` is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. This includes base 10, so don't include a `base` parameter for decimal + * values unless this behaviour is desired. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * An error is thrown if `base` is invalid. + * + * There is no limit to the number of digits of a value of type string (other than that of + * JavaScript's maximum array size). See `RANGE` to set the maximum and minimum possible exponent + * value of a BigNumber. + * + * ```ts + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e10000000') + * ``` + * + * BigNumber `NaN` is returned if `n` is invalid (unless `BigNumber.DEBUG` is `true`, see below). + * + * ```ts + * new BigNumber('.1*') // 'NaN' + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * ``` + * + * To aid in debugging, if `BigNumber.DEBUG` is `true` then an error will be thrown on an + * invalid `n`. An error will also be thrown if `n` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on these numbers may not result in the + * intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * // 'Error: Number has more than 15 significant digits' + * new BigNumber(823456789123456.3) + * // 'Error: Not a base 2 number' + * new BigNumber(9, 2) + * ``` + * + * A BigNumber can also be created from an object literal. + * Use `isBigNumber` to check that it is well-formed. + * + * ```ts + * new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123' + * ``` + * + * @param n A numeric value. + * @param base The base of `n`, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + constructor(n: BigNumber.Value, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.absoluteValue() // '0.8' + * ``` + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.abs() // '0.8' + * ``` + */ + abs(): BigNumber; + + /** + * Returns | | + * :-------:|:--------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of `n` + * -1 | If the value of this BigNumber is less than the value of `n` + * 0 | If this BigNumber and `n` have the same value + * `null` | If the value of either this BigNumber or `n` is `NaN` + * + * ```ts + * + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.comparedTo(NaN) // null + * y.comparedTo('110', 2) // -1 + * ``` + * @param n A numeric value. + * @param [base] The base of n. + */ + comparedTo(n: BigNumber.Value, base?: number): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.decimalPlaces() // 2 + * x.decimalPlaces(1) // '1234.6' + * x.decimalPlaces(2) // '1234.56' + * x.decimalPlaces(10) // '1234.56' + * x.decimalPlaces(0, 1) // '1234' + * x.decimalPlaces(0, 6) // '1235' + * x.decimalPlaces(1, 1) // '1234.5' + * x.decimalPlaces(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.decimalPlaces() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + decimalPlaces(): number | null; + decimalPlaces(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.dp() // 2 + * x.dp(1) // '1234.6' + * x.dp(2) // '1234.56' + * x.dp(10) // '1234.56' + * x.dp(0, 1) // '1234' + * x.dp(0, 6) // '1235' + * x.dp(1, 1) // '1234.5' + * x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + dp(): number | null; + dp(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.dividedBy(5) // '71' + * x.dividedBy(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.div(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + div(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.dividedToIntegerBy(0.7) // '7' + * x.dividedToIntegerBy('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedToIntegerBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.idiv(y) // '1' + * x.idiv(0.7) // '7' + * x.idiv('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + idiv(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.exponentiatedBy(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.exponentiatedBy(2) // '0.49' + * BigNumber(3).exponentiatedBy(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + exponentiatedBy(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + exponentiatedBy(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.pow(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.pow(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + pow(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + pow(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + * rounding mode `rm`. + * + * If `rm` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `rm` is invalid. + * + * ```ts + * x = new BigNumber(123.456) + * x.integerValue() // '123' + * x.integerValue(BigNumber.ROUND_CEIL) // '124' + * y = new BigNumber(-12.7) + * y.integerValue() // '-13' + * x.integerValue(BigNumber.ROUND_DOWN) // '-12' + * ``` + * + * @param {BigNumber.RoundingMode} [rm] The roundng mode, an integer, 0 to 8. + */ + integerValue(rm?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.isEqualTo('1e-324') // false + * BigNumber(-0).isEqualTo(x) // true ( -0 === 0 ) + * BigNumber(255).isEqualTo('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.isEqualTo(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.eq('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.eq(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + eq(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * ```ts + * x = new BigNumber(1) + * x.isFinite() // true + * y = new BigNumber(Infinity) + * y.isFinite() // false + * ``` + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).isGreaterThan(x) // false + * BigNumber(11, 3).isGreaterThan(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0 // true + * x = new BigNumber(0.1) + * x.gt(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.isGreaterThanOrEqualTo(0.1) // true + * BigNumber(1).isGreaterThanOrEqualTo(x) // true + * BigNumber(10, 18).isGreaterThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.gte(0.1) // true + * BigNumber(1).gte(x) // true + * BigNumber(10, 18).gte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is an integer, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(1) + * x.isInteger() // true + * y = new BigNumber(123.456) + * y.isInteger() // false + * ``` + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.isLessThan(0.1) // false + * BigNumber(0).isLessThan(x) // true + * BigNumber(11.1, 2).isLessThan(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.lt(0.1) // false + * BigNumber(0).lt(x) // true + * BigNumber(11.1, 2).lt(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).isLessThanOrEqualTo(x) // true + * BigNumber(10, 18).isLessThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.lte(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).lte(x) // true + * BigNumber(10, 18).lte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(NaN) + * x.isNaN() // true + * y = new BigNumber('Infinity') + * y.isNaN() // false + * ``` + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isNegative() // true + * y = new BigNumber(2) + * y.isNegative() // false + * ``` + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is positive, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isPositive() // false + * y = new BigNumber(2) + * y.isPositive() // true + * ``` + */ + isPositive(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isZero() // true + * ``` + */ + isZero(): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.3 - 0.1 // 0.19999999999999998 + * x = new BigNumber(0.3) + * x.minus(0.1) // '0.2' + * x.minus(0.6, 20) // '0' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + minus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.modulo('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + modulo(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.mod(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + mod(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.multipliedBy(3) // '1.8' + * BigNumber('7e+500').multipliedBy(y) // '1.26e+501' + * x.multipliedBy('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + multipliedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.times(3) // '1.8' + * BigNumber('7e+500').times(y) // '1.26e+501' + * x.times('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + times(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.negated() // '1.3' + * ``` + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.1 + 0.2 // 0.30000000000000004 + * x = new BigNumber(0.1) + * y = x.plus(0.2) // '0.3' + * BigNumber(0.7).plus(x).plus(y) // '1.1' + * x.plus('0.1', 8) // '0.225' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + plus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, or `null` if the value + * of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of the value of this + * BigNumber are counted as significant digits, otherwise they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision() // 9 + * y = new BigNumber(987000) + * y.precision(false) // 3 + * y.precision(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + precision(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision(6) // '9876.54' + * x.precision(6, BigNumber.ROUND_UP) // '9876.55' + * x.precision(2) // '9900' + * x.precision(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + precision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, + * or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of + * the value of this BigNumber are counted as significant digits, otherwise + * they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd() // 9 + * y = new BigNumber(987000) + * y.sd(false) // 3 + * y.sd(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + sd(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd(6) // '9876.54' + * x.sd(6, BigNumber.ROUND_UP) // '9876.55' + * x.sd(2) // '9900' + * x.sd(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + sd(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted by `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative + * or to the right if `n` is positive. + * + * The return value is always exact and unrounded. + * + * Throws if `n` is invalid. + * + * ```ts + * x = new BigNumber(1.23) + * x.shiftedBy(3) // '1230' + * x.shiftedBy(-3) // '0.00123' + * ``` + * + * @param n The shift value, integer, -9007199254740991 to 9007199254740991. + */ + shiftedBy(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.squareRoot() // '4' + * y = new BigNumber(3) + * y.squareRoot() // '1.73205080756887729353' + * ``` + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.sqrt() // '4' + * y = new BigNumber(3) + * y.sqrt() // '1.73205080756887729353' + * ``` + */ + sqrt(): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using + * rounding mode `roundingMode` to `decimalPlaces` decimal places, i.e with one digit before the + * decimal point and `decimalPlaces` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the number of digits after the + * decimal point defaults to the minimum number of digits necessary to represent the value + * exactly. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toExponential(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toExponential(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`. + * + * If the value of this BigNumber in normal notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or + * equal to 10**21, this method will always return normal notation. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, the return value will be unrounded + * and in normal notation. This is also unlike `Number.prototype.toFixed`, which returns the value + * to zero decimal places. It is useful when normal notation is required and the current + * `EXPONENTIAL_AT` setting causes `toString` to return exponential notation. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFixed(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFixed(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`, and formatted + * according to the properties of the `format` or `FORMAT` object. + * + * The formatting object may contain some or all of the properties shown in the examples below. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, then the return value is not + * rounded to a fixed number of decimal places. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * If `format` is omitted or is `null` or `undefined`, `FORMAT` is used. + * + * Throws if `decimalPlaces`, `roundingMode`, or `format` is invalid. + * + * ```ts + * fmt = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * + * x = new BigNumber('123456789.123456789') + * + * // Set the global formatting options + * BigNumber.config({ FORMAT: fmt }) + * + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(3) // '123,456,789.123' + * + * // If a reference to the object assigned to FORMAT has been retained, + * // the format properties can be changed directly + * fmt.groupSeparator = ' ' + * fmt.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * // Alternatively, pass the formatting options as an argument + * fmt = { + * decimalSeparator: ',', + * groupSeparator: '.', + * groupSize: 3, + * secondaryGroupSize: 2 + * } + * + * x.toFormat() // '123 456 789.12345 6789' + * x.toFormat(fmt) // '12.34.56.789,123456789' + * x.toFormat(2, fmt) // '12.34.56.789,12' + * x.toFormat(3, BigNumber.ROUND_UP, fmt) // '12.34.56.789,124' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + * @param [format] Formatting options object. See `BigNumber.Format`. + */ + toFormat(decimalPlaces: number, roundingMode: BigNumber.RoundingMode, format?: BigNumber.Format): string; + toFormat(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFormat(decimalPlaces?: number): string; + toFormat(decimalPlaces: number, format: BigNumber.Format): string; + toFormat(format: BigNumber.Format): string; + + /** + * Returns an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to `max_denominator`. + * If a maximum denominator, `max_denominator`, is not specified, or is `null` or `undefined`, the + * denominator will be the lowest value necessary to represent the number exactly. + * + * Throws if `max_denominator` is invalid. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param [max_denominator] The maximum denominator, integer > 0, or Infinity. + */ + toFraction(max_denominator?: BigNumber.Value): [BigNumber, BigNumber]; + + /** As `valueOf`. */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript primitive number. + * + * Using the unary plus operator gives the same result. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / z.toNumber() // -Infinity + * 1 / +z // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a string representing the value of this BigNumber rounded to `significantDigits` + * significant digits using rounding mode `roundingMode`. + * + * If `significantDigits` is less than the number of digits necessary to represent the integer + * part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `significantDigits` is omitted, or is `null` or `undefined`, then the return value is the + * same as `n.toString()`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param [significantDigits] Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer 0 to 8. + */ + toPrecision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): string; + toPrecision(): string; + + /** + * Returns a string representing the value of this BigNumber in base `base`, or base 10 if `base` + * is omitted or is `null` or `undefined`. + * + * For bases above 10, and using the default base conversion alphabet (see `ALPHABET`), values + * from 10 to 35 are represented by a-z (the same as `Number.prototype.toString`). + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings, otherwise it is not. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or + * greater than the positive component of the current `EXPONENTIAL_AT` setting, or a negative + * exponent equal to or less than the negative component of the setting, then exponential notation + * is returned. + * + * If `base` is `null` or `undefined` it is ignored. + * + * Throws if `base` is invalid. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param [base] The base, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + toString(base?: number): string; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative + * zero. + * + * ``ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; + + /** Helps ES6 import. */ + private static readonly default?: BigNumber.Constructor; + + /** Helps ES6 import. */ + private static readonly BigNumber?: BigNumber.Constructor; + + /** Rounds away from zero. */ + static readonly ROUND_UP: 0; + + /** Rounds towards zero. */ + static readonly ROUND_DOWN: 1; + + /** Rounds towards Infinity. */ + static readonly ROUND_CEIL: 2; + + /** Rounds towards -Infinity. */ + static readonly ROUND_FLOOR: 3; + + /** Rounds towards nearest neighbour. If equidistant, rounds away from zero . */ + static readonly ROUND_HALF_UP: 4; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards zero. */ + static readonly ROUND_HALF_DOWN: 5; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. */ + static readonly ROUND_HALF_EVEN: 6; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards Infinity. */ + static readonly ROUND_HALF_CEIL: 7; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity. */ + static readonly ROUND_HALF_FLOOR: 8; + + /** See `MODULO_MODE`. */ + static readonly EUCLID: 9; + + /** + * To aid in debugging, if a `BigNumber.DEBUG` property is `true` then an error will be thrown + * if the BigNumber constructor receives an invalid `BigNumber.Value`, or if `BigNumber.isBigNumber` + * receives a BigNumber instance that is malformed. + * + * ```ts + * // No error, and BigNumber NaN is returned. + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * BigNumber.DEBUG = true + * new BigNumber('blurgh') // '[BigNumber Error] Not a number' + * new BigNumber(9, 2) // '[BigNumber Error] Not a base 2 number' + * ``` + * + * An error will also be thrown if a `BigNumber.Value` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on such numbers may not result + * in the intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * // No error, and the returned BigNumber does not have the same value as the number literal. + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * new BigNumber(823456789123456.3) + * // '[BigNumber Error] Number primitive has more than 15 significant digits' + * ``` + * + * Check that a BigNumber instance is well-formed: + * + * ```ts + * x = new BigNumber(10) + * + * BigNumber.DEBUG = false + * // Change x.c to an illegitimate value. + * x.c = NaN + * // No error, as BigNumber.DEBUG is false. + * BigNumber.isBigNumber(x) // true + * + * BigNumber.DEBUG = true + * BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber' + * ``` + */ + static DEBUG?: boolean; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `object`, or + * with the default configuration if object is `null` or `undefined`. + * + * Throws if `object` is not an object. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.clone() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + * + * @param [object] The configuration object. + */ + static clone(object?: BigNumber.Config): BigNumber.Constructor; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.config({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.config().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static config(object?: BigNumber.Config): BigNumber.Config; + + /** + * Returns `true` if `value` is a BigNumber instance, otherwise returns `false`. + * + * If `BigNumber.DEBUG` is `true`, throws if a BigNumber instance is not well-formed. + * + * ```ts + * x = 42 + * y = new BigNumber(x) + * + * BigNumber.isBigNumber(x) // false + * y instanceof BigNumber // true + * BigNumber.isBigNumber(y) // true + * + * BN = BigNumber.clone(); + * z = new BN(x) + * z instanceof BigNumber // false + * BigNumber.isBigNumber(z) // true + * ``` + * + * @param value The value to test. + */ + static isBigNumber(value: any): value is BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.maximum(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.maximum.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static maximum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static max(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.minimum.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static minimum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static min(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value will have `decimalPlaces` decimal places, or less if trailing zeros are + * produced. If `decimalPlaces` is omitted, the current `DECIMAL_PLACES` setting will be used. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the + * `crypto` object in the host environment, the random digits of the return value are generated by + * either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * To be able to set `CRYPTO` to true when using Node.js, the `crypto` object must be available + * globally: + * + * ```ts + * global.crypto = require('crypto') + * ``` + * + * If `CRYPTO` is true, i.e. one of the `crypto` methods is to be used, the value of a returned + * BigNumber should be cryptographically secure and statistically indistinguishable from a random + * value. + * + * Throws if `decimalPlaces` is invalid. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + */ + static random(decimalPlaces?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the sum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653' + * + * arr = [2, new BigNumber(14), '15.9999', 12] + * BigNumber.sum.apply(null, arr) // '43.9999' + * ``` + * + * @param n A numeric value. + */ + static sum(...n: BigNumber.Value[]): BigNumber; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.set({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.set().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static set(object?: BigNumber.Config): BigNumber.Config; +} + +export function BigNumber(n: BigNumber.Value, base?: number): BigNumber; diff --git a/test/merkletreejs/node_modules/bignumber.js/bignumber.js b/test/merkletreejs/node_modules/bignumber.js/bignumber.js new file mode 100644 index 0000000..007f064 --- /dev/null +++ b/test/merkletreejs/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2922 @@ +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); + + // Node.js and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); diff --git a/test/merkletreejs/node_modules/bignumber.js/bignumber.mjs b/test/merkletreejs/node_modules/bignumber.js/bignumber.mjs new file mode 100644 index 0000000..d5e02e9 --- /dev/null +++ b/test/merkletreejs/node_modules/bignumber.js/bignumber.mjs @@ -0,0 +1,2907 @@ +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +export var BigNumber = clone(); + +export default BigNumber; diff --git a/test/merkletreejs/node_modules/bignumber.js/doc/API.html b/test/merkletreejs/node_modules/bignumber.js/doc/API.html new file mode 100644 index 0000000..a16c034 --- /dev/null +++ b/test/merkletreejs/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2249 @@ + + + + + + +bignumber.js API + + + + + + +
+ +

bignumber.js

+ +

A JavaScript library for arbitrary-precision arithmetic.

+

Hosted on GitHub.

+ +

API

+ +

+ See the README on GitHub for a + quick-start introduction. +

+

+ In all examples below, var and semicolons are not shown, and if a commented-out + value is in quotes it means toString has been called on the preceding expression. +

+ + +

CONSTRUCTOR

+ + +
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See + ALPHABET to extend this range). +

+

+ Returns a new instance of a BigNumber object with value n, where n + is a numeric value in the specified base, or base 10 if + base is omitted or is null or undefined. +

+

+ Note that the BigNnumber constructor accepts an n of type number purely + as a convenience so that string quotes don't have to be typed when entering literal values, + and that it is the toString value of n that is used rather than its + underlying binary floating point value converted to decimal. +

+
+x = new BigNumber(123.4567)                // '123.4567'
+// 'new' is optional
+y = BigNumber(x)                           // '123.4567'
+

+ If n is a base 10 value it can be in normal or exponential notation. + Values in other bases must be in normal notation. Values in any base can have fraction digits, + i.e. digits after the decimal point. +

+
+new BigNumber(43210)                       // '43210'
+new BigNumber('4.321e+4')                  // '43210'
+new BigNumber('-735.0918e-430')            // '-7.350918e-428'
+new BigNumber('123412421.234324', 5)       // '607236.557696'
+

+ Signed 0, signed Infinity and NaN are supported. +

+
+new BigNumber('-Infinity')                 // '-Infinity'
+new BigNumber(NaN)                         // 'NaN'
+new BigNumber(-0)                          // '0'
+new BigNumber('.5')                        // '0.5'
+new BigNumber('+2')                        // '2'
+

+ String values in hexadecimal literal form, e.g. '0xff' or '0xFF' + (but not '0xfF'), are valid, as are string values with the octal and binary + prefixs '0o' and '0b'. String values in octal literal form without + the prefix will be interpreted as decimals, e.g. '011' is interpreted as 11, not 9. +

+
+new BigNumber(-10110100.1, 2)              // '-180.5'
+new BigNumber('-0b10110100.1')             // '-180.5'
+new BigNumber('ff.8', 16)                  // '255.5'
+new BigNumber('0xff.8')                    // '255.5'
+

+ If a base is specified, n is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. This includes base + 10 so don't include a base parameter for decimal values unless + this behaviour is wanted. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789)                  // '1.23456789'
+new BigNumber(1.23456789, 10)              // '1.23457'
+

An error is thrown if base is invalid. See Errors.

+

+ There is no limit to the number of digits of a value of type string (other than + that of JavaScript's maximum array size). See RANGE to set + the maximum and minimum possible exponent value of a BigNumber. +

+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+

BigNumber NaN is returned if n is invalid + (unless BigNumber.DEBUG is true, see below).

+
+new BigNumber('.1*')                       // 'NaN'
+new BigNumber('blurgh')                    // 'NaN'
+new BigNumber(9, 2)                        // 'NaN'
+

+ To aid in debugging, if BigNumber.DEBUG is true then an error will + be thrown on an invalid n. An error will also be thrown if n is of + type number and has more than 15 significant digits, as calling + toString or valueOf on + these numbers may not result in the intended value. +

+
+console.log(823456789123456.3)            //  823456789123456.2
+new BigNumber(823456789123456.3)          // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+

+ A BigNumber can also be created from an object literal. + Use isBigNumber to check that it is well-formed. +

+
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true })    // '777.123'
+ + + + +

Methods

+

The static methods of a BigNumber constructor.

+ + + + +
clone + .clone([object]) ⇒ BigNumber constructor +
+

object: object

+

+ Returns a new independent BigNumber constructor with configuration as described by + object (see config), or with the default + configuration if object is null or undefined. +

+

+ Throws if object is not an object. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3)                        // 0.33333
+y.div(3)                        // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+ + + +
configset([object]) ⇒ object
+

+ object: object: an object that contains some or all of the following + properties. +

+

Configures the settings for this particular BigNumber constructor.

+ +
+
DECIMAL_PLACES
+
+ number: integer, 0 to 1e+9 inclusive
+ Default value: 20 +
+
+ The maximum number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power operations + with negative exponents.
+
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 })    // equivalent
+
+ + + +
ROUNDING_MODE
+
+ number: integer, 0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP) +
+
+ The rounding mode used in the above operations and the default rounding mode of + decimalPlaces, + precision, + toExponential, + toFixed, + toFormat and + toPrecision. +
+
The modes are available as enumerated properties of the BigNumber constructor.
+
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP })    // equivalent
+
+ + + +
EXPONENTIAL_AT
+
+ number: integer, magnitude 0 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to 0 inclusive, integer + 0 to 1e+9 inclusive ]
+ Default value: [-7, 20] +
+
+ The exponent value(s) at which toString returns exponential notation. +
+
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use [-7, 20]. +
+
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3)         // '12.3'        e is only 1
+new BigNumber(123)          // '1.23e+2'
+new BigNumber(0.123)        // '0.123'       e is only -1
+new BigNumber(0.0123)       // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789)    // '123456789'   e is only 8
+new BigNumber(0.000000123)  // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+
+ Regardless of the value of EXPONENTIAL_AT, the toFixed method + will always return a value in normal notation and the toExponential method + will always return a value in exponential form. +
+
+ Calling toString with a base argument, e.g. toString(10), will + also always return normal notation. +
+ + + +
RANGE
+
+ number: integer, magnitude 1 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to -1 inclusive, integer + 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9] +
+
+ The exponent value(s) beyond which overflow to Infinity and underflow to + zero occurs. +
+
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become Infinity and those with a + negative exponent of greater magnitude become zero. +
+ If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and Infinity, use [-324, 308]. +
+
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE     // [ -500, 500 ]
+new BigNumber('9.999e499')   // '9.999e+499'
+new BigNumber('1e500')       // 'Infinity'
+new BigNumber('1e-499')      // '1e-499'
+new BigNumber('1e-500')      // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999)         // '99999'      e is only 4
+new BigNumber(100000)        // 'Infinity'   e is 5
+new BigNumber(0.001)         // '0.01'       e is only -3
+new BigNumber(0.0001)        // '0'          e is -4
+
+
+ The largest possible magnitude of a finite BigNumber is + 9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. +
+ + + +
CRYPTO
+
+ boolean: true or false.
+ Default value: false +
+
+ The value that determines whether cryptographically-secure pseudo-random number + generation is used. +
+
+ If CRYPTO is set to true then the + random method will generate random digits using + crypto.getRandomValues in browsers that support it, or + crypto.randomBytes if using Node.js. +
+
+ If neither function is supported by the host environment then attempting to set + CRYPTO to true will fail and an exception will be thrown. +
+
+ If CRYPTO is false then the source of randomness used will be + Math.random (which is assumed to generate at least 30 bits of + randomness). +
+
See random.
+
+
+// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+
+global.crypto = crypto;
+
+BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO       // true
+BigNumber.random()              // 0.54340758610486147524
+
+ + + +
MODULO_MODE
+
+ number: integer, 0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN) +
+
The modulo mode used when calculating the modulus: a mod n.
+
+ The quotient, q = a / n, is calculated according to the + ROUNDING_MODE that corresponds to the chosen + MODULO_MODE. +
+
The remainder, r, is calculated as: r = a - n * q.
+
+ The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. +
+
+ + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0 + The remainder is positive if the dividend is negative, otherwise it is negative. +
ROUND_DOWN1 + The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator %. +
ROUND_FLOOR3 + The remainder has the same sign as the divisor.
+ This matches Python's % operator. +
ROUND_HALF_EVEN6The IEEE 754 remainder function.
EUCLID9 + The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n)) +
+
+
+ The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. +
+
See modulo.
+
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 })          // equivalent
+
+ + + +
POW_PRECISION
+
+ number: integer, 0 to 1e+9 inclusive.
+ Default value: 0 +
+
+ The maximum precision, i.e. number of significant digits, of the result of the power + operation (unless a modulus is specified). +
+
If set to 0, the number of significant digits will not be limited.
+
See exponentiatedBy.
+
BigNumber.config({ POW_PRECISION: 100 })
+ + + +
FORMAT
+
object
+
+ The FORMAT object configures the format of the string returned by the + toFormat method. +
+
+ The example below shows the properties of the FORMAT object that are + recognised, and their default values. +
+
+ Unlike the other configuration properties, the values of the properties of the + FORMAT object will not be checked for validity. The existing + FORMAT object will simply be replaced by the object that is passed in. + The object can include any number of the properties shown below. +
+
See toFormat for examples of usage.
+
+
+BigNumber.config({
+  FORMAT: {
+    // string to prepend
+    prefix: '',
+    // decimal separator
+    decimalSeparator: '.',
+    // grouping separator of the integer part
+    groupSeparator: ',',
+    // primary grouping size of the integer part
+    groupSize: 3,
+    // secondary grouping size of the integer part
+    secondaryGroupSize: 0,
+    // grouping separator of the fraction part
+    fractionGroupSeparator: ' ',
+    // grouping size of the fraction part
+    fractionGroupSize: 0,
+    // string to append
+    suffix: ''
+  }
+});
+
+ + + +
ALPHABET
+
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz' +
+
+ The alphabet used for base conversion. The length of the alphabet corresponds to the + maximum value of the base argument that can be passed to the + BigNumber constructor or + toString. +
+
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and + it must not contain whitespace or a repeated character, or the sign indicators + '+' and '-', or the decimal separator '.'. +
+
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString()                // '10'
+x.toString(12)              // 'T'
+
+ + + +
+

+

Returns an object with the above properties and their current values.

+

+ Throws if object is not an object, or if an invalid value is assigned to + one or more of the above properties. See Errors. +

+
+BigNumber.config({
+  DECIMAL_PLACES: 40,
+  ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+  EXPONENTIAL_AT: [-10, 20],
+  RANGE: [-500, 500],
+  CRYPTO: true,
+  MODULO_MODE: BigNumber.ROUND_FLOOR,
+  POW_PRECISION: 80,
+  FORMAT: {
+    groupSize: 3,
+    groupSeparator: ' ',
+    decimalSeparator: ','
+  },
+  ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES        // 40
+obj.RANGE                 // [-500, 500]
+ + + +
+ isBigNumber.isBigNumber(value) ⇒ boolean +
+

value: any

+

+ Returns true if value is a BigNumber instance, otherwise returns + false. +

+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x)             // false
+y instanceof BigNumber               // true
+BigNumber.isBigNumber(y)             // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber               // false
+BigNumber.isBigNumber(z)             // true
+

+ If value is a BigNumber instance and BigNumber.DEBUG is true, + then this method will also check if value is well-formed, and throw if it is not. + See Errors. +

+

+ The check can be useful if creating a BigNumber from an object literal. + See BigNumber. +

+
+x = new BigNumber(10)
+
+// Change x.c to an illegitimate value.
+x.c = NaN
+
+BigNumber.DEBUG = false
+
+// No error.
+BigNumber.isBigNumber(x)    // true
+
+BigNumber.DEBUG = true
+
+// Error.
+BigNumber.isBigNumber(x)    // '[BigNumber Error] Invalid BigNumber'
+ + + +
maximum.max(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the maximum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9')      // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max.apply(null, arr)                // '14'
+ + + +
minimum.min(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the minimum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9')      // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min.apply(null, arr)                // '-15.9999'
+ + + +
+ random.random([dp]) ⇒ BigNumber +
+

dp: number: integer, 0 to 1e+9 inclusive

+

+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and + less than 1. +

+

+ The return value will have dp decimal places (or less if trailing zeros are + produced).
+ If dp is omitted then the number of decimal places will default to the current + DECIMAL_PLACES setting. +

+

+ Depending on the value of this BigNumber constructor's + CRYPTO setting and the support for the + crypto object in the host environment, the random digits of the return value are + generated by either Math.random (fastest), crypto.getRandomValues + (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js). +

+

+ To be able to set CRYPTO to true when using + Node.js, the crypto object must be available globally: +

+
// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+global.crypto = crypto;
+

+ If CRYPTO is true, i.e. one of the + crypto methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. +

+

+ Throws if dp is invalid. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random()              // '0.4117936847'
+BigNumber.random(20)            // '0.78193327636914089009'
+ + + +
sum.sum(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the sum of the arguments.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.sum(4e9, x, '123456789.9')      // '7381326134.9378653'
+
+arr = [2, new BigNumber(14), '15.9999', 12]
+BigNumber.sum.apply(null, arr)            // '43.9999'
+ + + +

Properties

+

+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.) +

+

+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's + BigDecimal class. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0Rounds away from zero
ROUND_DOWN1Rounds towards zero
ROUND_CEIL2Rounds towards Infinity
ROUND_FLOOR3Rounds towards -Infinity
ROUND_HALF_UP4 + Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero +
ROUND_HALF_DOWN5 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero +
ROUND_HALF_EVEN6 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour +
ROUND_HALF_CEIL7 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity +
ROUND_HALF_FLOOR8 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity +
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 })     // equivalent
+ +
DEBUG
+

undefined|false|true

+

+ If BigNumber.DEBUG is set true then an error will be thrown + if this BigNumber constructor receives an invalid value, such as + a value of type number with more than 15 significant digits. + See BigNumber. +

+

+ An error will also be thrown if the isBigNumber + method receives a BigNumber that is not well-formed. + See isBigNumber. +

+
BigNumber.DEBUG = true
+ + +

INSTANCE

+ + +

Methods

+

The methods inherited by a BigNumber instance from its constructor's prototype object.

+

A BigNumber is immutable in the sense that it is not changed by its methods.

+

+ The treatment of ±0, ±Infinity and NaN is + consistent with how JavaScript treats these values. +

+

Many method names have a shorter alias.

+ + + +
absoluteValue.abs() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. +

+

The return value is always exact and unrounded.

+
+x = new BigNumber(-0.8)
+y = x.absoluteValue()           // '0.8'
+z = y.abs()                     // '0.8'
+ + + +
+ comparedTo.comparedTo(n [, base]) ⇒ number +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+ + + + + + + + + + + + + + + + + + +
Returns 
1If the value of this BigNumber is greater than the value of n
-1If the value of this BigNumber is less than the value of n
0If this BigNumber and n have the same value
nullIf the value of either this BigNumber or n is NaN
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y)                 // 1
+x.comparedTo(x.minus(1))        // 0
+y.comparedTo(NaN)               // null
+y.comparedTo('110', 2)          // -1
+ + + +
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber + rounded by rounding mode rm to a maximum of dp decimal places. +

+

+ If dp is omitted, or is null or undefined, the return + value is the number of decimal places of the value of this BigNumber, or null if + the value of this BigNumber is ±Infinity or NaN. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1)                     // '1234.6'
+x.dp()                                 // 2
+x.decimalPlaces(2)                     // '1234.56'
+x.dp(10)                               // '1234.56'
+x.decimalPlaces(0, 1)                  // '1234'
+x.dp(0, 6)                             // '1235'
+x.decimalPlaces(1, 1)                  // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN)     // '1234.6'
+x                                      // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp()                                 // 102
+ + + +
dividedBy.div(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber divided by + n, rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y)                  // '3.14159292035398230088'
+x.div(5)                        // '71'
+x.div(47, 16)                   // '5'
+ + + +
+ dividedToIntegerBy.idiv(n [, base]) ⇒ + BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + n. +

+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y)         // '1'
+x.idiv(0.7)                     // '7'
+x.idiv('0.f', 16)               // '5'
+ + + +
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber +
+

+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber +

+

+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by + n, i.e. raised to the power n, and optionally modulo a modulus + m. +

+

+ Throws if n is not an integer. See Errors. +

+

+ If n is negative the result is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.45610000 has over 50000 digits, the number of significant + digits calculated is limited to the value of the + POW_PRECISION setting (unless a modulus + m is specified). +

+

+ By default POW_PRECISION is set to 0. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. +

+

+ If m is specified and the value of m, n and this + BigNumber are integers, and n is positive, then a fast modular exponentiation + algorithm is used, otherwise the operation will be performed as + x.exponentiatedBy(n).modulo(m) with a + POW_PRECISION of 0. +

+
+Math.pow(0.7, 2)                // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2)            // '0.49'
+BigNumber(3).pow(-2)            // '0.11111111111111111111'
+ + + +
+ integerValue.integerValue([rm]) ⇒ BigNumber +
+

+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + rounding mode rm. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if rm is invalid. See Errors. +

+
+x = new BigNumber(123.456)
+x.integerValue()                        // '123'
+x.integerValue(BigNumber.ROUND_CEIL)    // '124'
+y = new BigNumber(-12.7)
+y.integerValue()                        // '-13'
+y.integerValue(BigNumber.ROUND_DOWN)    // '-12'
+

+ The following is an example of how to add a prototype method that emulates JavaScript's + Math.round function. Math.ceil, Math.floor and + Math.trunc can be emulated in the same way with + BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and + BigNumber.ROUND_DOWN respectively. +

+
+BigNumber.prototype.round = function () {
+  return this.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round()                               // '123'
+ + + +
isEqualTo.eq(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is equal to the value of + n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN. +

+

Note: This method uses the comparedTo method internally.

+
+0 === 1e-324                    // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324')           // false
+BigNumber(-0).eq(x)             // true  ( -0 === 0 )
+BigNumber(255).eq('ff', 16)     // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN)                // false
+ + + +
isFinite.isFinite() ⇒ boolean
+

+ Returns true if the value of this BigNumber is a finite number, otherwise + returns false. +

+

+ The only possible non-finite values of a BigNumber are NaN, Infinity + and -Infinity. +

+
+x = new BigNumber(1)
+x.isFinite()                    // true
+y = new BigNumber(Infinity)
+y.isFinite()                    // false
+

+ Note: The native method isFinite() can be used if + n <= Number.MAX_VALUE. +

+ + + +
isGreaterThan.gt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 > (0.3 - 0.2)                             // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2))    // false
+BigNumber(0).gt(x)                            // false
+BigNumber(11, 3).gt(11.1, 2)                  // true
+ + + +
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than or equal to the value + of n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) >= 0.1                     // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1)          // true
+BigNumber(1).gte(x)                    // true
+BigNumber(10, 18).gte('i', 36)         // true
+ + + +
isInteger.isInteger() ⇒ boolean
+

+ Returns true if the value of this BigNumber is an integer, otherwise returns + false. +

+
+x = new BigNumber(1)
+x.isInteger()                   // true
+y = new BigNumber(123.456)
+y.isInteger()                   // false
+ + + +
isLessThan.lt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) < 0.1                       // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1)                       // false
+BigNumber(0).lt(x)                      // true
+BigNumber(11.1, 2).lt(11, 3)            // true
+ + + +
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than or equal to the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 <= (0.3 - 0.2)                                // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2))  // true
+BigNumber(-1).lte(x)                              // true
+BigNumber(10, 18).lte('i', 36)                    // true
+ + + +
isNaN.isNaN() ⇒ boolean
+

+ Returns true if the value of this BigNumber is NaN, otherwise + returns false. +

+
+x = new BigNumber(NaN)
+x.isNaN()                       // true
+y = new BigNumber('Infinity')
+y.isNaN()                       // false
+

Note: The native method isNaN() can also be used.

+ + + +
isNegative.isNegative() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is negative, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isNegative()                  // true
+y = new BigNumber(2)
+y.isNegative()                  // false
+

Note: n < 0 can be used if n <= -Number.MIN_VALUE.

+ + + +
isPositive.isPositive() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is positive, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isPositive()                  // false
+y = new BigNumber(2)
+y.isPositive()                  // true
+ + + +
isZero.isZero() ⇒ boolean
+

+ Returns true if the value of this BigNumber is zero or minus zero, otherwise + returns false. +

+
+x = new BigNumber(-0)
+x.isZero() && x.isNegative()         // true
+y = new BigNumber(Infinity)
+y.isZero()                      // false
+

Note: n == 0 can be used if n >= Number.MIN_VALUE.

+ + + +
+ minus.minus(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber minus n.

+

The return value is always exact and unrounded.

+
+0.3 - 0.1                       // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1)                    // '0.2'
+x.minus(0.6, 20)                // '0'
+ + + +
modulo.mod(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. + the integer remainder of dividing this BigNumber by n. +

+

+ The value returned, and in particular its sign, is dependent on the value of the + MODULO_MODE setting of this BigNumber constructor. + If it is 1 (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's % operator (within the limits of double + precision) and BigDecimal's remainder method. +

+

The return value is always exact and unrounded.

+

+ See MODULO_MODE for a description of the other + modulo modes. +

+
+1 % 0.9                         // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9)                   // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33)                  // '3'
+ + + +
+ multipliedBy.times(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n. +

+

The return value is always exact and unrounded.

+
+0.6 * 3                         // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3)           // '1.8'
+BigNumber('7e+500').times(y)    // '1.26e+501'
+x.multipliedBy('-a', 16)        // '-6'
+ + + +
negated.negated() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + -1. +

+
+x = new BigNumber(1.8)
+x.negated()                     // '-1.8'
+y = new BigNumber(-1.3)
+y.negated()                     // '1.3'
+ + + +
plus.plus(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber plus n.

+

The return value is always exact and unrounded.

+
+0.1 + 0.2                       // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2)                 // '0.3'
+BigNumber(0.7).plus(x).plus(y)  // '1.1'
+x.plus('0.1', 8)                // '0.225'
+ + + +
+ precision.sd([d [, rm]]) ⇒ BigNumber|number +
+

+ d: number|boolean: integer, 1 to 1e+9 + inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive. +

+

+ If d is a number, returns a BigNumber whose value is the value of this BigNumber + rounded to a precision of d significant digits using rounding mode + rm. +

+

+ If d is omitted or is null or undefined, the return + value is the number of significant digits of the value of this BigNumber, or null + if the value of this BigNumber is ±Infinity or NaN. +

+

+ If d is true then any trailing zeros of the integer + part of a number are counted as significant digits, otherwise they are not. +

+

+ If rm is omitted or is null or undefined, + ROUNDING_MODE will be used. +

+

+ Throws if d or rm is invalid. See Errors. +

+
+x = new BigNumber(9876.54321)
+x.precision(6)                         // '9876.54'
+x.sd()                                 // 9
+x.precision(6, BigNumber.ROUND_UP)     // '9876.55'
+x.sd(2)                                // '9900'
+x.precision(2, 1)                      // '9800'
+x                                      // '9876.54321'
+y = new BigNumber(987000)
+y.precision()                          // 3
+y.sd(true)                             // 6
+ + + +
shiftedBy.shiftedBy(n) ⇒ BigNumber
+

+ n: number: integer, + -9007199254740991 to 9007199254740991 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber shifted by n + places. +

+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n + is negative or to the right if n is positive. +

+

The return value is always exact and unrounded.

+

+ Throws if n is invalid. See Errors. +

+
+x = new BigNumber(1.23)
+x.shiftedBy(3)                      // '1230'
+x.shiftedBy(-3)                     // '0.00123'
+ + + +
squareRoot.sqrt() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. +

+
+x = new BigNumber(16)
+x.squareRoot()                  // '4'
+y = new BigNumber(3)
+y.sqrt()                        // '1.73205080756887729353'
+ + + +
+ toExponential.toExponential([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode rm to dp decimal places, i.e with one digit + before the decimal point and dp digits after it. +

+

+ If the value of this BigNumber in exponential notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ If dp is omitted, or is null or undefined, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential()               // '4.56e+1'
+y.toExponential()               // '4.56e+1'
+x.toExponential(0)              // '5e+1'
+y.toExponential(0)              // '5e+1'
+x.toExponential(1)              // '4.6e+1'
+y.toExponential(1)              // '4.6e+1'
+y.toExponential(1, 1)           // '4.5e+1'  (ROUND_DOWN)
+x.toExponential(3)              // '4.560e+1'
+y.toExponential(3)              // '4.560e+1'
+ + + +
+ toFixed.toFixed([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm. +

+

+ If the value of this BigNumber in normal notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ Unlike Number.prototype.toFixed, which returns exponential notation if a number + is greater or equal to 1021, this method will always return normal + notation. +

+

+ If dp is omitted or is null or undefined, the return + value will be unrounded and in normal notation. This is also unlike + Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current + EXPONENTIAL_AT setting causes + toString to return exponential notation.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed()                     // '3'
+y.toFixed()                     // '3.456'
+y.toFixed(0)                    // '3'
+x.toFixed(2)                    // '3.46'
+y.toFixed(2)                    // '3.46'
+y.toFixed(2, 1)                 // '3.45'  (ROUND_DOWN)
+x.toFixed(5)                    // '3.45600'
+y.toFixed(5)                    // '3.45600'
+ + + +
+ toFormat.toFormat([dp [, rm[, format]]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+ format: object: see FORMAT +

+

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm, and formatted + according to the properties of the format object. +

+

+ See FORMAT and the examples below for the properties of the + format object, their types, and their usage. A formatting object may contain + some or all of the recognised properties. +

+

+ If dp is omitted or is null or undefined, then the + return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used.
+ If format is omitted or is null or undefined, the + FORMAT object is used. +

+

+ Throws if dp, rm or format is invalid. See + Errors. +

+
+fmt = {
+  prefix: '',
+  decimalSeparator: '.',
+  groupSeparator: ',',
+  groupSize: 3,
+  secondaryGroupSize: 0,
+  fractionGroupSeparator: ' ',
+  fractionGroupSize: 0,
+  suffix: ''
+}
+
+x = new BigNumber('123456789.123456789')
+
+// Set the global formatting options
+BigNumber.config({ FORMAT: fmt })
+
+x.toFormat()                              // '123,456,789.123456789'
+x.toFormat(3)                             // '123,456,789.123'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+fmt.groupSeparator = ' '
+fmt.fractionGroupSize = 5
+x.toFormat()                              // '123 456 789.12345 6789'
+
+// Alternatively, pass the formatting options as an argument
+fmt = {
+  prefix: '=> ',
+  decimalSeparator: ',',
+  groupSeparator: '.',
+  groupSize: 3,
+  secondaryGroupSize: 2
+}
+
+x.toFormat()                              // '123 456 789.12345 6789'
+x.toFormat(fmt)                           // '=> 12.34.56.789,123456789'
+x.toFormat(2, fmt)                        // '=> 12.34.56.789,12'
+x.toFormat(3, BigNumber.ROUND_UP, fmt)    // '=> 12.34.56.789,124'
+ + + +
+ toFraction.toFraction([maximum_denominator]) + ⇒ [BigNumber, BigNumber] +
+

+ maximum_denominator: + number|string|BigNumber: integer >= 1 and <= + Infinity +

+

+ Returns an array of two BigNumbers representing the value of this BigNumber as a simple + fraction with an integer numerator and an integer denominator. The denominator will be a + positive non-zero value less than or equal to maximum_denominator. +

+

+ If a maximum_denominator is not specified, or is null or + undefined, the denominator will be the lowest value necessary to represent the + number exactly. +

+

+ Throws if maximum_denominator is invalid. See Errors. +

+
+x = new BigNumber(1.75)
+x.toFraction()                  // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction()                 // '157079632679,50000000000'
+pi.toFraction(100000)           // '312689, 99532'
+pi.toFraction(10000)            // '355, 113'
+pi.toFraction(100)              // '311, 99'
+pi.toFraction(10)               // '22, 7'
+pi.toFraction(1)                // '3, 1'
+ + + +
toJSON.toJSON() ⇒ string
+

As valueOf.

+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+    return key === '' ? val : new BigNumber(val)
+})
+ + + +
toNumber.toNumber() ⇒ number
+

Returns the value of this BigNumber as a JavaScript number primitive.

+

+ This method is identical to using type coercion with the unary plus operator. +

+
+x = new BigNumber(456.789)
+x.toNumber()                    // 456.789
++x                              // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber()                    // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber()                // -Infinity
+1 / +z                          // -Infinity
+ + + +
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string +
+

+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber rounded to sd + significant digits using rounding mode rm. +

+

+ If sd is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. +

+

+ If sd is omitted, or is null or undefined, then the + return value is the same as n.toString().
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if sd or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision()                 // '45.6'
+y.toPrecision()                 // '45.6'
+x.toPrecision(1)                // '5e+1'
+y.toPrecision(1)                // '5e+1'
+y.toPrecision(2, 0)             // '4.6e+1'  (ROUND_UP)
+y.toPrecision(2, 1)             // '4.5e+1'  (ROUND_DOWN)
+x.toPrecision(5)                // '45.600'
+y.toPrecision(5)                // '45.600'
+ + + +
toString.toString([base]) ⇒ string
+

+ base: number: integer, 2 to ALPHABET.length + inclusive (see ALPHABET). +

+

+ Returns a string representing the value of this BigNumber in the specified base, or base + 10 if base is omitted or is null or + undefined. +

+

+ For bases above 10, and using the default base conversion alphabet + (see ALPHABET), values from 10 to + 35 are represented by a-z + (as with Number.prototype.toString). +

+

+ If a base is specified the value is rounded according to the current + DECIMAL_PLACES + and ROUNDING_MODE settings. +

+

+ If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current EXPONENTIAL_AT setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. +

+

If base is null or undefined it is ignored.

+

+ Throws if base is invalid. See Errors. +

+
+x = new BigNumber(750000)
+x.toString()                    // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString()                    // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2)                   // '101101010.111'
+y.toString(9)                   // '442.77777777777777777778'
+y.toString(32)                  // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString()                    // '1.23456789'
+z.toString(10)                  // '1.2346'
+ + + +
valueOf.valueOf() ⇒ string
+

+ As toString, but does not accept a base argument and includes + the minus sign for negative zero. +

+
+x = new BigNumber('-0')
+x.toString()                    // '0'
+x.valueOf()                     // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf()                     // '1.777e+457'
+ + + +

Properties

+

The properties of a BigNumber instance:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionTypeValue
ccoefficient*number[] Array of base 1e14 numbers
eexponentnumberInteger, -1000000000 to 1000000000 inclusive
ssignnumber-1 or 1
+

*significand

+

+ The value of any of the c, e and s properties may also + be null. +

+

+ The above properties are best considered to be read-only. In early versions of this library it + was okay to change the exponent of a BigNumber by writing to its exponent property directly, + but this is no longer reliable as the value of the first element of the coefficient array is + now dependent on the exponent. +

+

+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. +

+
x = new BigNumber(0.123)              // '0.123'
+x.toExponential()                     // '1.23e-1'
+x.c                                   // '1,2,3'
+x.e                                   // -1
+x.s                                   // 1
+
+y = new Number(-123.4567000e+2)       // '-12345.67'
+y.toExponential()                     // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2')  // '-12345.67'
+z.toExponential()                     // '-1.234567e+4'
+z.c                                   // '1,2,3,4,5,6,7'
+z.e                                   // 4
+z.s                                   // -1
+ + + +

Zero, NaN and Infinity

+

+ The table below shows how ±0, NaN and + ±Infinity are stored. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ces
±0[0]0±1
NaNnullnullnull
±Infinitynullnull±1
+
+x = new Number(-0)              // 0
+1 / x == -Infinity              // true
+
+y = new BigNumber(-0)           // '0'
+y.c                             // '0' ( [0].toString() )
+y.e                             // 0
+y.s                             // -1
+ + + +

Errors

+

The table below shows the errors that are thrown.

+

+ The errors are generic Error objects whose message begins + '[BigNumber Error]'. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThrows
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy +
Base not a primitive number
Base not an integer
Base out of range
Number primitive has more than 15 significant digits*
Not a base... number*
Not a number*
cloneObject expected
configObject expected
DECIMAL_PLACES not a primitive number
DECIMAL_PLACES not an integer
DECIMAL_PLACES out of range
ROUNDING_MODE not a primitive number
ROUNDING_MODE not an integer
ROUNDING_MODE out of range
EXPONENTIAL_AT not a primitive number
EXPONENTIAL_AT not an integer
EXPONENTIAL_AT out of range
RANGE not a primitive number
RANGE not an integer
RANGE cannot be zero
RANGE cannot be zero
CRYPTO not true or false
crypto unavailable
MODULO_MODE not a primitive number
MODULO_MODE not an integer
MODULO_MODE out of range
POW_PRECISION not a primitive number
POW_PRECISION not an integer
POW_PRECISION out of range
FORMAT not an object
ALPHABET invalid
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision +
Argument not a primitive number
Argument not an integer
Argument out of range
+ decimalPlaces
+ precision +
Argument not true or false
exponentiatedByArgument not an integer
isBigNumberInvalid BigNumber*
+ minimum
+ maximum +
Not a number*
+ random + crypto unavailable
+ toFormat + Argument not an object
toFractionArgument not an integer
Argument out of range
toStringBase not a primitive number
Base not an integer
Base out of range
+

*Only thrown if BigNumber.DEBUG is true.

+

To determine if an exception is a BigNumber Error:

+
+try {
+  // ...
+} catch (e) {
+  if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+      // ...
+  }
+}
+ + + +

Type coercion

+

+ To prevent the accidental use of a BigNumber in primitive number operations, or the + accidental addition of a BigNumber to a string, the valueOf method can be safely + overwritten as shown below. +

+

+ The valueOf method is the same as the + toJSON method, and both are the same as the + toString method except they do not take a base + argument and they include the minus sign for negative zero. +

+
+BigNumber.prototype.valueOf = function () {
+  throw Error('valueOf called!')
+}
+
+x = new BigNumber(1)
+x / 2                    // '[BigNumber Error] valueOf called!'
+x + 'abc'                // '[BigNumber Error] valueOf called!'
+
+ + + +

FAQ

+ +
Why are trailing fractional zeros removed from BigNumbers?
+

+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. +

+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y)                      // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y)                 // 4.1400000
+

+ To specify the precision of a value is to specify that the value lies + within a certain range. +

+

+ In the first example, x has a value of 1.0. The trailing zero shows + the precision of the value, implying that it is in the range 0.95 to + 1.05. Similarly, the precision indicated by the trailing zeros of y + indicates that the value is in the range 1.09995 to 1.10005. +

+

+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, + and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the + range of the result of the addition implied by the precision of its operands is + 2.04995 to 2.15005. +

+

+ The result given by BigDecimal of 2.1000 however, indicates that the value is in + the range 2.09995 to 2.10005 and therefore the precision implied by + its trailing zeros may be misleading. +

+

+ In the second example, the true range is 4.122744 to 4.157256 yet + the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 + to 4.14000005. Again, the precision implied by the trailing zeros may be + misleading. +

+

+ This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the toExponential, toFixed and + toPrecision methods enable trailing zeros to be added if and when required.
+

+
+ + + diff --git a/test/merkletreejs/node_modules/bignumber.js/package.json b/test/merkletreejs/node_modules/bignumber.js/package.json new file mode 100644 index 0000000..71fc0d1 --- /dev/null +++ b/test/merkletreejs/node_modules/bignumber.js/package.json @@ -0,0 +1,50 @@ +{ + "name": "bignumber.js", + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "version": "9.1.2", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "repository": { + "type": "git", + "url": "https://github.com/MikeMcl/bignumber.js.git" + }, + "main": "bignumber", + "module": "bignumber.mjs", + "browser": "bignumber.js", + "types": "bignumber.d.ts", + "exports": { + ".": { + "types": "./bignumber.d.ts", + "require": "./bignumber.js", + "import": "./bignumber.mjs", + "browser": "./bignumber.js" + }, + "./bignumber.mjs": "./bignumber.mjs", + "./bignumber.js": "./bignumber.js", + "./package.json": "./package.json" + }, + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "engines": { + "node": "*" + }, + "license": "MIT", + "scripts": { + "test": "node test/test" + }, + "dependencies": {} +} diff --git a/test/merkletreejs/node_modules/bn.js/.npmignore b/test/merkletreejs/node_modules/bn.js/.npmignore new file mode 100644 index 0000000..6d1eebb --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/.npmignore @@ -0,0 +1,6 @@ +benchmarks/ +coverage/ +node_modules/ +npm-debug.log +1.js +logo.png diff --git a/test/merkletreejs/node_modules/bn.js/.travis.yml b/test/merkletreejs/node_modules/bn.js/.travis.yml new file mode 100644 index 0000000..936b7b7 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "5" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "4" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/test/merkletreejs/node_modules/bn.js/README.md b/test/merkletreejs/node_modules/bn.js/README.md new file mode 100644 index 0000000..fee65ba --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/README.md @@ -0,0 +1,219 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way the work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +The only available postfix at the moment is: + +* `n` - which means that the argument of the function must be a plain JavaScript + number + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available) +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b)` - set specified bit to `1` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this tricks one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +## LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2015. + +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. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/test/merkletreejs/node_modules/bn.js/lib/bn.js b/test/merkletreejs/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000..29a4c51 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3427 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/test/merkletreejs/node_modules/bn.js/package.json b/test/merkletreejs/node_modules/bn.js/package.json new file mode 100644 index 0000000..8835213 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/package.json @@ -0,0 +1,33 @@ +{ + "name": "bn.js", + "version": "4.11.6", + "description": "Big number implementation in pure javascript", + "main": "lib/bn.js", + "scripts": { + "lint": "semistandard", + "unit": "mocha --reporter=spec test/*-test.js", + "test": "npm run lint && npm run unit" + }, + "repository": { + "type": "git", + "url": "git@github.com:indutny/bn.js" + }, + "keywords": [ + "BN", + "BigNum", + "Big number", + "Modulo", + "Montgomery" + ], + "author": "Fedor Indutny ", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "homepage": "https://github.com/indutny/bn.js", + "devDependencies": { + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "semistandard": "^7.0.4" + } +} diff --git a/test/merkletreejs/node_modules/bn.js/test/arithmetic-test.js b/test/merkletreejs/node_modules/bn.js/test/arithmetic-test.js new file mode 100644 index 0000000..c3a0d7d --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/arithmetic-test.js @@ -0,0 +1,635 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; +var fixtures = require('./fixtures'); + +describe('BN.js/Arithmetic', function () { + describe('.add()', function () { + it('should add numbers', function () { + assert.equal(new BN(14).add(new BN(26)).toString(16), '28'); + var k = new BN(0x1234); + var r = k; + + for (var i = 0; i < 257; i++) { + r = r.add(k); + } + + assert.equal(r.toString(16), '125868'); + }); + + it('should handle carry properly (in-place)', function () { + var k = new BN('abcdefabcdefabcdef', 16); + var r = new BN('deadbeef', 16); + + for (var i = 0; i < 257; i++) { + r.iadd(k); + } + + assert.equal(r.toString(16), 'ac79bd9b79be7a277bde'); + }); + + it('should properly do positive + negative', function () { + var a = new BN('abcd', 16); + var b = new BN('-abce', 16); + + assert.equal(a.iadd(b).toString(16), '-1'); + + a = new BN('abcd', 16); + b = new BN('-abce', 16); + + assert.equal(a.add(b).toString(16), '-1'); + assert.equal(b.add(a).toString(16), '-1'); + }); + }); + + describe('.iaddn()', function () { + it('should allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should add negative number', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(-200); + + assert.equal(a.toString(), '-300'); + }); + + it('should allow neg + pos with big number', function () { + var a = new BN('-1000000000', 10); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.toString(), '-999999800'); + }); + + it('should carry limb', function () { + var a = new BN('3ffffff', 16); + + assert.equal(a.iaddn(1).toString(16), '4000000'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).iaddn(0x4000000); + }, /^Error: Assertion failed$/); + }); + }); + + describe('.sub()', function () { + it('should subtract small numbers', function () { + assert.equal(new BN(26).sub(new BN(14)).toString(16), 'c'); + assert.equal(new BN(14).sub(new BN(26)).toString(16), '-c'); + assert.equal(new BN(26).sub(new BN(26)).toString(16), '0'); + assert.equal(new BN(-26).sub(new BN(26)).toString(16), '-34'); + }); + + var a = new BN( + '31ff3c61db2db84b9823d320907a573f6ad37c437abe458b1802cda041d6384' + + 'a7d8daef41395491e2', + 16); + var b = new BN( + '6f0e4d9f1d6071c183677f601af9305721c91d31b0bbbae8fb790000', + 16); + var r = new BN( + '31ff3c61db2db84b9823d3208989726578fd75276287cd9516533a9acfb9a67' + + '76281f34583ddb91e2', + 16); + + it('should subtract big numbers', function () { + assert.equal(a.sub(b).cmp(r), 0); + }); + + it('should subtract numbers in place', function () { + assert.equal(b.clone().isub(a).neg().cmp(r), 0); + }); + + it('should subtract with carry', function () { + // Carry and copy + var a = new BN('12345', 16); + var b = new BN('1000000000000', 16); + assert.equal(a.isub(b).toString(16), '-fffffffedcbb'); + + a = new BN('12345', 16); + b = new BN('1000000000000', 16); + assert.equal(b.isub(a).toString(16), 'fffffffedcbb'); + }); + }); + + describe('.isubn()', function () { + it('should subtract negative number', function () { + var r = new BN( + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b', 16); + assert.equal(r.isubn(-1).toString(16), + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681c'); + }); + + it('should work for positive numbers', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(200); + assert.equal(a.negative, 1); + assert.equal(a.toString(), '-300'); + }); + + it('should not allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(-200); + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should change sign on small numbers at 0', function () { + var a = new BN(0).subn(2); + assert.equal(a.toString(), '-2'); + }); + + it('should change sign on small numbers at 1', function () { + var a = new BN(1).subn(2); + assert.equal(a.toString(), '-1'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).isubn(0x4000000); + }, /^Error: Assertion failed$/); + }); + }); + + function testMethod (name, mul) { + describe(name, function () { + it('should multiply numbers of different signs', function () { + var offsets = [ + 1, // smallMulTo + 250, // comb10MulTo + 1000, // bigMulTo + 15000 // jumboMulTo + ]; + + for (var i = 0; i < offsets.length; ++i) { + var x = new BN(1).ishln(offsets[i]); + + assert.equal(mul(x, x).isNeg(), false); + assert.equal(mul(x, x.neg()).isNeg(), true); + assert.equal(mul(x.neg(), x).isNeg(), true); + assert.equal(mul(x.neg(), x.neg()).isNeg(), false); + } + }); + + it('should multiply with carry', function () { + var n = new BN(0x1001); + var r = n; + + for (var i = 0; i < 4; i++) { + r = mul(r, n); + } + + assert.equal(r.toString(16), '100500a00a005001'); + }); + + it('should correctly multiply big numbers', function () { + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal( + mul(n, n).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40'); + assert.equal( + mul(mul(n, n), n).toString(16), + '1b888e01a06e974017a28a5b4da436169761c9730b7aeedf75fc60f687b' + + '46e0cf2cb11667f795d5569482640fe5f628939467a01a612b02350' + + '0d0161e9730279a7561043af6197798e41b7432458463e64fa81158' + + '907322dc330562697d0d600'); + }); + + it('should multiply neg number on 0', function () { + assert.equal( + mul(new BN('-100000000000'), new BN('3').div(new BN('4'))) + .toString(16), + '0' + ); + }); + + it('should regress mul big numbers', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + assert.equal(mul(q, q).toString(16), qs); + }); + }); + } + + testMethod('.mul()', function (x, y) { + return BN.prototype.mul.apply(x, [ y ]); + }); + + testMethod('.mulf()', function (x, y) { + return BN.prototype.mulf.apply(x, [ y ]); + }); + + describe('.imul()', function () { + it('should multiply numbers in-place', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('deadbeefa551edebabba8', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + + a = new BN('abcdef01234567890abcd214a25123f512361e6d236', 16); + b = new BN('deadbeefa551edebabba8121234fd21bac0341324dd', 16); + c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should multiply by 0', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('0', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should regress mul big numbers in-place', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + + assert.equal(q.isqr().toString(16), qs); + }); + }); + + describe('.muln()', function () { + it('should multiply number by small number', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('dead', 16); + var c = a.mul(b); + + assert.equal(a.muln(0xdead).toString(16), c.toString(16)); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).imuln(0x4000000); + }, /^Error: Assertion failed$/); + }); + }); + + describe('.pow()', function () { + it('should raise number to the power', function () { + var a = new BN('ab', 16); + var b = new BN('13', 10); + var c = a.pow(b); + + assert.equal(c.toString(16), '15963da06977df51909c9ba5b'); + }); + }); + + describe('.div()', function () { + it('should divide small numbers (<=26 bits)', function () { + assert.equal(new BN('256').div(new BN(10)).toString(10), + '25'); + assert.equal(new BN('-256').div(new BN(10)).toString(10), + '-25'); + assert.equal(new BN('256').div(new BN(-10)).toString(10), + '-25'); + assert.equal(new BN('-256').div(new BN(-10)).toString(10), + '25'); + + assert.equal(new BN('10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('10').div(new BN(-256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(-256)).toString(10), + '0'); + }); + + it('should divide large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').div(new BN('611111124969028')) + .toString(10), '1'); + assert.equal(new BN('-1222222225255589').div(new BN('611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('1222222225255589').div(new BN('-611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('-1222222225255589').div(new BN('-611111124969028')) + .toString(10), '1'); + + assert.equal(new BN('611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + }); + + it('should divide numbers', function () { + assert.equal(new BN('69527932928').div(new BN('16974594')).toString(16), + 'fff'); + assert.equal(new BN('-69527932928').div(new BN('16974594')).toString(16), + '-fff'); + + var b = new BN( + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40', + 16); + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal(b.div(n).toString(16), n.toString(16)); + + assert.equal(new BN('1').div(new BN('-5')).toString(10), '0'); + }); + + it('should not fail on regression after moving to _wordDiv', function () { + // Regression after moving to word div + var p = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + 16); + var a = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16); + var as = a.sqr(); + assert.equal( + as.div(p).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729e58090b9'); + + p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.div(p).toString(16), + 'ffffffff00000002000000000000000000000001000000000000000000000001'); + }); + }); + + describe('.idivn()', function () { + it('should divide numbers in-place', function () { + assert.equal(new BN('10', 16).idivn(3).toString(16), '5'); + assert.equal(new BN('12', 16).idivn(3).toString(16), '6'); + assert.equal(new BN('10000000000000000').idivn(3).toString(10), + '3333333333333333'); + assert.equal( + new BN('100000000000000000000000000000').idivn(3).toString(10), + '33333333333333333333333333333'); + + var t = new BN(3); + assert.equal( + new BN('12345678901234567890123456', 16).idivn(3).toString(16), + new BN('12345678901234567890123456', 16).div(t).toString(16)); + }); + }); + + describe('.divRound()', function () { + it('should divide numbers with rounding', function () { + assert.equal(new BN(9).divRound(new BN(20)).toString(10), + '0'); + assert.equal(new BN(10).divRound(new BN(20)).toString(10), + '1'); + assert.equal(new BN(150).divRound(new BN(20)).toString(10), + '8'); + assert.equal(new BN(149).divRound(new BN(20)).toString(10), + '7'); + assert.equal(new BN(149).divRound(new BN(17)).toString(10), + '9'); + assert.equal(new BN(144).divRound(new BN(17)).toString(10), + '8'); + assert.equal(new BN(-144).divRound(new BN(17)).toString(10), + '-8'); + }); + + it('should return 1 on exact division', function () { + assert.equal(new BN(144).divRound(new BN(144)).toString(10), '1'); + }); + }); + + describe('.mod()', function () { + it('should modulo small numbers (<=26 bits)', function () { + assert.equal(new BN('256').mod(new BN(10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(10)).toString(10), + '-6'); + assert.equal(new BN('256').mod(new BN(-10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(-10)).toString(10), + '-6'); + + assert.equal(new BN('10').mod(new BN(256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(256)).toString(10), + '-10'); + assert.equal(new BN('10').mod(new BN(-256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(-256)).toString(10), + '-10'); + }); + + it('should modulo large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').mod(new BN('611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('611111124969028')) + .toString(10), '-611111100286561'); + assert.equal(new BN('1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '-611111100286561'); + + assert.equal(new BN('611111124969028').mod(new BN('1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('1222222225255589')) + .toString(10), '-611111124969028'); + assert.equal(new BN('611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '-611111124969028'); + }); + + it('should mod numbers', function () { + assert.equal(new BN('10').mod(new BN(256)).toString(16), + 'a'); + assert.equal(new BN('69527932928').mod(new BN('16974594')).toString(16), + '102f302'); + + // 178 = 10 * 17 + 8 + assert.equal(new BN(178).div(new BN(10)).toNumber(), 17); + assert.equal(new BN(178).mod(new BN(10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(10)).toNumber(), 8); + + // -178 = 10 * (-17) + (-8) + assert.equal(new BN(-178).div(new BN(10)).toNumber(), -17); + assert.equal(new BN(-178).mod(new BN(10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(10)).toNumber(), 2); + + // 178 = -10 * (-17) + 8 + assert.equal(new BN(178).div(new BN(-10)).toNumber(), -17); + assert.equal(new BN(178).mod(new BN(-10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(-10)).toNumber(), 8); + + // -178 = -10 * (17) + (-8) + assert.equal(new BN(-178).div(new BN(-10)).toNumber(), 17); + assert.equal(new BN(-178).mod(new BN(-10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(-10)).toNumber(), 2); + + // -4 = 1 * (-3) + -1 + assert.equal(new BN(-4).div(new BN(-3)).toNumber(), 1); + assert.equal(new BN(-4).mod(new BN(-3)).toNumber(), -1); + + // -4 = -1 * (3) + -1 + assert.equal(new BN(-4).mod(new BN(3)).toNumber(), -1); + // -4 = 1 * (-3) + (-1 + 3) + assert.equal(new BN(-4).umod(new BN(-3)).toNumber(), 2); + + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.mod(p).toString(16), + '0'); + }); + + it('should properly carry the sign inside division', function () { + var a = new BN('945304eb96065b2a98b57a48a06ae28d285a71b5', 'hex'); + var b = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe', + 'hex'); + + assert.equal(a.mul(b).mod(a).cmpn(0), 0); + }); + }); + + describe('.modn()', function () { + it('should act like .mod() on small numbers', function () { + assert.equal(new BN('10', 16).modn(256).toString(16), '10'); + assert.equal(new BN('100', 16).modn(256).toString(16), '0'); + assert.equal(new BN('1001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(257).toString(16), + new BN('100000000001', 16).mod(new BN(257)).toString(16)); + assert.equal(new BN('123456789012', 16).modn(3).toString(16), + new BN('123456789012', 16).mod(new BN(3)).toString(16)); + }); + }); + + describe('.abs()', function () { + it('should return absolute value', function () { + assert.equal(new BN(0x1001).abs().toString(), '4097'); + assert.equal(new BN(-0x1001).abs().toString(), '4097'); + assert.equal(new BN('ffffffff', 16).abs().toString(), '4294967295'); + }); + }); + + describe('.invm()', function () { + it('should invert relatively-prime numbers', function () { + var p = new BN(257); + var a = new BN(3); + var b = a.invm(p); + assert.equal(a.mul(b).mod(p).toString(16), '1'); + + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + a = new BN('deadbeef', 16); + b = a.invm(p192); + assert.equal(a.mul(b).mod(p192).toString(16), '1'); + + // Even base + var phi = new BN('872d9b030ba368706b68932cf07a0e0c', 16); + var e = new BN(65537); + var d = e.invm(phi); + assert.equal(e.mul(d).mod(phi).toString(16), '1'); + + // Even base (take #2) + a = new BN('5'); + b = new BN('6'); + var r = a.invm(b); + assert.equal(r.mul(a).mod(b).toString(16), '1'); + }); + }); + + describe('.gcd()', function () { + it('should return GCD', function () { + assert.equal(new BN(3).gcd(new BN(2)).toString(10), '1'); + assert.equal(new BN(18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(-12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(0)).toString(10), '18'); + assert.equal(new BN(0).gcd(new BN(-18)).toString(10), '18'); + assert.equal(new BN(2).gcd(new BN(0)).toString(10), '2'); + assert.equal(new BN(0).gcd(new BN(3)).toString(10), '3'); + assert.equal(new BN(0).gcd(new BN(0)).toString(10), '0'); + }); + }); + + describe('.egcd()', function () { + it('should return EGCD', function () { + assert.equal(new BN(3).egcd(new BN(2)).gcd.toString(10), '1'); + assert.equal(new BN(18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(-18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(0).egcd(new BN(12)).gcd.toString(10), '12'); + }); + it('should not allow 0 input', function () { + assert.throws(function () { + new BN(1).egcd(0); + }, /^Error: Assertion failed$/); + }); + it('should not allow negative input', function () { + assert.throws(function () { + new BN(1).egcd(-1); + }, /^Error: Assertion failed$/); + }); + }); + + describe('BN.max(a, b)', function () { + it('should return maximum', function () { + assert.equal(BN.max(new BN(3), new BN(2)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(3)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.max(new BN(2), new BN(-2)).toString(16), '2'); + }); + }); + + describe('BN.min(a, b)', function () { + it('should return minimum', function () { + assert.equal(BN.min(new BN(3), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(3)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(-2)).toString(16), '-2'); + }); + }); + + describe('BN.ineg', function () { + it('shouldn\'t change sign for zero', function () { + assert.equal(new BN(0).ineg().toString(10), '0'); + }); + }); +}); diff --git a/test/merkletreejs/node_modules/bn.js/test/binary-test.js b/test/merkletreejs/node_modules/bn.js/test/binary-test.js new file mode 100644 index 0000000..37b6421 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/binary-test.js @@ -0,0 +1,233 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Binary', function () { + describe('.shl()', function () { + it('should shl numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').shln(45).toString(16), + '206060200000000000000'); + }); + + it('should ushl numbers', function () { + assert.equal(new BN('69527932928').ushln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').ushln(45).toString(16), + '206060200000000000000'); + }); + }); + + describe('.shr()', function () { + it('should shr numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').shrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').shrn(256).toString(16), + '0'); + }); + + it('should ushr numbers', function () { + assert.equal(new BN('69527932928').ushrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').ushrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').ushrn(256).toString(16), + '0'); + }); + }); + + describe('.bincn()', function () { + it('should increment bit', function () { + assert.equal(new BN(0).bincn(1).toString(16), '2'); + assert.equal(new BN(2).bincn(1).toString(16), '4'); + assert.equal(new BN(2).bincn(1).bincn(1).toString(16), + new BN(2).bincn(2).toString(16)); + assert.equal(new BN(0xffffff).bincn(1).toString(16), '1000001'); + assert.equal(new BN(2).bincn(63).toString(16), + '8000000000000002'); + }); + }); + + describe('.imaskn()', function () { + it('should mask bits in-place', function () { + assert.equal(new BN(0).imaskn(1).toString(16), '0'); + assert.equal(new BN(3).imaskn(1).toString(16), '1'); + assert.equal(new BN('123456789', 16).imaskn(4).toString(16), '9'); + assert.equal(new BN('123456789', 16).imaskn(16).toString(16), '6789'); + assert.equal(new BN('123456789', 16).imaskn(28).toString(16), '3456789'); + }); + + it('should not mask when number is bigger than length', function () { + assert.equal(new BN(0xe3).imaskn(56).toString(16), 'e3'); + assert.equal(new BN(0xe3).imaskn(26).toString(16), 'e3'); + }); + }); + + describe('.testn()', function () { + it('should support test specific bit', function () { + [ + 'ff', + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' + ].forEach(function (hex) { + var bn = new BN(hex, 16); + var bl = bn.bitLength(); + + for (var i = 0; i < bl; ++i) { + assert.equal(bn.testn(i), true); + } + + // test off the end + assert.equal(bn.testn(bl), false); + }); + + var xbits = '01111001010111001001000100011101' + + '11010011101100011000111001011101' + + '10010100111000000001011000111101' + + '01011111001111100100011110000010' + + '01011010100111010001010011000100' + + '01101001011110100001001111100110' + + '001110010111'; + + var x = new BN( + '23478905234580795234378912401239784125643978256123048348957342' + ); + for (var i = 0; i < x.bitLength(); ++i) { + assert.equal(x.testn(i), (xbits.charAt(i) === '1'), 'Failed @ bit ' + i); + } + }); + + it('should have short-cuts', function () { + var x = new BN('abcd', 16); + assert(!x.testn(128)); + }); + }); + + describe('.and()', function () { + it('should and numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .and(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .and(new BN('abcd', 16)).toString(16), + 'abcd'); + }); + }); + + describe('.iand()', function () { + it('should iand numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .iand(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + assert.equal(new BN('1000000000000000000000000000000000000001', 2) + .iand(new BN('1', 2)) + .toString(2), '1'); + assert.equal(new BN('1', 2) + .iand(new BN('1000000000000000000000000000000000000001', 2)) + .toString(2), '1'); + }); + }); + + describe('.or()', function () { + it('should or numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .or(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + }); + + it('should or numbers of different limb-length', function () { + assert.equal( + new BN('abcd00000000', 16) + .or(new BN('abcd', 16)).toString(16), + 'abcd0000abcd'); + }); + }); + + describe('.ior()', function () { + it('should ior numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .ior(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + assert.equal(new BN('1000000000000000000000000000000000000000', 2) + .ior(new BN('1', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + assert.equal(new BN('1', 2) + .ior(new BN('1000000000000000000000000000000000000000', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + }); + }); + + describe('.xor()', function () { + it('should xor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .xor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + }); + }); + + describe('.ixor()', function () { + it('should ixor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1', 2)) + .toString(2), '11001100110011001100110011001101'); + assert.equal(new BN('1', 2) + .ixor(new BN('11001100110011001100110011001100', 2)) + .toString(2), '11001100110011001100110011001101'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .xor(new BN('abcd', 16)).toString(16), + 'abcd00005432'); + }); + }); + + describe('.setn()', function () { + it('should allow single bits to be set', function () { + assert.equal(new BN(0).setn(2, true).toString(2), '100'); + assert.equal(new BN(0).setn(27, true).toString(2), + '1000000000000000000000000000'); + assert.equal(new BN(0).setn(63, true).toString(16), + new BN(1).iushln(63).toString(16)); + assert.equal(new BN('1000000000000000000000000001', 2).setn(27, false) + .toString(2), '1'); + assert.equal(new BN('101', 2).setn(2, false).toString(2), '1'); + }); + }); + + describe('.notn()', function () { + it('should allow bitwise negation', function () { + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(32).toString(2), + '11111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(32).toString(2), + '11111111111111111111111111000111'); + assert.equal(new BN('111000111', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111111000111'); + }); + }); +}); diff --git a/test/merkletreejs/node_modules/bn.js/test/constructor-test.js b/test/merkletreejs/node_modules/bn.js/test/constructor-test.js new file mode 100644 index 0000000..11c7df0 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/constructor-test.js @@ -0,0 +1,149 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Constructor', function () { + describe('with Smi input', function () { + it('should accept one limb number', function () { + assert.equal(new BN(12345).toString(16), '3039'); + }); + + it('should accept two-limb number', function () { + assert.equal(new BN(0x4123456).toString(16), '4123456'); + }); + + it('should accept 52 bits of precision', function () { + var num = Math.pow(2, 52); + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should accept max safe integer', function () { + var num = Math.pow(2, 53) - 1; + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should not accept an unsafe integer', function () { + var num = Math.pow(2, 53); + + assert.throws(function () { + return new BN(num, 10); + }, /^Error: Assertion failed$/); + }); + + it('should accept two-limb LE number', function () { + assert.equal(new BN(0x4123456, null, 'le').toString(16), '56341204'); + }); + }); + + describe('with String input', function () { + it('should accept base-16', function () { + assert.equal(new BN('1A6B765D8CDF', 16).toString(16), '1a6b765d8cdf'); + assert.equal(new BN('1A6B765D8CDF', 16).toString(), '29048849665247'); + }); + + it('should accept base-hex', function () { + assert.equal(new BN('FF', 'hex').toString(), '255'); + }); + + it('should accept base-16 with spaces', function () { + var num = 'a89c e5af8724 c0a23e0e 0ff77500'; + assert.equal(new BN(num, 16).toString(16), num.replace(/ /g, '')); + }); + + it('should accept long base-16', function () { + var num = '123456789abcdef123456789abcdef123456789abcdef'; + assert.equal(new BN(num, 16).toString(16), num); + }); + + it('should accept positive base-10', function () { + assert.equal(new BN('10654321').toString(), '10654321'); + assert.equal(new BN('29048849665247').toString(16), '1a6b765d8cdf'); + }); + + it('should accept negative base-10', function () { + assert.equal(new BN('-29048849665247').toString(16), '-1a6b765d8cdf'); + }); + + it('should accept long base-10', function () { + var num = '10000000000000000'; + assert.equal(new BN(num).toString(10), num); + }); + + it('should accept base-2', function () { + var base2 = '11111111111111111111111111111111111111111111111111111'; + assert.equal(new BN(base2, 2).toString(2), base2); + }); + + it('should accept base-36', function () { + var base36 = 'zzZzzzZzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'; + assert.equal(new BN(base36, 36).toString(36), base36.toLowerCase()); + }); + + it('should not overflow limbs during base-10', function () { + var num = '65820182292848241686198767302293' + + '20890292528855852623664389292032'; + assert(new BN(num).words[0] < 0x4000000); + }); + + it('should accept base-16 LE integer', function () { + assert.equal(new BN('1A6B765D8CDF', 16, 'le').toString(16), + 'df8c5d766b1a'); + }); + }); + + describe('with Array input', function () { + it('should not fail on empty array', function () { + assert.equal(new BN([]).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN([ 1, 2, 3 ]).toString(16), '10203'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toString(16), '1020304'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ]).toString(16), '102030405'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toString(16), + '102030405060708'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray().join(','), '1,2,3,4'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray().join(','), + '1,2,3,4,5,6,7,8'); + }); + + it('should import little endian', function () { + assert.equal(new BN([ 1, 2, 3 ], 10, 'le').toString(16), '30201'); + assert.equal(new BN([ 1, 2, 3, 4 ], 10, 'le').toString(16), '4030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 10, 'le').toString(16), + '504030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ], 'le').toString(16), + '807060504030201'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray('le').join(','), '4,3,2,1'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray('le').join(','), + '8,7,6,5,4,3,2,1'); + }); + + it('should import big endian with implicit base', function () { + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 'le').toString(16), '504030201'); + }); + }); + + // the Array code is able to handle Buffer + describe('with Buffer input', function () { + it('should not fail on empty Buffer', function () { + assert.equal(new BN(new Buffer(0)).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex')).toString(16), '10203'); + }); + + it('should import little endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex'), 'le').toString(16), '30201'); + }); + }); + + describe('with BN input', function () { + it('should clone BN', function () { + var num = new BN(12345); + assert.equal(new BN(num).toString(10), '12345'); + }); + }); +}); diff --git a/test/merkletreejs/node_modules/bn.js/test/fixtures.js b/test/merkletreejs/node_modules/bn.js/test/fixtures.js new file mode 100644 index 0000000..39fd661 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/fixtures.js @@ -0,0 +1,264 @@ +exports.dhGroups = { + p16: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199' + + 'ffffffffffffffff', + priv: '6d5923e6449122cbbcc1b96093e0b7e4fd3e469f58daddae' + + '53b49b20664f4132675df9ce98ae0cfdcac0f4181ccb643b' + + '625f98104dcf6f7d8e81961e2cab4b5014895260cb977c7d' + + '2f981f8532fb5da60b3676dfe57f293f05d525866053ac7e' + + '65abfd19241146e92e64f309a97ef3b529af4d6189fa416c' + + '9e1a816c3bdf88e5edf48fbd8233ef9038bb46faa95122c0' + + '5a426be72039639cd2d53d37254b3d258960dcb33c255ede' + + '20e9d7b4b123c8b4f4b986f53cdd510d042166f7dd7dca98' + + '7c39ab36381ba30a5fdd027eb6128d2ef8e5802a2194d422' + + 'b05fe6e1cb4817789b923d8636c1ec4b7601c90da3ddc178' + + '52f59217ae070d87f2e75cbfb6ff92430ad26a71c8373452' + + 'ae1cc5c93350e2d7b87e0acfeba401aaf518580937bf0b6c' + + '341f8c49165a47e49ce50853989d07171c00f43dcddddf72' + + '94fb9c3f4e1124e98ef656b797ef48974ddcd43a21fa06d0' + + '565ae8ce494747ce9e0ea0166e76eb45279e5c6471db7df8' + + 'cc88764be29666de9c545e72da36da2f7a352fb17bdeb982' + + 'a6dc0193ec4bf00b2e533efd6cd4d46e6fb237b775615576' + + 'dd6c7c7bbc087a25e6909d1ebc6e5b38e5c8472c0fc429c6' + + 'f17da1838cbcd9bbef57c5b5522fd6053e62ba21fe97c826' + + 'd3889d0cc17e5fa00b54d8d9f0f46fb523698af965950f4b' + + '941369e180f0aece3870d9335f2301db251595d173902cad' + + '394eaa6ffef8be6c', + pub: 'd53703b7340bc89bfc47176d351e5cf86d5a18d9662eca3c' + + '9759c83b6ccda8859649a5866524d77f79e501db923416ca' + + '2636243836d3e6df752defc0fb19cc386e3ae48ad647753f' + + 'bf415e2612f8a9fd01efe7aca249589590c7e6a0332630bb' + + '29c5b3501265d720213790556f0f1d114a9e2071be3620bd' + + '4ee1e8bb96689ac9e226f0a4203025f0267adc273a43582b' + + '00b70b490343529eaec4dcff140773cd6654658517f51193' + + '13f21f0a8e04fe7d7b21ffeca85ff8f87c42bb8d9cb13a72' + + 'c00e9c6e9dfcedda0777af951cc8ccab90d35e915e707d8e' + + '4c2aca219547dd78e9a1a0730accdc9ad0b854e51edd1e91' + + '4756760bab156ca6e3cb9c625cf0870def34e9ac2e552800' + + 'd6ce506d43dbbc75acfa0c8d8fb12daa3c783fb726f187d5' + + '58131779239c912d389d0511e0f3a81969d12aeee670e48f' + + 'ba41f7ed9f10705543689c2506b976a8ffabed45e33795b0' + + '1df4f6b993a33d1deab1316a67419afa31fbb6fdd252ee8c' + + '7c7d1d016c44e3fcf6b41898d7f206aa33760b505e4eff2e' + + 'c624bc7fe636b1d59e45d6f904fc391419f13d1f0cdb5b6c' + + '2378b09434159917dde709f8a6b5dc30994d056e3f964371' + + '11587ac7af0a442b8367a7bd940f752ddabf31cf01171e24' + + 'd78df136e9681cd974ce4f858a5fb6efd3234a91857bb52d' + + '9e7b414a8bc66db4b5a73bbeccfb6eb764b4f0cbf0375136' + + 'b024b04e698d54a5' + }, + p17: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934028492' + + '36c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bd' + + 'f8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831' + + '179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1b' + + 'db7f1447e6cc254b332051512bd7af426fb8f401378cd2bf' + + '5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6' + + 'd55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f3' + + '23a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aa' + + 'cc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be328' + + '06a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55c' + + 'da56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee' + + '12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff', + priv: '6017f2bc23e1caff5b0a8b4e1fc72422b5204415787801dc' + + '025762b8dbb98ab57603aaaa27c4e6bdf742b4a1726b9375' + + 'a8ca3cf07771779589831d8bd18ddeb79c43e7e77d433950' + + 'e652e49df35b11fa09644874d71d62fdaffb580816c2c88c' + + '2c4a2eefd4a660360316741b05a15a2e37f236692ad3c463' + + 'fff559938fc6b77176e84e1bb47fb41af691c5eb7bb81bd8' + + 'c918f52625a1128f754b08f5a1403b84667231c4dfe07ed4' + + '326234c113931ce606037e960f35a2dfdec38a5f057884d3' + + '0af8fab3be39c1eeb390205fd65982191fc21d5aa30ddf51' + + 'a8e1c58c0c19fc4b4a7380ea9e836aaf671c90c29bc4bcc7' + + '813811aa436a7a9005de9b507957c56a9caa1351b6efc620' + + '7225a18f6e97f830fb6a8c4f03b82f4611e67ab9497b9271' + + 'd6ac252793cc3e5538990dbd894d2dbc2d152801937d9f74' + + 'da4b741b50b4d40e4c75e2ac163f7b397fd555648b249f97' + + 'ffe58ffb6d096aa84534c4c5729cff137759bd34e80db4ab' + + '47e2b9c52064e7f0bf677f72ac9e5d0c6606943683f9d12f' + + '180cf065a5cb8ec3179a874f358847a907f8471d15f1e728' + + '7023249d6d13c82da52628654438f47b8b5cdf4761fbf6ad' + + '9219eceac657dbd06cf2ab776ad4c968f81c3d039367f0a4' + + 'd77c7ec4435c27b6c147071665100063b5666e06eb2fb2cc' + + '3159ba34bc98ca346342195f6f1fb053ddc3bc1873564d40' + + '1c6738cdf764d6e1ff25ca5926f80102ea6593c17170966b' + + 'b5d7352dd7fb821230237ea3ebed1f920feaadbd21be295a' + + '69f2083deae9c5cdf5f4830eb04b7c1f80cc61c17232d79f' + + '7ecc2cc462a7965f804001c89982734e5abba2d31df1b012' + + '152c6b226dff34510b54be8c2cd68d795def66c57a3abfb6' + + '896f1d139e633417f8c694764974d268f46ece3a8d6616ea' + + 'a592144be48ee1e0a1595d3e5edfede5b27cec6c48ceb2ff' + + 'b42cb44275851b0ebf87dfc9aa2d0cb0805e9454b051dfe8' + + 'a29fadd82491a4b4c23f2d06ba45483ab59976da1433c9ce' + + '500164b957a04cf62dd67595319b512fc4b998424d1164dd' + + 'bbe5d1a0f7257cbb04ec9b5ed92079a1502d98725023ecb2', + pub: '3bf836229c7dd874fe37c1790d201e82ed8e192ed61571ca' + + '7285264974eb2a0171f3747b2fc23969a916cbd21e14f7e2' + + 'f0d72dcd2247affba926f9e7bb99944cb5609aed85e71b89' + + 'e89d2651550cb5bd8281bd3144066af78f194032aa777739' + + 'cccb7862a1af401f99f7e5c693f25ddce2dedd9686633820' + + 'd28d0f5ed0c6b5a094f5fe6170b8e2cbc9dff118398baee6' + + 'e895a6301cb6e881b3cae749a5bdf5c56fc897ff68bc73f2' + + '4811bb108b882872bade1f147d886a415cda2b93dd90190c' + + 'be5c2dd53fe78add5960e97f58ff2506afe437f4cf4c912a' + + '397c1a2139ac6207d3ab76e6b7ffd23bb6866dd7f87a9ae5' + + '578789084ff2d06ea0d30156d7a10496e8ebe094f5703539' + + '730f5fdbebc066de417be82c99c7da59953071f49da7878d' + + 'a588775ff2a7f0084de390f009f372af75cdeba292b08ea8' + + '4bd13a87e1ca678f9ad148145f7cef3620d69a891be46fbb' + + 'cad858e2401ec0fd72abdea2f643e6d0197b7646fbb83220' + + '0f4cf7a7f6a7559f9fb0d0f1680822af9dbd8dec4cd1b5e1' + + '7bc799e902d9fe746ddf41da3b7020350d3600347398999a' + + 'baf75d53e03ad2ee17de8a2032f1008c6c2e6618b62f225b' + + 'a2f350179445debe68500fcbb6cae970a9920e321b468b74' + + '5fb524fb88abbcacdca121d737c44d30724227a99745c209' + + 'b970d1ff93bbc9f28b01b4e714d6c9cbd9ea032d4e964d8e' + + '8fff01db095160c20b7646d9fcd314c4bc11bcc232aeccc0' + + 'fbedccbc786951025597522eef283e3f56b44561a0765783' + + '420128638c257e54b972a76e4261892d81222b3e2039c61a' + + 'ab8408fcaac3d634f848ab3ee65ea1bd13c6cd75d2e78060' + + 'e13cf67fbef8de66d2049e26c0541c679fff3e6afc290efe' + + '875c213df9678e4a7ec484bc87dae5f0a1c26d7583e38941' + + 'b7c68b004d4df8b004b666f9448aac1cc3ea21461f41ea5d' + + 'd0f7a9e6161cfe0f58bcfd304bdc11d78c2e9d542e86c0b5' + + '6985cc83f693f686eaac17411a8247bf62f5ccc7782349b5' + + 'cc1f20e312fa2acc0197154d1bfee507e8db77e8f2732f2d' + + '641440ccf248e8643b2bd1e1f9e8239356ab91098fcb431d', + q: 'a899c59999bf877d96442d284359783bdc64b5f878b688fe' + + '51407f0526e616553ad0aaaac4d5bed3046f10a1faaf42bb' + + '2342dc4b7908eea0c46e4c4576897675c2bfdc4467870d3d' + + 'cd90adaed4359237a4bc6924bfb99aa6bf5f5ede15b574ea' + + 'e977eac096f3c67d09bda574c6306c6123fa89d2f086b8dc' + + 'ff92bc570c18d83fe6c810ccfd22ce4c749ef5e6ead3fffe' + + 'c63d95e0e3fde1df9db6a35fa1d107058f37e41957769199' + + 'd945dd7a373622c65f0af3fd9eb1ddc5c764bbfaf7a3dc37' + + '2548e683b970dac4aa4b9869080d2376c9adecebb84e172c' + + '09aeeb25fb8df23e60033260c4f8aac6b8b98ab894b1fb84' + + 'ebb83c0fb2081c3f3eee07f44e24d8fabf76f19ed167b0d7' + + 'ff971565aa4efa3625fce5a43ceeaa3eebb3ce88a00f597f' + + '048c69292b38dba2103ecdd5ec4ccfe3b2d87fa6202f334b' + + 'c1cab83b608dfc875b650b69f2c7e23c0b2b4adf149a6100' + + 'db1b6dbad4679ecb1ea95eafaba3bd00db11c2134f5a8686' + + '358b8b2ab49a1b2e85e1e45caeac5cd4dc0b3b5fffba8871' + + '1c6baf399edd48dad5e5c313702737a6dbdcede80ca358e5' + + '1d1c4fe42e8948a084403f61baed38aa9a1a5ce2918e9f33' + + '100050a430b47bc592995606440272a4994677577a6aaa1b' + + 'a101045dbec5a4e9566dab5445d1af3ed19519f07ac4e2a8' + + 'bd0a84b01978f203a9125a0be020f71fab56c2c9e344d4f4' + + '12d53d3cd8eb74ca5122002e931e3cb0bd4b7492436be17a' + + 'd7ebe27148671f59432c36d8c56eb762655711cfc8471f70' + + '83a8b7283bcb3b1b1d47d37c23d030288cfcef05fbdb4e16' + + '652ee03ee7b77056a808cd700bc3d9ef826eca9a59be959c' + + '947c865d6b372a1ca2d503d7df6d7611b12111665438475a' + + '1c64145849b3da8c2d343410df892d958db232617f9896f1' + + 'de95b8b5a47132be80dd65298c7f2047858409bf762dbc05' + + 'a62ca392ac40cfb8201a0607a2cae07d99a307625f2b2d04' + + 'fe83fbd3ab53602263410f143b73d5b46fc761882e78c782' + + 'd2c36e716a770a7aefaf7f76cea872db7bffefdbc4c2f9e0' + + '39c19adac915e7a63dcb8c8c78c113f29a3e0bc10e100ce0', + qs: '6f0a2fb763eaeb8eb324d564f03d4a55fdcd709e5f1b65e9' + + '5702b0141182f9f945d71bc3e64a7dfdae7482a7dd5a4e58' + + 'bc38f78de2013f2c468a621f08536969d2c8d011bb3bc259' + + '2124692c91140a5472cad224acdacdeae5751dadfdf068b8' + + '77bfa7374694c6a7be159fc3d24ff9eeeecaf62580427ad8' + + '622d48c51a1c4b1701d768c79d8c819776e096d2694107a2' + + 'f3ec0c32224795b59d32894834039dacb369280afb221bc0' + + '90570a93cf409889b818bb30cccee98b2aa26dbba0f28499' + + '08e1a3cd43fa1f1fb71049e5c77c3724d74dc351d9989057' + + '37bbda3805bd6b1293da8774410fb66e3194e18cdb304dd9' + + 'a0b59b583dcbc9fc045ac9d56aea5cfc9f8a0b95da1e11b7' + + '574d1f976e45fe12294997fac66ca0b83fc056183549e850' + + 'a11413cc4abbe39a211e8c8cbf82f2a23266b3c10ab9e286' + + '07a1b6088909cddff856e1eb6b2cde8bdac53fa939827736' + + 'ca1b892f6c95899613442bd02dbdb747f02487718e2d3f22' + + 'f73734d29767ed8d0e346d0c4098b6fdcb4df7d0c4d29603' + + '5bffe80d6c65ae0a1b814150d349096baaf950f2caf298d2' + + 'b292a1d48cf82b10734fe8cedfa16914076dfe3e9b51337b' + + 'ed28ea1e6824bb717b641ca0e526e175d3e5ed7892aebab0' + + 'f207562cc938a821e2956107c09b6ce4049adddcd0b7505d' + + '49ae6c69a20122461102d465d93dc03db026be54c303613a' + + 'b8e5ce3fd4f65d0b6162ff740a0bf5469ffd442d8c509cd2' + + '3b40dab90f6776ca17fc0678774bd6eee1fa85ababa52ec1' + + 'a15031eb677c6c488661dddd8b83d6031fe294489ded5f08' + + '8ad1689a14baeae7e688afa3033899c81f58de39b392ca94' + + 'af6f15a46f19fa95c06f9493c8b96a9be25e78b9ea35013b' + + 'caa76de6303939299d07426a88a334278fc3d0d9fa71373e' + + 'be51d3c1076ab93a11d3d0d703366ff8cde4c11261d488e5' + + '60a2bdf3bfe2476032294800d6a4a39d306e65c6d7d8d66e' + + '5ec63eee94531e83a9bddc458a2b508285c0ee10b7bd94da' + + '2815a0c5bd5b2e15cbe66355e42f5af8955cdfc0b3a4996d' + + '288db1f4b32b15643b18193e378cb7491f3c3951cdd044b1' + + 'a519571bffac2da986f5f1d506c66530a55f70751e24fa8e' + + 'd83ac2347f4069fb561a5565e78c6f0207da24e889a93a96' + + '65f717d9fe8a2938a09ab5f81be7ccecf466c0397fc15a57' + + '469939793f302739765773c256a3ca55d0548afd117a7cae' + + '98ca7e0d749a130c7b743d376848e255f8fdbe4cb4480b63' + + 'cd2c015d1020cf095d175f3ca9dcdfbaf1b2a6e6468eee4c' + + 'c750f2132a77f376bd9782b9d0ff4da98621b898e251a263' + + '4301ba2214a8c430b2f7a79dbbfd6d7ff6e9b0c137b025ff' + + '587c0bf912f0b19d4fff96b1ecd2ca990c89b386055c60f2' + + '3b94214bd55096f17a7b2c0fa12b333235101cd6f28a128c' + + '782e8a72671adadebbd073ded30bd7f09fb693565dcf0bf3' + + '090c21d13e5b0989dd8956f18f17f4f69449a13549c9d80a' + + '77e5e61b5aeeee9528634100e7bc390672f0ded1ca53555b' + + 'abddbcf700b9da6192255bddf50a76b709fbed251dce4c7e' + + '1ca36b85d1e97c1bc9d38c887a5adf140f9eeef674c31422' + + 'e65f63cae719f8c1324e42fa5fd8500899ef5aa3f9856aa7' + + 'ce10c85600a040343204f36bfeab8cfa6e9deb8a2edd2a8e' + + '018d00c7c9fa3a251ad0f57183c37e6377797653f382ec7a' + + '2b0145e16d3c856bc3634b46d90d7198aff12aff88a30e34' + + 'e2bfaf62705f3382576a9d3eeb0829fca2387b5b654af46e' + + '5cf6316fb57d59e5ea6c369061ac64d99671b0e516529dd5' + + 'd9c48ea0503e55fee090d36c5ea8b5954f6fcc0060794e1c' + + 'b7bc24aa1e5c0142fd4ce6e8fd5aa92a7bf84317ea9e1642' + + 'b6995bac6705adf93cbce72433ed0871139970d640f67b78' + + 'e63a7a6d849db2567df69ac7d79f8c62664ac221df228289' + + 'd0a4f9ebd9acb4f87d49da64e51a619fd3f3baccbd9feb12' + + '5abe0cc2c8d17ed1d8546da2b6c641f4d3020a5f9b9f26ac' + + '16546c2d61385505612275ea344c2bbf1ce890023738f715' + + '5e9eba6a071678c8ebd009c328c3eb643679de86e69a9fa5' + + '67a9e146030ff03d546310a0a568c5ba0070e0da22f2cef8' + + '54714b04d399bbc8fd261f9e8efcd0e83bdbc3f5cfb2d024' + + '3e398478cc598e000124eb8858f9df8f52946c2a1ca5c400' + } +}; diff --git a/test/merkletreejs/node_modules/bn.js/test/pummel/dh-group-test.js b/test/merkletreejs/node_modules/bn.js/test/pummel/dh-group-test.js new file mode 100644 index 0000000..37a259f --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/pummel/dh-group-test.js @@ -0,0 +1,23 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../../').BN; +var fixtures = require('../fixtures'); + +describe('BN.js/Slow DH test', function () { + var groups = fixtures.dhGroups; + Object.keys(groups).forEach(function (name) { + it('should match public key for ' + name + ' group', function () { + var group = groups[name]; + + this.timeout(3600 * 1000); + + var base = new BN(2); + var mont = BN.red(new BN(group.prime, 16)); + var priv = new BN(group.priv, 16); + var multed = base.toRed(mont).redPow(priv).fromRed(); + var actual = new Buffer(multed.toArray()); + assert.equal(actual.toString('hex'), group.pub); + }); + }); +}); diff --git a/test/merkletreejs/node_modules/bn.js/test/red-test.js b/test/merkletreejs/node_modules/bn.js/test/red-test.js new file mode 100644 index 0000000..fc2498c --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/red-test.js @@ -0,0 +1,263 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Reduction context', function () { + function testMethod (name, fn) { + describe(name + ' method', function () { + it('should support add, iadd, sub, isub operations', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(123).toRed(m); + var b = new BN(231).toRed(m); + + assert.equal(a.redAdd(b).fromRed().toString(10), '97'); + assert.equal(a.redSub(b).fromRed().toString(10), '149'); + assert.equal(b.redSub(a).fromRed().toString(10), '108'); + + assert.equal(a.clone().redIAdd(b).fromRed().toString(10), '97'); + assert.equal(a.clone().redISub(b).fromRed().toString(10), '149'); + assert.equal(b.clone().redISub(a).fromRed().toString(10), '108'); + }); + + it('should support pow and mul operations', function () { + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p192); + var a = new BN(123); + var b = new BN(231); + var c = a.toRed(m).redMul(b.toRed(m)).fromRed(); + assert(c.cmp(a.mul(b).mod(p192)) === 0); + + assert.equal(a.toRed(m).redPow(new BN(3)).fromRed() + .cmp(a.sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(4)).fromRed() + .cmp(a.sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(8)).fromRed() + .cmp(a.sqr().sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(9)).fromRed() + .cmp(a.sqr().sqr().sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(17)).fromRed() + .cmp(a.sqr().sqr().sqr().sqr().mul(a)), 0); + assert.equal( + a.toRed(m).redPow(new BN('deadbeefabbadead', 16)).fromRed() + .toString(16), + '3aa0e7e304e320b68ef61592bcb00341866d6fa66e11a4d6'); + }); + + it('should sqrtm numbers', function () { + var p = new BN(263); + var m = fn(p); + var q = new BN(11).toRed(m); + + var qr = q.redSqrt(); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(); + assert.equal(qr.redSqr().cmp(q), 0); + + p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + m = fn(p); + + q = new BN(13).toRed(m); + qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + // Tonelli-shanks + p = new BN(13); + m = fn(p); + q = new BN(10).toRed(m); + assert.equal(q.redSqrt().fromRed().toString(10), '7'); + }); + + it('should invm numbers', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(3).toRed(m); + var b = a.redInvm(); + assert.equal(a.redMul(b).fromRed().toString(16), '1'); + }); + + it('should invm numbers (regression)', function () { + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'e1d969b8192fbac73ea5b7921896d6a2263d4d4077bb8e5055361d1f7f8163f3', + 16); + + var m = fn(p); + a = a.toRed(m); + + assert.equal(a.redInvm().fromRed().negative, 0); + }); + + it('should imul numbers', function () { + var p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p); + + var a = new BN('deadbeefabbadead', 16); + var b = new BN('abbadeadbeefdead', 16); + var c = a.mul(b).mod(p); + + assert.equal(a.toRed(m).redIMul(b.toRed(m)).fromRed().toString(16), + c.toString(16)); + }); + + it('should pow(base, 0) == 1', function () { + var base = new BN(256).toRed(BN.red('k256')); + var exponent = new BN(0); + var result = base.redPow(exponent); + assert.equal(result.toString(), '1'); + }); + + it('should shl numbers', function () { + var base = new BN(256).toRed(BN.red('k256')); + var result = base.redShl(1); + assert.equal(result.toString(), '512'); + }); + + it('should reduce when converting to red', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(5).toRed(m); + + assert.doesNotThrow(function () { + var b = a.redISub(new BN(512).toRed(m)); + b.redISub(new BN(512).toRed(m)); + }); + }); + + it('redNeg and zero value', function () { + var a = new BN(0).toRed(BN.red('k256')).redNeg(); + assert.equal(a.isZero(), true); + }); + + it('should not allow modulus <= 1', function () { + assert.throws(function () { + BN.red(new BN(0)); + }, /^Error: modulus must be greater than 1$/); + + assert.throws(function () { + BN.red(new BN(1)); + }, /^Error: modulus must be greater than 1$/); + + assert.doesNotThrow(function () { + BN.red(new BN(2)); + }); + }); + }); + } + + testMethod('Plain', BN.red); + testMethod('Montgomery', BN.mont); + + describe('Pseudo-Mersenne Primes', function () { + it('should reduce numbers mod k256', function () { + var p = BN._prime('k256'); + + assert.equal(p.ireduce(new BN(0xdead)).toString(16), 'dead'); + assert.equal(p.ireduce(new BN('deadbeef', 16)).toString(16), 'deadbeef'); + + var num = new BN('fedcba9876543210fedcba9876543210dead' + + 'fedcba9876543210fedcba9876543210dead', + 16); + var exp = num.mod(p.p).toString(16); + assert.equal(p.ireduce(num).toString(16), exp); + + var regr = new BN('f7e46df64c1815962bf7bc9c56128798' + + '3f4fcef9cb1979573163b477eab93959' + + '335dfb29ef07a4d835d22aa3b6797760' + + '70a8b8f59ba73d56d01a79af9', + 16); + exp = regr.mod(p.p).toString(16); + + assert.equal(p.ireduce(regr).toString(16), exp); + }); + + it('should not fail to invm number mod k256', function () { + var regr2 = new BN( + '6c150c4aa9a8cf1934485d40674d4a7cd494675537bda36d49405c5d2c6f496f', 16); + regr2 = regr2.toRed(BN.red('k256')); + assert.equal(regr2.redInvm().redMul(regr2).fromRed().cmpn(1), 0); + }); + + it('should correctly square the number', function () { + var p = BN._prime('k256').p; + var red = BN.red('k256'); + + var n = new BN('9cd8cb48c3281596139f147c1364a3ed' + + 'e88d3f310fdb0eb98c924e599ca1b3c9', + 16); + var expected = n.sqr().mod(p); + var actual = n.toRed(red).redSqr().fromRed(); + + assert.equal(actual.toString(16), expected.toString(16)); + }); + + it('redISqr should return right result', function () { + var n = new BN('30f28939', 16); + var actual = n.toRed(BN.red('k256')).redISqr().fromRed(); + assert.equal(actual.toString(16), '95bd93d19520eb1'); + }); + }); + + it('should avoid 4.1.0 regresion', function () { + function bits2int (obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { + bits.ishrn(shift); + } + return bits; + } + var t = new Buffer('aff1651e4cd6036d57aa8b2a05ccf1a9d5a40166340ecbbdc55' + + 'be10b568aa0aa3d05ce9a2fcec9df8ed018e29683c6051cb83e' + + '46ce31ba4edb045356a8d0d80b', 'hex'); + var g = new BN('5c7ff6b06f8f143fe8288433493e4769c4d988ace5be25a0e24809670' + + '716c613d7b0cee6932f8faa7c44d2cb24523da53fbe4f6ec3595892d1' + + 'aa58c4328a06c46a15662e7eaa703a1decf8bbb2d05dbe2eb956c142a' + + '338661d10461c0d135472085057f3494309ffa73c611f78b32adbb574' + + '0c361c9f35be90997db2014e2ef5aa61782f52abeb8bd6432c4dd097b' + + 'c5423b285dafb60dc364e8161f4a2a35aca3a10b1c4d203cc76a470a3' + + '3afdcbdd92959859abd8b56e1725252d78eac66e71ba9ae3f1dd24871' + + '99874393cd4d832186800654760e1e34c09e4d155179f9ec0dc4473f9' + + '96bdce6eed1cabed8b6f116f7ad9cf505df0f998e34ab27514b0ffe7', + 16); + var p = new BN('9db6fb5951b66bb6fe1e140f1d2ce5502374161fd6538df1648218642' + + 'f0b5c48c8f7a41aadfa187324b87674fa1822b00f1ecf8136943d7c55' + + '757264e5a1a44ffe012e9936e00c1d3e9310b01c7d179805d3058b2a9' + + 'f4bb6f9716bfe6117c6b5b3cc4d9be341104ad4a80ad6c94e005f4b99' + + '3e14f091eb51743bf33050c38de235567e1b34c3d6a5c0ceaa1a0f368' + + '213c3d19843d0b4b09dcb9fc72d39c8de41f1bf14d4bb4563ca283716' + + '21cad3324b6a2d392145bebfac748805236f5ca2fe92b871cd8f9c36d' + + '3292b5509ca8caa77a2adfc7bfd77dda6f71125a7456fea153e433256' + + 'a2261c6a06ed3693797e7995fad5aabbcfbe3eda2741e375404ae25b', + 16); + var q = new BN('f2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde' + + '9998c1f', 16); + var k = bits2int(t, q); + var expectedR = '89ec4bb1400eccff8e7d9aa515cd1de7803f2daff09693ee7fd1353e' + + '90a68307'; + var r = g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + assert.equal(r.toString(16), expectedR); + }); + + it('K256.split for 512 bits number should return equal numbers', function () { + var red = BN.red('k256'); + var input = new BN(1).iushln(512).subn(1); + assert.equal(input.bitLength(), 512); + var output = new BN(0); + red.prime.split(input, output); + assert.equal(input.cmp(output), 0); + }); +}); diff --git a/test/merkletreejs/node_modules/bn.js/test/utils-test.js b/test/merkletreejs/node_modules/bn.js/test/utils-test.js new file mode 100644 index 0000000..8571905 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/test/utils-test.js @@ -0,0 +1,345 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Utils', function () { + describe('.toString()', function () { + describe('binary padding', function () { + it('should have a length of 256', function () { + var a = new BN(0); + + assert.equal(a.toString(2, 256).length, 256); + }); + }); + describe('hex padding', function () { + it('should have length of 8 from leading 15', function () { + var a = new BN('ffb9602', 16); + + assert.equal(a.toString('hex', 2).length, 8); + }); + + it('should have length of 8 from leading zero', function () { + var a = new BN('fb9604', 16); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 8 from leading zeros', function () { + var a = new BN(0); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 64 from leading 15', function () { + var a = new BN( + 'ffb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 2).length, 64); + }); + + it('should have length of 64 from leading zero', function () { + var a = new BN( + 'fb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 64).length, 64); + }); + }); + }); + + describe('.isNeg()', function () { + it('should return true for negative numbers', function () { + assert.equal(new BN(-1).isNeg(), true); + assert.equal(new BN(1).isNeg(), false); + assert.equal(new BN(0).isNeg(), false); + assert.equal(new BN('-0', 10).isNeg(), false); + }); + }); + + describe('.isOdd()', function () { + it('should return true for odd numbers', function () { + assert.equal(new BN(0).isOdd(), false); + assert.equal(new BN(1).isOdd(), true); + assert.equal(new BN(2).isOdd(), false); + assert.equal(new BN('-0', 10).isOdd(), false); + assert.equal(new BN('-1', 10).isOdd(), true); + assert.equal(new BN('-2', 10).isOdd(), false); + }); + }); + + describe('.isEven()', function () { + it('should return true for even numbers', function () { + assert.equal(new BN(0).isEven(), true); + assert.equal(new BN(1).isEven(), false); + assert.equal(new BN(2).isEven(), true); + assert.equal(new BN('-0', 10).isEven(), true); + assert.equal(new BN('-1', 10).isEven(), false); + assert.equal(new BN('-2', 10).isEven(), true); + }); + }); + + describe('.isZero()', function () { + it('should return true for zero', function () { + assert.equal(new BN(0).isZero(), true); + assert.equal(new BN(1).isZero(), false); + assert.equal(new BN(0xffffffff).isZero(), false); + }); + }); + + describe('.bitLength()', function () { + it('should return proper bitLength', function () { + assert.equal(new BN(0).bitLength(), 0); + assert.equal(new BN(0x1).bitLength(), 1); + assert.equal(new BN(0x2).bitLength(), 2); + assert.equal(new BN(0x3).bitLength(), 2); + assert.equal(new BN(0x4).bitLength(), 3); + assert.equal(new BN(0x8).bitLength(), 4); + assert.equal(new BN(0x10).bitLength(), 5); + assert.equal(new BN(0x100).bitLength(), 9); + assert.equal(new BN(0x123456).bitLength(), 21); + assert.equal(new BN('123456789', 16).bitLength(), 33); + assert.equal(new BN('8023456789', 16).bitLength(), 40); + }); + }); + + describe('.byteLength()', function () { + it('should return proper byteLength', function () { + assert.equal(new BN(0).byteLength(), 0); + assert.equal(new BN(0x1).byteLength(), 1); + assert.equal(new BN(0x2).byteLength(), 1); + assert.equal(new BN(0x3).byteLength(), 1); + assert.equal(new BN(0x4).byteLength(), 1); + assert.equal(new BN(0x8).byteLength(), 1); + assert.equal(new BN(0x10).byteLength(), 1); + assert.equal(new BN(0x100).byteLength(), 2); + assert.equal(new BN(0x123456).byteLength(), 3); + assert.equal(new BN('123456789', 16).byteLength(), 5); + assert.equal(new BN('8023456789', 16).byteLength(), 5); + }); + }); + + describe('.toArray()', function () { + it('should return [ 0 ] for `0`', function () { + var n = new BN(0); + assert.deepEqual(n.toArray('be'), [ 0 ]); + assert.deepEqual(n.toArray('le'), [ 0 ]); + }); + + it('should zero pad to desired lengths', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toArray('be', 5), [ 0x00, 0x00, 0x12, 0x34, 0x56 ]); + assert.deepEqual(n.toArray('le', 5), [ 0x56, 0x34, 0x12, 0x00, 0x00 ]); + }); + + it('should throw when naturally larger than desired length', function () { + var n = new BN(0x123456); + assert.throws(function () { + n.toArray('be', 2); + }, /^Error: byte array longer than desired length$/); + }); + }); + + describe('.toBuffer', function () { + it('should return proper Buffer', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toBuffer('be', 5).toString('hex'), '0000123456'); + assert.deepEqual(n.toBuffer('le', 5).toString('hex'), '5634120000'); + }); + }); + + describe('.toNumber()', function () { + it('should return proper Number if below the limit', function () { + assert.deepEqual(new BN(0x123456).toNumber(), 0x123456); + assert.deepEqual(new BN(0x3ffffff).toNumber(), 0x3ffffff); + assert.deepEqual(new BN(0x4000000).toNumber(), 0x4000000); + assert.deepEqual(new BN(0x10000000000000).toNumber(), 0x10000000000000); + assert.deepEqual(new BN(0x10040004004000).toNumber(), 0x10040004004000); + assert.deepEqual(new BN(-0x123456).toNumber(), -0x123456); + assert.deepEqual(new BN(-0x3ffffff).toNumber(), -0x3ffffff); + assert.deepEqual(new BN(-0x4000000).toNumber(), -0x4000000); + assert.deepEqual(new BN(-0x10000000000000).toNumber(), -0x10000000000000); + assert.deepEqual(new BN(-0x10040004004000).toNumber(), -0x10040004004000); + }); + + it('should throw when number exceeds 53 bits', function () { + var n = new BN(1).iushln(54); + assert.throws(function () { + n.toNumber(); + }, /^Error: Number can only safely store up to 53 bits$/); + }); + }); + + describe('.zeroBits()', function () { + it('should return proper zeroBits', function () { + assert.equal(new BN(0).zeroBits(), 0); + assert.equal(new BN(0x1).zeroBits(), 0); + assert.equal(new BN(0x2).zeroBits(), 1); + assert.equal(new BN(0x3).zeroBits(), 0); + assert.equal(new BN(0x4).zeroBits(), 2); + assert.equal(new BN(0x8).zeroBits(), 3); + assert.equal(new BN(0x10).zeroBits(), 4); + assert.equal(new BN(0x100).zeroBits(), 8); + assert.equal(new BN(0x1000000).zeroBits(), 24); + assert.equal(new BN(0x123456).zeroBits(), 1); + }); + }); + + describe('.toJSON', function () { + it('should return hex string', function () { + assert.equal(new BN(0x123).toJSON(), '123'); + }); + }); + + describe('.cmpn', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmpn(42), 0); + assert.equal(new BN(42).cmpn(43), -1); + assert.equal(new BN(42).cmpn(41), 1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffe), 0); + assert.equal(new BN(0x3fffffe).cmpn(0x3ffffff), -1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffd), 1); + assert.throws(function () { + new BN(0x3fffffe).cmpn(0x4000000); + }, /^Error: Number is too big$/); + assert.equal(new BN(42).cmpn(-42), 1); + assert.equal(new BN(-42).cmpn(42), -1); + assert.equal(new BN(-42).cmpn(-42), 0); + assert.equal(1 / new BN(-42).cmpn(-42), Infinity); + }); + }); + + describe('.cmp', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmp(new BN(42)), 0); + assert.equal(new BN(42).cmp(new BN(43)), -1); + assert.equal(new BN(42).cmp(new BN(41)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffe)), 0); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3ffffff)), -1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffd)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x4000000)), -1); + assert.equal(new BN(42).cmp(new BN(-42)), 1); + assert.equal(new BN(-42).cmp(new BN(42)), -1); + assert.equal(new BN(-42).cmp(new BN(-42)), 0); + assert.equal(1 / new BN(-42).cmp(new BN(-42)), Infinity); + }); + }); + + describe('comparison shorthands', function () { + it('.gtn greater than', function () { + assert.equal(new BN(3).gtn(2), true); + assert.equal(new BN(3).gtn(3), false); + assert.equal(new BN(3).gtn(4), false); + }); + it('.gt greater than', function () { + assert.equal(new BN(3).gt(new BN(2)), true); + assert.equal(new BN(3).gt(new BN(3)), false); + assert.equal(new BN(3).gt(new BN(4)), false); + }); + it('.gten greater than or equal', function () { + assert.equal(new BN(3).gten(3), true); + assert.equal(new BN(3).gten(2), true); + assert.equal(new BN(3).gten(4), false); + }); + it('.gte greater than or equal', function () { + assert.equal(new BN(3).gte(new BN(3)), true); + assert.equal(new BN(3).gte(new BN(2)), true); + assert.equal(new BN(3).gte(new BN(4)), false); + }); + it('.ltn less than', function () { + assert.equal(new BN(2).ltn(3), true); + assert.equal(new BN(2).ltn(2), false); + assert.equal(new BN(2).ltn(1), false); + }); + it('.lt less than', function () { + assert.equal(new BN(2).lt(new BN(3)), true); + assert.equal(new BN(2).lt(new BN(2)), false); + assert.equal(new BN(2).lt(new BN(1)), false); + }); + it('.lten less than or equal', function () { + assert.equal(new BN(3).lten(3), true); + assert.equal(new BN(3).lten(2), false); + assert.equal(new BN(3).lten(4), true); + }); + it('.lte less than or equal', function () { + assert.equal(new BN(3).lte(new BN(3)), true); + assert.equal(new BN(3).lte(new BN(2)), false); + assert.equal(new BN(3).lte(new BN(4)), true); + }); + it('.eqn equal', function () { + assert.equal(new BN(3).eqn(3), true); + assert.equal(new BN(3).eqn(2), false); + assert.equal(new BN(3).eqn(4), false); + }); + it('.eq equal', function () { + assert.equal(new BN(3).eq(new BN(3)), true); + assert.equal(new BN(3).eq(new BN(2)), false); + assert.equal(new BN(3).eq(new BN(4)), false); + }); + }); + + describe('.fromTwos', function () { + it('should convert from two\'s complement to negative number', function () { + assert.equal(new BN('00000000', 16).fromTwos(32).toNumber(), 0); + assert.equal(new BN('00000001', 16).fromTwos(32).toNumber(), 1); + assert.equal(new BN('7fffffff', 16).fromTwos(32).toNumber(), 2147483647); + assert.equal(new BN('80000000', 16).fromTwos(32).toNumber(), -2147483648); + assert.equal(new BN('f0000000', 16).fromTwos(32).toNumber(), -268435456); + assert.equal(new BN('f1234567', 16).fromTwos(32).toNumber(), -249346713); + assert.equal(new BN('ffffffff', 16).fromTwos(32).toNumber(), -1); + assert.equal(new BN('fffffffe', 16).fromTwos(32).toNumber(), -2); + assert.equal(new BN('fffffffffffffffffffffffffffffffe', 16) + .fromTwos(128).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'fffffffffffffffffffffffffffffffe', 16).fromTwos(256).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toNumber(), -1); + assert.equal(new BN('7fffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toString(10), + new BN('5789604461865809771178549250434395392663499' + + '2332820282019728792003956564819967', 10).toString(10)); + assert.equal(new BN('80000000000000000000000000000000' + + '00000000000000000000000000000000', 16).fromTwos(256).toString(10), + new BN('-578960446186580977117854925043439539266349' + + '92332820282019728792003956564819968', 10).toString(10)); + }); + }); + + describe('.toTwos', function () { + it('should convert from negative number to two\'s complement', function () { + assert.equal(new BN(0).toTwos(32).toString(16), '0'); + assert.equal(new BN(1).toTwos(32).toString(16), '1'); + assert.equal(new BN(2147483647).toTwos(32).toString(16), '7fffffff'); + assert.equal(new BN('-2147483648', 10).toTwos(32).toString(16), '80000000'); + assert.equal(new BN('-268435456', 10).toTwos(32).toString(16), 'f0000000'); + assert.equal(new BN('-249346713', 10).toTwos(32).toString(16), 'f1234567'); + assert.equal(new BN('-1', 10).toTwos(32).toString(16), 'ffffffff'); + assert.equal(new BN('-2', 10).toTwos(32).toString(16), 'fffffffe'); + assert.equal(new BN('-2', 10).toTwos(128).toString(16), + 'fffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-2', 10).toTwos(256).toString(16), + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-1', 10).toTwos(256).toString(16), + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('5789604461865809771178549250434395392663' + + '4992332820282019728792003956564819967', 10).toTwos(256).toString(16), + '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('-578960446186580977117854925043439539266' + + '34992332820282019728792003956564819968', 10).toTwos(256).toString(16), + '8000000000000000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('.isBN', function () { + it('should return true for BN', function () { + assert.equal(BN.isBN(new BN()), true); + }); + + it('should return false for everything else', function () { + assert.equal(BN.isBN(1), false); + assert.equal(BN.isBN([]), false); + assert.equal(BN.isBN({}), false); + }); + }); +}); diff --git a/test/merkletreejs/node_modules/bn.js/util/genCombMulTo.js b/test/merkletreejs/node_modules/bn.js/util/genCombMulTo.js new file mode 100644 index 0000000..8b456c7 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/util/genCombMulTo.js @@ -0,0 +1,65 @@ +'use strict'; + +// NOTE: This could be potentionally used to generate loop-less multiplications +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('var w' + k + ' = c;'); + src.push('c = 0;'); + for (var j = minJ; j <= maxJ; j++) { + i = k - j; + + src.push('lo = Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid = Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = Math.imul(ah' + i + ', bh' + j + ');'); + + src.push('w' + k + ' = (w' + k + ' + lo) | 0;'); + src.push('w' + k + ' = (w' + k + ' + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (c + hi) | 0;'); + src.push('c = (c + (mid >>> 13)) | 0;'); + src.push('c = (c + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/test/merkletreejs/node_modules/bn.js/util/genCombMulTo10.js b/test/merkletreejs/node_modules/bn.js/util/genCombMulTo10.js new file mode 100644 index 0000000..cf2e6e8 --- /dev/null +++ b/test/merkletreejs/node_modules/bn.js/util/genCombMulTo10.js @@ -0,0 +1,65 @@ +'use strict'; + +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');'); + src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');'); + src.push( + 'mid = (mid + Math.imul(ah' + (k - minJ) + ', bl' + minJ + ')) | 0;'); + src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');'); + + for (var j = minJ + 1; j <= maxJ; j++) { + i = k - j; + + src.push('lo = (lo + Math.imul(al' + i + ', bl' + j + ')) | 0;'); + src.push('mid = (mid + Math.imul(al' + i + ', bh' + j + ')) | 0;'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = (hi + Math.imul(ah' + i + ', bh' + j + ')) | 0;'); + } + + src.push('var w' + k + ' = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (((hi + (mid >>> 13)) | 0) + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/test/merkletreejs/node_modules/buffer-reverse/LICENSE b/test/merkletreejs/node_modules/buffer-reverse/LICENSE new file mode 100644 index 0000000..bba5218 --- /dev/null +++ b/test/merkletreejs/node_modules/buffer-reverse/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Daniel Cousens + +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. diff --git a/test/merkletreejs/node_modules/buffer-reverse/README.md b/test/merkletreejs/node_modules/buffer-reverse/README.md new file mode 100644 index 0000000..aafa348 --- /dev/null +++ b/test/merkletreejs/node_modules/buffer-reverse/README.md @@ -0,0 +1,37 @@ +# buffer-reverse + +[![NPM](http://img.shields.io/npm/v/buffer-reverse.svg)](https://www.npmjs.org/package/buffer-reverse) +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-reverse.png)](http://travis-ci.org/crypto-browserify/buffer-reverse) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A lite module for byte reverse on buffers. + + +## Examples + +``` javascript +var reverse = require("buffer-reverse") +var a = new Buffer('00ff0f', 'hex') + +console.log(reverse(a)) +// => +``` + + +Or for those seeking those few extra cycles, perform the operation in place: + +``` javascript +var reverseInplace = require("buffer-reverse/inplace") +var a = new Buffer('00ff0f', 'hex') + +console.log(reverseInplace(a)) +// => + +// See that a has been mutated +console.log(a) +// => +``` + + +## License [MIT](LICENSE) diff --git a/test/merkletreejs/node_modules/buffer-reverse/index.js b/test/merkletreejs/node_modules/buffer-reverse/index.js new file mode 100644 index 0000000..2ecd6f5 --- /dev/null +++ b/test/merkletreejs/node_modules/buffer-reverse/index.js @@ -0,0 +1,10 @@ +module.exports = function reverse (src) { + var buffer = new Buffer(src.length) + + for (var i = 0, j = src.length - 1; i <= j; ++i, --j) { + buffer[i] = src[j] + buffer[j] = src[i] + } + + return buffer +} diff --git a/test/merkletreejs/node_modules/buffer-reverse/inplace.js b/test/merkletreejs/node_modules/buffer-reverse/inplace.js new file mode 100644 index 0000000..feeea1c --- /dev/null +++ b/test/merkletreejs/node_modules/buffer-reverse/inplace.js @@ -0,0 +1,10 @@ +module.exports = function reverseInplace (buffer) { + for (var i = 0, j = buffer.length - 1; i < j; ++i, --j) { + var t = buffer[j] + + buffer[j] = buffer[i] + buffer[i] = t + } + + return buffer +} diff --git a/test/merkletreejs/node_modules/buffer-reverse/package.json b/test/merkletreejs/node_modules/buffer-reverse/package.json new file mode 100644 index 0000000..843c65a --- /dev/null +++ b/test/merkletreejs/node_modules/buffer-reverse/package.json @@ -0,0 +1,41 @@ +{ + "name": "buffer-reverse", + "version": "1.0.1", + "description": "A lite module for reverse-operations on buffers", + "files": [ + "index.js", + "inplace.js" + ], + "main": "index.js", + "scripts": { + "standard": "standard", + "test": "npm run-script standard && npm run-script unit", + "unit": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/crypto-browserify/buffer-reverse.git" + }, + "bugs": { + "url": "https://github.com/crypto-browserify/buffer-reverse/issues" + }, + "homepage": "https://github.com/crypto-browserify/buffer-reverse", + "keywords": [ + "bits", + "reverse", + "buffer", + "buffer-reverse", + "crypto", + "inline", + "math", + "memory", + "performance", + "reverse" + ], + "author": "Daniel Cousens", + "license": "MIT", + "devDependencies": { + "standard": "*", + "tape": "*" + } +} diff --git a/test/merkletreejs/node_modules/call-bind/.eslintignore b/test/merkletreejs/node_modules/call-bind/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/test/merkletreejs/node_modules/call-bind/.eslintrc b/test/merkletreejs/node_modules/call-bind/.eslintrc new file mode 100644 index 0000000..dfa9a6c --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-magic-numbers": 0, + }, +} diff --git a/test/merkletreejs/node_modules/call-bind/.github/FUNDING.yml b/test/merkletreejs/node_modules/call-bind/.github/FUNDING.yml new file mode 100644 index 0000000..c70c2ec --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/call-bind/.nycrc b/test/merkletreejs/node_modules/call-bind/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/call-bind/CHANGELOG.md b/test/merkletreejs/node_modules/call-bind/CHANGELOG.md new file mode 100644 index 0000000..717bcc3 --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/CHANGELOG.md @@ -0,0 +1,77 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.5](https://github.com/ljharb/call-bind/compare/v1.0.4...v1.0.5) - 2023-10-19 + +### Commits + +- [Fix] throw an error on non-functions as early as possible [`f262408`](https://github.com/ljharb/call-bind/commit/f262408f822c840fbc268080f3ad7c429611066d) +- [Deps] update `set-function-length` [`3fff271`](https://github.com/ljharb/call-bind/commit/3fff27145a1e3a76a5b74f1d7c3c43d0fa3b9871) + +## [v1.0.4](https://github.com/ljharb/call-bind/compare/v1.0.3...v1.0.4) - 2023-10-19 + +## [v1.0.3](https://github.com/ljharb/call-bind/compare/v1.0.2...v1.0.3) - 2023-10-19 + +### Commits + +- [actions] reuse common workflows [`a994df6`](https://github.com/ljharb/call-bind/commit/a994df69f401f4bf735a4ccd77029b85d1549453) +- [meta] use `npmignore` to autogenerate an npmignore file [`eef3ef2`](https://github.com/ljharb/call-bind/commit/eef3ef21e1f002790837fedb8af2679c761fbdf5) +- [readme] flesh out content [`1845ccf`](https://github.com/ljharb/call-bind/commit/1845ccfd9976a607884cfc7157c93192cc16cf22) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`5b47d53`](https://github.com/ljharb/call-bind/commit/5b47d53d2fd74af5ea0a44f1d51e503cd42f7a90) +- [Refactor] use `set-function-length` [`a0e165c`](https://github.com/ljharb/call-bind/commit/a0e165c5dc61db781cbc919b586b1c2b8da0b150) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`9c50103`](https://github.com/ljharb/call-bind/commit/9c50103f44137279a817317cf6cc421a658f85b4) +- [meta] simplify "exports" [`019c6d0`](https://github.com/ljharb/call-bind/commit/019c6d06b0e1246ceed8e579f57e44441cbbf6d9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`23bd718`](https://github.com/ljharb/call-bind/commit/23bd718a288d3b03042062b4ef5153b3cea83f11) +- [actions] update codecov uploader [`62552d7`](https://github.com/ljharb/call-bind/commit/62552d79cc79e05825e99aaba134ae5b37f33da5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ec81665`](https://github.com/ljharb/call-bind/commit/ec81665b300f87eabff597afdc8b8092adfa7afd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`35d67fc`](https://github.com/ljharb/call-bind/commit/35d67fcea883e686650f736f61da5ddca2592de8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`0266d8d`](https://github.com/ljharb/call-bind/commit/0266d8d2a45086a922db366d0c2932fa463662ff) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`43a5b28`](https://github.com/ljharb/call-bind/commit/43a5b28a444e710e1bbf92adb8afb5cf7523a223) +- [Deps] update `define-data-property`, `function-bind`, `get-intrinsic` [`780eb36`](https://github.com/ljharb/call-bind/commit/780eb36552514f8cc99c70821ce698697c2726a5) +- [Dev Deps] update `aud`, `tape` [`90d50ad`](https://github.com/ljharb/call-bind/commit/90d50ad03b061e0268b3380b0065fcaec183dc05) +- [meta] use `prepublishOnly` script for npm 7+ [`44c5433`](https://github.com/ljharb/call-bind/commit/44c5433b7980e02b4870007046407cf6fc543329) +- [Deps] update `get-intrinsic` [`86bfbfc`](https://github.com/ljharb/call-bind/commit/86bfbfcf34afdc6eabc93ce3d408548d0e27d958) +- [Deps] update `get-intrinsic` [`5c53354`](https://github.com/ljharb/call-bind/commit/5c5335489be0294c18cd7a8bb6e08226ee019ff5) +- [actions] update checkout action [`4c393a8`](https://github.com/ljharb/call-bind/commit/4c393a8173b3c8e5b30d5b3297b3b94d48bf87f3) +- [Deps] update `get-intrinsic` [`4e70bde`](https://github.com/ljharb/call-bind/commit/4e70bdec0626acb11616d66250fc14565e716e91) +- [Deps] update `get-intrinsic` [`55ae803`](https://github.com/ljharb/call-bind/commit/55ae803a920bd93c369cd798c20de31f91e9fc60) + +## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11 + +### Commits + +- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d) + +## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1) +- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e) +- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb) +- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71) +- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee) +- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2) +- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8) +- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6) + +## v1.0.0 - 2020-10-30 + +### Commits + +- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50) +- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df) +- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65) +- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13) +- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4) +- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717) +- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af) +- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650) +- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f) diff --git a/test/merkletreejs/node_modules/call-bind/LICENSE b/test/merkletreejs/node_modules/call-bind/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/call-bind/README.md b/test/merkletreejs/node_modules/call-bind/README.md new file mode 100644 index 0000000..48e9047 --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/README.md @@ -0,0 +1,64 @@ +# call-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly `.call.bind()` a function. + +## Getting started + +```sh +npm install --save call-bind +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBind = require('call-bind'); +const callBound = require('call-bind/callBound'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBind(f); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(1, 2, 3); + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind.svg +[deps-url]: https://david-dm.org/ljharb/call-bind +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind +[codecov-image]: https://codecov.io/gh/ljharb/call-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind +[actions-url]: https://github.com/ljharb/call-bind/actions diff --git a/test/merkletreejs/node_modules/call-bind/callBound.js b/test/merkletreejs/node_modules/call-bind/callBound.js new file mode 100644 index 0000000..8374adf --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/test/merkletreejs/node_modules/call-bind/index.js b/test/merkletreejs/node_modules/call-bind/index.js new file mode 100644 index 0000000..184ee2b --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/index.js @@ -0,0 +1,44 @@ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); +var setFunctionLength = require('set-function-length'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} diff --git a/test/merkletreejs/node_modules/call-bind/package.json b/test/merkletreejs/node_modules/call-bind/package.json new file mode 100644 index 0000000..f946e1a --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/package.json @@ -0,0 +1,90 @@ +{ + "name": "call-bind", + "version": "1.0.5", + "description": "Robustly `.call.bind()` a function", + "main": "index.js", + "exports": { + ".": "./index.js", + "./callBound": "./callBound.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-strict-mode": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "dependencies": { + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.1", + "set-function-length": "^1.1.1" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/call-bind/test/callBound.js b/test/merkletreejs/node_modules/call-bind/test/callBound.js new file mode 100644 index 0000000..c32319d --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/test/callBound.js @@ -0,0 +1,54 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../callBound'); + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + // prototype function + t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/call-bind/test/index.js b/test/merkletreejs/node_modules/call-bind/test/index.js new file mode 100644 index 0000000..1fd4668 --- /dev/null +++ b/test/merkletreejs/node_modules/call-bind/test/index.js @@ -0,0 +1,80 @@ +'use strict'; + +var callBind = require('../'); +var bind = require('function-bind'); +var gOPD = require('gopd'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +/* + * older engines have length nonconfigurable + * in io.js v3, it is configurable except on bound functions, hence the .bind() + */ +var functionsHaveConfigurableLengths = !!( + gOPD + && Object.getOwnPropertyDescriptor + && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable +); + +test('callBind', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { callBind(nonFunction); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + + var bound = callBind(func); + t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + + var boundR = callBind(func, sentinel); + t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + + var boundArg = callBind(func, sentinel, 1); + t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.test('callBind.apply', function (st) { + var aBound = callBind.apply(func); + st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); + st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + + var aBoundArg = callBind.apply(func); + st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); + st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + + var aBoundR = callBind.apply(func, sentinel); + st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); + st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); + st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); + + st.end(); + }); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/crc-32/LICENSE b/test/merkletreejs/node_modules/crc-32/LICENSE new file mode 100644 index 0000000..5723c45 --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (C) 2014-present SheetJS LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/test/merkletreejs/node_modules/crc-32/README.md b/test/merkletreejs/node_modules/crc-32/README.md new file mode 100644 index 0000000..082127a --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/README.md @@ -0,0 +1,200 @@ +# crc32 + +Standard CRC-32 algorithm implementation in JS (for the browser and nodejs). +Emphasis on correctness, performance, and IE6+ support. + +## Installation + +With [npm](https://www.npmjs.org/package/crc-32): + +```bash +$ npm install crc-32 +``` + +When installed globally, npm installs a script `crc32` that computes the +checksum for a specified file or standard input. + +
+ CDN Availability (click to show) + +| CDN | URL | +|-----------:|:-------------------------------------------| +| `unpkg` | | +| `jsDelivr` | | +| `CDNjs` | | + +
+ + +## Integration + +Using NodeJS or a bundler: + +```js +var CRC32 = require("crc-32"); +``` + +In the browser, the `crc32.js` script can be loaded directly: + +```html + +``` + +The browser script exposes a variable `CRC32`. + +The script will manipulate `module.exports` if available . This is not always +desirable. To prevent the behavior, define `DO_NOT_EXPORT_CRC`. + +### CRC32C (Castagnoli) + +The module and CDNs also include a parallel script for CRC32C calculations. + +Using NodeJS or a bundler: + +```js +var CRC32C = require("crc-32/crc32c"); +``` + +In the browser, the `crc32c.js` script can be loaded directly: + +```html + +``` + +The browser exposes a variable `CRC32C`. + +The script will manipulate `module.exports` if available . This is not always +desirable. To prevent the behavior, define `DO_NOT_EXPORT_CRC`. + +## Usage + +In all cases, the relevant function takes an argument representing data and an +optional second argument representing the starting "seed" (for rolling CRC). + +The return value is a signed 32-bit integer. + +- `CRC32.buf(byte array or buffer[, seed])` assumes the argument is a sequence + of 8-bit unsigned integers (nodejs `Buffer`, `Uint8Array` or array of bytes). + +- `CRC32.bstr(binary string[, seed])` assumes the argument is a binary string + where byte `i` is the low byte of the UCS-2 char: `str.charCodeAt(i) & 0xFF` + +- `CRC32.str(string[, seed])` assumes the argument is a standard JS string and + calculates the hash of the UTF-8 encoding. + +For example: + +```js +// var CRC32 = require('crc-32'); // uncomment this line if in node +CRC32.str("SheetJS") // -1647298270 +CRC32.bstr("SheetJS") // -1647298270 +CRC32.buf([ 83, 104, 101, 101, 116, 74, 83 ]) // -1647298270 + +crc32 = CRC32.buf([83, 104]) // -1826163454 "Sh" +crc32 = CRC32.str("eet", crc32) // 1191034598 "Sheet" +CRC32.bstr("JS", crc32) // -1647298270 "SheetJS" + +[CRC32.str("\u2603"), CRC32.str("\u0003")] // [ -1743909036, 1259060791 ] +[CRC32.bstr("\u2603"), CRC32.bstr("\u0003")] // [ 1259060791, 1259060791 ] +[CRC32.buf([0x2603]), CRC32.buf([0x0003])] // [ 1259060791, 1259060791 ] + +// var CRC32C = require('crc-32/crc32c'); // uncomment this line if in node +CRC32C.str("SheetJS") // -284764294 +CRC32C.bstr("SheetJS") // -284764294 +CRC32C.buf([ 83, 104, 101, 101, 116, 74, 83 ]) // -284764294 + +crc32c = CRC32C.buf([83, 104]) // -297065629 "Sh" +crc32c = CRC32C.str("eet", crc32c) // 1241364256 "Sheet" +CRC32C.bstr("JS", crc32c) // -284764294 "SheetJS" + +[CRC32C.str("\u2603"), CRC32C.str("\u0003")] // [ 1253703093, 1093509285 ] +[CRC32C.bstr("\u2603"), CRC32C.bstr("\u0003")] // [ 1093509285, 1093509285 ] +[CRC32C.buf([0x2603]), CRC32C.buf([0x0003])] // [ 1093509285, 1093509285 ] +``` + +### Best Practices + +Even though the initial seed is optional, for performance reasons it is highly +recommended to explicitly pass the default seed 0. + +In NodeJS with the native Buffer implementation, it is oftentimes faster to +convert binary strings with `Buffer.from(bstr, "binary")` first: + +```js +/* Frequently slower in NodeJS */ +crc32 = CRC32.bstr(bstr, 0); +/* Frequently faster in NodeJS */ +crc32 = CRC32.buf(Buffer.from(bstr, "binary"), 0); +``` + +This does not apply to browser `Buffer` shims, and thus is not implemented in +the library directly. + +## Testing + +`make test` will run the nodejs-based test. + +To run the in-browser tests, run a local server and go to the `ctest` directory. +`make ctestserv` will start a python `SimpleHTTPServer` server on port 8000. + +To update the browser artifacts, run `make ctest`. + +To generate the bits file, use the `crc32` function from python `zlib`: + +```python +>>> from zlib import crc32 +>>> x="foo bar baz٪☃🍣" +>>> crc32(x) +1531648243 +>>> crc32(x+x) +-218791105 +>>> crc32(x+x+x) +1834240887 +``` + +The included `crc32.njs` script can process files or standard input: + +```bash +$ echo "this is a test" > t.txt +$ bin/crc32.njs t.txt +1912935186 +``` + +For comparison, the included `crc32.py` script uses python `zlib`: + +```bash +$ bin/crc32.py t.txt +1912935186 +``` + +On OSX the command `cksum` generates unsigned CRC-32 with Algorithm 3: + +```bash +$ cksum -o 3 < IE8.Win7.For.Windows.VMware.zip +1891069052 4161613172 +$ crc32 --unsigned ~/Downloads/IE8.Win7.For.Windows.VMware.zip +1891069052 +``` + +## Performance + +`make perf` will run algorithmic performance tests (which should justify certain +decisions in the code). + +The [`adler-32` project](http://git.io/adler32) has more performance notes + +## License + +Please consult the attached LICENSE file for details. All rights not explicitly +granted by the Apache 2.0 license are reserved by the Original Author. + +## Badges + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/crc32.svg)](https://saucelabs.com/u/crc32) + +[![Build Status](https://travis-ci.org/SheetJS/js-crc32.svg?branch=master)](https://travis-ci.org/SheetJS/js-crc32) +[![Coverage Status](http://img.shields.io/coveralls/SheetJS/js-crc32/master.svg)](https://coveralls.io/r/SheetJS/js-crc32?branch=master) +[![Dependencies Status](https://david-dm.org/sheetjs/js-crc32/status.svg)](https://david-dm.org/sheetjs/js-crc32) +[![NPM Downloads](https://img.shields.io/npm/dt/crc-32.svg)](https://npmjs.org/package/crc-32) +[![ghit.me](https://ghit.me/badge.svg?repo=sheetjs/js-xlsx)](https://ghit.me/repo/sheetjs/js-xlsx) +[![Analytics](https://ga-beacon.appspot.com/UA-36810333-1/SheetJS/js-crc32?pixel)](https://github.com/SheetJS/js-crc32) diff --git a/test/merkletreejs/node_modules/crc-32/bin/crc32.njs b/test/merkletreejs/node_modules/crc-32/bin/crc32.njs new file mode 100755 index 0000000..334e7d2 --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/bin/crc32.njs @@ -0,0 +1,105 @@ +#!/usr/bin/env node +/* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +/* eslint-env node */ +/* vim: set ts=2 ft=javascript: */ +/*jshint node:true */ + +var X/*:CRC32Module*/; +try { X = require('../'); } catch(e) { X = require('crc-32'); } + +function help()/*:number*/ { +[ +"usage: crc32 [options] [filename]", +"", +"Options:", +" -h, --help output usage information", +" -V, --version output the version number", +" -S, --seed= use integer seed as starting value (rolling CRC)", +" -H, --hex-seed= use hex seed as starting value (rolling CRC)", +" -d, --signed print result with format `%d` (default)", +" -u, --unsigned print result with format `%u`", +" -x, --hex print result with format `%0.8x`", +" -X, --HEX print result with format `%0.8X`", +" -c, --crc32c use CRC32C (Castagnoli)", +" -F, --format= use specified printf format", +"", +"Set filename = '-' or pipe data into crc32 to read from stdin", +"Default output mode is signed (-d)", +"" +].forEach(function(l) { console.log(l); }); + return 0; +} + +function version()/*:number*/ { console.log(X.version); return 0; } + +var fs = require('fs'); +try { require('exit-on-epipe'); } catch(e) {} + +function die(msg/*:string*/, ec/*:?number*/)/*:void*/ { console.error(msg); process.exit(ec || 0); } + +var args/*:Array*/ = process.argv.slice(2); +var filename/*:string*/ = ""; +var fmt/*:string*/ = ""; +var seed = 0, r = 10; + +for(var i = 0; i < args.length; ++i) { + var arg = args[i]; + if(arg.charCodeAt(0) != 45) { if(filename === "") filename = arg; continue; } + var m = arg.indexOf("=") == -1 ? arg : arg.substr(0, arg.indexOf("=")); + switch(m) { + case "-": filename = "-"; break; + + case "--help": case "-h": process.exit(help()); break; + case "--version": case "-V": process.exit(version()); break; + + case "--crc32c": case "-c": try { X = require('../crc32c'); } catch(e) { X = require('crc-32/crc32c'); } break; + + case "--signed": case "-d": fmt = "%d"; break; + case "--unsigned": case "-u": fmt = "%u"; break; + case "--hex": case "-x": fmt = "%0.8x"; break; + case "--HEX": case "-X": fmt = "%0.8X"; break; + case "--format": case "-F": + try { + require("printj"); + fmt = ((m!=arg) ? arg.substr(m.length+1) : args[++i])||""; + } catch(e) { + console.error("The `crc-32` module removed the `printj` dependency for formatting"); + console.error("Use the `crc32-cli` module instead:"); + console.error(" $ npx crc32-cli [options] [filename]"); + } break; + + case "--hex-seed": case "-H": r = 16; + /* falls through */ + case "--seed": case "-S": + seed=parseInt((m!=arg) ? arg.substr(m.length+1) : args[++i], r)||0; break; + + default: die("crc32: unrecognized option `" + arg + "'", 22); + } +} + +if(!process.stdin.isTTY) filename = filename || "-"; +if(filename.length===0) die("crc32: must specify a filename ('-' for stdin)",1); + +var crc32 = seed; +// $FlowIgnore -- Writable is callable but type sig disagrees +var writable = require('stream').Writable(); +writable._write = function(chunk, e, cb) { crc32 = X.buf(chunk, crc32); cb(); }; +writable._writev = function(chunks, cb) { + chunks.forEach(function(c) { crc32 = X.buf(c.chunk, crc32);}); + cb(); +}; +writable.on('finish', function() { + if(fmt === "") console.log(crc32); + else try { console.log(require("printj").sprintf(fmt, crc32)); } catch(e) { + switch(fmt) { + case "%d": console.log(crc32); break; + case "%u": console.log(crc32 >>> 0); break; + case "%0.8x": console.log((crc32 >>> 0).toString(16).padStart(8, "0").toLowerCase()); break; + case "%0.8X": console.log((crc32 >>> 0).toString(16).padStart(8, "0").toUpperCase()); break; + } + } +}); + +if(filename === "-") process.stdin.pipe(writable); +else if(fs.existsSync(filename)) fs.createReadStream(filename).pipe(writable); +else die("crc32: " + filename + ": No such file or directory", 2); diff --git a/test/merkletreejs/node_modules/crc-32/crc32.js b/test/merkletreejs/node_modules/crc-32/crc32.js new file mode 100644 index 0000000..c92664a --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/crc32.js @@ -0,0 +1,115 @@ +/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +/* vim: set ts=2: */ +/*exported CRC32 */ +var CRC32; +(function (factory) { + /*jshint ignore:start */ + /*eslint-disable */ + if(typeof DO_NOT_EXPORT_CRC === 'undefined') { + if('object' === typeof exports) { + factory(exports); + } else if ('function' === typeof define && define.amd) { + define(function () { + var module = {}; + factory(module); + return module; + }); + } else { + factory(CRC32 = {}); + } + } else { + factory(CRC32 = {}); + } + /*eslint-enable */ + /*jshint ignore:end */ +}(function(CRC32) { +CRC32.version = '1.2.2'; +/*global Int32Array */ +function signed_crc_table() { + var c = 0, table = new Array(256); + + for(var n =0; n != 256; ++n){ + c = n; + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + table[n] = c; + } + + return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; +} + +var T0 = signed_crc_table(); +function slice_by_16_tables(T) { + var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; + + for(n = 0; n != 256; ++n) table[n] = T[n]; + for(n = 0; n != 256; ++n) { + v = T[n]; + for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; + } + var out = []; + for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); + return out; +} +var TT = slice_by_16_tables(T0); +var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; +var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; +var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; +function crc32_bstr(bstr, seed) { + var C = seed ^ -1; + for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; + return ~C; +} + +function crc32_buf(B, seed) { + var C = seed ^ -1, L = B.length - 15, i = 0; + for(; i < L;) C = + Tf[B[i++] ^ (C & 255)] ^ + Te[B[i++] ^ ((C >> 8) & 255)] ^ + Td[B[i++] ^ ((C >> 16) & 255)] ^ + Tc[B[i++] ^ (C >>> 24)] ^ + Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ + T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ + T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; + L += 15; + while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; + return ~C; +} + +function crc32_str(str, seed) { + var C = seed ^ -1; + for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { + c = str.charCodeAt(i++); + if(c < 0x80) { + C = (C>>>8) ^ T0[(C^c)&0xFF]; + } else if(c < 0x800) { + C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } else if(c >= 0xD800 && c < 0xE000) { + c = (c&1023)+64; d = str.charCodeAt(i++)&1023; + C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; + } else { + C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } + } + return ~C; +} +CRC32.table = T0; +// $FlowIgnore +CRC32.bstr = crc32_bstr; +// $FlowIgnore +CRC32.buf = crc32_buf; +// $FlowIgnore +CRC32.str = crc32_str; +})); diff --git a/test/merkletreejs/node_modules/crc-32/crc32c.js b/test/merkletreejs/node_modules/crc-32/crc32c.js new file mode 100644 index 0000000..447fc8f --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/crc32c.js @@ -0,0 +1,115 @@ +/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +/* vim: set ts=2: */ +/*exported CRC32C */ +var CRC32C; +(function (factory) { + /*jshint ignore:start */ + /*eslint-disable */ + if(typeof DO_NOT_EXPORT_CRC === 'undefined') { + if('object' === typeof exports) { + factory(exports); + } else if ('function' === typeof define && define.amd) { + define(function () { + var module = {}; + factory(module); + return module; + }); + } else { + factory(CRC32C = {}); + } + } else { + factory(CRC32C = {}); + } + /*eslint-enable */ + /*jshint ignore:end */ +}(function(CRC32C) { +CRC32C.version = '1.2.2'; +/*global Int32Array */ +function signed_crc_table() { + var c = 0, table = new Array(256); + + for(var n =0; n != 256; ++n){ + c = n; + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-2097792136 ^ (c >>> 1)) : (c >>> 1)); + table[n] = c; + } + + return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; +} + +var T0 = signed_crc_table(); +function slice_by_16_tables(T) { + var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; + + for(n = 0; n != 256; ++n) table[n] = T[n]; + for(n = 0; n != 256; ++n) { + v = T[n]; + for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; + } + var out = []; + for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); + return out; +} +var TT = slice_by_16_tables(T0); +var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; +var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; +var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; +function crc32_bstr(bstr, seed) { + var C = seed ^ -1; + for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; + return ~C; +} + +function crc32_buf(B, seed) { + var C = seed ^ -1, L = B.length - 15, i = 0; + for(; i < L;) C = + Tf[B[i++] ^ (C & 255)] ^ + Te[B[i++] ^ ((C >> 8) & 255)] ^ + Td[B[i++] ^ ((C >> 16) & 255)] ^ + Tc[B[i++] ^ (C >>> 24)] ^ + Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ + T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ + T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; + L += 15; + while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; + return ~C; +} + +function crc32_str(str, seed) { + var C = seed ^ -1; + for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { + c = str.charCodeAt(i++); + if(c < 0x80) { + C = (C>>>8) ^ T0[(C^c)&0xFF]; + } else if(c < 0x800) { + C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } else if(c >= 0xD800 && c < 0xE000) { + c = (c&1023)+64; d = str.charCodeAt(i++)&1023; + C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; + } else { + C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } + } + return ~C; +} +CRC32C.table = T0; +// $FlowIgnore +CRC32C.bstr = crc32_bstr; +// $FlowIgnore +CRC32C.buf = crc32_buf; +// $FlowIgnore +CRC32C.str = crc32_str; +})); diff --git a/test/merkletreejs/node_modules/crc-32/package.json b/test/merkletreejs/node_modules/crc-32/package.json new file mode 100644 index 0000000..a523291 --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/package.json @@ -0,0 +1,43 @@ +{ + "name": "crc-32", + "version": "1.2.2", + "author": "sheetjs", + "description": "Pure-JS CRC-32", + "keywords": [ "crc", "crc32", "checksum" ], + "bin": { + "crc32": "bin/crc32.njs" + }, + "main": "crc32.js", + "types": "types/index.d.ts", + "typesVersions": { "*": { "*": ["types/index.d.ts" ] } }, + "dependencies": { + }, + "devDependencies": { + "printj": "~1.3.1", + "exit-on-epipe": "~1.0.1", + "mocha": "~2.5.3", + "blanket": "~1.2.3", + "codepage": "~1.10.0", + "@sheetjs/uglify-js": "~2.7.3", + "@types/node": "^8.0.7", + "dtslint": "^0.1.2", + "typescript": "2.2.0" + }, + "repository": { "type": "git", "url": "git://github.com/SheetJS/js-crc32.git" }, + "scripts": { + "test": "make test", + "build": "make", + "lint": "make fullint", + "dtslint": "dtslint types" + }, + "config": { + "blanket": { + "pattern": "crc32.js" + } + }, + "homepage": "https://sheetjs.com/", + "files": ["crc32.js", "crc32c.js", "bin/crc32.njs", "LICENSE", "README.md", "types/index.d.ts", "types/*.json"], + "bugs": { "url": "https://github.com/SheetJS/js-crc32/issues" }, + "license": "Apache-2.0", + "engines": { "node": ">=0.8" } +} diff --git a/test/merkletreejs/node_modules/crc-32/types/index.d.ts b/test/merkletreejs/node_modules/crc-32/types/index.d.ts new file mode 100644 index 0000000..1638690 --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/types/index.d.ts @@ -0,0 +1,14 @@ +/* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +// TypeScript Version: 2.2 + +/** Version string */ +export const version: string; + +/** Process a node buffer or byte array */ +export function buf(data: number[] | Uint8Array, seed?: number): number; + +/** Process a binary string */ +export function bstr(data: string, seed?: number): number; + +/** Process a JS string based on the UTF8 encoding */ +export function str(data: string, seed?: number): number; diff --git a/test/merkletreejs/node_modules/crc-32/types/tsconfig.json b/test/merkletreejs/node_modules/crc-32/types/tsconfig.json new file mode 100644 index 0000000..6e122c7 --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/types/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ "es5" ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": ".", + "paths": { "crc-32": ["."] }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/test/merkletreejs/node_modules/crc-32/types/tslint.json b/test/merkletreejs/node_modules/crc-32/types/tslint.json new file mode 100644 index 0000000..d9401a9 --- /dev/null +++ b/test/merkletreejs/node_modules/crc-32/types/tslint.json @@ -0,0 +1,11 @@ +{ + "extends": "dtslint/dtslint.json", + "rules": { + "whitespace": false, + "no-sparse-arrays": false, + "only-arrow-functions": false, + "no-consecutive-blank-lines": false, + "prefer-conditional-expression": false, + "one-variable-per-declaration": false + } +} diff --git a/test/merkletreejs/node_modules/cross-fetch/CHANGELOG.md b/test/merkletreejs/node_modules/cross-fetch/CHANGELOG.md new file mode 100644 index 0000000..2e432a6 --- /dev/null +++ b/test/merkletreejs/node_modules/cross-fetch/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [4.0.0](https://github.com/lquixada/cross-fetch/compare/v4.0.0-alpha.13...v4.0.0) (2023-07-03) diff --git a/test/merkletreejs/node_modules/cross-fetch/LICENSE b/test/merkletreejs/node_modules/cross-fetch/LICENSE new file mode 100644 index 0000000..9198b86 --- /dev/null +++ b/test/merkletreejs/node_modules/cross-fetch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Leonardo Quixadá + +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. diff --git a/test/merkletreejs/node_modules/cross-fetch/README.md b/test/merkletreejs/node_modules/cross-fetch/README.md new file mode 100644 index 0000000..5e38a16 --- /dev/null +++ b/test/merkletreejs/node_modules/cross-fetch/README.md @@ -0,0 +1,165 @@ +cross-fetch
+[![NPM Version](https://img.shields.io/npm/v/cross-fetch.svg?branch=main)](https://www.npmjs.com/package/cross-fetch) +[![Downloads Per Week](https://img.shields.io/npm/dw/cross-fetch.svg?color=blue)](https://www.npmjs.com/package/cross-fetch) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) +[![CI](https://github.com/lquixada/cross-fetch/actions/workflows/ci.yml/badge.svg)](https://github.com/lquixada/cross-fetch/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/lquixada/cross-fetch/branch/main/graph/badge.svg)](https://codecov.io/gh/lquixada/cross-fetch) +================ + +Universal WHATWG Fetch API for Node, Browsers, Workers and React Native. The scenario that cross-fetch really shines is when the same JavaScript codebase needs to run on different platforms. + +- **Platform agnostic**: browsers, Node or React Native +- **Optional polyfill**: it's up to you if something is going to be added to the global object or not +- **Simple interface**: no instantiation, no configuration and no extra dependency +- **WHATWG compliant**: it works the same way wherever your code runs +- **TypeScript support**: better development experience with types. +- **Worker support**: works on different types of workers such as Service Workers and CloudFlare Workers + + +* * * + +## Table of Contents + +- [Table of Contents](#table-of-contents) +- [Install](#install) +- [Usage](#usage) +- [Demo \& API](#demo--api) +- [FAQ](#faq) + - [Yet another fetch library?](#yet-another-fetch-library) + - [Why polyfill might not be a good idea?](#why-polyfill-might-not-be-a-good-idea) + - [How does cross-fetch work?](#how-does-cross-fetch-work) +- [Who's Using It?](#whos-using-it) +- [Thanks](#thanks) +- [License](#license) +- [Author](#author) + +* * * + +## Install + +```sh +npm install --save cross-fetch +``` + +As a [ponyfill](https://github.com/sindresorhus/ponyfill) (imports locally): + +```javascript +// Using ES6 modules with Babel or TypeScript +import fetch from 'cross-fetch'; + +// Using CommonJS modules +const fetch = require('cross-fetch'); +``` + +As a polyfill (installs globally): + +```javascript +// Using ES6 modules +import 'cross-fetch/polyfill'; + +// Using CommonJS modules +require('cross-fetch/polyfill'); +``` + + +The CDN build is also available on unpkg: + +```html + +``` + +This adds the fetch function to the window object. Note that this is not UMD compatible. + + +* * * + +## Usage + +With [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise): + +```javascript +import fetch from 'cross-fetch'; +// Or just: import 'cross-fetch/polyfill'; + +fetch('//api.github.com/users/lquixada') + .then(res => { + if (res.status >= 400) { + throw new Error("Bad response from server"); + } + return res.json(); + }) + .then(user => { + console.log(user); + }) + .catch(err => { + console.error(err); + }); +``` + +With [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function): + +```javascript +import fetch from 'cross-fetch'; +// Or just: import 'cross-fetch/polyfill'; + +(async () => { + try { + const res = await fetch('//api.github.com/users/lquixada'); + + if (res.status >= 400) { + throw new Error("Bad response from server"); + } + + const user = await res.json(); + + console.log(user); + } catch (err) { + console.error(err); + } +})(); +``` + +## Demo & API + +You can find a comprehensive doc at [Github's fetch](https://github.github.io/fetch/) page. If you want to play with cross-fetch, check our [**JSFiddle playground**](https://jsfiddle.net/lquixada/3ypqgacp/). + +> **Tip**: Run the fiddle on various browsers and with different settings (for instance: cross-domain requests, wrong urls or text requests). Don't forget to open the console in the test suite page and play around. + + +## FAQ + +#### Yet another fetch library? + +I did a lot of research in order to find a fetch library that could be simple, cross-platform and provide polyfill as an option. There's a plethora of libs out there but none could match those requirements. + +#### Why polyfill might not be a good idea? + +In a word? Risk. If the spec changes in the future, it might be problematic to debug. Read more about it on [sindresorhus's ponyfill](https://github.com/sindresorhus/ponyfill#how-are-ponyfills-better-than-polyfills) page. It's up to you if you're fine with it or not. + +#### How does cross-fetch work? + +Just like isomorphic-fetch, it is just a proxy. If you're in node, it delivers you the [node-fetch](https://github.com/bitinn/node-fetch/) library, if you're in a browser or React Native, it delivers you the github's [whatwg-fetch](https://github.com/github/fetch/). The same strategy applies whether you're using polyfill or ponyfill. + + +## Who's Using It? + +|[![The New York Times](./docs/images/logo-nytimes.png)](https://www.nytimes.com/)|[![Apollo GraphQL](./docs/images/logo-apollo.png)](https://github.com/apollographql/apollo-client/)|[![Facebook](./docs/images/logo-facebook.png)](https://github.com/facebook/fbjs/)|[![Swagger](./docs/images/logo-swagger.png)](https://swagger.io/)|[![VulcanJS](./docs/images/logo-vulcanjs.png)](http://vulcanjs.org)|[![graphql-request](./docs/images/logo-graphql-request.png)](https://github.com/prisma/graphql-request)| +|:---:|:---:|:---:|:---:|:---:|:---:| +|The New York Times|Apollo GraphQL|Facebook|Swagger|VulcanJS|graphql-request| + + +## Thanks + +Heavily inspired by the works of [matthew-andrews](https://github.com/matthew-andrews). Kudos to him! + + +## License + +cross-fetch is licensed under the [MIT license](https://github.com/lquixada/cross-fetch/blob/main/LICENSE) © [Leonardo Quixadá](https://twitter.com/lquixada/) + + +## Author + +|[![@lquixada](https://avatars0.githubusercontent.com/u/195494?v=4&s=96)](https://github.com/lquixada)| +|:---:| +|[@lquixada](http://www.github.com/lquixada)| diff --git a/test/merkletreejs/node_modules/cross-fetch/index.d.ts b/test/merkletreejs/node_modules/cross-fetch/index.d.ts new file mode 100644 index 0000000..3c030c0 --- /dev/null +++ b/test/merkletreejs/node_modules/cross-fetch/index.d.ts @@ -0,0 +1,14 @@ +/// + +declare const _fetch: typeof fetch; +declare const _Request: typeof Request; +declare const _Response: typeof Response; +declare const _Headers: typeof Headers; + +declare module "cross-fetch" { + export const fetch: typeof _fetch; + export const Request: typeof _Request; + export const Response: typeof _Response; + export const Headers: typeof _Headers; + export default fetch; +} diff --git a/test/merkletreejs/node_modules/cross-fetch/package.json b/test/merkletreejs/node_modules/cross-fetch/package.json new file mode 100644 index 0000000..30f0690 --- /dev/null +++ b/test/merkletreejs/node_modules/cross-fetch/package.json @@ -0,0 +1,128 @@ +{ + "name": "cross-fetch", + "version": "4.0.0", + "description": "Universal WHATWG Fetch API for Node, Browsers and React Native", + "homepage": "https://github.com/lquixada/cross-fetch", + "main": "dist/node-ponyfill.js", + "browser": "dist/browser-ponyfill.js", + "react-native": "dist/react-native-ponyfill.js", + "types": "index.d.ts", + "scripts": { + "commit": "cz", + "prepare": "husky install", + "prepublishOnly": "rimraf dist && make dist" + }, + "lint-staged": { + "*.js": [ + "standard --fix" + ] + }, + "config": { + "commitizen": { + "path": "cz-conventional-changelog" + } + }, + "standard": { + "env": [ + "browser", + "mocha", + "serviceworker" + ], + "globals": [ + "expect", + "assert", + "chai", + "Mocha" + ], + "ignore": [ + "/dist/", + "api.spec.js", + "bundle.js", + "test.js", + "*.bundle.js", + "*.ts" + ] + }, + "mocha": { + "require": [ + "chai/register-expect.js", + "chai/register-assert.js" + ], + "check-leaks": true + }, + "nyc": { + "temp-dir": ".reports/.coverage" + }, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/lquixada/cross-fetch.git" + }, + "author": "Leonardo Quixada ", + "license": "MIT", + "bugs": { + "url": "https://github.com/lquixada/cross-fetch/issues" + }, + "dependencies": { + "node-fetch": "^2.6.12" + }, + "devDependencies": { + "@commitlint/cli": "17.6.6", + "@commitlint/config-conventional": "17.6.6", + "@rollup/plugin-terser": "0.4.3", + "@types/chai": "4.3.5", + "@types/mocha": "10.0.1", + "@types/node": "18.15.13", + "body-parser": "1.20.2", + "chai": "4.3.7", + "codecov": "3.8.3", + "commitizen": "4.3.0", + "cz-conventional-changelog": "3.3.0", + "express": "4.18.2", + "husky": "8.0.3", + "lint-staged": "13.2.3", + "mocha": "10.2.0", + "mocha-headless-chrome": "4.0.0", + "nock": "13.3.1", + "nyc": "15.1.0", + "rimraf": "5.0.1", + "rollup": "3.26.0", + "rollup-plugin-copy": "3.4.0", + "semver": "7.5.3", + "serve-index": "1.9.1", + "standard": "17.1.0", + "standard-version": "9.5.0", + "typescript": "5.1.6", + "webpack": "5.88.1", + "webpack-cli": "5.1.4", + "whatwg-fetch": "3.6.2", + "yargs": "17.7.2" + }, + "files": [ + "dist", + "polyfill", + "index.d.ts" + ], + "keywords": [ + "fetch", + "http", + "url", + "promise", + "async", + "await", + "isomorphic", + "universal", + "node", + "react", + "native", + "browser", + "ponyfill", + "whatwg", + "xhr", + "ajax" + ] +} diff --git a/test/merkletreejs/node_modules/cross-fetch/polyfill/package.json b/test/merkletreejs/node_modules/cross-fetch/polyfill/package.json new file mode 100644 index 0000000..7258820 --- /dev/null +++ b/test/merkletreejs/node_modules/cross-fetch/polyfill/package.json @@ -0,0 +1,9 @@ +{ + "name": "cross-fetch-polyfill", + "version": "0.0.0", + "main": "../dist/node-polyfill.js", + "browser": "../dist/browser-polyfill.js", + "react-native": "../dist/react-native-polyfill.js", + "types": "../index.d.ts", + "license": "MIT" +} diff --git a/test/merkletreejs/node_modules/crypto-js/CONTRIBUTING.md b/test/merkletreejs/node_modules/crypto-js/CONTRIBUTING.md new file mode 100644 index 0000000..09bf774 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/CONTRIBUTING.md @@ -0,0 +1,28 @@ +# Contribution + +# Git Flow + +The crypto-js project uses [git flow](https://github.com/nvie/gitflow) to manage branches. +Do your changes on the `develop` or even better on a `feature/*` branch. Don't do any changes on the `master` branch. + +# Pull request + +Target your pull request on `develop` branch. Other pull request won't be accepted. + +# How to build + +1. Clone + +2. Run + + ```sh + npm install + ``` + +3. Run + + ```sh + npm run build + ``` + +4. Check `build` folder \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/LICENSE b/test/merkletreejs/node_modules/crypto-js/LICENSE new file mode 100644 index 0000000..b0828e5 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/LICENSE @@ -0,0 +1,24 @@ +# License + +[The MIT License (MIT)](http://opensource.org/licenses/MIT) + +Copyright (c) 2009-2013 Jeff Mott +Copyright (c) 2013-2016 Evan Vosberg + +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. diff --git a/test/merkletreejs/node_modules/crypto-js/README.md b/test/merkletreejs/node_modules/crypto-js/README.md new file mode 100644 index 0000000..6a9bcdf --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/README.md @@ -0,0 +1,275 @@ +# crypto-js + +JavaScript library of crypto standards. + +## Discontinued + +Active development of CryptoJS has been discontinued. This library is no longer maintained. + +Nowadays, NodeJS and modern browsers have a native `Crypto` module. The latest version of CryptoJS already uses the native Crypto module for random number generation, since `Math.random()` is not crypto-safe. Further development of CryptoJS would result in it only being a wrapper of native Crypto. Therefore, development and maintenance has been discontinued, it is time to go for the native `crypto` module. + +## Node.js (Install) + +Requirements: + +- Node.js +- npm (Node.js package manager) + +```bash +npm install crypto-js +``` + +### Usage + +ES6 import for typical API call signing use case: + +```javascript +import sha256 from 'crypto-js/sha256'; +import hmacSHA512 from 'crypto-js/hmac-sha512'; +import Base64 from 'crypto-js/enc-base64'; + +const message, nonce, path, privateKey; // ... +const hashDigest = sha256(nonce + message); +const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey)); +``` + +Modular include: + +```javascript +var AES = require("crypto-js/aes"); +var SHA256 = require("crypto-js/sha256"); +... +console.log(SHA256("Message")); +``` + +Including all libraries, for access to extra methods: + +```javascript +var CryptoJS = require("crypto-js"); +console.log(CryptoJS.HmacSHA1("Message", "Key")); +``` + +## Client (browser) + +Requirements: + +- Node.js +- Bower (package manager for frontend) + +```bash +bower install crypto-js +``` + +### Usage + +Modular include: + +```javascript +require.config({ + packages: [ + { + name: 'crypto-js', + location: 'path-to/bower_components/crypto-js', + main: 'index' + } + ] +}); + +require(["crypto-js/aes", "crypto-js/sha256"], function (AES, SHA256) { + console.log(SHA256("Message")); +}); +``` + +Including all libraries, for access to extra methods: + +```javascript +// Above-mentioned will work or use this simple form +require.config({ + paths: { + 'crypto-js': 'path-to/bower_components/crypto-js/crypto-js' + } +}); + +require(["crypto-js"], function (CryptoJS) { + console.log(CryptoJS.HmacSHA1("Message", "Key")); +}); +``` + +### Usage without RequireJS + +```html + + +``` + +## API + +See: https://cryptojs.gitbook.io/docs/ + +### AES Encryption + +#### Plain text encryption + +```javascript +var CryptoJS = require("crypto-js"); + +// Encrypt +var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString(); + +// Decrypt +var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123'); +var originalText = bytes.toString(CryptoJS.enc.Utf8); + +console.log(originalText); // 'my message' +``` + +#### Object encryption + +```javascript +var CryptoJS = require("crypto-js"); + +var data = [{id: 1}, {id: 2}] + +// Encrypt +var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString(); + +// Decrypt +var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123'); +var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); + +console.log(decryptedData); // [{id: 1}, {id: 2}] +``` + +### List of modules + + +- ```crypto-js/core``` +- ```crypto-js/x64-core``` +- ```crypto-js/lib-typedarrays``` + +--- + +- ```crypto-js/md5``` +- ```crypto-js/sha1``` +- ```crypto-js/sha256``` +- ```crypto-js/sha224``` +- ```crypto-js/sha512``` +- ```crypto-js/sha384``` +- ```crypto-js/sha3``` +- ```crypto-js/ripemd160``` + +--- + +- ```crypto-js/hmac-md5``` +- ```crypto-js/hmac-sha1``` +- ```crypto-js/hmac-sha256``` +- ```crypto-js/hmac-sha224``` +- ```crypto-js/hmac-sha512``` +- ```crypto-js/hmac-sha384``` +- ```crypto-js/hmac-sha3``` +- ```crypto-js/hmac-ripemd160``` + +--- + +- ```crypto-js/pbkdf2``` + +--- + +- ```crypto-js/aes``` +- ```crypto-js/tripledes``` +- ```crypto-js/rc4``` +- ```crypto-js/rabbit``` +- ```crypto-js/rabbit-legacy``` +- ```crypto-js/evpkdf``` + +--- + +- ```crypto-js/format-openssl``` +- ```crypto-js/format-hex``` + +--- + +- ```crypto-js/enc-latin1``` +- ```crypto-js/enc-utf8``` +- ```crypto-js/enc-hex``` +- ```crypto-js/enc-utf16``` +- ```crypto-js/enc-base64``` + +--- + +- ```crypto-js/mode-cfb``` +- ```crypto-js/mode-ctr``` +- ```crypto-js/mode-ctr-gladman``` +- ```crypto-js/mode-ofb``` +- ```crypto-js/mode-ecb``` + +--- + +- ```crypto-js/pad-pkcs7``` +- ```crypto-js/pad-ansix923``` +- ```crypto-js/pad-iso10126``` +- ```crypto-js/pad-iso97971``` +- ```crypto-js/pad-zeropadding``` +- ```crypto-js/pad-nopadding``` + + +## Release notes + +### 4.2.0 + +Change default hash algorithm and iteration's for PBKDF2 to prevent weak security by using the default configuration. + +Custom KDF Hasher + +Blowfish support + +### 4.1.1 + +Fix module order in bundled release. + +Include the browser field in the released package.json. + +### 4.1.0 + +Added url safe variant of base64 encoding. [357](https://github.com/brix/crypto-js/pull/357) + +Avoid webpack to add crypto-browser package. [364](https://github.com/brix/crypto-js/pull/364) + +### 4.0.0 + +This is an update including breaking changes for some environments. + +In this version `Math.random()` has been replaced by the random methods of the native crypto module. + +For this reason CryptoJS might not run in some JavaScript environments without native crypto module. Such as IE 10 or before or React Native. + +### 3.3.0 + +Rollback, `3.3.0` is the same as `3.1.9-1`. + +The move of using native secure crypto module will be shifted to a new `4.x.x` version. As it is a breaking change the impact is too big for a minor release. + +### 3.2.1 + +The usage of the native crypto module has been fixed. The import and access of the native crypto module has been improved. + +### 3.2.0 + +In this version `Math.random()` has been replaced by the random methods of the native crypto module. + +For this reason CryptoJS might does not run in some JavaScript environments without native crypto module. Such as IE 10 or before. + +If it's absolute required to run CryptoJS in such an environment, stay with `3.1.x` version. Encrypting and decrypting stays compatible. But keep in mind `3.1.x` versions still use `Math.random()` which is cryptographically not secure, as it's not random enough. + +This version came along with `CRITICAL` `BUG`. + +DO NOT USE THIS VERSION! Please, go for a newer version! + +### 3.1.x + +The `3.1.x` are based on the original CryptoJS, wrapped in CommonJS modules. + + diff --git a/test/merkletreejs/node_modules/crypto-js/aes.js b/test/merkletreejs/node_modules/crypto-js/aes.js new file mode 100644 index 0000000..166e3ea --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/aes.js @@ -0,0 +1,234 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + var t; + + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); + }()); + + + return CryptoJS.AES; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/blowfish.js b/test/merkletreejs/node_modules/crypto-js/blowfish.js new file mode 100644 index 0000000..149812f --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/blowfish.js @@ -0,0 +1,471 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + const N = 16; + + //Origin pbox and sbox, derived from PI + const ORIG_P = [ + 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, + 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, + 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, + 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, + 0x9216D5D9, 0x8979FB1B + ]; + + const ORIG_S = [ + [ 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, + 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, + 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, + 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, + 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, + 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, + 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, + 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, + 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, + 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, + 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, + 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, + 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, + 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, + 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, + 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, + 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, + 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, + 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, + 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, + 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, + 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, + 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, + 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, + 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, + 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, + 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, + 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, + 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, + 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, + 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, + 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, + 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, + 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, + 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, + 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, + 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, + 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, + 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, + 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, + 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, + 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, + 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, + 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, + 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, + 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, + 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, + 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, + 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, + 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, + 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, + 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, + 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, + 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, + 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, + 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, + 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, + 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, + 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, + 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, + 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, + 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, + 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, + 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A ], + [ 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, + 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, + 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, + 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, + 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, + 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, + 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, + 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, + 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, + 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, + 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, + 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, + 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, + 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, + 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, + 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, + 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, + 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, + 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, + 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, + 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, + 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, + 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, + 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, + 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, + 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, + 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, + 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, + 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, + 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, + 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, + 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, + 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, + 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, + 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, + 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, + 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, + 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, + 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, + 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, + 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, + 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, + 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, + 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, + 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, + 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, + 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, + 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, + 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, + 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, + 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, + 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, + 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, + 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, + 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, + 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, + 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, + 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, + 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, + 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, + 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, + 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, + 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, + 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 ], + [ 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, + 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, + 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, + 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, + 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, + 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, + 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, + 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, + 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, + 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, + 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, + 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, + 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, + 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, + 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, + 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, + 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, + 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, + 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, + 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, + 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, + 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, + 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, + 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, + 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, + 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, + 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, + 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, + 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, + 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, + 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, + 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, + 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, + 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, + 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, + 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, + 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, + 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, + 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, + 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, + 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, + 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, + 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, + 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, + 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, + 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, + 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, + 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, + 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, + 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, + 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, + 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, + 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, + 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, + 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, + 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, + 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, + 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, + 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, + 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, + 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, + 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, + 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, + 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 ], + [ 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, + 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, + 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, + 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, + 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, + 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, + 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, + 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, + 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, + 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, + 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, + 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, + 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, + 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, + 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, + 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, + 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, + 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, + 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, + 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, + 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, + 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, + 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, + 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, + 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, + 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, + 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, + 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, + 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, + 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, + 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, + 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, + 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, + 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, + 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, + 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, + 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, + 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, + 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, + 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, + 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, + 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, + 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, + 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, + 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, + 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, + 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, + 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, + 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, + 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, + 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, + 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, + 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, + 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, + 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, + 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, + 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, + 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, + 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, + 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, + 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, + 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, + 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, + 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 ] + ]; + + var BLOWFISH_CTX = { + pbox: [], + sbox: [] + } + + function F(ctx, x){ + let a = (x >> 24) & 0xFF; + let b = (x >> 16) & 0xFF; + let c = (x >> 8) & 0xFF; + let d = x & 0xFF; + + let y = ctx.sbox[0][a] + ctx.sbox[1][b]; + y = y ^ ctx.sbox[2][c]; + y = y + ctx.sbox[3][d]; + + return y; + } + + function BlowFish_Encrypt(ctx, left, right){ + let Xl = left; + let Xr = right; + let temp; + + for(let i = 0; i < N; ++i){ + Xl = Xl ^ ctx.pbox[i]; + Xr = F(ctx, Xl) ^ Xr; + + temp = Xl; + Xl = Xr; + Xr = temp; + } + + temp = Xl; + Xl = Xr; + Xr = temp; + + Xr = Xr ^ ctx.pbox[N]; + Xl = Xl ^ ctx.pbox[N + 1]; + + return {left: Xl, right: Xr}; + } + + function BlowFish_Decrypt(ctx, left, right){ + let Xl = left; + let Xr = right; + let temp; + + for(let i = N + 1; i > 1; --i){ + Xl = Xl ^ ctx.pbox[i]; + Xr = F(ctx, Xl) ^ Xr; + + temp = Xl; + Xl = Xr; + Xr = temp; + } + + temp = Xl; + Xl = Xr; + Xr = temp; + + Xr = Xr ^ ctx.pbox[1]; + Xl = Xl ^ ctx.pbox[0]; + + return {left: Xl, right: Xr}; + } + + /** + * Initialization ctx's pbox and sbox. + * + * @param {Object} ctx The object has pbox and sbox. + * @param {Array} key An array of 32-bit words. + * @param {int} keysize The length of the key. + * + * @example + * + * BlowFishInit(BLOWFISH_CTX, key, 128/32); + */ + function BlowFishInit(ctx, key, keysize) + { + for(let Row = 0; Row < 4; Row++) + { + ctx.sbox[Row] = []; + for(let Col = 0; Col < 256; Col++) + { + ctx.sbox[Row][Col] = ORIG_S[Row][Col]; + } + } + + let keyIndex = 0; + for(let index = 0; index < N + 2; index++) + { + ctx.pbox[index] = ORIG_P[index] ^ key[keyIndex]; + keyIndex++; + if(keyIndex >= keysize) + { + keyIndex = 0; + } + } + + let Data1 = 0; + let Data2 = 0; + let res = 0; + for(let i = 0; i < N + 2; i += 2) + { + res = BlowFish_Encrypt(ctx, Data1, Data2); + Data1 = res.left; + Data2 = res.right; + ctx.pbox[i] = Data1; + ctx.pbox[i + 1] = Data2; + } + + for(let i = 0; i < 4; i++) + { + for(let j = 0; j < 256; j += 2) + { + res = BlowFish_Encrypt(ctx, Data1, Data2); + Data1 = res.left; + Data2 = res.right; + ctx.sbox[i][j] = Data1; + ctx.sbox[i][j + 1] = Data2; + } + } + + return true; + } + + /** + * Blowfish block cipher algorithm. + */ + var Blowfish = C_algo.Blowfish = BlockCipher.extend({ + _doReset: function () { + // Skip reset of nRounds has been set before and key did not change + if (this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + //Initialization pbox and sbox + BlowFishInit(BLOWFISH_CTX, keyWords, keySize); + }, + + encryptBlock: function (M, offset) { + var res = BlowFish_Encrypt(BLOWFISH_CTX, M[offset], M[offset + 1]); + M[offset] = res.left; + M[offset + 1] = res.right; + }, + + decryptBlock: function (M, offset) { + var res = BlowFish_Decrypt(BLOWFISH_CTX, M[offset], M[offset + 1]); + M[offset] = res.left; + M[offset + 1] = res.right; + }, + + blockSize: 64/32, + + keySize: 128/32, + + ivSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Blowfish.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Blowfish.decrypt(ciphertext, key, cfg); + */ + C.Blowfish = BlockCipher._createHelper(Blowfish); + }()); + + + return CryptoJS.Blowfish; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/bower.json b/test/merkletreejs/node_modules/crypto-js/bower.json new file mode 100644 index 0000000..4dee617 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/bower.json @@ -0,0 +1,39 @@ +{ + "name": "crypto-js", + "version": "4.2.0", + "description": "JavaScript library of crypto standards.", + "license": "MIT", + "homepage": "http://github.com/brix/crypto-js", + "repository": { + "type": "git", + "url": "http://github.com/brix/crypto-js.git" + }, + "keywords": [ + "security", + "crypto", + "Hash", + "MD5", + "SHA1", + "SHA-1", + "SHA256", + "SHA-256", + "RC4", + "Rabbit", + "AES", + "DES", + "PBKDF2", + "HMAC", + "OFB", + "CFB", + "CTR", + "CBC", + "Base64", + "Base64url" + ], + "main": "index.js", + "dependencies": {}, + "browser": { + "crypto": false + }, + "ignore": [] +} diff --git a/test/merkletreejs/node_modules/crypto-js/cipher-core.js b/test/merkletreejs/node_modules/crypto-js/cipher-core.js new file mode 100644 index 0000000..903f462 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/cipher-core.js @@ -0,0 +1,895 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./evpkdf")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./evpkdf"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Cipher core components. + */ + CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + var StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + var block; + + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + var modeCreator; + + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + modeCreator = mode.createDecryptor; + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + + if (this._mode && this._mode.__creator == modeCreator) { + this._mode.init(this, iv && iv.words); + } else { + this._mode = modeCreator.call(mode, this, iv && iv.words); + this._mode.__creator = modeCreator; + } + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + var finalProcessedBlocks; + + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + var wordArray; + + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + var salt; + + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt, hasher) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + if (!hasher) { + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + } else { + var key = EvpKDF.create({ keySize: keySize + ivSize, hasher: hasher }).compute(password, salt); + } + + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); + }()); + + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/core.js b/test/merkletreejs/node_modules/crypto-js/core.js new file mode 100644 index 0000000..e3a498b --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/core.js @@ -0,0 +1,807 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(); + } + else if (typeof define === "function" && define.amd) { + // AMD + define([], factory); + } + else { + // Global (browser) + root.CryptoJS = factory(); + } +}(this, function () { + + /*globals window, global, require*/ + + /** + * CryptoJS core components. + */ + var CryptoJS = CryptoJS || (function (Math, undefined) { + + var crypto; + + // Native crypto from window (Browser) + if (typeof window !== 'undefined' && window.crypto) { + crypto = window.crypto; + } + + // Native crypto in web worker (Browser) + if (typeof self !== 'undefined' && self.crypto) { + crypto = self.crypto; + } + + // Native crypto from worker + if (typeof globalThis !== 'undefined' && globalThis.crypto) { + crypto = globalThis.crypto; + } + + // Native (experimental IE 11) crypto from window (Browser) + if (!crypto && typeof window !== 'undefined' && window.msCrypto) { + crypto = window.msCrypto; + } + + // Native crypto from global (NodeJS) + if (!crypto && typeof global !== 'undefined' && global.crypto) { + crypto = global.crypto; + } + + // Native crypto import via require (NodeJS) + if (!crypto && typeof require === 'function') { + try { + crypto = require('crypto'); + } catch (err) {} + } + + /* + * Cryptographically secure pseudorandom number generator + * + * As Math.random() is cryptographically not safe to use + */ + var cryptoSecureRandomInt = function () { + if (crypto) { + // Use getRandomValues method (Browser) + if (typeof crypto.getRandomValues === 'function') { + try { + return crypto.getRandomValues(new Uint32Array(1))[0]; + } catch (err) {} + } + + // Use randomBytes method (NodeJS) + if (typeof crypto.randomBytes === 'function') { + try { + return crypto.randomBytes(4).readInt32LE(); + } catch (err) {} + } + } + + throw new Error('Native crypto module could not be used to get secure random number.'); + }; + + /* + * Local polyfill of Object.create + + */ + var create = Object.create || (function () { + function F() {} + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()); + + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + var subtype = create(this); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else { + // Copy one word at a time + for (var j = 0; j < thatSigBytes; j += 4) { + thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2]; + } + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + + for (var i = 0; i < nBytes; i += 4) { + words.push(cryptoSecureRandomInt()); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + var processedWords; + + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; + }(Math)); + + + return CryptoJS; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/crypto-js.js b/test/merkletreejs/node_modules/crypto-js/crypto-js.js new file mode 100644 index 0000000..958ee53 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/crypto-js.js @@ -0,0 +1,6657 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(); + } + else if (typeof define === "function" && define.amd) { + // AMD + define([], factory); + } + else { + // Global (browser) + root.CryptoJS = factory(); + } +}(this, function () { + + /*globals window, global, require*/ + + /** + * CryptoJS core components. + */ + var CryptoJS = CryptoJS || (function (Math, undefined) { + + var crypto; + + // Native crypto from window (Browser) + if (typeof window !== 'undefined' && window.crypto) { + crypto = window.crypto; + } + + // Native crypto in web worker (Browser) + if (typeof self !== 'undefined' && self.crypto) { + crypto = self.crypto; + } + + // Native crypto from worker + if (typeof globalThis !== 'undefined' && globalThis.crypto) { + crypto = globalThis.crypto; + } + + // Native (experimental IE 11) crypto from window (Browser) + if (!crypto && typeof window !== 'undefined' && window.msCrypto) { + crypto = window.msCrypto; + } + + // Native crypto from global (NodeJS) + if (!crypto && typeof global !== 'undefined' && global.crypto) { + crypto = global.crypto; + } + + // Native crypto import via require (NodeJS) + if (!crypto && typeof require === 'function') { + try { + crypto = require('crypto'); + } catch (err) {} + } + + /* + * Cryptographically secure pseudorandom number generator + * + * As Math.random() is cryptographically not safe to use + */ + var cryptoSecureRandomInt = function () { + if (crypto) { + // Use getRandomValues method (Browser) + if (typeof crypto.getRandomValues === 'function') { + try { + return crypto.getRandomValues(new Uint32Array(1))[0]; + } catch (err) {} + } + + // Use randomBytes method (NodeJS) + if (typeof crypto.randomBytes === 'function') { + try { + return crypto.randomBytes(4).readInt32LE(); + } catch (err) {} + } + } + + throw new Error('Native crypto module could not be used to get secure random number.'); + }; + + /* + * Local polyfill of Object.create + + */ + var create = Object.create || (function () { + function F() {} + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()); + + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + var subtype = create(this); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else { + // Copy one word at a time + for (var j = 0; j < thatSigBytes; j += 4) { + thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2]; + } + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + + for (var i = 0; i < nBytes; i += 4) { + words.push(cryptoSecureRandomInt()); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + var processedWords; + + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; + }(Math)); + + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var X32WordArray = C_lib.WordArray; + + /** + * x64 namespace. + */ + var C_x64 = C.x64 = {}; + + /** + * A 64-bit word. + */ + var X64Word = C_x64.Word = Base.extend({ + /** + * Initializes a newly created 64-bit word. + * + * @param {number} high The high 32 bits. + * @param {number} low The low 32 bits. + * + * @example + * + * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); + */ + init: function (high, low) { + this.high = high; + this.low = low; + } + + /** + * Bitwise NOTs this word. + * + * @return {X64Word} A new x64-Word object after negating. + * + * @example + * + * var negated = x64Word.not(); + */ + // not: function () { + // var high = ~this.high; + // var low = ~this.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ANDs this word with the passed word. + * + * @param {X64Word} word The x64-Word to AND with this word. + * + * @return {X64Word} A new x64-Word object after ANDing. + * + * @example + * + * var anded = x64Word.and(anotherX64Word); + */ + // and: function (word) { + // var high = this.high & word.high; + // var low = this.low & word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to OR with this word. + * + * @return {X64Word} A new x64-Word object after ORing. + * + * @example + * + * var ored = x64Word.or(anotherX64Word); + */ + // or: function (word) { + // var high = this.high | word.high; + // var low = this.low | word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise XORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to XOR with this word. + * + * @return {X64Word} A new x64-Word object after XORing. + * + * @example + * + * var xored = x64Word.xor(anotherX64Word); + */ + // xor: function (word) { + // var high = this.high ^ word.high; + // var low = this.low ^ word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the left. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftL(25); + */ + // shiftL: function (n) { + // if (n < 32) { + // var high = (this.high << n) | (this.low >>> (32 - n)); + // var low = this.low << n; + // } else { + // var high = this.low << (n - 32); + // var low = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the right. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftR(7); + */ + // shiftR: function (n) { + // if (n < 32) { + // var low = (this.low >>> n) | (this.high << (32 - n)); + // var high = this.high >>> n; + // } else { + // var low = this.high >>> (n - 32); + // var high = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Rotates this word n bits to the left. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotL(25); + */ + // rotL: function (n) { + // return this.shiftL(n).or(this.shiftR(64 - n)); + // }, + + /** + * Rotates this word n bits to the right. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotR(7); + */ + // rotR: function (n) { + // return this.shiftR(n).or(this.shiftL(64 - n)); + // }, + + /** + * Adds this word with the passed word. + * + * @param {X64Word} word The x64-Word to add with this word. + * + * @return {X64Word} A new x64-Word object after adding. + * + * @example + * + * var added = x64Word.add(anotherX64Word); + */ + // add: function (word) { + // var low = (this.low + word.low) | 0; + // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; + // var high = (this.high + word.high + carry) | 0; + + // return X64Word.create(high, low); + // } + }); + + /** + * An array of 64-bit words. + * + * @property {Array} words The array of CryptoJS.x64.Word objects. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var X64WordArray = C_x64.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.x64.WordArray.create(); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ]); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ], 10); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 8; + } + }, + + /** + * Converts this 64-bit word array to a 32-bit word array. + * + * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. + * + * @example + * + * var x32WordArray = x64WordArray.toX32(); + */ + toX32: function () { + // Shortcuts + var x64Words = this.words; + var x64WordsLength = x64Words.length; + + // Convert + var x32Words = []; + for (var i = 0; i < x64WordsLength; i++) { + var x64Word = x64Words[i]; + x32Words.push(x64Word.high); + x32Words.push(x64Word.low); + } + + return X32WordArray.create(x32Words, this.sigBytes); + }, + + /** + * Creates a copy of this word array. + * + * @return {X64WordArray} The clone. + * + * @example + * + * var clone = x64WordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + + // Clone "words" array + var words = clone.words = this.words.slice(0); + + // Clone each X64Word object + var wordsLength = words.length; + for (var i = 0; i < wordsLength; i++) { + words[i] = words[i].clone(); + } + + return clone; + } + }); + }()); + + + (function () { + // Check if typed arrays are supported + if (typeof ArrayBuffer != 'function') { + return; + } + + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + + // Reference original init + var superInit = WordArray.init; + + // Augment WordArray.init to handle typed arrays + var subInit = WordArray.init = function (typedArray) { + // Convert buffers to uint8 + if (typedArray instanceof ArrayBuffer) { + typedArray = new Uint8Array(typedArray); + } + + // Convert other array views to uint8 + if ( + typedArray instanceof Int8Array || + (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || + typedArray instanceof Int16Array || + typedArray instanceof Uint16Array || + typedArray instanceof Int32Array || + typedArray instanceof Uint32Array || + typedArray instanceof Float32Array || + typedArray instanceof Float64Array + ) { + typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); + } + + // Handle Uint8Array + if (typedArray instanceof Uint8Array) { + // Shortcut + var typedArrayByteLength = typedArray.byteLength; + + // Extract bytes + var words = []; + for (var i = 0; i < typedArrayByteLength; i++) { + words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); + } + + // Initialize this word array + superInit.call(this, words, typedArrayByteLength); + } else { + // Else call normal init + superInit.apply(this, arguments); + } + }; + + subInit.prototype = WordArray; + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * UTF-16 BE encoding strategy. + */ + var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { + /** + * Converts a word array to a UTF-16 BE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 BE string. + * + * @static + * + * @example + * + * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 BE string to a word array. + * + * @param {string} utf16Str The UTF-16 BE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + /** + * UTF-16 LE encoding strategy. + */ + C_enc.Utf16LE = { + /** + * Converts a word array to a UTF-16 LE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 LE string. + * + * @static + * + * @example + * + * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 LE string to a word array. + * + * @param {string} utf16Str The UTF-16 LE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + function swapEndian(word) { + return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); + } + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + var Base64 = C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64url encoding strategy. + */ + var Base64url = C_enc.Base64url = { + /** + * Converts a word array to a Base64url string. + * + * @param {WordArray} wordArray The word array. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {string} The Base64url string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64url.stringify(wordArray); + */ + stringify: function (wordArray, urlSafe) { + if (urlSafe === undefined) { + urlSafe = true + } + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = urlSafe ? this._safe_map : this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64url string to a word array. + * + * @param {string} base64Str The Base64url string. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64url.parse(base64String); + */ + parse: function (base64Str, urlSafe) { + if (urlSafe === undefined) { + urlSafe = true + } + + // Shortcuts + var base64StrLength = base64Str.length; + var map = urlSafe ? this._safe_map : this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + _safe_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); + }(Math)); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Reusable object + var W = []; + + /** + * SHA-1 hash algorithm. + */ + var SHA1 = C_algo.SHA1 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476, + 0xc3d2e1f0 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + // Computation + for (var i = 0; i < 80; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + + var t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else /* if (i < 80) */ { + t += (b ^ c ^ d) - 0x359d3e2a; + } + + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA1('message'); + * var hash = CryptoJS.SHA1(wordArray); + */ + C.SHA1 = Hasher._createHelper(SHA1); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA1(message, key); + */ + C.HmacSHA1 = Hasher._createHmacHelper(SHA1); + }()); + + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Initialization and round constants tables + var H = []; + var K = []; + + // Compute constants + (function () { + function isPrime(n) { + var sqrtN = Math.sqrt(n); + for (var factor = 2; factor <= sqrtN; factor++) { + if (!(n % factor)) { + return false; + } + } + + return true; + } + + function getFractionalBits(n) { + return ((n - (n | 0)) * 0x100000000) | 0; + } + + var n = 2; + var nPrime = 0; + while (nPrime < 64) { + if (isPrime(n)) { + if (nPrime < 8) { + H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); + } + K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); + + nPrime++; + } + + n++; + } + }()); + + // Reusable object + var W = []; + + /** + * SHA-256 hash algorithm. + */ + var SHA256 = C_algo.SHA256 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init(H.slice(0)); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + var f = H[5]; + var g = H[6]; + var h = H[7]; + + // Computation + for (var i = 0; i < 64; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var gamma0x = W[i - 15]; + var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3); + + var gamma1x = W[i - 2]; + var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + + var ch = (e & f) ^ (~e & g); + var maj = (a & b) ^ (a & c) ^ (b & c); + + var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + + var t1 = h + sigma1 + ch + K[i] + W[i]; + var t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + H[7] = (H[7] + h) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA256('message'); + * var hash = CryptoJS.SHA256(wordArray); + */ + C.SHA256 = Hasher._createHelper(SHA256); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA256(message, key); + */ + C.HmacSHA256 = Hasher._createHmacHelper(SHA256); + }(Math)); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + + /** + * SHA-224 hash algorithm. + */ + var SHA224 = C_algo.SHA224 = SHA256.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]); + }, + + _doFinalize: function () { + var hash = SHA256._doFinalize.call(this); + + hash.sigBytes -= 4; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA224('message'); + * var hash = CryptoJS.SHA224(wordArray); + */ + C.SHA224 = SHA256._createHelper(SHA224); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA224(message, key); + */ + C.HmacSHA224 = SHA256._createHmacHelper(SHA224); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + + function X64Word_create() { + return X64Word.create.apply(X64Word, arguments); + } + + // Constants + var K = [ + X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), + X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), + X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), + X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), + X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), + X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), + X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), + X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), + X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), + X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), + X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), + X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), + X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), + X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), + X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), + X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), + X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), + X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), + X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), + X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), + X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), + X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), + X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), + X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), + X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), + X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), + X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), + X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), + X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), + X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), + X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), + X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), + X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), + X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), + X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), + X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), + X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), + X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), + X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), + X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) + ]; + + // Reusable objects + var W = []; + (function () { + for (var i = 0; i < 80; i++) { + W[i] = X64Word_create(); + } + }()); + + /** + * SHA-512 hash algorithm. + */ + var SHA512 = C_algo.SHA512 = Hasher.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), + new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), + new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), + new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var H = this._hash.words; + + var H0 = H[0]; + var H1 = H[1]; + var H2 = H[2]; + var H3 = H[3]; + var H4 = H[4]; + var H5 = H[5]; + var H6 = H[6]; + var H7 = H[7]; + + var H0h = H0.high; + var H0l = H0.low; + var H1h = H1.high; + var H1l = H1.low; + var H2h = H2.high; + var H2l = H2.low; + var H3h = H3.high; + var H3l = H3.low; + var H4h = H4.high; + var H4l = H4.low; + var H5h = H5.high; + var H5l = H5.low; + var H6h = H6.high; + var H6l = H6.low; + var H7h = H7.high; + var H7l = H7.low; + + // Working variables + var ah = H0h; + var al = H0l; + var bh = H1h; + var bl = H1l; + var ch = H2h; + var cl = H2l; + var dh = H3h; + var dl = H3l; + var eh = H4h; + var el = H4l; + var fh = H5h; + var fl = H5l; + var gh = H6h; + var gl = H6l; + var hh = H7h; + var hl = H7l; + + // Rounds + for (var i = 0; i < 80; i++) { + var Wil; + var Wih; + + // Shortcut + var Wi = W[i]; + + // Extend message + if (i < 16) { + Wih = Wi.high = M[offset + i * 2] | 0; + Wil = Wi.low = M[offset + i * 2 + 1] | 0; + } else { + // Gamma0 + var gamma0x = W[i - 15]; + var gamma0xh = gamma0x.high; + var gamma0xl = gamma0x.low; + var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); + + // Gamma1 + var gamma1x = W[i - 2]; + var gamma1xh = gamma1x.high; + var gamma1xl = gamma1x.low; + var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[i - 7]; + var Wi7h = Wi7.high; + var Wi7l = Wi7.low; + + var Wi16 = W[i - 16]; + var Wi16h = Wi16.high; + var Wi16l = Wi16.low; + + Wil = gamma0l + Wi7l; + Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + Wil = Wil + gamma1l; + Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + Wil = Wil + Wi16l; + Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + + Wi.high = Wih; + Wi.low = Wil; + } + + var chh = (eh & fh) ^ (~eh & gh); + var chl = (el & fl) ^ (~el & gl); + var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + var majl = (al & bl) ^ (al & cl) ^ (bl & cl); + + var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[i]; + var Kih = Ki.high; + var Kil = Ki.low; + + var t1l = hl + sigma1l; + var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + var t1l = t1l + chl; + var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + var t1l = t1l + Kil; + var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + var t1l = t1l + Wil; + var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + + // t2 = sigma0 + maj + var t2l = sigma0l + majl; + var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + + // Update working variables + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + } + + // Intermediate hash value + H0l = H0.low = (H0l + al); + H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); + H1l = H1.low = (H1l + bl); + H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); + H2l = H2.low = (H2l + cl); + H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); + H3l = H3.low = (H3l + dl); + H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); + H4l = H4.low = (H4l + el); + H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); + H5l = H5.low = (H5l + fl); + H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); + H6l = H6.low = (H6l + gl); + H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); + H7l = H7.low = (H7l + hl); + H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Convert hash to 32-bit word array before returning + var hash = this._hash.toX32(); + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + + blockSize: 1024/32 + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA512('message'); + * var hash = CryptoJS.SHA512(wordArray); + */ + C.SHA512 = Hasher._createHelper(SHA512); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA512(message, key); + */ + C.HmacSHA512 = Hasher._createHmacHelper(SHA512); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + var SHA512 = C_algo.SHA512; + + /** + * SHA-384 hash algorithm. + */ + var SHA384 = C_algo.SHA384 = SHA512.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), + new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), + new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), + new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) + ]); + }, + + _doFinalize: function () { + var hash = SHA512._doFinalize.call(this); + + hash.sigBytes -= 16; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA384('message'); + * var hash = CryptoJS.SHA384(wordArray); + */ + C.SHA384 = SHA512._createHelper(SHA384); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA384(message, key); + */ + C.HmacSHA384 = SHA512._createHmacHelper(SHA384); + }()); + + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var C_algo = C.algo; + + // Constants tables + var RHO_OFFSETS = []; + var PI_INDEXES = []; + var ROUND_CONSTANTS = []; + + // Compute Constants + (function () { + // Compute rho offset constants + var x = 1, y = 0; + for (var t = 0; t < 24; t++) { + RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + + var newX = y % 5; + var newY = (2 * x + 3 * y) % 5; + x = newX; + y = newY; + } + + // Compute pi index constants + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; + } + } + + // Compute round constants + var LFSR = 0x01; + for (var i = 0; i < 24; i++) { + var roundConstantMsw = 0; + var roundConstantLsw = 0; + + for (var j = 0; j < 7; j++) { + if (LFSR & 0x01) { + var bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else /* if (bitPosition >= 32) */ { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + + // Compute next LFSR + if (LFSR & 0x80) { + // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + + ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); + } + }()); + + // Reusable objects for temporary values + var T = []; + (function () { + for (var i = 0; i < 25; i++) { + T[i] = X64Word.create(); + } + }()); + + /** + * SHA-3 hash algorithm. + */ + var SHA3 = C_algo.SHA3 = Hasher.extend({ + /** + * Configuration options. + * + * @property {number} outputLength + * The desired number of bits in the output hash. + * Only values permitted are: 224, 256, 384, 512. + * Default: 512 + */ + cfg: Hasher.cfg.extend({ + outputLength: 512 + }), + + _doReset: function () { + var state = this._state = [] + for (var i = 0; i < 25; i++) { + state[i] = new X64Word.init(); + } + + this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var state = this._state; + var nBlockSizeLanes = this.blockSize / 2; + + // Absorb + for (var i = 0; i < nBlockSizeLanes; i++) { + // Shortcuts + var M2i = M[offset + 2 * i]; + var M2i1 = M[offset + 2 * i + 1]; + + // Swap endian + M2i = ( + (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | + (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) + ); + M2i1 = ( + (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | + (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) + ); + + // Absorb message into state + var lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + + // Rounds + for (var round = 0; round < 24; round++) { + // Theta + for (var x = 0; x < 5; x++) { + // Mix column lanes + var tMsw = 0, tLsw = 0; + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + + // Temporary values + var Tx = T[x]; + Tx.high = tMsw; + Tx.low = tLsw; + } + for (var x = 0; x < 5; x++) { + // Shortcuts + var Tx4 = T[(x + 4) % 5]; + var Tx1 = T[(x + 1) % 5]; + var Tx1Msw = Tx1.high; + var Tx1Lsw = Tx1.low; + + // Mix surrounding columns + var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } + } + + // Rho Pi + for (var laneIndex = 1; laneIndex < 25; laneIndex++) { + var tMsw; + var tLsw; + + // Shortcuts + var lane = state[laneIndex]; + var laneMsw = lane.high; + var laneLsw = lane.low; + var rhoOffset = RHO_OFFSETS[laneIndex]; + + // Rotate lanes + if (rhoOffset < 32) { + tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else /* if (rhoOffset >= 32) */ { + tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + + // Transpose lanes + var TPiLane = T[PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + + // Rho pi at x = y = 0 + var T0 = T[0]; + var state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + + // Chi + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + // Shortcuts + var laneIndex = x + 5 * y; + var lane = state[laneIndex]; + var TLane = T[laneIndex]; + var Tx1Lane = T[((x + 1) % 5) + 5 * y]; + var Tx2Lane = T[((x + 2) % 5) + 5 * y]; + + // Mix rows + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + + // Iota + var lane = state[0]; + var roundConstant = ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + lane.low ^= roundConstant.low; + } + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + var blockSizeBits = this.blockSize * 32; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var state = this._state; + var outputLengthBytes = this.cfg.outputLength / 8; + var outputLengthLanes = outputLengthBytes / 8; + + // Squeeze + var hashWords = []; + for (var i = 0; i < outputLengthLanes; i++) { + // Shortcuts + var lane = state[i]; + var laneMsw = lane.high; + var laneLsw = lane.low; + + // Swap endian + laneMsw = ( + (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | + (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) + ); + laneLsw = ( + (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | + (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) + ); + + // Squeeze state to retrieve hash + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + + // Return final computed hash + return new WordArray.init(hashWords, outputLengthBytes); + }, + + clone: function () { + var clone = Hasher.clone.call(this); + + var state = clone._state = this._state.slice(0); + for (var i = 0; i < 25; i++) { + state[i] = state[i].clone(); + } + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA3('message'); + * var hash = CryptoJS.SHA3(wordArray); + */ + C.SHA3 = Hasher._createHelper(SHA3); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA3(message, key); + */ + C.HmacSHA3 = Hasher._createHmacHelper(SHA3); + }(Math)); + + + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var _zl = WordArray.create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); + var _zr = WordArray.create([ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); + var _sl = WordArray.create([ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); + var _sr = WordArray.create([ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); + + var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); + var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); + + /** + * RIPEMD160 hash algorithm. + */ + var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ + _doReset: function () { + this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); + }, + + _doProcessBlock: function (M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + // Shortcut + var H = this._hash.words; + var hl = _hl.words; + var hr = _hr.words; + var zl = _zl.words; + var zr = _zr.words; + var sl = _sl.words; + var sr = _sr.words; + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + + } + + function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); + + } + + function rotl(x,n) { + return (x<>>(32-n)); + } + + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.RIPEMD160('message'); + * var hash = CryptoJS.RIPEMD160(wordArray); + */ + C.RIPEMD160 = Hasher._createHelper(RIPEMD160); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacRIPEMD160(message, key); + */ + C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); + }(Math)); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var C_algo = C.algo; + + /** + * HMAC algorithm. + */ + var HMAC = C_algo.HMAC = Base.extend({ + /** + * Initializes a newly created HMAC. + * + * @param {Hasher} hasher The hash algorithm to use. + * @param {WordArray|string} key The secret key. + * + * @example + * + * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); + */ + init: function (hasher, key) { + // Init hasher + hasher = this._hasher = new hasher.init(); + + // Convert string to WordArray, else assume WordArray already + if (typeof key == 'string') { + key = Utf8.parse(key); + } + + // Shortcuts + var hasherBlockSize = hasher.blockSize; + var hasherBlockSizeBytes = hasherBlockSize * 4; + + // Allow arbitrary length keys + if (key.sigBytes > hasherBlockSizeBytes) { + key = hasher.finalize(key); + } + + // Clamp excess bits + key.clamp(); + + // Clone key for inner and outer pads + var oKey = this._oKey = key.clone(); + var iKey = this._iKey = key.clone(); + + // Shortcuts + var oKeyWords = oKey.words; + var iKeyWords = iKey.words; + + // XOR keys with pad constants + for (var i = 0; i < hasherBlockSize; i++) { + oKeyWords[i] ^= 0x5c5c5c5c; + iKeyWords[i] ^= 0x36363636; + } + oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; + + // Set initial values + this.reset(); + }, + + /** + * Resets this HMAC to its initial state. + * + * @example + * + * hmacHasher.reset(); + */ + reset: function () { + // Shortcut + var hasher = this._hasher; + + // Reset + hasher.reset(); + hasher.update(this._iKey); + }, + + /** + * Updates this HMAC with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {HMAC} This HMAC instance. + * + * @example + * + * hmacHasher.update('message'); + * hmacHasher.update(wordArray); + */ + update: function (messageUpdate) { + this._hasher.update(messageUpdate); + + // Chainable + return this; + }, + + /** + * Finalizes the HMAC computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The HMAC. + * + * @example + * + * var hmac = hmacHasher.finalize(); + * var hmac = hmacHasher.finalize('message'); + * var hmac = hmacHasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Shortcut + var hasher = this._hasher; + + // Compute HMAC + var innerHash = hasher.finalize(messageUpdate); + hasher.reset(); + var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); + + return hmac; + } + }); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + var HMAC = C_algo.HMAC; + + /** + * Password-Based Key Derivation Function 2 algorithm. + */ + var PBKDF2 = C_algo.PBKDF2 = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hasher to use. Default: SHA256 + * @property {number} iterations The number of iterations to perform. Default: 250000 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: SHA256, + iterations: 250000 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.PBKDF2.create(); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init HMAC + var hmac = HMAC.create(cfg.hasher, password); + + // Initial values + var derivedKey = WordArray.create(); + var blockIndex = WordArray.create([0x00000001]); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var blockIndexWords = blockIndex.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + var block = hmac.update(salt).finalize(blockIndex); + hmac.reset(); + + // Shortcuts + var blockWords = block.words; + var blockWordsLength = blockWords.length; + + // Iterations + var intermediate = block; + for (var i = 1; i < iterations; i++) { + intermediate = hmac.finalize(intermediate); + hmac.reset(); + + // Shortcut + var intermediateWords = intermediate.words; + + // XOR intermediate with block + for (var j = 0; j < blockWordsLength; j++) { + blockWords[j] ^= intermediateWords[j]; + } + } + + derivedKey.concat(block); + blockIndexWords[0]++; + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.PBKDF2(password, salt); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.PBKDF2 = function (password, salt, cfg) { + return PBKDF2.create(cfg).compute(password, salt); + }; + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + var block; + + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; + }()); + + + /** + * Cipher core components. + */ + CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + var StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + var block; + + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + var modeCreator; + + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + modeCreator = mode.createDecryptor; + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + + if (this._mode && this._mode.__creator == modeCreator) { + this._mode.init(this, iv && iv.words); + } else { + this._mode = modeCreator.call(mode, this, iv && iv.words); + this._mode.__creator = modeCreator; + } + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + var finalProcessedBlocks; + + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + var wordArray; + + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + var salt; + + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt, hasher) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + if (!hasher) { + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + } else { + var key = EvpKDF.create({ keySize: keySize + ivSize, hasher: hasher }).compute(password, salt); + } + + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); + }()); + + + /** + * Cipher Feedback block mode. + */ + CryptoJS.mode.CFB = (function () { + var CFB = CryptoJS.lib.BlockCipherMode.extend(); + + CFB.Encryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + CFB.Decryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { + var keystream; + + // Shortcut + var iv = this._iv; + + // Generate keystream + if (iv) { + keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + keystream = this._prevBlock; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + + return CFB; + }()); + + + /** + * Counter block mode. + */ + CryptoJS.mode.CTR = (function () { + var CTR = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = CTR.Encryptor = CTR.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Increment counter + counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTR.Decryptor = Encryptor; + + return CTR; + }()); + + + /** @preserve + * Counter block mode compatible with Dr Brian Gladman fileenc.c + * derived from CryptoJS.mode.CTR + * Jan Hruby jhruby.web@gmail.com + */ + CryptoJS.mode.CTRGladman = (function () { + var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); + + function incWord(word) + { + if (((word >> 24) & 0xff) === 0xff) { //overflow + var b1 = (word >> 16)&0xff; + var b2 = (word >> 8)&0xff; + var b3 = word & 0xff; + + if (b1 === 0xff) // overflow b1 + { + b1 = 0; + if (b2 === 0xff) + { + b2 = 0; + if (b3 === 0xff) + { + b3 = 0; + } + else + { + ++b3; + } + } + else + { + ++b2; + } + } + else + { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } + else + { + word += (0x01 << 24); + } + return word; + } + + function incCounter(counter) + { + if ((counter[0] = incWord(counter[0])) === 0) + { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = incWord(counter[1]); + } + return counter; + } + + var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + + incCounter(counter); + + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTRGladman.Decryptor = Encryptor; + + return CTRGladman; + }()); + + + + + /** + * Output Feedback block mode. + */ + CryptoJS.mode.OFB = (function () { + var OFB = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = OFB.Encryptor = OFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var keystream = this._keystream; + + // Generate keystream + if (iv) { + keystream = this._keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + OFB.Decryptor = Encryptor; + + return OFB; + }()); + + + /** + * Electronic Codebook block mode. + */ + CryptoJS.mode.ECB = (function () { + var ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + } + }); + + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + } + }); + + return ECB; + }()); + + + /** + * ANSI X.923 padding strategy. + */ + CryptoJS.pad.AnsiX923 = { + pad: function (data, blockSize) { + // Shortcuts + var dataSigBytes = data.sigBytes; + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; + + // Compute last byte position + var lastBytePos = dataSigBytes + nPaddingBytes - 1; + + // Pad + data.clamp(); + data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); + data.sigBytes += nPaddingBytes; + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + /** + * ISO 10126 padding strategy. + */ + CryptoJS.pad.Iso10126 = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Pad + data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). + concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + /** + * ISO/IEC 9797-1 Padding Method 2. + */ + CryptoJS.pad.Iso97971 = { + pad: function (data, blockSize) { + // Add 0x80 byte + data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); + + // Zero pad the rest + CryptoJS.pad.ZeroPadding.pad(data, blockSize); + }, + + unpad: function (data) { + // Remove zero padding + CryptoJS.pad.ZeroPadding.unpad(data); + + // Remove one more byte -- the 0x80 byte + data.sigBytes--; + } + }; + + + /** + * Zero padding strategy. + */ + CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + for (var i = data.sigBytes - 1; i >= 0; i--) { + if (((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + data.sigBytes = i + 1; + break; + } + } + } + }; + + + /** + * A noop padding strategy. + */ + CryptoJS.pad.NoPadding = { + pad: function () { + }, + + unpad: function () { + } + }; + + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var CipherParams = C_lib.CipherParams; + var C_enc = C.enc; + var Hex = C_enc.Hex; + var C_format = C.format; + + var HexFormatter = C_format.Hex = { + /** + * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The hexadecimally encoded string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.format.Hex.stringify(cipherParams); + */ + stringify: function (cipherParams) { + return cipherParams.ciphertext.toString(Hex); + }, + + /** + * Converts a hexadecimally encoded ciphertext string to a cipher params object. + * + * @param {string} input The hexadecimally encoded string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.Hex.parse(hexString); + */ + parse: function (input) { + var ciphertext = Hex.parse(input); + return CipherParams.create({ ciphertext: ciphertext }); + } + }; + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + var t; + + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Permuted Choice 1 constants + var PC1 = [ + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, + 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4 + ]; + + // Permuted Choice 2 constants + var PC2 = [ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ]; + + // Cumulative bit shift constants + var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; + + // SBOXes and round permutation constants + var SBOX_P = [ + { + 0x0: 0x808200, + 0x10000000: 0x8000, + 0x20000000: 0x808002, + 0x30000000: 0x2, + 0x40000000: 0x200, + 0x50000000: 0x808202, + 0x60000000: 0x800202, + 0x70000000: 0x800000, + 0x80000000: 0x202, + 0x90000000: 0x800200, + 0xa0000000: 0x8200, + 0xb0000000: 0x808000, + 0xc0000000: 0x8002, + 0xd0000000: 0x800002, + 0xe0000000: 0x0, + 0xf0000000: 0x8202, + 0x8000000: 0x0, + 0x18000000: 0x808202, + 0x28000000: 0x8202, + 0x38000000: 0x8000, + 0x48000000: 0x808200, + 0x58000000: 0x200, + 0x68000000: 0x808002, + 0x78000000: 0x2, + 0x88000000: 0x800200, + 0x98000000: 0x8200, + 0xa8000000: 0x808000, + 0xb8000000: 0x800202, + 0xc8000000: 0x800002, + 0xd8000000: 0x8002, + 0xe8000000: 0x202, + 0xf8000000: 0x800000, + 0x1: 0x8000, + 0x10000001: 0x2, + 0x20000001: 0x808200, + 0x30000001: 0x800000, + 0x40000001: 0x808002, + 0x50000001: 0x8200, + 0x60000001: 0x200, + 0x70000001: 0x800202, + 0x80000001: 0x808202, + 0x90000001: 0x808000, + 0xa0000001: 0x800002, + 0xb0000001: 0x8202, + 0xc0000001: 0x202, + 0xd0000001: 0x800200, + 0xe0000001: 0x8002, + 0xf0000001: 0x0, + 0x8000001: 0x808202, + 0x18000001: 0x808000, + 0x28000001: 0x800000, + 0x38000001: 0x200, + 0x48000001: 0x8000, + 0x58000001: 0x800002, + 0x68000001: 0x2, + 0x78000001: 0x8202, + 0x88000001: 0x8002, + 0x98000001: 0x800202, + 0xa8000001: 0x202, + 0xb8000001: 0x808200, + 0xc8000001: 0x800200, + 0xd8000001: 0x0, + 0xe8000001: 0x8200, + 0xf8000001: 0x808002 + }, + { + 0x0: 0x40084010, + 0x1000000: 0x4000, + 0x2000000: 0x80000, + 0x3000000: 0x40080010, + 0x4000000: 0x40000010, + 0x5000000: 0x40084000, + 0x6000000: 0x40004000, + 0x7000000: 0x10, + 0x8000000: 0x84000, + 0x9000000: 0x40004010, + 0xa000000: 0x40000000, + 0xb000000: 0x84010, + 0xc000000: 0x80010, + 0xd000000: 0x0, + 0xe000000: 0x4010, + 0xf000000: 0x40080000, + 0x800000: 0x40004000, + 0x1800000: 0x84010, + 0x2800000: 0x10, + 0x3800000: 0x40004010, + 0x4800000: 0x40084010, + 0x5800000: 0x40000000, + 0x6800000: 0x80000, + 0x7800000: 0x40080010, + 0x8800000: 0x80010, + 0x9800000: 0x0, + 0xa800000: 0x4000, + 0xb800000: 0x40080000, + 0xc800000: 0x40000010, + 0xd800000: 0x84000, + 0xe800000: 0x40084000, + 0xf800000: 0x4010, + 0x10000000: 0x0, + 0x11000000: 0x40080010, + 0x12000000: 0x40004010, + 0x13000000: 0x40084000, + 0x14000000: 0x40080000, + 0x15000000: 0x10, + 0x16000000: 0x84010, + 0x17000000: 0x4000, + 0x18000000: 0x4010, + 0x19000000: 0x80000, + 0x1a000000: 0x80010, + 0x1b000000: 0x40000010, + 0x1c000000: 0x84000, + 0x1d000000: 0x40004000, + 0x1e000000: 0x40000000, + 0x1f000000: 0x40084010, + 0x10800000: 0x84010, + 0x11800000: 0x80000, + 0x12800000: 0x40080000, + 0x13800000: 0x4000, + 0x14800000: 0x40004000, + 0x15800000: 0x40084010, + 0x16800000: 0x10, + 0x17800000: 0x40000000, + 0x18800000: 0x40084000, + 0x19800000: 0x40000010, + 0x1a800000: 0x40004010, + 0x1b800000: 0x80010, + 0x1c800000: 0x0, + 0x1d800000: 0x4010, + 0x1e800000: 0x40080010, + 0x1f800000: 0x84000 + }, + { + 0x0: 0x104, + 0x100000: 0x0, + 0x200000: 0x4000100, + 0x300000: 0x10104, + 0x400000: 0x10004, + 0x500000: 0x4000004, + 0x600000: 0x4010104, + 0x700000: 0x4010000, + 0x800000: 0x4000000, + 0x900000: 0x4010100, + 0xa00000: 0x10100, + 0xb00000: 0x4010004, + 0xc00000: 0x4000104, + 0xd00000: 0x10000, + 0xe00000: 0x4, + 0xf00000: 0x100, + 0x80000: 0x4010100, + 0x180000: 0x4010004, + 0x280000: 0x0, + 0x380000: 0x4000100, + 0x480000: 0x4000004, + 0x580000: 0x10000, + 0x680000: 0x10004, + 0x780000: 0x104, + 0x880000: 0x4, + 0x980000: 0x100, + 0xa80000: 0x4010000, + 0xb80000: 0x10104, + 0xc80000: 0x10100, + 0xd80000: 0x4000104, + 0xe80000: 0x4010104, + 0xf80000: 0x4000000, + 0x1000000: 0x4010100, + 0x1100000: 0x10004, + 0x1200000: 0x10000, + 0x1300000: 0x4000100, + 0x1400000: 0x100, + 0x1500000: 0x4010104, + 0x1600000: 0x4000004, + 0x1700000: 0x0, + 0x1800000: 0x4000104, + 0x1900000: 0x4000000, + 0x1a00000: 0x4, + 0x1b00000: 0x10100, + 0x1c00000: 0x4010000, + 0x1d00000: 0x104, + 0x1e00000: 0x10104, + 0x1f00000: 0x4010004, + 0x1080000: 0x4000000, + 0x1180000: 0x104, + 0x1280000: 0x4010100, + 0x1380000: 0x0, + 0x1480000: 0x10004, + 0x1580000: 0x4000100, + 0x1680000: 0x100, + 0x1780000: 0x4010004, + 0x1880000: 0x10000, + 0x1980000: 0x4010104, + 0x1a80000: 0x10104, + 0x1b80000: 0x4000004, + 0x1c80000: 0x4000104, + 0x1d80000: 0x4010000, + 0x1e80000: 0x4, + 0x1f80000: 0x10100 + }, + { + 0x0: 0x80401000, + 0x10000: 0x80001040, + 0x20000: 0x401040, + 0x30000: 0x80400000, + 0x40000: 0x0, + 0x50000: 0x401000, + 0x60000: 0x80000040, + 0x70000: 0x400040, + 0x80000: 0x80000000, + 0x90000: 0x400000, + 0xa0000: 0x40, + 0xb0000: 0x80001000, + 0xc0000: 0x80400040, + 0xd0000: 0x1040, + 0xe0000: 0x1000, + 0xf0000: 0x80401040, + 0x8000: 0x80001040, + 0x18000: 0x40, + 0x28000: 0x80400040, + 0x38000: 0x80001000, + 0x48000: 0x401000, + 0x58000: 0x80401040, + 0x68000: 0x0, + 0x78000: 0x80400000, + 0x88000: 0x1000, + 0x98000: 0x80401000, + 0xa8000: 0x400000, + 0xb8000: 0x1040, + 0xc8000: 0x80000000, + 0xd8000: 0x400040, + 0xe8000: 0x401040, + 0xf8000: 0x80000040, + 0x100000: 0x400040, + 0x110000: 0x401000, + 0x120000: 0x80000040, + 0x130000: 0x0, + 0x140000: 0x1040, + 0x150000: 0x80400040, + 0x160000: 0x80401000, + 0x170000: 0x80001040, + 0x180000: 0x80401040, + 0x190000: 0x80000000, + 0x1a0000: 0x80400000, + 0x1b0000: 0x401040, + 0x1c0000: 0x80001000, + 0x1d0000: 0x400000, + 0x1e0000: 0x40, + 0x1f0000: 0x1000, + 0x108000: 0x80400000, + 0x118000: 0x80401040, + 0x128000: 0x0, + 0x138000: 0x401000, + 0x148000: 0x400040, + 0x158000: 0x80000000, + 0x168000: 0x80001040, + 0x178000: 0x40, + 0x188000: 0x80000040, + 0x198000: 0x1000, + 0x1a8000: 0x80001000, + 0x1b8000: 0x80400040, + 0x1c8000: 0x1040, + 0x1d8000: 0x80401000, + 0x1e8000: 0x400000, + 0x1f8000: 0x401040 + }, + { + 0x0: 0x80, + 0x1000: 0x1040000, + 0x2000: 0x40000, + 0x3000: 0x20000000, + 0x4000: 0x20040080, + 0x5000: 0x1000080, + 0x6000: 0x21000080, + 0x7000: 0x40080, + 0x8000: 0x1000000, + 0x9000: 0x20040000, + 0xa000: 0x20000080, + 0xb000: 0x21040080, + 0xc000: 0x21040000, + 0xd000: 0x0, + 0xe000: 0x1040080, + 0xf000: 0x21000000, + 0x800: 0x1040080, + 0x1800: 0x21000080, + 0x2800: 0x80, + 0x3800: 0x1040000, + 0x4800: 0x40000, + 0x5800: 0x20040080, + 0x6800: 0x21040000, + 0x7800: 0x20000000, + 0x8800: 0x20040000, + 0x9800: 0x0, + 0xa800: 0x21040080, + 0xb800: 0x1000080, + 0xc800: 0x20000080, + 0xd800: 0x21000000, + 0xe800: 0x1000000, + 0xf800: 0x40080, + 0x10000: 0x40000, + 0x11000: 0x80, + 0x12000: 0x20000000, + 0x13000: 0x21000080, + 0x14000: 0x1000080, + 0x15000: 0x21040000, + 0x16000: 0x20040080, + 0x17000: 0x1000000, + 0x18000: 0x21040080, + 0x19000: 0x21000000, + 0x1a000: 0x1040000, + 0x1b000: 0x20040000, + 0x1c000: 0x40080, + 0x1d000: 0x20000080, + 0x1e000: 0x0, + 0x1f000: 0x1040080, + 0x10800: 0x21000080, + 0x11800: 0x1000000, + 0x12800: 0x1040000, + 0x13800: 0x20040080, + 0x14800: 0x20000000, + 0x15800: 0x1040080, + 0x16800: 0x80, + 0x17800: 0x21040000, + 0x18800: 0x40080, + 0x19800: 0x21040080, + 0x1a800: 0x0, + 0x1b800: 0x21000000, + 0x1c800: 0x1000080, + 0x1d800: 0x40000, + 0x1e800: 0x20040000, + 0x1f800: 0x20000080 + }, + { + 0x0: 0x10000008, + 0x100: 0x2000, + 0x200: 0x10200000, + 0x300: 0x10202008, + 0x400: 0x10002000, + 0x500: 0x200000, + 0x600: 0x200008, + 0x700: 0x10000000, + 0x800: 0x0, + 0x900: 0x10002008, + 0xa00: 0x202000, + 0xb00: 0x8, + 0xc00: 0x10200008, + 0xd00: 0x202008, + 0xe00: 0x2008, + 0xf00: 0x10202000, + 0x80: 0x10200000, + 0x180: 0x10202008, + 0x280: 0x8, + 0x380: 0x200000, + 0x480: 0x202008, + 0x580: 0x10000008, + 0x680: 0x10002000, + 0x780: 0x2008, + 0x880: 0x200008, + 0x980: 0x2000, + 0xa80: 0x10002008, + 0xb80: 0x10200008, + 0xc80: 0x0, + 0xd80: 0x10202000, + 0xe80: 0x202000, + 0xf80: 0x10000000, + 0x1000: 0x10002000, + 0x1100: 0x10200008, + 0x1200: 0x10202008, + 0x1300: 0x2008, + 0x1400: 0x200000, + 0x1500: 0x10000000, + 0x1600: 0x10000008, + 0x1700: 0x202000, + 0x1800: 0x202008, + 0x1900: 0x0, + 0x1a00: 0x8, + 0x1b00: 0x10200000, + 0x1c00: 0x2000, + 0x1d00: 0x10002008, + 0x1e00: 0x10202000, + 0x1f00: 0x200008, + 0x1080: 0x8, + 0x1180: 0x202000, + 0x1280: 0x200000, + 0x1380: 0x10000008, + 0x1480: 0x10002000, + 0x1580: 0x2008, + 0x1680: 0x10202008, + 0x1780: 0x10200000, + 0x1880: 0x10202000, + 0x1980: 0x10200008, + 0x1a80: 0x2000, + 0x1b80: 0x202008, + 0x1c80: 0x200008, + 0x1d80: 0x0, + 0x1e80: 0x10000000, + 0x1f80: 0x10002008 + }, + { + 0x0: 0x100000, + 0x10: 0x2000401, + 0x20: 0x400, + 0x30: 0x100401, + 0x40: 0x2100401, + 0x50: 0x0, + 0x60: 0x1, + 0x70: 0x2100001, + 0x80: 0x2000400, + 0x90: 0x100001, + 0xa0: 0x2000001, + 0xb0: 0x2100400, + 0xc0: 0x2100000, + 0xd0: 0x401, + 0xe0: 0x100400, + 0xf0: 0x2000000, + 0x8: 0x2100001, + 0x18: 0x0, + 0x28: 0x2000401, + 0x38: 0x2100400, + 0x48: 0x100000, + 0x58: 0x2000001, + 0x68: 0x2000000, + 0x78: 0x401, + 0x88: 0x100401, + 0x98: 0x2000400, + 0xa8: 0x2100000, + 0xb8: 0x100001, + 0xc8: 0x400, + 0xd8: 0x2100401, + 0xe8: 0x1, + 0xf8: 0x100400, + 0x100: 0x2000000, + 0x110: 0x100000, + 0x120: 0x2000401, + 0x130: 0x2100001, + 0x140: 0x100001, + 0x150: 0x2000400, + 0x160: 0x2100400, + 0x170: 0x100401, + 0x180: 0x401, + 0x190: 0x2100401, + 0x1a0: 0x100400, + 0x1b0: 0x1, + 0x1c0: 0x0, + 0x1d0: 0x2100000, + 0x1e0: 0x2000001, + 0x1f0: 0x400, + 0x108: 0x100400, + 0x118: 0x2000401, + 0x128: 0x2100001, + 0x138: 0x1, + 0x148: 0x2000000, + 0x158: 0x100000, + 0x168: 0x401, + 0x178: 0x2100400, + 0x188: 0x2000001, + 0x198: 0x2100000, + 0x1a8: 0x0, + 0x1b8: 0x2100401, + 0x1c8: 0x100401, + 0x1d8: 0x400, + 0x1e8: 0x2000400, + 0x1f8: 0x100001 + }, + { + 0x0: 0x8000820, + 0x1: 0x20000, + 0x2: 0x8000000, + 0x3: 0x20, + 0x4: 0x20020, + 0x5: 0x8020820, + 0x6: 0x8020800, + 0x7: 0x800, + 0x8: 0x8020000, + 0x9: 0x8000800, + 0xa: 0x20800, + 0xb: 0x8020020, + 0xc: 0x820, + 0xd: 0x0, + 0xe: 0x8000020, + 0xf: 0x20820, + 0x80000000: 0x800, + 0x80000001: 0x8020820, + 0x80000002: 0x8000820, + 0x80000003: 0x8000000, + 0x80000004: 0x8020000, + 0x80000005: 0x20800, + 0x80000006: 0x20820, + 0x80000007: 0x20, + 0x80000008: 0x8000020, + 0x80000009: 0x820, + 0x8000000a: 0x20020, + 0x8000000b: 0x8020800, + 0x8000000c: 0x0, + 0x8000000d: 0x8020020, + 0x8000000e: 0x8000800, + 0x8000000f: 0x20000, + 0x10: 0x20820, + 0x11: 0x8020800, + 0x12: 0x20, + 0x13: 0x800, + 0x14: 0x8000800, + 0x15: 0x8000020, + 0x16: 0x8020020, + 0x17: 0x20000, + 0x18: 0x0, + 0x19: 0x20020, + 0x1a: 0x8020000, + 0x1b: 0x8000820, + 0x1c: 0x8020820, + 0x1d: 0x20800, + 0x1e: 0x820, + 0x1f: 0x8000000, + 0x80000010: 0x20000, + 0x80000011: 0x800, + 0x80000012: 0x8020020, + 0x80000013: 0x20820, + 0x80000014: 0x20, + 0x80000015: 0x8020000, + 0x80000016: 0x8000000, + 0x80000017: 0x8000820, + 0x80000018: 0x8020820, + 0x80000019: 0x8000020, + 0x8000001a: 0x8000800, + 0x8000001b: 0x0, + 0x8000001c: 0x20800, + 0x8000001d: 0x820, + 0x8000001e: 0x20020, + 0x8000001f: 0x8020800 + } + ]; + + // Masks that select the SBOX input + var SBOX_MASK = [ + 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f + ]; + + /** + * DES block cipher algorithm. + */ + var DES = C_algo.DES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Select 56 bits according to PC1 + var keyBits = []; + for (var i = 0; i < 56; i++) { + var keyBitPos = PC1[i] - 1; + keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; + } + + // Assemble 16 subkeys + var subKeys = this._subKeys = []; + for (var nSubKey = 0; nSubKey < 16; nSubKey++) { + // Create subkey + var subKey = subKeys[nSubKey] = []; + + // Shortcut + var bitShift = BIT_SHIFTS[nSubKey]; + + // Select 48 bits according to PC2 + for (var i = 0; i < 24; i++) { + // Select from the left 28 key bits + subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); + + // Select from the right 28 key bits + subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); + } + + // Since each subkey is applied to an expanded 32-bit input, + // the subkey can be broken into 8 values scaled to 32-bits, + // which allows the key to be used without expansion + subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); + for (var i = 1; i < 7; i++) { + subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); + } + subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); + } + + // Compute inverse subkeys + var invSubKeys = this._invSubKeys = []; + for (var i = 0; i < 16; i++) { + invSubKeys[i] = subKeys[15 - i]; + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._subKeys); + }, + + decryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._invSubKeys); + }, + + _doCryptBlock: function (M, offset, subKeys) { + // Get input + this._lBlock = M[offset]; + this._rBlock = M[offset + 1]; + + // Initial permutation + exchangeLR.call(this, 4, 0x0f0f0f0f); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeRL.call(this, 2, 0x33333333); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeLR.call(this, 1, 0x55555555); + + // Rounds + for (var round = 0; round < 16; round++) { + // Shortcuts + var subKey = subKeys[round]; + var lBlock = this._lBlock; + var rBlock = this._rBlock; + + // Feistel function + var f = 0; + for (var i = 0; i < 8; i++) { + f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; + } + this._lBlock = rBlock; + this._rBlock = lBlock ^ f; + } + + // Undo swap from last round + var t = this._lBlock; + this._lBlock = this._rBlock; + this._rBlock = t; + + // Final permutation + exchangeLR.call(this, 1, 0x55555555); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeRL.call(this, 2, 0x33333333); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeLR.call(this, 4, 0x0f0f0f0f); + + // Set output + M[offset] = this._lBlock; + M[offset + 1] = this._rBlock; + }, + + keySize: 64/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + // Swap bits across the left and right words + function exchangeLR(offset, mask) { + var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; + this._rBlock ^= t; + this._lBlock ^= t << offset; + } + + function exchangeRL(offset, mask) { + var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; + this._lBlock ^= t; + this._rBlock ^= t << offset; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); + */ + C.DES = BlockCipher._createHelper(DES); + + /** + * Triple-DES block cipher algorithm. + */ + var TripleDES = C_algo.TripleDES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + // Make sure the key length is valid (64, 128 or >= 192 bit) + if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) { + throw new Error('Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.'); + } + + // Extend the key according to the keying options defined in 3DES standard + var key1 = keyWords.slice(0, 2); + var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4); + var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6); + + // Create DES instances + this._des1 = DES.createEncryptor(WordArray.create(key1)); + this._des2 = DES.createEncryptor(WordArray.create(key2)); + this._des3 = DES.createEncryptor(WordArray.create(key3)); + }, + + encryptBlock: function (M, offset) { + this._des1.encryptBlock(M, offset); + this._des2.decryptBlock(M, offset); + this._des3.encryptBlock(M, offset); + }, + + decryptBlock: function (M, offset) { + this._des3.decryptBlock(M, offset); + this._des2.encryptBlock(M, offset); + this._des1.decryptBlock(M, offset); + }, + + keySize: 192/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); + */ + C.TripleDES = BlockCipher._createHelper(TripleDES); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + /** + * RC4 stream cipher algorithm. + */ + var RC4 = C_algo.RC4 = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySigBytes = key.sigBytes; + + // Init sbox + var S = this._S = []; + for (var i = 0; i < 256; i++) { + S[i] = i; + } + + // Key setup + for (var i = 0, j = 0; i < 256; i++) { + var keyByteIndex = i % keySigBytes; + var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; + + j = (j + S[i] + keyByte) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + } + + // Counters + this._i = this._j = 0; + }, + + _doProcessBlock: function (M, offset) { + M[offset] ^= generateKeystreamWord.call(this); + }, + + keySize: 256/32, + + ivSize: 0 + }); + + function generateKeystreamWord() { + // Shortcuts + var S = this._S; + var i = this._i; + var j = this._j; + + // Generate keystream word + var keystreamWord = 0; + for (var n = 0; n < 4; n++) { + i = (i + 1) % 256; + j = (j + S[i]) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + + keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); + } + + // Update counters + this._i = i; + this._j = j; + + return keystreamWord; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); + */ + C.RC4 = StreamCipher._createHelper(RC4); + + /** + * Modified RC4 stream cipher algorithm. + */ + var RC4Drop = C_algo.RC4Drop = RC4.extend({ + /** + * Configuration options. + * + * @property {number} drop The number of keystream words to drop. Default 192 + */ + cfg: RC4.cfg.extend({ + drop: 192 + }), + + _doReset: function () { + RC4._doReset.call(this); + + // Drop + for (var i = this.cfg.drop; i > 0; i--) { + generateKeystreamWord.call(this); + } + } + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); + */ + C.RC4Drop = StreamCipher._createHelper(RC4Drop); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm + */ + var Rabbit = C_algo.Rabbit = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Swap endian + for (var i = 0; i < 4; i++) { + K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | + (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); + } + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); + */ + C.Rabbit = StreamCipher._createHelper(Rabbit); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm. + * + * This is a legacy version that neglected to convert the key to little-endian. + * This error doesn't affect the cipher's security, + * but it does affect its compatibility with other implementations. + */ + var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); + */ + C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); + }()); + + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + const N = 16; + + //Origin pbox and sbox, derived from PI + const ORIG_P = [ + 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, + 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, + 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, + 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, + 0x9216D5D9, 0x8979FB1B + ]; + + const ORIG_S = [ + [ 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, + 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, + 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, + 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, + 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, + 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, + 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, + 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, + 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, + 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, + 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, + 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, + 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, + 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, + 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, + 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, + 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, + 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, + 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, + 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, + 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, + 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, + 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, + 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, + 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, + 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, + 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, + 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, + 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, + 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, + 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, + 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, + 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, + 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, + 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, + 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, + 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, + 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, + 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, + 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, + 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, + 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, + 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, + 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, + 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, + 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, + 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, + 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, + 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, + 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, + 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, + 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, + 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, + 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, + 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, + 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, + 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, + 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, + 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, + 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, + 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, + 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, + 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, + 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A ], + [ 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, + 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, + 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, + 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, + 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, + 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, + 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, + 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, + 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, + 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, + 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, + 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, + 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, + 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, + 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, + 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, + 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, + 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, + 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, + 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, + 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, + 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, + 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, + 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, + 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, + 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, + 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, + 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, + 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, + 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, + 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, + 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, + 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, + 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, + 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, + 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, + 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, + 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, + 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, + 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, + 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, + 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, + 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, + 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, + 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, + 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, + 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, + 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, + 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, + 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, + 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, + 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, + 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, + 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, + 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, + 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, + 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, + 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, + 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, + 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, + 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, + 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, + 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, + 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 ], + [ 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, + 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, + 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, + 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, + 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, + 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, + 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, + 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, + 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, + 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, + 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, + 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, + 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, + 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, + 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, + 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, + 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, + 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, + 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, + 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, + 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, + 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, + 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, + 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, + 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, + 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, + 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, + 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, + 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, + 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, + 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, + 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, + 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, + 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, + 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, + 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, + 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, + 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, + 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, + 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, + 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, + 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, + 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, + 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, + 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, + 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, + 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, + 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, + 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, + 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, + 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, + 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, + 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, + 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, + 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, + 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, + 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, + 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, + 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, + 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, + 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, + 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, + 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, + 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 ], + [ 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, + 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, + 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, + 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, + 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, + 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, + 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, + 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, + 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, + 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, + 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, + 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, + 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, + 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, + 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, + 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, + 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, + 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, + 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, + 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, + 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, + 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, + 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, + 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, + 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, + 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, + 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, + 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, + 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, + 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, + 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, + 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, + 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, + 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, + 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, + 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, + 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, + 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, + 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, + 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, + 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, + 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, + 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, + 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, + 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, + 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, + 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, + 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, + 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, + 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, + 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, + 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, + 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, + 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, + 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, + 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, + 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, + 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, + 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, + 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, + 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, + 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, + 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, + 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 ] + ]; + + var BLOWFISH_CTX = { + pbox: [], + sbox: [] + } + + function F(ctx, x){ + let a = (x >> 24) & 0xFF; + let b = (x >> 16) & 0xFF; + let c = (x >> 8) & 0xFF; + let d = x & 0xFF; + + let y = ctx.sbox[0][a] + ctx.sbox[1][b]; + y = y ^ ctx.sbox[2][c]; + y = y + ctx.sbox[3][d]; + + return y; + } + + function BlowFish_Encrypt(ctx, left, right){ + let Xl = left; + let Xr = right; + let temp; + + for(let i = 0; i < N; ++i){ + Xl = Xl ^ ctx.pbox[i]; + Xr = F(ctx, Xl) ^ Xr; + + temp = Xl; + Xl = Xr; + Xr = temp; + } + + temp = Xl; + Xl = Xr; + Xr = temp; + + Xr = Xr ^ ctx.pbox[N]; + Xl = Xl ^ ctx.pbox[N + 1]; + + return {left: Xl, right: Xr}; + } + + function BlowFish_Decrypt(ctx, left, right){ + let Xl = left; + let Xr = right; + let temp; + + for(let i = N + 1; i > 1; --i){ + Xl = Xl ^ ctx.pbox[i]; + Xr = F(ctx, Xl) ^ Xr; + + temp = Xl; + Xl = Xr; + Xr = temp; + } + + temp = Xl; + Xl = Xr; + Xr = temp; + + Xr = Xr ^ ctx.pbox[1]; + Xl = Xl ^ ctx.pbox[0]; + + return {left: Xl, right: Xr}; + } + + /** + * Initialization ctx's pbox and sbox. + * + * @param {Object} ctx The object has pbox and sbox. + * @param {Array} key An array of 32-bit words. + * @param {int} keysize The length of the key. + * + * @example + * + * BlowFishInit(BLOWFISH_CTX, key, 128/32); + */ + function BlowFishInit(ctx, key, keysize) + { + for(let Row = 0; Row < 4; Row++) + { + ctx.sbox[Row] = []; + for(let Col = 0; Col < 256; Col++) + { + ctx.sbox[Row][Col] = ORIG_S[Row][Col]; + } + } + + let keyIndex = 0; + for(let index = 0; index < N + 2; index++) + { + ctx.pbox[index] = ORIG_P[index] ^ key[keyIndex]; + keyIndex++; + if(keyIndex >= keysize) + { + keyIndex = 0; + } + } + + let Data1 = 0; + let Data2 = 0; + let res = 0; + for(let i = 0; i < N + 2; i += 2) + { + res = BlowFish_Encrypt(ctx, Data1, Data2); + Data1 = res.left; + Data2 = res.right; + ctx.pbox[i] = Data1; + ctx.pbox[i + 1] = Data2; + } + + for(let i = 0; i < 4; i++) + { + for(let j = 0; j < 256; j += 2) + { + res = BlowFish_Encrypt(ctx, Data1, Data2); + Data1 = res.left; + Data2 = res.right; + ctx.sbox[i][j] = Data1; + ctx.sbox[i][j + 1] = Data2; + } + } + + return true; + } + + /** + * Blowfish block cipher algorithm. + */ + var Blowfish = C_algo.Blowfish = BlockCipher.extend({ + _doReset: function () { + // Skip reset of nRounds has been set before and key did not change + if (this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + //Initialization pbox and sbox + BlowFishInit(BLOWFISH_CTX, keyWords, keySize); + }, + + encryptBlock: function (M, offset) { + var res = BlowFish_Encrypt(BLOWFISH_CTX, M[offset], M[offset + 1]); + M[offset] = res.left; + M[offset + 1] = res.right; + }, + + decryptBlock: function (M, offset) { + var res = BlowFish_Decrypt(BLOWFISH_CTX, M[offset], M[offset + 1]); + M[offset] = res.left; + M[offset + 1] = res.right; + }, + + blockSize: 64/32, + + keySize: 128/32, + + ivSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Blowfish.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Blowfish.decrypt(ciphertext, key, cfg); + */ + C.Blowfish = BlockCipher._createHelper(Blowfish); + }()); + + + return CryptoJS; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/docs/QuickStartGuide.wiki b/test/merkletreejs/node_modules/crypto-js/docs/QuickStartGuide.wiki new file mode 100644 index 0000000..6b20199 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/docs/QuickStartGuide.wiki @@ -0,0 +1,470 @@ + + +---- + += Quick-start Guide = + +== Hashers == + +=== The Hasher Algorithms === + +==== MD5 ==== + +MD5 is a widely used hash function. It's been used in a variety of security applications and is also commonly used to check the integrity of files. Though, MD5 is not collision resistant, and it isn't suitable for applications like SSL certificates or digital signatures that rely on this property. + +{{{ + + +}}} + +==== SHA-1 ==== + +The SHA hash functions were designed by the National Security Agency (NSA). SHA-1 is the most established of the existing SHA hash functions, and it's used in a variety of security applications and protocols. Though, SHA-1's collision resistance has been weakening as new attacks are discovered or improved. + +{{{ + + +}}} + +==== SHA-2 ==== + +SHA-256 is one of the four variants in the SHA-2 set. It isn't as widely used as SHA-1, though it appears to provide much better security. + +{{{ + + +}}} + +SHA-512 is largely identical to SHA-256 but operates on 64-bit words rather than 32. + +{{{ + + +}}} + +CryptoJS also supports SHA-224 and SHA-384, which are largely identical but truncated versions of SHA-256 and SHA-512 respectively. + +==== SHA-3 ==== + +SHA-3 is the winner of a five-year competition to select a new cryptographic hash algorithm where 64 competing designs were evaluated. + +{{{ + + +}}} + +SHA-3 can be configured to output hash lengths of one of 224, 256, 384, or 512 bits. The default is 512 bits. + +{{{ + + +}}} + +==== RIPEMD-160 ==== + +{{{ + + +}}} + +=== The Hasher Input === + +The hash algorithms accept either strings or instances of CryptoJS.lib.WordArray. A WordArray object represents an array of 32-bit words. When you pass a string, it's automatically converted to a WordArray encoded as UTF-8. + +=== The Hasher Output === + +The hash you get back isn't a string yet. It's a WordArray object. When you use a WordArray object in a string context, it's automatically converted to a hex string. + +{{{ + + +}}} + +You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder. + +{{{ + + + +}}} + +=== Progressive Hashing === + +{{{ + + +}}} + +== HMAC == + +Keyed-hash message authentication codes (HMAC) is a mechanism for message authentication using cryptographic hash functions. + +HMAC can be used in combination with any iterated cryptographic hash function. + +{{{ + + + + + +}}} + +=== Progressive HMAC Hashing === + +{{{ + + +}}} + +== PBKDF2 == + +PBKDF2 is a password-based key derivation function. In many applications of cryptography, user security is ultimately dependent on a password, and because a password usually can't be used directly as a cryptographic key, some processing is required. + +A salt provides a large set of keys for any given password, and an iteration count increases the cost of producing keys from a password, thereby also increasing the difficulty of attack. + +{{{ + + +}}} + +== Ciphers == + +=== The Cipher Algorithms === + +==== AES ==== + +The Advanced Encryption Standard (AES) is a U.S. Federal Information Processing Standard (FIPS). It was selected after a 5-year process where 15 competing designs were evaluated. + +{{{ + + +}}} + +CryptoJS supports AES-128, AES-192, and AES-256. It will pick the variant by the size of the key you pass in. If you use a passphrase, then it will generate a 256-bit key. + +==== DES, Triple DES ==== + +DES is a previously dominant algorithm for encryption, and was published as an official Federal Information Processing Standard (FIPS). DES is now considered to be insecure due to the small key size. + +{{{ + + +}}} + +Triple DES applies DES three times to each block to increase the key size. The algorithm is believed to be secure in this form. + +{{{ + + +}}} + +==== Rabbit ==== + +Rabbit is a high-performance stream cipher and a finalist in the eSTREAM Portfolio. It is one of the four designs selected after a 3 1/2-year process where 22 designs were evaluated. + +{{{ + + +}}} + +==== RC4, RC4Drop ==== + +RC4 is a widely-used stream cipher. It's used in popular protocols such as SSL and WEP. Although remarkable for its simplicity and speed, the algorithm's history doesn't inspire confidence in its security. + +{{{ + + +}}} + +It was discovered that the first few bytes of keystream are strongly non-random and leak information about the key. We can defend against this attack by discarding the initial portion of the keystream. This modified algorithm is traditionally called RC4-drop. + +By default, 192 words (768 bytes) are dropped, but you can configure the algorithm to drop any number of words. + +{{{ + + +}}} + +=== Custom Key and IV === + +{{{ + + +}}} + +=== Block Modes and Padding === + +{{{ + + + + +}}} + +CryptoJS supports the following modes: + + * CBC (the default) + * CFB + * CTR + * OFB + * ECB + +And CryptoJS supports the following padding schemes: + + * Pkcs7 (the default) + * Iso97971 + * AnsiX923 + * Iso10126 + * ZeroPadding + * NoPadding + +=== The Cipher Input === + +For the plaintext message, the cipher algorithms accept either strings or instances of CryptoJS.lib.WordArray. + +For the key, when you pass a string, it's treated as a passphrase and used to derive an actual key and IV. Or you can pass a WordArray that represents the actual key. If you pass the actual key, you must also pass the actual IV. + +For the ciphertext, the cipher algorithms accept either strings or instances of CryptoJS.lib.CipherParams. A CipherParams object represents a collection of parameters such as the IV, a salt, and the raw ciphertext itself. When you pass a string, it's automatically converted to a CipherParams object according to a configurable format strategy. + +=== The Cipher Output === + +The plaintext you get back after decryption is a WordArray object. See Hashers' Output for more detail. + +The ciphertext you get back after encryption isn't a string yet. It's a CipherParams object. A CipherParams object gives you access to all the parameters used during encryption. When you use a CipherParams object in a string context, it's automatically converted to a string according to a format strategy. The default is an OpenSSL-compatible format. + +{{{ + + +}}} + +You can define your own formats in order to be compatible with other crypto implementations. A format is an object with two methods—stringify and parse—that converts between CipherParams objects and ciphertext strings. + +Here's how you might write a JSON formatter: + +{{{ + + +}}} + +=== Progressive Ciphering === + +{{{ + + +}}} + +=== Interoperability === + +==== With OpenSSL ==== + +Encrypt with OpenSSL: + +{{{ +openssl enc -aes-256-cbc -in infile -out outfile -pass pass:"Secret Passphrase" -e -base64 +}}} + +Decrypt with CryptoJS: + +{{{ + + +}}} + +== Encoders == + +CryptoJS can convert from encoding formats such as Base64, Latin1 or Hex to WordArray objects and vica versa. + +{{{ + + + + +}}} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/enc-base64.js b/test/merkletreejs/node_modules/crypto-js/enc-base64.js new file mode 100644 index 0000000..0ffcd53 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/enc-base64.js @@ -0,0 +1,136 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + var Base64 = C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + return CryptoJS.enc.Base64; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/enc-base64url.js b/test/merkletreejs/node_modules/crypto-js/enc-base64url.js new file mode 100644 index 0000000..af682e3 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/enc-base64url.js @@ -0,0 +1,148 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64url encoding strategy. + */ + var Base64url = C_enc.Base64url = { + /** + * Converts a word array to a Base64url string. + * + * @param {WordArray} wordArray The word array. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {string} The Base64url string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64url.stringify(wordArray); + */ + stringify: function (wordArray, urlSafe) { + if (urlSafe === undefined) { + urlSafe = true + } + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = urlSafe ? this._safe_map : this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64url string to a word array. + * + * @param {string} base64Str The Base64url string. + * + * @param {boolean} urlSafe Whether to use url safe + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64url.parse(base64String); + */ + parse: function (base64Str, urlSafe) { + if (urlSafe === undefined) { + urlSafe = true + } + + // Shortcuts + var base64StrLength = base64Str.length; + var map = urlSafe ? this._safe_map : this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + _safe_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + var bitsCombined = bits1 | bits2; + words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + return CryptoJS.enc.Base64url; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/enc-hex.js b/test/merkletreejs/node_modules/crypto-js/enc-hex.js new file mode 100644 index 0000000..88161ff --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/enc-hex.js @@ -0,0 +1,18 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.enc.Hex; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/enc-latin1.js b/test/merkletreejs/node_modules/crypto-js/enc-latin1.js new file mode 100644 index 0000000..ade56dc --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/enc-latin1.js @@ -0,0 +1,18 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.enc.Latin1; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/enc-utf16.js b/test/merkletreejs/node_modules/crypto-js/enc-utf16.js new file mode 100644 index 0000000..7de6245 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/enc-utf16.js @@ -0,0 +1,149 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * UTF-16 BE encoding strategy. + */ + var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { + /** + * Converts a word array to a UTF-16 BE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 BE string. + * + * @static + * + * @example + * + * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 BE string to a word array. + * + * @param {string} utf16Str The UTF-16 BE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + /** + * UTF-16 LE encoding strategy. + */ + C_enc.Utf16LE = { + /** + * Converts a word array to a UTF-16 LE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 LE string. + * + * @static + * + * @example + * + * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 LE string to a word array. + * + * @param {string} utf16Str The UTF-16 LE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + function swapEndian(word) { + return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); + } + }()); + + + return CryptoJS.enc.Utf16; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/enc-utf8.js b/test/merkletreejs/node_modules/crypto-js/enc-utf8.js new file mode 100644 index 0000000..e7a251d --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/enc-utf8.js @@ -0,0 +1,18 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.enc.Utf8; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/evpkdf.js b/test/merkletreejs/node_modules/crypto-js/evpkdf.js new file mode 100644 index 0000000..578974a --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/evpkdf.js @@ -0,0 +1,134 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha1", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + var block; + + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.EvpKDF; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/format-hex.js b/test/merkletreejs/node_modules/crypto-js/format-hex.js new file mode 100644 index 0000000..2e9a861 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/format-hex.js @@ -0,0 +1,66 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var CipherParams = C_lib.CipherParams; + var C_enc = C.enc; + var Hex = C_enc.Hex; + var C_format = C.format; + + var HexFormatter = C_format.Hex = { + /** + * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The hexadecimally encoded string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.format.Hex.stringify(cipherParams); + */ + stringify: function (cipherParams) { + return cipherParams.ciphertext.toString(Hex); + }, + + /** + * Converts a hexadecimally encoded ciphertext string to a cipher params object. + * + * @param {string} input The hexadecimally encoded string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.Hex.parse(hexString); + */ + parse: function (input) { + var ciphertext = Hex.parse(input); + return CipherParams.create({ ciphertext: ciphertext }); + } + }; + }()); + + + return CryptoJS.format.Hex; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/format-openssl.js b/test/merkletreejs/node_modules/crypto-js/format-openssl.js new file mode 100644 index 0000000..3373edc --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/format-openssl.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.format.OpenSSL; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-md5.js b/test/merkletreejs/node_modules/crypto-js/hmac-md5.js new file mode 100644 index 0000000..ad7a90a --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-md5.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./md5"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./md5", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacMD5; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-ripemd160.js b/test/merkletreejs/node_modules/crypto-js/hmac-ripemd160.js new file mode 100644 index 0000000..73d55a7 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-ripemd160.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./ripemd160"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./ripemd160", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacRIPEMD160; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-sha1.js b/test/merkletreejs/node_modules/crypto-js/hmac-sha1.js new file mode 100644 index 0000000..0b570cb --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-sha1.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha1", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA1; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-sha224.js b/test/merkletreejs/node_modules/crypto-js/hmac-sha224.js new file mode 100644 index 0000000..3778863 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-sha224.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256"), require("./sha224"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256", "./sha224", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA224; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-sha256.js b/test/merkletreejs/node_modules/crypto-js/hmac-sha256.js new file mode 100644 index 0000000..33b0c9f --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-sha256.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA256; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-sha3.js b/test/merkletreejs/node_modules/crypto-js/hmac-sha3.js new file mode 100644 index 0000000..1248804 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-sha3.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha3"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha3", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA3; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-sha384.js b/test/merkletreejs/node_modules/crypto-js/hmac-sha384.js new file mode 100644 index 0000000..0036e2b --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-sha384.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"), require("./sha384"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha512", "./sha384", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA384; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac-sha512.js b/test/merkletreejs/node_modules/crypto-js/hmac-sha512.js new file mode 100644 index 0000000..c1005b6 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac-sha512.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha512", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.HmacSHA512; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/hmac.js b/test/merkletreejs/node_modules/crypto-js/hmac.js new file mode 100644 index 0000000..8c09851 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/hmac.js @@ -0,0 +1,143 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var C_algo = C.algo; + + /** + * HMAC algorithm. + */ + var HMAC = C_algo.HMAC = Base.extend({ + /** + * Initializes a newly created HMAC. + * + * @param {Hasher} hasher The hash algorithm to use. + * @param {WordArray|string} key The secret key. + * + * @example + * + * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); + */ + init: function (hasher, key) { + // Init hasher + hasher = this._hasher = new hasher.init(); + + // Convert string to WordArray, else assume WordArray already + if (typeof key == 'string') { + key = Utf8.parse(key); + } + + // Shortcuts + var hasherBlockSize = hasher.blockSize; + var hasherBlockSizeBytes = hasherBlockSize * 4; + + // Allow arbitrary length keys + if (key.sigBytes > hasherBlockSizeBytes) { + key = hasher.finalize(key); + } + + // Clamp excess bits + key.clamp(); + + // Clone key for inner and outer pads + var oKey = this._oKey = key.clone(); + var iKey = this._iKey = key.clone(); + + // Shortcuts + var oKeyWords = oKey.words; + var iKeyWords = iKey.words; + + // XOR keys with pad constants + for (var i = 0; i < hasherBlockSize; i++) { + oKeyWords[i] ^= 0x5c5c5c5c; + iKeyWords[i] ^= 0x36363636; + } + oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; + + // Set initial values + this.reset(); + }, + + /** + * Resets this HMAC to its initial state. + * + * @example + * + * hmacHasher.reset(); + */ + reset: function () { + // Shortcut + var hasher = this._hasher; + + // Reset + hasher.reset(); + hasher.update(this._iKey); + }, + + /** + * Updates this HMAC with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {HMAC} This HMAC instance. + * + * @example + * + * hmacHasher.update('message'); + * hmacHasher.update(wordArray); + */ + update: function (messageUpdate) { + this._hasher.update(messageUpdate); + + // Chainable + return this; + }, + + /** + * Finalizes the HMAC computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The HMAC. + * + * @example + * + * var hmac = hmacHasher.finalize(); + * var hmac = hmacHasher.finalize('message'); + * var hmac = hmacHasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Shortcut + var hasher = this._hasher; + + // Compute HMAC + var innerHash = hasher.finalize(messageUpdate); + hasher.reset(); + var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); + + return hmac; + } + }); + }()); + + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/index.js b/test/merkletreejs/node_modules/crypto-js/index.js new file mode 100644 index 0000000..b696646 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/index.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./enc-base64url"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy"), require("./blowfish")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./enc-base64url", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy", "./blowfish"], factory); + } + else { + // Global (browser) + root.CryptoJS = factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/lib-typedarrays.js b/test/merkletreejs/node_modules/crypto-js/lib-typedarrays.js new file mode 100644 index 0000000..264b210 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/lib-typedarrays.js @@ -0,0 +1,76 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Check if typed arrays are supported + if (typeof ArrayBuffer != 'function') { + return; + } + + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + + // Reference original init + var superInit = WordArray.init; + + // Augment WordArray.init to handle typed arrays + var subInit = WordArray.init = function (typedArray) { + // Convert buffers to uint8 + if (typedArray instanceof ArrayBuffer) { + typedArray = new Uint8Array(typedArray); + } + + // Convert other array views to uint8 + if ( + typedArray instanceof Int8Array || + (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || + typedArray instanceof Int16Array || + typedArray instanceof Uint16Array || + typedArray instanceof Int32Array || + typedArray instanceof Uint32Array || + typedArray instanceof Float32Array || + typedArray instanceof Float64Array + ) { + typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); + } + + // Handle Uint8Array + if (typedArray instanceof Uint8Array) { + // Shortcut + var typedArrayByteLength = typedArray.byteLength; + + // Extract bytes + var words = []; + for (var i = 0; i < typedArrayByteLength; i++) { + words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); + } + + // Initialize this word array + superInit.call(this, words, typedArrayByteLength); + } else { + // Else call normal init + superInit.apply(this, arguments); + } + }; + + subInit.prototype = WordArray; + }()); + + + return CryptoJS.lib.WordArray; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/md5.js b/test/merkletreejs/node_modules/crypto-js/md5.js new file mode 100644 index 0000000..72fce03 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/md5.js @@ -0,0 +1,268 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); + }(Math)); + + + return CryptoJS.MD5; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/mode-cfb.js b/test/merkletreejs/node_modules/crypto-js/mode-cfb.js new file mode 100644 index 0000000..444c9cb --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/mode-cfb.js @@ -0,0 +1,80 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Cipher Feedback block mode. + */ + CryptoJS.mode.CFB = (function () { + var CFB = CryptoJS.lib.BlockCipherMode.extend(); + + CFB.Encryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + CFB.Decryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { + var keystream; + + // Shortcut + var iv = this._iv; + + // Generate keystream + if (iv) { + keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + keystream = this._prevBlock; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + + return CFB; + }()); + + + return CryptoJS.mode.CFB; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/mode-ctr-gladman.js b/test/merkletreejs/node_modules/crypto-js/mode-ctr-gladman.js new file mode 100644 index 0000000..bbc5687 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/mode-ctr-gladman.js @@ -0,0 +1,116 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** @preserve + * Counter block mode compatible with Dr Brian Gladman fileenc.c + * derived from CryptoJS.mode.CTR + * Jan Hruby jhruby.web@gmail.com + */ + CryptoJS.mode.CTRGladman = (function () { + var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); + + function incWord(word) + { + if (((word >> 24) & 0xff) === 0xff) { //overflow + var b1 = (word >> 16)&0xff; + var b2 = (word >> 8)&0xff; + var b3 = word & 0xff; + + if (b1 === 0xff) // overflow b1 + { + b1 = 0; + if (b2 === 0xff) + { + b2 = 0; + if (b3 === 0xff) + { + b3 = 0; + } + else + { + ++b3; + } + } + else + { + ++b2; + } + } + else + { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } + else + { + word += (0x01 << 24); + } + return word; + } + + function incCounter(counter) + { + if ((counter[0] = incWord(counter[0])) === 0) + { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = incWord(counter[1]); + } + return counter; + } + + var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + + incCounter(counter); + + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTRGladman.Decryptor = Encryptor; + + return CTRGladman; + }()); + + + + + return CryptoJS.mode.CTRGladman; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/mode-ctr.js b/test/merkletreejs/node_modules/crypto-js/mode-ctr.js new file mode 100644 index 0000000..c3d470a --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/mode-ctr.js @@ -0,0 +1,58 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Counter block mode. + */ + CryptoJS.mode.CTR = (function () { + var CTR = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = CTR.Encryptor = CTR.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Increment counter + counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTR.Decryptor = Encryptor; + + return CTR; + }()); + + + return CryptoJS.mode.CTR; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/mode-ecb.js b/test/merkletreejs/node_modules/crypto-js/mode-ecb.js new file mode 100644 index 0000000..ff06921 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/mode-ecb.js @@ -0,0 +1,40 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Electronic Codebook block mode. + */ + CryptoJS.mode.ECB = (function () { + var ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + } + }); + + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + } + }); + + return ECB; + }()); + + + return CryptoJS.mode.ECB; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/mode-ofb.js b/test/merkletreejs/node_modules/crypto-js/mode-ofb.js new file mode 100644 index 0000000..c01314c --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/mode-ofb.js @@ -0,0 +1,54 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Output Feedback block mode. + */ + CryptoJS.mode.OFB = (function () { + var OFB = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = OFB.Encryptor = OFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var keystream = this._keystream; + + // Generate keystream + if (iv) { + keystream = this._keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + OFB.Decryptor = Encryptor; + + return OFB; + }()); + + + return CryptoJS.mode.OFB; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/package.json b/test/merkletreejs/node_modules/crypto-js/package.json new file mode 100644 index 0000000..4b9a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/package.json @@ -0,0 +1,42 @@ +{ + "name": "crypto-js", + "version": "4.2.0", + "description": "JavaScript library of crypto standards.", + "license": "MIT", + "author": { + "name": "Evan Vosberg", + "url": "http://github.com/evanvosberg" + }, + "homepage": "http://github.com/brix/crypto-js", + "repository": { + "type": "git", + "url": "http://github.com/brix/crypto-js.git" + }, + "keywords": [ + "security", + "crypto", + "Hash", + "MD5", + "SHA1", + "SHA-1", + "SHA256", + "SHA-256", + "RC4", + "Rabbit", + "AES", + "DES", + "PBKDF2", + "HMAC", + "OFB", + "CFB", + "CTR", + "CBC", + "Base64", + "Base64url" + ], + "main": "index.js", + "dependencies": {}, + "browser": { + "crypto": false + } +} diff --git a/test/merkletreejs/node_modules/crypto-js/pad-ansix923.js b/test/merkletreejs/node_modules/crypto-js/pad-ansix923.js new file mode 100644 index 0000000..f01f21e --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pad-ansix923.js @@ -0,0 +1,49 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * ANSI X.923 padding strategy. + */ + CryptoJS.pad.AnsiX923 = { + pad: function (data, blockSize) { + // Shortcuts + var dataSigBytes = data.sigBytes; + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; + + // Compute last byte position + var lastBytePos = dataSigBytes + nPaddingBytes - 1; + + // Pad + data.clamp(); + data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); + data.sigBytes += nPaddingBytes; + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Ansix923; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/pad-iso10126.js b/test/merkletreejs/node_modules/crypto-js/pad-iso10126.js new file mode 100644 index 0000000..6e2aefd --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pad-iso10126.js @@ -0,0 +1,44 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * ISO 10126 padding strategy. + */ + CryptoJS.pad.Iso10126 = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Pad + data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). + concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Iso10126; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/pad-iso97971.js b/test/merkletreejs/node_modules/crypto-js/pad-iso97971.js new file mode 100644 index 0000000..41049b4 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pad-iso97971.js @@ -0,0 +1,40 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * ISO/IEC 9797-1 Padding Method 2. + */ + CryptoJS.pad.Iso97971 = { + pad: function (data, blockSize) { + // Add 0x80 byte + data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); + + // Zero pad the rest + CryptoJS.pad.ZeroPadding.pad(data, blockSize); + }, + + unpad: function (data) { + // Remove zero padding + CryptoJS.pad.ZeroPadding.unpad(data); + + // Remove one more byte -- the 0x80 byte + data.sigBytes--; + } + }; + + + return CryptoJS.pad.Iso97971; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/pad-nopadding.js b/test/merkletreejs/node_modules/crypto-js/pad-nopadding.js new file mode 100644 index 0000000..c7787c9 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pad-nopadding.js @@ -0,0 +1,30 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * A noop padding strategy. + */ + CryptoJS.pad.NoPadding = { + pad: function () { + }, + + unpad: function () { + } + }; + + + return CryptoJS.pad.NoPadding; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/pad-pkcs7.js b/test/merkletreejs/node_modules/crypto-js/pad-pkcs7.js new file mode 100644 index 0000000..3555168 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pad-pkcs7.js @@ -0,0 +1,18 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + return CryptoJS.pad.Pkcs7; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/pad-zeropadding.js b/test/merkletreejs/node_modules/crypto-js/pad-zeropadding.js new file mode 100644 index 0000000..a1a459e --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pad-zeropadding.js @@ -0,0 +1,47 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** + * Zero padding strategy. + */ + CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + for (var i = data.sigBytes - 1; i >= 0; i--) { + if (((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + data.sigBytes = i + 1; + break; + } + } + } + }; + + + return CryptoJS.pad.ZeroPadding; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/pbkdf2.js b/test/merkletreejs/node_modules/crypto-js/pbkdf2.js new file mode 100644 index 0000000..6850934 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/pbkdf2.js @@ -0,0 +1,145 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256"), require("./hmac")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256", "./hmac"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + var HMAC = C_algo.HMAC; + + /** + * Password-Based Key Derivation Function 2 algorithm. + */ + var PBKDF2 = C_algo.PBKDF2 = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hasher to use. Default: SHA256 + * @property {number} iterations The number of iterations to perform. Default: 250000 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: SHA256, + iterations: 250000 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.PBKDF2.create(); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init HMAC + var hmac = HMAC.create(cfg.hasher, password); + + // Initial values + var derivedKey = WordArray.create(); + var blockIndex = WordArray.create([0x00000001]); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var blockIndexWords = blockIndex.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + var block = hmac.update(salt).finalize(blockIndex); + hmac.reset(); + + // Shortcuts + var blockWords = block.words; + var blockWordsLength = blockWords.length; + + // Iterations + var intermediate = block; + for (var i = 1; i < iterations; i++) { + intermediate = hmac.finalize(intermediate); + hmac.reset(); + + // Shortcut + var intermediateWords = intermediate.words; + + // XOR intermediate with block + for (var j = 0; j < blockWordsLength; j++) { + blockWords[j] ^= intermediateWords[j]; + } + } + + derivedKey.concat(block); + blockIndexWords[0]++; + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.PBKDF2(password, salt); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.PBKDF2 = function (password, salt, cfg) { + return PBKDF2.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.PBKDF2; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/rabbit-legacy.js b/test/merkletreejs/node_modules/crypto-js/rabbit-legacy.js new file mode 100644 index 0000000..e118b6b --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/rabbit-legacy.js @@ -0,0 +1,190 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm. + * + * This is a legacy version that neglected to convert the key to little-endian. + * This error doesn't affect the cipher's security, + * but it does affect its compatibility with other implementations. + */ + var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); + */ + C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); + }()); + + + return CryptoJS.RabbitLegacy; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/rabbit.js b/test/merkletreejs/node_modules/crypto-js/rabbit.js new file mode 100644 index 0000000..1b06833 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/rabbit.js @@ -0,0 +1,192 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm + */ + var Rabbit = C_algo.Rabbit = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Swap endian + for (var i = 0; i < 4; i++) { + K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | + (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); + } + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); + */ + C.Rabbit = StreamCipher._createHelper(Rabbit); + }()); + + + return CryptoJS.Rabbit; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/rc4.js b/test/merkletreejs/node_modules/crypto-js/rc4.js new file mode 100644 index 0000000..0e4bdff --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/rc4.js @@ -0,0 +1,139 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + /** + * RC4 stream cipher algorithm. + */ + var RC4 = C_algo.RC4 = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySigBytes = key.sigBytes; + + // Init sbox + var S = this._S = []; + for (var i = 0; i < 256; i++) { + S[i] = i; + } + + // Key setup + for (var i = 0, j = 0; i < 256; i++) { + var keyByteIndex = i % keySigBytes; + var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; + + j = (j + S[i] + keyByte) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + } + + // Counters + this._i = this._j = 0; + }, + + _doProcessBlock: function (M, offset) { + M[offset] ^= generateKeystreamWord.call(this); + }, + + keySize: 256/32, + + ivSize: 0 + }); + + function generateKeystreamWord() { + // Shortcuts + var S = this._S; + var i = this._i; + var j = this._j; + + // Generate keystream word + var keystreamWord = 0; + for (var n = 0; n < 4; n++) { + i = (i + 1) % 256; + j = (j + S[i]) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + + keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); + } + + // Update counters + this._i = i; + this._j = j; + + return keystreamWord; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); + */ + C.RC4 = StreamCipher._createHelper(RC4); + + /** + * Modified RC4 stream cipher algorithm. + */ + var RC4Drop = C_algo.RC4Drop = RC4.extend({ + /** + * Configuration options. + * + * @property {number} drop The number of keystream words to drop. Default 192 + */ + cfg: RC4.cfg.extend({ + drop: 192 + }), + + _doReset: function () { + RC4._doReset.call(this); + + // Drop + for (var i = this.cfg.drop; i > 0; i--) { + generateKeystreamWord.call(this); + } + } + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); + */ + C.RC4Drop = StreamCipher._createHelper(RC4Drop); + }()); + + + return CryptoJS.RC4; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/ripemd160.js b/test/merkletreejs/node_modules/crypto-js/ripemd160.js new file mode 100644 index 0000000..24feb47 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/ripemd160.js @@ -0,0 +1,267 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var _zl = WordArray.create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); + var _zr = WordArray.create([ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); + var _sl = WordArray.create([ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); + var _sr = WordArray.create([ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); + + var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); + var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); + + /** + * RIPEMD160 hash algorithm. + */ + var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ + _doReset: function () { + this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); + }, + + _doProcessBlock: function (M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + // Shortcut + var H = this._hash.words; + var hl = _hl.words; + var hr = _hr.words; + var zl = _zl.words; + var zr = _zr.words; + var sl = _sl.words; + var sr = _sr.words; + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + + } + + function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); + + } + + function rotl(x,n) { + return (x<>>(32-n)); + } + + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.RIPEMD160('message'); + * var hash = CryptoJS.RIPEMD160(wordArray); + */ + C.RIPEMD160 = Hasher._createHelper(RIPEMD160); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacRIPEMD160(message, key); + */ + C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); + }(Math)); + + + return CryptoJS.RIPEMD160; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/sha1.js b/test/merkletreejs/node_modules/crypto-js/sha1.js new file mode 100644 index 0000000..6691149 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/sha1.js @@ -0,0 +1,150 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Reusable object + var W = []; + + /** + * SHA-1 hash algorithm. + */ + var SHA1 = C_algo.SHA1 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476, + 0xc3d2e1f0 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + // Computation + for (var i = 0; i < 80; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + + var t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else /* if (i < 80) */ { + t += (b ^ c ^ d) - 0x359d3e2a; + } + + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA1('message'); + * var hash = CryptoJS.SHA1(wordArray); + */ + C.SHA1 = Hasher._createHelper(SHA1); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA1(message, key); + */ + C.HmacSHA1 = Hasher._createHmacHelper(SHA1); + }()); + + + return CryptoJS.SHA1; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/sha224.js b/test/merkletreejs/node_modules/crypto-js/sha224.js new file mode 100644 index 0000000..d8ce988 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/sha224.js @@ -0,0 +1,80 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./sha256")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./sha256"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + + /** + * SHA-224 hash algorithm. + */ + var SHA224 = C_algo.SHA224 = SHA256.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]); + }, + + _doFinalize: function () { + var hash = SHA256._doFinalize.call(this); + + hash.sigBytes -= 4; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA224('message'); + * var hash = CryptoJS.SHA224(wordArray); + */ + C.SHA224 = SHA256._createHelper(SHA224); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA224(message, key); + */ + C.HmacSHA224 = SHA256._createHmacHelper(SHA224); + }()); + + + return CryptoJS.SHA224; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/sha256.js b/test/merkletreejs/node_modules/crypto-js/sha256.js new file mode 100644 index 0000000..de2d7fc --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/sha256.js @@ -0,0 +1,199 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Initialization and round constants tables + var H = []; + var K = []; + + // Compute constants + (function () { + function isPrime(n) { + var sqrtN = Math.sqrt(n); + for (var factor = 2; factor <= sqrtN; factor++) { + if (!(n % factor)) { + return false; + } + } + + return true; + } + + function getFractionalBits(n) { + return ((n - (n | 0)) * 0x100000000) | 0; + } + + var n = 2; + var nPrime = 0; + while (nPrime < 64) { + if (isPrime(n)) { + if (nPrime < 8) { + H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); + } + K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); + + nPrime++; + } + + n++; + } + }()); + + // Reusable object + var W = []; + + /** + * SHA-256 hash algorithm. + */ + var SHA256 = C_algo.SHA256 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init(H.slice(0)); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + var f = H[5]; + var g = H[6]; + var h = H[7]; + + // Computation + for (var i = 0; i < 64; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var gamma0x = W[i - 15]; + var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3); + + var gamma1x = W[i - 2]; + var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + + var ch = (e & f) ^ (~e & g); + var maj = (a & b) ^ (a & c) ^ (b & c); + + var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + + var t1 = h + sigma1 + ch + K[i] + W[i]; + var t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + H[7] = (H[7] + h) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA256('message'); + * var hash = CryptoJS.SHA256(wordArray); + */ + C.SHA256 = Hasher._createHelper(SHA256); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA256(message, key); + */ + C.HmacSHA256 = Hasher._createHmacHelper(SHA256); + }(Math)); + + + return CryptoJS.SHA256; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/sha3.js b/test/merkletreejs/node_modules/crypto-js/sha3.js new file mode 100644 index 0000000..34ad86c --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/sha3.js @@ -0,0 +1,326 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var C_algo = C.algo; + + // Constants tables + var RHO_OFFSETS = []; + var PI_INDEXES = []; + var ROUND_CONSTANTS = []; + + // Compute Constants + (function () { + // Compute rho offset constants + var x = 1, y = 0; + for (var t = 0; t < 24; t++) { + RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + + var newX = y % 5; + var newY = (2 * x + 3 * y) % 5; + x = newX; + y = newY; + } + + // Compute pi index constants + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; + } + } + + // Compute round constants + var LFSR = 0x01; + for (var i = 0; i < 24; i++) { + var roundConstantMsw = 0; + var roundConstantLsw = 0; + + for (var j = 0; j < 7; j++) { + if (LFSR & 0x01) { + var bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else /* if (bitPosition >= 32) */ { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + + // Compute next LFSR + if (LFSR & 0x80) { + // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + + ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); + } + }()); + + // Reusable objects for temporary values + var T = []; + (function () { + for (var i = 0; i < 25; i++) { + T[i] = X64Word.create(); + } + }()); + + /** + * SHA-3 hash algorithm. + */ + var SHA3 = C_algo.SHA3 = Hasher.extend({ + /** + * Configuration options. + * + * @property {number} outputLength + * The desired number of bits in the output hash. + * Only values permitted are: 224, 256, 384, 512. + * Default: 512 + */ + cfg: Hasher.cfg.extend({ + outputLength: 512 + }), + + _doReset: function () { + var state = this._state = [] + for (var i = 0; i < 25; i++) { + state[i] = new X64Word.init(); + } + + this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var state = this._state; + var nBlockSizeLanes = this.blockSize / 2; + + // Absorb + for (var i = 0; i < nBlockSizeLanes; i++) { + // Shortcuts + var M2i = M[offset + 2 * i]; + var M2i1 = M[offset + 2 * i + 1]; + + // Swap endian + M2i = ( + (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | + (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) + ); + M2i1 = ( + (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | + (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) + ); + + // Absorb message into state + var lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + + // Rounds + for (var round = 0; round < 24; round++) { + // Theta + for (var x = 0; x < 5; x++) { + // Mix column lanes + var tMsw = 0, tLsw = 0; + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + + // Temporary values + var Tx = T[x]; + Tx.high = tMsw; + Tx.low = tLsw; + } + for (var x = 0; x < 5; x++) { + // Shortcuts + var Tx4 = T[(x + 4) % 5]; + var Tx1 = T[(x + 1) % 5]; + var Tx1Msw = Tx1.high; + var Tx1Lsw = Tx1.low; + + // Mix surrounding columns + var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } + } + + // Rho Pi + for (var laneIndex = 1; laneIndex < 25; laneIndex++) { + var tMsw; + var tLsw; + + // Shortcuts + var lane = state[laneIndex]; + var laneMsw = lane.high; + var laneLsw = lane.low; + var rhoOffset = RHO_OFFSETS[laneIndex]; + + // Rotate lanes + if (rhoOffset < 32) { + tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else /* if (rhoOffset >= 32) */ { + tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + + // Transpose lanes + var TPiLane = T[PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + + // Rho pi at x = y = 0 + var T0 = T[0]; + var state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + + // Chi + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + // Shortcuts + var laneIndex = x + 5 * y; + var lane = state[laneIndex]; + var TLane = T[laneIndex]; + var Tx1Lane = T[((x + 1) % 5) + 5 * y]; + var Tx2Lane = T[((x + 2) % 5) + 5 * y]; + + // Mix rows + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + + // Iota + var lane = state[0]; + var roundConstant = ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + lane.low ^= roundConstant.low; + } + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + var blockSizeBits = this.blockSize * 32; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var state = this._state; + var outputLengthBytes = this.cfg.outputLength / 8; + var outputLengthLanes = outputLengthBytes / 8; + + // Squeeze + var hashWords = []; + for (var i = 0; i < outputLengthLanes; i++) { + // Shortcuts + var lane = state[i]; + var laneMsw = lane.high; + var laneLsw = lane.low; + + // Swap endian + laneMsw = ( + (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | + (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) + ); + laneLsw = ( + (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | + (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) + ); + + // Squeeze state to retrieve hash + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + + // Return final computed hash + return new WordArray.init(hashWords, outputLengthBytes); + }, + + clone: function () { + var clone = Hasher.clone.call(this); + + var state = clone._state = this._state.slice(0); + for (var i = 0; i < 25; i++) { + state[i] = state[i].clone(); + } + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA3('message'); + * var hash = CryptoJS.SHA3(wordArray); + */ + C.SHA3 = Hasher._createHelper(SHA3); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA3(message, key); + */ + C.HmacSHA3 = Hasher._createHmacHelper(SHA3); + }(Math)); + + + return CryptoJS.SHA3; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/sha384.js b/test/merkletreejs/node_modules/crypto-js/sha384.js new file mode 100644 index 0000000..a0b95bf --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/sha384.js @@ -0,0 +1,83 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core", "./sha512"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + var SHA512 = C_algo.SHA512; + + /** + * SHA-384 hash algorithm. + */ + var SHA384 = C_algo.SHA384 = SHA512.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), + new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), + new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), + new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) + ]); + }, + + _doFinalize: function () { + var hash = SHA512._doFinalize.call(this); + + hash.sigBytes -= 16; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA384('message'); + * var hash = CryptoJS.SHA384(wordArray); + */ + C.SHA384 = SHA512._createHelper(SHA384); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA384(message, key); + */ + C.HmacSHA384 = SHA512._createHmacHelper(SHA384); + }()); + + + return CryptoJS.SHA384; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/sha512.js b/test/merkletreejs/node_modules/crypto-js/sha512.js new file mode 100644 index 0000000..d274ab0 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/sha512.js @@ -0,0 +1,326 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./x64-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./x64-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + + function X64Word_create() { + return X64Word.create.apply(X64Word, arguments); + } + + // Constants + var K = [ + X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), + X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), + X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), + X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), + X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), + X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), + X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), + X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), + X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), + X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), + X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), + X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), + X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), + X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), + X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), + X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), + X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), + X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), + X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), + X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), + X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), + X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), + X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), + X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), + X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), + X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), + X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), + X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), + X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), + X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), + X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), + X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), + X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), + X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), + X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), + X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), + X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), + X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), + X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), + X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) + ]; + + // Reusable objects + var W = []; + (function () { + for (var i = 0; i < 80; i++) { + W[i] = X64Word_create(); + } + }()); + + /** + * SHA-512 hash algorithm. + */ + var SHA512 = C_algo.SHA512 = Hasher.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), + new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), + new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), + new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var H = this._hash.words; + + var H0 = H[0]; + var H1 = H[1]; + var H2 = H[2]; + var H3 = H[3]; + var H4 = H[4]; + var H5 = H[5]; + var H6 = H[6]; + var H7 = H[7]; + + var H0h = H0.high; + var H0l = H0.low; + var H1h = H1.high; + var H1l = H1.low; + var H2h = H2.high; + var H2l = H2.low; + var H3h = H3.high; + var H3l = H3.low; + var H4h = H4.high; + var H4l = H4.low; + var H5h = H5.high; + var H5l = H5.low; + var H6h = H6.high; + var H6l = H6.low; + var H7h = H7.high; + var H7l = H7.low; + + // Working variables + var ah = H0h; + var al = H0l; + var bh = H1h; + var bl = H1l; + var ch = H2h; + var cl = H2l; + var dh = H3h; + var dl = H3l; + var eh = H4h; + var el = H4l; + var fh = H5h; + var fl = H5l; + var gh = H6h; + var gl = H6l; + var hh = H7h; + var hl = H7l; + + // Rounds + for (var i = 0; i < 80; i++) { + var Wil; + var Wih; + + // Shortcut + var Wi = W[i]; + + // Extend message + if (i < 16) { + Wih = Wi.high = M[offset + i * 2] | 0; + Wil = Wi.low = M[offset + i * 2 + 1] | 0; + } else { + // Gamma0 + var gamma0x = W[i - 15]; + var gamma0xh = gamma0x.high; + var gamma0xl = gamma0x.low; + var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); + + // Gamma1 + var gamma1x = W[i - 2]; + var gamma1xh = gamma1x.high; + var gamma1xl = gamma1x.low; + var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[i - 7]; + var Wi7h = Wi7.high; + var Wi7l = Wi7.low; + + var Wi16 = W[i - 16]; + var Wi16h = Wi16.high; + var Wi16l = Wi16.low; + + Wil = gamma0l + Wi7l; + Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + Wil = Wil + gamma1l; + Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + Wil = Wil + Wi16l; + Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + + Wi.high = Wih; + Wi.low = Wil; + } + + var chh = (eh & fh) ^ (~eh & gh); + var chl = (el & fl) ^ (~el & gl); + var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + var majl = (al & bl) ^ (al & cl) ^ (bl & cl); + + var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[i]; + var Kih = Ki.high; + var Kil = Ki.low; + + var t1l = hl + sigma1l; + var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + var t1l = t1l + chl; + var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + var t1l = t1l + Kil; + var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + var t1l = t1l + Wil; + var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + + // t2 = sigma0 + maj + var t2l = sigma0l + majl; + var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + + // Update working variables + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + } + + // Intermediate hash value + H0l = H0.low = (H0l + al); + H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); + H1l = H1.low = (H1l + bl); + H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); + H2l = H2.low = (H2l + cl); + H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); + H3l = H3.low = (H3l + dl); + H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); + H4l = H4.low = (H4l + el); + H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); + H5l = H5.low = (H5l + fl); + H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); + H6l = H6.low = (H6l + gl); + H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); + H7l = H7.low = (H7l + hl); + H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Convert hash to 32-bit word array before returning + var hash = this._hash.toX32(); + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + + blockSize: 1024/32 + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA512('message'); + * var hash = CryptoJS.SHA512(wordArray); + */ + C.SHA512 = Hasher._createHelper(SHA512); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA512(message, key); + */ + C.HmacSHA512 = Hasher._createHmacHelper(SHA512); + }()); + + + return CryptoJS.SHA512; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/tripledes.js b/test/merkletreejs/node_modules/crypto-js/tripledes.js new file mode 100644 index 0000000..1a92477 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/tripledes.js @@ -0,0 +1,779 @@ +;(function (root, factory, undef) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Permuted Choice 1 constants + var PC1 = [ + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, + 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4 + ]; + + // Permuted Choice 2 constants + var PC2 = [ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ]; + + // Cumulative bit shift constants + var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; + + // SBOXes and round permutation constants + var SBOX_P = [ + { + 0x0: 0x808200, + 0x10000000: 0x8000, + 0x20000000: 0x808002, + 0x30000000: 0x2, + 0x40000000: 0x200, + 0x50000000: 0x808202, + 0x60000000: 0x800202, + 0x70000000: 0x800000, + 0x80000000: 0x202, + 0x90000000: 0x800200, + 0xa0000000: 0x8200, + 0xb0000000: 0x808000, + 0xc0000000: 0x8002, + 0xd0000000: 0x800002, + 0xe0000000: 0x0, + 0xf0000000: 0x8202, + 0x8000000: 0x0, + 0x18000000: 0x808202, + 0x28000000: 0x8202, + 0x38000000: 0x8000, + 0x48000000: 0x808200, + 0x58000000: 0x200, + 0x68000000: 0x808002, + 0x78000000: 0x2, + 0x88000000: 0x800200, + 0x98000000: 0x8200, + 0xa8000000: 0x808000, + 0xb8000000: 0x800202, + 0xc8000000: 0x800002, + 0xd8000000: 0x8002, + 0xe8000000: 0x202, + 0xf8000000: 0x800000, + 0x1: 0x8000, + 0x10000001: 0x2, + 0x20000001: 0x808200, + 0x30000001: 0x800000, + 0x40000001: 0x808002, + 0x50000001: 0x8200, + 0x60000001: 0x200, + 0x70000001: 0x800202, + 0x80000001: 0x808202, + 0x90000001: 0x808000, + 0xa0000001: 0x800002, + 0xb0000001: 0x8202, + 0xc0000001: 0x202, + 0xd0000001: 0x800200, + 0xe0000001: 0x8002, + 0xf0000001: 0x0, + 0x8000001: 0x808202, + 0x18000001: 0x808000, + 0x28000001: 0x800000, + 0x38000001: 0x200, + 0x48000001: 0x8000, + 0x58000001: 0x800002, + 0x68000001: 0x2, + 0x78000001: 0x8202, + 0x88000001: 0x8002, + 0x98000001: 0x800202, + 0xa8000001: 0x202, + 0xb8000001: 0x808200, + 0xc8000001: 0x800200, + 0xd8000001: 0x0, + 0xe8000001: 0x8200, + 0xf8000001: 0x808002 + }, + { + 0x0: 0x40084010, + 0x1000000: 0x4000, + 0x2000000: 0x80000, + 0x3000000: 0x40080010, + 0x4000000: 0x40000010, + 0x5000000: 0x40084000, + 0x6000000: 0x40004000, + 0x7000000: 0x10, + 0x8000000: 0x84000, + 0x9000000: 0x40004010, + 0xa000000: 0x40000000, + 0xb000000: 0x84010, + 0xc000000: 0x80010, + 0xd000000: 0x0, + 0xe000000: 0x4010, + 0xf000000: 0x40080000, + 0x800000: 0x40004000, + 0x1800000: 0x84010, + 0x2800000: 0x10, + 0x3800000: 0x40004010, + 0x4800000: 0x40084010, + 0x5800000: 0x40000000, + 0x6800000: 0x80000, + 0x7800000: 0x40080010, + 0x8800000: 0x80010, + 0x9800000: 0x0, + 0xa800000: 0x4000, + 0xb800000: 0x40080000, + 0xc800000: 0x40000010, + 0xd800000: 0x84000, + 0xe800000: 0x40084000, + 0xf800000: 0x4010, + 0x10000000: 0x0, + 0x11000000: 0x40080010, + 0x12000000: 0x40004010, + 0x13000000: 0x40084000, + 0x14000000: 0x40080000, + 0x15000000: 0x10, + 0x16000000: 0x84010, + 0x17000000: 0x4000, + 0x18000000: 0x4010, + 0x19000000: 0x80000, + 0x1a000000: 0x80010, + 0x1b000000: 0x40000010, + 0x1c000000: 0x84000, + 0x1d000000: 0x40004000, + 0x1e000000: 0x40000000, + 0x1f000000: 0x40084010, + 0x10800000: 0x84010, + 0x11800000: 0x80000, + 0x12800000: 0x40080000, + 0x13800000: 0x4000, + 0x14800000: 0x40004000, + 0x15800000: 0x40084010, + 0x16800000: 0x10, + 0x17800000: 0x40000000, + 0x18800000: 0x40084000, + 0x19800000: 0x40000010, + 0x1a800000: 0x40004010, + 0x1b800000: 0x80010, + 0x1c800000: 0x0, + 0x1d800000: 0x4010, + 0x1e800000: 0x40080010, + 0x1f800000: 0x84000 + }, + { + 0x0: 0x104, + 0x100000: 0x0, + 0x200000: 0x4000100, + 0x300000: 0x10104, + 0x400000: 0x10004, + 0x500000: 0x4000004, + 0x600000: 0x4010104, + 0x700000: 0x4010000, + 0x800000: 0x4000000, + 0x900000: 0x4010100, + 0xa00000: 0x10100, + 0xb00000: 0x4010004, + 0xc00000: 0x4000104, + 0xd00000: 0x10000, + 0xe00000: 0x4, + 0xf00000: 0x100, + 0x80000: 0x4010100, + 0x180000: 0x4010004, + 0x280000: 0x0, + 0x380000: 0x4000100, + 0x480000: 0x4000004, + 0x580000: 0x10000, + 0x680000: 0x10004, + 0x780000: 0x104, + 0x880000: 0x4, + 0x980000: 0x100, + 0xa80000: 0x4010000, + 0xb80000: 0x10104, + 0xc80000: 0x10100, + 0xd80000: 0x4000104, + 0xe80000: 0x4010104, + 0xf80000: 0x4000000, + 0x1000000: 0x4010100, + 0x1100000: 0x10004, + 0x1200000: 0x10000, + 0x1300000: 0x4000100, + 0x1400000: 0x100, + 0x1500000: 0x4010104, + 0x1600000: 0x4000004, + 0x1700000: 0x0, + 0x1800000: 0x4000104, + 0x1900000: 0x4000000, + 0x1a00000: 0x4, + 0x1b00000: 0x10100, + 0x1c00000: 0x4010000, + 0x1d00000: 0x104, + 0x1e00000: 0x10104, + 0x1f00000: 0x4010004, + 0x1080000: 0x4000000, + 0x1180000: 0x104, + 0x1280000: 0x4010100, + 0x1380000: 0x0, + 0x1480000: 0x10004, + 0x1580000: 0x4000100, + 0x1680000: 0x100, + 0x1780000: 0x4010004, + 0x1880000: 0x10000, + 0x1980000: 0x4010104, + 0x1a80000: 0x10104, + 0x1b80000: 0x4000004, + 0x1c80000: 0x4000104, + 0x1d80000: 0x4010000, + 0x1e80000: 0x4, + 0x1f80000: 0x10100 + }, + { + 0x0: 0x80401000, + 0x10000: 0x80001040, + 0x20000: 0x401040, + 0x30000: 0x80400000, + 0x40000: 0x0, + 0x50000: 0x401000, + 0x60000: 0x80000040, + 0x70000: 0x400040, + 0x80000: 0x80000000, + 0x90000: 0x400000, + 0xa0000: 0x40, + 0xb0000: 0x80001000, + 0xc0000: 0x80400040, + 0xd0000: 0x1040, + 0xe0000: 0x1000, + 0xf0000: 0x80401040, + 0x8000: 0x80001040, + 0x18000: 0x40, + 0x28000: 0x80400040, + 0x38000: 0x80001000, + 0x48000: 0x401000, + 0x58000: 0x80401040, + 0x68000: 0x0, + 0x78000: 0x80400000, + 0x88000: 0x1000, + 0x98000: 0x80401000, + 0xa8000: 0x400000, + 0xb8000: 0x1040, + 0xc8000: 0x80000000, + 0xd8000: 0x400040, + 0xe8000: 0x401040, + 0xf8000: 0x80000040, + 0x100000: 0x400040, + 0x110000: 0x401000, + 0x120000: 0x80000040, + 0x130000: 0x0, + 0x140000: 0x1040, + 0x150000: 0x80400040, + 0x160000: 0x80401000, + 0x170000: 0x80001040, + 0x180000: 0x80401040, + 0x190000: 0x80000000, + 0x1a0000: 0x80400000, + 0x1b0000: 0x401040, + 0x1c0000: 0x80001000, + 0x1d0000: 0x400000, + 0x1e0000: 0x40, + 0x1f0000: 0x1000, + 0x108000: 0x80400000, + 0x118000: 0x80401040, + 0x128000: 0x0, + 0x138000: 0x401000, + 0x148000: 0x400040, + 0x158000: 0x80000000, + 0x168000: 0x80001040, + 0x178000: 0x40, + 0x188000: 0x80000040, + 0x198000: 0x1000, + 0x1a8000: 0x80001000, + 0x1b8000: 0x80400040, + 0x1c8000: 0x1040, + 0x1d8000: 0x80401000, + 0x1e8000: 0x400000, + 0x1f8000: 0x401040 + }, + { + 0x0: 0x80, + 0x1000: 0x1040000, + 0x2000: 0x40000, + 0x3000: 0x20000000, + 0x4000: 0x20040080, + 0x5000: 0x1000080, + 0x6000: 0x21000080, + 0x7000: 0x40080, + 0x8000: 0x1000000, + 0x9000: 0x20040000, + 0xa000: 0x20000080, + 0xb000: 0x21040080, + 0xc000: 0x21040000, + 0xd000: 0x0, + 0xe000: 0x1040080, + 0xf000: 0x21000000, + 0x800: 0x1040080, + 0x1800: 0x21000080, + 0x2800: 0x80, + 0x3800: 0x1040000, + 0x4800: 0x40000, + 0x5800: 0x20040080, + 0x6800: 0x21040000, + 0x7800: 0x20000000, + 0x8800: 0x20040000, + 0x9800: 0x0, + 0xa800: 0x21040080, + 0xb800: 0x1000080, + 0xc800: 0x20000080, + 0xd800: 0x21000000, + 0xe800: 0x1000000, + 0xf800: 0x40080, + 0x10000: 0x40000, + 0x11000: 0x80, + 0x12000: 0x20000000, + 0x13000: 0x21000080, + 0x14000: 0x1000080, + 0x15000: 0x21040000, + 0x16000: 0x20040080, + 0x17000: 0x1000000, + 0x18000: 0x21040080, + 0x19000: 0x21000000, + 0x1a000: 0x1040000, + 0x1b000: 0x20040000, + 0x1c000: 0x40080, + 0x1d000: 0x20000080, + 0x1e000: 0x0, + 0x1f000: 0x1040080, + 0x10800: 0x21000080, + 0x11800: 0x1000000, + 0x12800: 0x1040000, + 0x13800: 0x20040080, + 0x14800: 0x20000000, + 0x15800: 0x1040080, + 0x16800: 0x80, + 0x17800: 0x21040000, + 0x18800: 0x40080, + 0x19800: 0x21040080, + 0x1a800: 0x0, + 0x1b800: 0x21000000, + 0x1c800: 0x1000080, + 0x1d800: 0x40000, + 0x1e800: 0x20040000, + 0x1f800: 0x20000080 + }, + { + 0x0: 0x10000008, + 0x100: 0x2000, + 0x200: 0x10200000, + 0x300: 0x10202008, + 0x400: 0x10002000, + 0x500: 0x200000, + 0x600: 0x200008, + 0x700: 0x10000000, + 0x800: 0x0, + 0x900: 0x10002008, + 0xa00: 0x202000, + 0xb00: 0x8, + 0xc00: 0x10200008, + 0xd00: 0x202008, + 0xe00: 0x2008, + 0xf00: 0x10202000, + 0x80: 0x10200000, + 0x180: 0x10202008, + 0x280: 0x8, + 0x380: 0x200000, + 0x480: 0x202008, + 0x580: 0x10000008, + 0x680: 0x10002000, + 0x780: 0x2008, + 0x880: 0x200008, + 0x980: 0x2000, + 0xa80: 0x10002008, + 0xb80: 0x10200008, + 0xc80: 0x0, + 0xd80: 0x10202000, + 0xe80: 0x202000, + 0xf80: 0x10000000, + 0x1000: 0x10002000, + 0x1100: 0x10200008, + 0x1200: 0x10202008, + 0x1300: 0x2008, + 0x1400: 0x200000, + 0x1500: 0x10000000, + 0x1600: 0x10000008, + 0x1700: 0x202000, + 0x1800: 0x202008, + 0x1900: 0x0, + 0x1a00: 0x8, + 0x1b00: 0x10200000, + 0x1c00: 0x2000, + 0x1d00: 0x10002008, + 0x1e00: 0x10202000, + 0x1f00: 0x200008, + 0x1080: 0x8, + 0x1180: 0x202000, + 0x1280: 0x200000, + 0x1380: 0x10000008, + 0x1480: 0x10002000, + 0x1580: 0x2008, + 0x1680: 0x10202008, + 0x1780: 0x10200000, + 0x1880: 0x10202000, + 0x1980: 0x10200008, + 0x1a80: 0x2000, + 0x1b80: 0x202008, + 0x1c80: 0x200008, + 0x1d80: 0x0, + 0x1e80: 0x10000000, + 0x1f80: 0x10002008 + }, + { + 0x0: 0x100000, + 0x10: 0x2000401, + 0x20: 0x400, + 0x30: 0x100401, + 0x40: 0x2100401, + 0x50: 0x0, + 0x60: 0x1, + 0x70: 0x2100001, + 0x80: 0x2000400, + 0x90: 0x100001, + 0xa0: 0x2000001, + 0xb0: 0x2100400, + 0xc0: 0x2100000, + 0xd0: 0x401, + 0xe0: 0x100400, + 0xf0: 0x2000000, + 0x8: 0x2100001, + 0x18: 0x0, + 0x28: 0x2000401, + 0x38: 0x2100400, + 0x48: 0x100000, + 0x58: 0x2000001, + 0x68: 0x2000000, + 0x78: 0x401, + 0x88: 0x100401, + 0x98: 0x2000400, + 0xa8: 0x2100000, + 0xb8: 0x100001, + 0xc8: 0x400, + 0xd8: 0x2100401, + 0xe8: 0x1, + 0xf8: 0x100400, + 0x100: 0x2000000, + 0x110: 0x100000, + 0x120: 0x2000401, + 0x130: 0x2100001, + 0x140: 0x100001, + 0x150: 0x2000400, + 0x160: 0x2100400, + 0x170: 0x100401, + 0x180: 0x401, + 0x190: 0x2100401, + 0x1a0: 0x100400, + 0x1b0: 0x1, + 0x1c0: 0x0, + 0x1d0: 0x2100000, + 0x1e0: 0x2000001, + 0x1f0: 0x400, + 0x108: 0x100400, + 0x118: 0x2000401, + 0x128: 0x2100001, + 0x138: 0x1, + 0x148: 0x2000000, + 0x158: 0x100000, + 0x168: 0x401, + 0x178: 0x2100400, + 0x188: 0x2000001, + 0x198: 0x2100000, + 0x1a8: 0x0, + 0x1b8: 0x2100401, + 0x1c8: 0x100401, + 0x1d8: 0x400, + 0x1e8: 0x2000400, + 0x1f8: 0x100001 + }, + { + 0x0: 0x8000820, + 0x1: 0x20000, + 0x2: 0x8000000, + 0x3: 0x20, + 0x4: 0x20020, + 0x5: 0x8020820, + 0x6: 0x8020800, + 0x7: 0x800, + 0x8: 0x8020000, + 0x9: 0x8000800, + 0xa: 0x20800, + 0xb: 0x8020020, + 0xc: 0x820, + 0xd: 0x0, + 0xe: 0x8000020, + 0xf: 0x20820, + 0x80000000: 0x800, + 0x80000001: 0x8020820, + 0x80000002: 0x8000820, + 0x80000003: 0x8000000, + 0x80000004: 0x8020000, + 0x80000005: 0x20800, + 0x80000006: 0x20820, + 0x80000007: 0x20, + 0x80000008: 0x8000020, + 0x80000009: 0x820, + 0x8000000a: 0x20020, + 0x8000000b: 0x8020800, + 0x8000000c: 0x0, + 0x8000000d: 0x8020020, + 0x8000000e: 0x8000800, + 0x8000000f: 0x20000, + 0x10: 0x20820, + 0x11: 0x8020800, + 0x12: 0x20, + 0x13: 0x800, + 0x14: 0x8000800, + 0x15: 0x8000020, + 0x16: 0x8020020, + 0x17: 0x20000, + 0x18: 0x0, + 0x19: 0x20020, + 0x1a: 0x8020000, + 0x1b: 0x8000820, + 0x1c: 0x8020820, + 0x1d: 0x20800, + 0x1e: 0x820, + 0x1f: 0x8000000, + 0x80000010: 0x20000, + 0x80000011: 0x800, + 0x80000012: 0x8020020, + 0x80000013: 0x20820, + 0x80000014: 0x20, + 0x80000015: 0x8020000, + 0x80000016: 0x8000000, + 0x80000017: 0x8000820, + 0x80000018: 0x8020820, + 0x80000019: 0x8000020, + 0x8000001a: 0x8000800, + 0x8000001b: 0x0, + 0x8000001c: 0x20800, + 0x8000001d: 0x820, + 0x8000001e: 0x20020, + 0x8000001f: 0x8020800 + } + ]; + + // Masks that select the SBOX input + var SBOX_MASK = [ + 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f + ]; + + /** + * DES block cipher algorithm. + */ + var DES = C_algo.DES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Select 56 bits according to PC1 + var keyBits = []; + for (var i = 0; i < 56; i++) { + var keyBitPos = PC1[i] - 1; + keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; + } + + // Assemble 16 subkeys + var subKeys = this._subKeys = []; + for (var nSubKey = 0; nSubKey < 16; nSubKey++) { + // Create subkey + var subKey = subKeys[nSubKey] = []; + + // Shortcut + var bitShift = BIT_SHIFTS[nSubKey]; + + // Select 48 bits according to PC2 + for (var i = 0; i < 24; i++) { + // Select from the left 28 key bits + subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); + + // Select from the right 28 key bits + subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); + } + + // Since each subkey is applied to an expanded 32-bit input, + // the subkey can be broken into 8 values scaled to 32-bits, + // which allows the key to be used without expansion + subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); + for (var i = 1; i < 7; i++) { + subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); + } + subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); + } + + // Compute inverse subkeys + var invSubKeys = this._invSubKeys = []; + for (var i = 0; i < 16; i++) { + invSubKeys[i] = subKeys[15 - i]; + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._subKeys); + }, + + decryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._invSubKeys); + }, + + _doCryptBlock: function (M, offset, subKeys) { + // Get input + this._lBlock = M[offset]; + this._rBlock = M[offset + 1]; + + // Initial permutation + exchangeLR.call(this, 4, 0x0f0f0f0f); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeRL.call(this, 2, 0x33333333); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeLR.call(this, 1, 0x55555555); + + // Rounds + for (var round = 0; round < 16; round++) { + // Shortcuts + var subKey = subKeys[round]; + var lBlock = this._lBlock; + var rBlock = this._rBlock; + + // Feistel function + var f = 0; + for (var i = 0; i < 8; i++) { + f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; + } + this._lBlock = rBlock; + this._rBlock = lBlock ^ f; + } + + // Undo swap from last round + var t = this._lBlock; + this._lBlock = this._rBlock; + this._rBlock = t; + + // Final permutation + exchangeLR.call(this, 1, 0x55555555); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeRL.call(this, 2, 0x33333333); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeLR.call(this, 4, 0x0f0f0f0f); + + // Set output + M[offset] = this._lBlock; + M[offset + 1] = this._rBlock; + }, + + keySize: 64/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + // Swap bits across the left and right words + function exchangeLR(offset, mask) { + var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; + this._rBlock ^= t; + this._lBlock ^= t << offset; + } + + function exchangeRL(offset, mask) { + var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; + this._lBlock ^= t; + this._rBlock ^= t << offset; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); + */ + C.DES = BlockCipher._createHelper(DES); + + /** + * Triple-DES block cipher algorithm. + */ + var TripleDES = C_algo.TripleDES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + // Make sure the key length is valid (64, 128 or >= 192 bit) + if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) { + throw new Error('Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.'); + } + + // Extend the key according to the keying options defined in 3DES standard + var key1 = keyWords.slice(0, 2); + var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4); + var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6); + + // Create DES instances + this._des1 = DES.createEncryptor(WordArray.create(key1)); + this._des2 = DES.createEncryptor(WordArray.create(key2)); + this._des3 = DES.createEncryptor(WordArray.create(key3)); + }, + + encryptBlock: function (M, offset) { + this._des1.encryptBlock(M, offset); + this._des2.decryptBlock(M, offset); + this._des3.encryptBlock(M, offset); + }, + + decryptBlock: function (M, offset) { + this._des3.decryptBlock(M, offset); + this._des2.encryptBlock(M, offset); + this._des1.decryptBlock(M, offset); + }, + + keySize: 192/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); + */ + C.TripleDES = BlockCipher._createHelper(TripleDES); + }()); + + + return CryptoJS.TripleDES; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/crypto-js/x64-core.js b/test/merkletreejs/node_modules/crypto-js/x64-core.js new file mode 100644 index 0000000..57dcc14 --- /dev/null +++ b/test/merkletreejs/node_modules/crypto-js/x64-core.js @@ -0,0 +1,304 @@ +;(function (root, factory) { + if (typeof exports === "object") { + // CommonJS + module.exports = exports = factory(require("./core")); + } + else if (typeof define === "function" && define.amd) { + // AMD + define(["./core"], factory); + } + else { + // Global (browser) + factory(root.CryptoJS); + } +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var X32WordArray = C_lib.WordArray; + + /** + * x64 namespace. + */ + var C_x64 = C.x64 = {}; + + /** + * A 64-bit word. + */ + var X64Word = C_x64.Word = Base.extend({ + /** + * Initializes a newly created 64-bit word. + * + * @param {number} high The high 32 bits. + * @param {number} low The low 32 bits. + * + * @example + * + * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); + */ + init: function (high, low) { + this.high = high; + this.low = low; + } + + /** + * Bitwise NOTs this word. + * + * @return {X64Word} A new x64-Word object after negating. + * + * @example + * + * var negated = x64Word.not(); + */ + // not: function () { + // var high = ~this.high; + // var low = ~this.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ANDs this word with the passed word. + * + * @param {X64Word} word The x64-Word to AND with this word. + * + * @return {X64Word} A new x64-Word object after ANDing. + * + * @example + * + * var anded = x64Word.and(anotherX64Word); + */ + // and: function (word) { + // var high = this.high & word.high; + // var low = this.low & word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to OR with this word. + * + * @return {X64Word} A new x64-Word object after ORing. + * + * @example + * + * var ored = x64Word.or(anotherX64Word); + */ + // or: function (word) { + // var high = this.high | word.high; + // var low = this.low | word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise XORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to XOR with this word. + * + * @return {X64Word} A new x64-Word object after XORing. + * + * @example + * + * var xored = x64Word.xor(anotherX64Word); + */ + // xor: function (word) { + // var high = this.high ^ word.high; + // var low = this.low ^ word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the left. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftL(25); + */ + // shiftL: function (n) { + // if (n < 32) { + // var high = (this.high << n) | (this.low >>> (32 - n)); + // var low = this.low << n; + // } else { + // var high = this.low << (n - 32); + // var low = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the right. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftR(7); + */ + // shiftR: function (n) { + // if (n < 32) { + // var low = (this.low >>> n) | (this.high << (32 - n)); + // var high = this.high >>> n; + // } else { + // var low = this.high >>> (n - 32); + // var high = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Rotates this word n bits to the left. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotL(25); + */ + // rotL: function (n) { + // return this.shiftL(n).or(this.shiftR(64 - n)); + // }, + + /** + * Rotates this word n bits to the right. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotR(7); + */ + // rotR: function (n) { + // return this.shiftR(n).or(this.shiftL(64 - n)); + // }, + + /** + * Adds this word with the passed word. + * + * @param {X64Word} word The x64-Word to add with this word. + * + * @return {X64Word} A new x64-Word object after adding. + * + * @example + * + * var added = x64Word.add(anotherX64Word); + */ + // add: function (word) { + // var low = (this.low + word.low) | 0; + // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; + // var high = (this.high + word.high + carry) | 0; + + // return X64Word.create(high, low); + // } + }); + + /** + * An array of 64-bit words. + * + * @property {Array} words The array of CryptoJS.x64.Word objects. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var X64WordArray = C_x64.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.x64.WordArray.create(); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ]); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ], 10); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 8; + } + }, + + /** + * Converts this 64-bit word array to a 32-bit word array. + * + * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. + * + * @example + * + * var x32WordArray = x64WordArray.toX32(); + */ + toX32: function () { + // Shortcuts + var x64Words = this.words; + var x64WordsLength = x64Words.length; + + // Convert + var x32Words = []; + for (var i = 0; i < x64WordsLength; i++) { + var x64Word = x64Words[i]; + x32Words.push(x64Word.high); + x32Words.push(x64Word.low); + } + + return X32WordArray.create(x32Words, this.sigBytes); + }, + + /** + * Creates a copy of this word array. + * + * @return {X64WordArray} The clone. + * + * @example + * + * var clone = x64WordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + + // Clone "words" array + var words = clone.words = this.words.slice(0); + + // Clone each X64Word object + var wordsLength = words.length; + for (var i = 0; i < wordsLength; i++) { + words[i] = words[i].clone(); + } + + return clone; + } + }); + }()); + + + return CryptoJS; + +})); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/define-data-property/.eslintrc b/test/merkletreejs/node_modules/define-data-property/.eslintrc new file mode 100644 index 0000000..75443e8 --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/.eslintrc @@ -0,0 +1,24 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": 0, + "id-length": 0, + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": "off", + }, + }, + ], +} diff --git a/test/merkletreejs/node_modules/define-data-property/.github/FUNDING.yml b/test/merkletreejs/node_modules/define-data-property/.github/FUNDING.yml new file mode 100644 index 0000000..3e17725 --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/define-data-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/define-data-property/.nycrc b/test/merkletreejs/node_modules/define-data-property/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/define-data-property/CHANGELOG.md b/test/merkletreejs/node_modules/define-data-property/CHANGELOG.md new file mode 100644 index 0000000..94bad09 --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.1](https://github.com/ljharb/define-data-property/compare/v1.1.0...v1.1.1) - 2023-10-12 + +### Commits + +- [Tests] fix tests in ES3 engines [`5c6920e`](https://github.com/ljharb/define-data-property/commit/5c6920edd1f52f675b02f417e539c28135b43f94) +- [Dev Deps] update `@types/es-value-fixtures`, `@types/for-each`, `@types/gopd`, `@types/has-property-descriptors`, `tape`, `typescript` [`7d82dfc`](https://github.com/ljharb/define-data-property/commit/7d82dfc20f778b4465bba06335dd53f6f431aea3) +- [Fix] IE 8 has a broken `Object.defineProperty` [`0672e1a`](https://github.com/ljharb/define-data-property/commit/0672e1af2a9fcc787e7c23b96dea60d290df5548) +- [meta] emit types on prepack [`73acb1f`](https://github.com/ljharb/define-data-property/commit/73acb1f903c21b314ec7156bf10f73c7910530c0) +- [Dev Deps] update `tape`, `typescript` [`9489a77`](https://github.com/ljharb/define-data-property/commit/9489a7738bf2ecf0ac71d5b78ec4ca6ad7ba0142) + +## [v1.1.0](https://github.com/ljharb/define-data-property/compare/v1.0.1...v1.1.0) - 2023-09-13 + +### Commits + +- [New] add `loose` arg [`155235a`](https://github.com/ljharb/define-data-property/commit/155235a4c4d7741f6de01cd87c99599a56654b72) +- [New] allow `null` to be passed for the non* args [`7d2fa5f`](https://github.com/ljharb/define-data-property/commit/7d2fa5f06be0392736c13b126f7cd38979f34792) + +## [v1.0.1](https://github.com/ljharb/define-data-property/compare/v1.0.0...v1.0.1) - 2023-09-12 + +### Commits + +- [meta] add TS types [`43d763c`](https://github.com/ljharb/define-data-property/commit/43d763c6c883f652de1c9c02ef6216ee507ffa69) +- [Dev Deps] update `@types/tape`, `typescript` [`f444985`](https://github.com/ljharb/define-data-property/commit/f444985811c36f3e6448a03ad2f9b7898917f4c7) +- [meta] add `safe-publish-latest`, [`172bb10`](https://github.com/ljharb/define-data-property/commit/172bb10890896ebb160e64398f6ee55760107bee) + +## v1.0.0 - 2023-09-12 + +### Commits + +- Initial implementation, tests, readme [`5b43d6b`](https://github.com/ljharb/define-data-property/commit/5b43d6b44e675a904810467a7d4e0adb7efc3196) +- Initial commit [`35e577a`](https://github.com/ljharb/define-data-property/commit/35e577a6ba59a98befa97776d70d90f3bea9009d) +- npm init [`82a0a04`](https://github.com/ljharb/define-data-property/commit/82a0a04a321ca7de220af02d41e2745e8a9962ed) +- Only apps should have lockfiles [`96df244`](https://github.com/ljharb/define-data-property/commit/96df244a3c6f426f9a2437be825d1c6f5dd7158e) +- [meta] use `npmignore` to autogenerate an npmignore file [`a87ff18`](https://github.com/ljharb/define-data-property/commit/a87ff18cb79e14c2eb5720486c4759fd9a189375) diff --git a/test/merkletreejs/node_modules/define-data-property/LICENSE b/test/merkletreejs/node_modules/define-data-property/LICENSE new file mode 100644 index 0000000..b4213ac --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/define-data-property/README.md b/test/merkletreejs/node_modules/define-data-property/README.md new file mode 100644 index 0000000..f2304da --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/README.md @@ -0,0 +1,67 @@ +# define-data-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Define a data property on an object. Will fall back to assignment in an engine without descriptors. + +The three `non*` argument can also be passed `null`, which will use the existing state if available. + +The `loose` argument will mean that if you attempt to set a non-normal data property, in an environment without descriptor support, it will fall back to normal assignment. + +## Usage + +```javascript +var defineDataProperty = require('define-data-property'); +var assert = require('assert'); + +var obj = {}; +defineDataProperty(obj, 'key', 'value'); +defineDataProperty( + obj, + 'key2', + 'value', + true, // nonEnumerable, optional + false, // nonWritable, optional + true, // nonConfigurable, optional + false // loose, optional +); + +assert.deepEqual( + Object.getOwnPropertyDescriptors(obj), + { + key: { + configurable: true, + enumerable: true, + value: 'value', + writable: true, + }, + key2: { + configurable: false, + enumerable: false, + value: 'value', + writable: true, + }, + } +); +``` + +[package-url]: https://npmjs.org/package/define-data-property +[npm-version-svg]: https://versionbadg.es/ljharb/define-data-property.svg +[deps-svg]: https://david-dm.org/ljharb/define-data-property.svg +[deps-url]: https://david-dm.org/ljharb/define-data-property +[dev-deps-svg]: https://david-dm.org/ljharb/define-data-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/define-data-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/define-data-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/define-data-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/define-data-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=define-data-property +[codecov-image]: https://codecov.io/gh/ljharb/define-data-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/define-data-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/define-data-property +[actions-url]: https://github.com/ljharb/define-data-property/actions diff --git a/test/merkletreejs/node_modules/define-data-property/index.d.ts b/test/merkletreejs/node_modules/define-data-property/index.d.ts new file mode 100644 index 0000000..d2e353d --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/index.d.ts @@ -0,0 +1,3 @@ +declare const _exports: (obj: Record, property: PropertyKey, value: unknown, nonEnumerable?: boolean | null, nonWritable?: boolean | null, nonConfigurable?: boolean | null, loose?: boolean) => void; +export = _exports; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/define-data-property/index.d.ts.map b/test/merkletreejs/node_modules/define-data-property/index.d.ts.map new file mode 100644 index 0000000..39aca4b --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"8BAqBiB,OAAO,WAAW,EAAE,OAAO,CAAC,YAAY,WAAW,SAAS,OAAO,kBAAkB,OAAO,GAAG,IAAI,gBAAgB,OAAO,GAAG,IAAI,oBAAoB,OAAO,GAAG,IAAI,UAAU,OAAO,KAAK,IAAI"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/define-data-property/index.js b/test/merkletreejs/node_modules/define-data-property/index.js new file mode 100644 index 0000000..9534065 --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var hasPropertyDescriptors = require('has-property-descriptors')(); + +var GetIntrinsic = require('get-intrinsic'); + +var $defineProperty = hasPropertyDescriptors && GetIntrinsic('%Object.defineProperty%', true); +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +var $SyntaxError = GetIntrinsic('%SyntaxError%'); +var $TypeError = GetIntrinsic('%TypeError%'); + +var gopd = require('gopd'); + +/** @type {(obj: Record, property: PropertyKey, value: unknown, nonEnumerable?: boolean | null, nonWritable?: boolean | null, nonConfigurable?: boolean | null, loose?: boolean) => void} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; diff --git a/test/merkletreejs/node_modules/define-data-property/package.json b/test/merkletreejs/node_modules/define-data-property/package.json new file mode 100644 index 0000000..1bb5815 --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/package.json @@ -0,0 +1,113 @@ +{ + "name": "define-data-property", + "version": "1.1.1", + "description": "Define a data property on an object. Will fall back to assignment in an engine without descriptors.", + "main": "index.js", + "exports": { + ".": [ + { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "sideEffects": false, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated && npm run emit-types", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "preemit-types": "rm -f *.ts *.ts.map test/*.ts test/*.ts.map", + "emit-types": "npm run tsc -- --noEmit false --emitDeclarationOnly", + "postemit-types": "rm test/*.ts test/*.ts.map", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/define-data-property.git" + }, + "keywords": [ + "define", + "data", + "property", + "object", + "accessor", + "javascript", + "ecmascript", + "enumerable", + "configurable", + "writable" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/define-data-property/issues" + }, + "homepage": "https://github.com/ljharb/define-data-property#readme", + "dependencies": { + "get-intrinsic": "^1.2.1", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/es-value-fixtures": "^1.4.1", + "@types/for-each": "^0.3.1", + "@types/get-intrinsic": "^1.2.0", + "@types/gopd": "^1.0.1", + "@types/has": "^1.0.0", + "@types/has-property-descriptors": "^1.0.1", + "@types/object-inspect": "^1.8.2", + "@types/object.getownpropertydescriptors": "^2.1.2", + "@types/tape": "^5.6.1", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "has": "^1.0.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "object.getownpropertydescriptors": "^2.1.7", + "reflect.ownkeys": "^1.1.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1", + "typescript": "^5.3.0-dev.20231012" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "!*.ts", + "!*.ts.map", + "types/reflect.ownkeys" + ] + } +} diff --git a/test/merkletreejs/node_modules/define-data-property/test/index.js b/test/merkletreejs/node_modules/define-data-property/test/index.js new file mode 100644 index 0000000..405508e --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/test/index.js @@ -0,0 +1,392 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var has = require('has'); +var hasPropertyDescriptors = require('has-property-descriptors')(); +var getOwnPropertyDescriptors = require('object.getownpropertydescriptors'); +var ownKeys = require('reflect.ownkeys'); + +var defineDataProperty = require('../'); + +test('defineDataProperty', function (t) { + t.test('argument validation', function (st) { + forEach(v.primitives, function (nonObject) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty(nonObject, 'key', 'value'); }, + TypeError, + 'throws on non-object input: ' + inspect(nonObject) + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, nonPropertyKey, 'value'); }, + TypeError, + 'throws on non-PropertyKey input: ' + inspect(nonPropertyKey) + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + if (nonBoolean !== null) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', nonBoolean); }, + TypeError, + 'throws on non-boolean nonEnumerable: ' + inspect(nonBoolean) + ); + + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', false, nonBoolean); }, + TypeError, + 'throws on non-boolean nonWritable: ' + inspect(nonBoolean) + ); + + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', false, false, nonBoolean); }, + TypeError, + 'throws on non-boolean nonConfigurable: ' + inspect(nonBoolean) + ); + } + }); + + st.end(); + }); + + t.test('normal data property', function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + st.ok(has(obj, 'existing'), 'has initial own property'); + st.equal(obj.existing, 'existing property', 'has expected initial value'); + + var res = defineDataProperty(obj, 'added', 'added property'); + st.equal(res, void undefined, 'returns `undefined`'); + st.ok(has(obj, 'added'), 'has expected own property'); + st.equal(obj.added, 'added property', 'has expected value'); + + defineDataProperty(obj, 'existing', 'new value'); + st.ok(has(obj, 'existing'), 'still has expected own property'); + st.equal(obj.existing, 'new value', 'has new expected value'); + + defineDataProperty(obj, 'explicit1', 'new value', false); + st.ok(has(obj, 'explicit1'), 'has expected own property (explicit enumerable)'); + st.equal(obj.explicit1, 'new value', 'has new expected value (explicit enumerable)'); + + defineDataProperty(obj, 'explicit2', 'new value', false, false); + st.ok(has(obj, 'explicit2'), 'has expected own property (explicit writable)'); + st.equal(obj.explicit2, 'new value', 'has new expected value (explicit writable)'); + + defineDataProperty(obj, 'explicit3', 'new value', false, false, false); + st.ok(has(obj, 'explicit3'), 'has expected own property (explicit configurable)'); + st.equal(obj.explicit3, 'new value', 'has new expected value (explicit configurable)'); + + st.end(); + }); + + t.test('loose mode', { skip: !hasPropertyDescriptors }, function (st) { + var obj = { existing: 'existing property' }; + + defineDataProperty(obj, 'added', 'added value 1', true, null, null, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: true, + enumerable: !hasPropertyDescriptors, + value: 'added value 1', + writable: true + } + }, + 'in loose mode, obj still adds property 1' + ); + + defineDataProperty(obj, 'added', 'added value 2', false, true, null, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: true, + enumerable: true, + value: 'added value 2', + writable: !hasPropertyDescriptors + } + }, + 'in loose mode, obj still adds property 2' + ); + + defineDataProperty(obj, 'added', 'added value 3', false, false, true, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: !hasPropertyDescriptors, + enumerable: true, + value: 'added value 3', + writable: true + } + }, + 'in loose mode, obj still adds property 3' + ); + + st.end(); + }); + + t.test('non-normal data property, ES3', { skip: hasPropertyDescriptors }, function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', true); }, + SyntaxError, + 'nonEnumerable throws a Syntax Error' + ); + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', false, true); }, + SyntaxError, + 'nonWritable throws a Syntax Error' + ); + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', false, false, true); }, + SyntaxError, + 'nonWritable throws a Syntax Error' + ); + + st.deepEqual( + ownKeys(obj), + ['existing'], + 'obj still has expected keys' + ); + st.equal(obj.existing, 'existing property', 'obj still has expected values'); + + st.end(); + }); + + t.test('new non-normal data property, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + + defineDataProperty(obj, 'nonEnum', null, true); + defineDataProperty(obj, 'nonWrit', null, false, true); + defineDataProperty(obj, 'nonConf', null, false, false, true); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + nonEnum: { + configurable: true, + enumerable: false, + value: null, + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: null, + writable: false + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj has expected property descriptors' + ); + + st.end(); + }); + + t.test('existing non-normal data property, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + // test case changing an existing non-normal property + + /** @type {Record} */ + var obj = {}; + Object.defineProperty(obj, 'nonEnum', { configurable: true, enumerable: false, value: null, writable: true }); + Object.defineProperty(obj, 'nonWrit', { configurable: true, enumerable: true, value: null, writable: false }); + Object.defineProperty(obj, 'nonConf', { configurable: false, enumerable: true, value: null, writable: true }); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + nonEnum: { + configurable: true, + enumerable: false, + value: null, + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: null, + writable: false + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj initially has expected property descriptors' + ); + + defineDataProperty(obj, 'nonEnum', 'new value', false); + defineDataProperty(obj, 'nonWrit', 'new value', false, false); + st['throws']( + function () { defineDataProperty(obj, 'nonConf', 'new value', false, false, false); }, + TypeError, + 'can not alter a nonconfigurable property' + ); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + nonEnum: { + configurable: true, + enumerable: true, + value: 'new value', + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: 'new value', + writable: true + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj ends up with expected property descriptors' + ); + + st.end(); + }); + + t.test('frozen object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var frozen = Object.freeze({ existing: true }); + + st['throws']( + function () { defineDataProperty(frozen, 'existing', 'new value'); }, + TypeError, + 'frozen object can not modify an existing property' + ); + + st['throws']( + function () { defineDataProperty(frozen, 'new', 'new property'); }, + TypeError, + 'frozen object can not add a new property' + ); + + st.end(); + }); + + t.test('sealed object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var sealed = Object.seal({ existing: true }); + st.deepEqual( + Object.getOwnPropertyDescriptor(sealed, 'existing'), + { + configurable: false, + enumerable: true, + value: true, + writable: true + }, + 'existing value on sealed object has expected descriptor' + ); + + defineDataProperty(sealed, 'existing', 'new value'); + + st.deepEqual( + Object.getOwnPropertyDescriptor(sealed, 'existing'), + { + configurable: false, + enumerable: true, + value: 'new value', + writable: true + }, + 'existing value on sealed object has changed descriptor' + ); + + st['throws']( + function () { defineDataProperty(sealed, 'new', 'new property'); }, + TypeError, + 'sealed object can not add a new property' + ); + + st.end(); + }); + + t.test('nonextensible object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var nonExt = Object.preventExtensions({ existing: true }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(nonExt, 'existing'), + { + configurable: true, + enumerable: true, + value: true, + writable: true + }, + 'existing value on non-extensible object has expected descriptor' + ); + + defineDataProperty(nonExt, 'existing', 'new value', true); + + st.deepEqual( + Object.getOwnPropertyDescriptor(nonExt, 'existing'), + { + configurable: true, + enumerable: false, + value: 'new value', + writable: true + }, + 'existing value on non-extensible object has changed descriptor' + ); + + st['throws']( + function () { defineDataProperty(nonExt, 'new', 'new property'); }, + TypeError, + 'non-extensible object can not add a new property' + ); + + st.end(); + }); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/define-data-property/tsconfig.json b/test/merkletreejs/node_modules/define-data-property/tsconfig.json new file mode 100644 index 0000000..69f060d --- /dev/null +++ b/test/merkletreejs/node_modules/define-data-property/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/test/merkletreejs/node_modules/ethereum-bloom-filters/LICENSE b/test/merkletreejs/node_modules/ethereum-bloom-filters/LICENSE new file mode 100644 index 0000000..a98ddf1 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-bloom-filters/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Josh Stevens + +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. diff --git a/test/merkletreejs/node_modules/ethereum-bloom-filters/README.md b/test/merkletreejs/node_modules/ethereum-bloom-filters/README.md new file mode 100644 index 0000000..321c4dc --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-bloom-filters/README.md @@ -0,0 +1,188 @@ +[![npm version](https://badge.fury.io/js/ethereum-bloom-filters.svg)](https://badge.fury.io/js/ethereum-bloom-filters) +![downloads](https://img.shields.io/npm/dw/ethereum-bloom-filters) + +# ethereum-bloom-filters + +A lightweight bloom filter client which allows you to test ethereum blooms for fast checks of set membership. + +This package only has 1 dependency which is on `js-sha3` which has no dependencies on at all. + +## Installation + +### npm: + +```js +$ npm install ethereum-bloom-filters +``` + +### yarn: + +```js +$ yarn add ethereum-bloom-filters +``` + +## Usage + +### JavaScript (ES3) + +```js +var ethereumBloomFilters = require('ethereum-bloom-filters'); +``` + +### JavaScript (ES5 or ES6) + +```js +const ethereumBloomFilters = require('ethereum-bloom-filters'); +``` + +### JavaScript (ES6) / TypeScript + +```js +import { + isBloom, + isUserEthereumAddressInBloom, + isContractAddressInBloom, + isTopic, + isTopicInBloom, + isInBloom, +} from 'ethereum-bloom-filters'; +``` + +### Including within a web application which doesn't use any transpiler + +When using angular, react or vuejs these frameworks handle dependencies and transpile them so they work on the web, so if you're using any of them just use the above code snippets to start using this package. + +If you're using a standard web application you can go [here](https://github.com/joshstevens19/ethereum-bloom-filters/tree/master/web-scripts) to copy any of the versioned script files and then dropping it into your web application, making sure you reference it within a script tag in the head of the website. + +This will expose the library as a global variable named `ethereumBloomFilters`, you can then execute the methods through this variable: + +```js +ethereumBloomFilters.isBloom(...) +ethereumBloomFilters.isUserEthereumAddressInBloom(...) +ethereumBloomFilters.isContractAddressInBloom(...) +ethereumBloomFilters.isTopic(...) +ethereumBloomFilters.isTopicInBloom(...) +ethereumBloomFilters.isInBloom(...) +``` + +You can find out more about the functions parameters below. + +We do not expose an cdn for security reasons. + +## What are bloom filters? + +A Bloom filter is a probabilistic, space-efficient data structure used for fast checks of set membership. That probably doesn’t mean much to you yet, and so let’s explore how bloom filters might be used. + +Imagine that we have some large set of data, and we want to be able to quickly test if some element is currently in that set. The naive way of checking might be to query the set to see if our element is in there. That’s probably fine if our data set is relatively small. Unfortunately, if our data set is really big, this search might take a while. Luckily, we have tricks to speed things up in the ethereum world! + +A bloom filter is one of these tricks. The basic idea behind the Bloom filter is to hash each new element that goes into the data set, take certain bits from this hash, and then use those bits to fill in parts of a fixed-size bit array (e.g. set certain bits to 1). This bit array is called a bloom filter. + +Later, when we want to check if an element is in the set, we simply hash the element and check that the right bits are in the bloom filter. If at least one of the bits is 0, then the element definitely isn’t in our data set! If all of the bits are 1, then the element might be in the data set, but we need to actually query the database to be sure. So we might have false positives, but we’ll never have false negatives. This can greatly reduce the number of database queries we have to make. + +## ethereum-bloom-filters benefits with an real life example + +A ethereum real life example in where this is useful is if you want to update a users balance on every new block so it stays as close to real time as possible. Without using a bloom filter on every new block you would have to force the balances even if that user may not of had any activity within that block. But if you use the logBlooms from the block you can test the bloom filter against the users ethereum address before you do any more slow operations, this will dramatically decrease the amount of calls you do as you will only be doing those extra operations if that ethereum address is within that block (minus the false positives outcome which will be negligible). This will be highly performant for your app. + +## Requirements for blooms to be queryable + +Blooms do not work with eth transactions (purely sending eth), eth transactions do not emit logs so do not exist in the bloom filter. This is what ethereum did purposely but it means you should query the eth balance every block to make sure it's in sync. Blooms will only work if the transaction emits an event which then ends up in the logs. The bloom filter is there to help you find logs. A contract can be written which does not emit an event and in that case, would not be queryable from a bloom filter. The erc20 token spec requires you to fire an event on `approval` and `transfer` so blooms will work for `approval` and `transfer` for ALL erc20 tokens, this will be most people's primary use-case. Saying that this can be used in any way you want with any use-case as long as events are emitted then it's queryable. + +## Functions + +### isBloom + +```ts +isBloom(bloom: string): boolean; +``` + +Returns true if the bloom is a valid bloom. + +### isUserEthereumAddressInBloom + +```ts +isUserEthereumAddressInBloom(bloom: string, ethereumAddress: string): boolean; +``` + +Returns true if the ethereum users address is part of the given bloom +note: false positives are possible. + +### isContractAddressInBloom + +```ts +isContractAddressInBloom(bloom: string, contractAddress: string): boolean; +``` + +Returns true if the contract address is part of the given bloom +note: false positives are possible. + +### isTopic + +```ts +isTopic(topic: string): boolean; +``` + +Returns true if the topic is valid + +### isTopicInBloom + +```ts +isTopicInBloom(bloom: string, topic: string): boolean; +``` + +Returns true if the topic is part of the given bloom +note: false positives are possible. + +### isInBloom + +This is the raw base method which the other bloom methods above use. You can pass in a bloom and a value which will return true if its part of the given bloom. + +```ts +isInBloom(bloom: string, value: string | Uint8Array): boolean; +``` + +Returns true if the value is part of the given bloom +note: false positives are possible. + +## Issues + +Please raise any issues in the below link. + +https://github.com/joshstevens19/ethereum-bloom-filters/issues + +## Thanks And Support + +This package is brought to you by [Josh Stevens](https://github.com/joshstevens19). My aim is to be able to keep creating these awesome packages to help the Ethereum space grow with easier-to-use tools to allow the learning curve to get involved with blockchain development easier and making Ethereum ecosystem better. If you want to help with that vision and allow me to invest more time into creating cool packages or if this package has saved you a lot of development time donations are welcome, every little helps. By donating, you are supporting me to be able to maintain existing packages, extend existing packages (as Ethereum matures), and allowing me to build more packages for Ethereum due to being able to invest more time into it. Thanks, everyone! + +## Direct donations + +Direct donations any token accepted - Eth address > `0x699c2daD091ffcF18f3cd9E8495929CA3a64dFe1` + +## Github sponsors + +[sponsor me](https://github.com/sponsors/joshstevens19) via github using fiat money + +## Contributors dev guide + +To run locally firstly run: + +```js +$ npm install +``` + +To build: + +```js +$ tsc +``` + +To watch build: + +```js +$ tsc --watch +``` + +To run tests: + +```js +$ npm test +``` diff --git a/test/merkletreejs/node_modules/ethereum-bloom-filters/package.json b/test/merkletreejs/node_modules/ethereum-bloom-filters/package.json new file mode 100644 index 0000000..3c4dc7b --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-bloom-filters/package.json @@ -0,0 +1,45 @@ +{ + "name": "ethereum-bloom-filters", + "version": "1.0.10", + "description": "Ability to test bloom filters for ethereum.", + "main": "dist/index.js", + "scripts": { + "build": "tsc && npm run build-web-scripts", + "watch": "tsc --watch", + "test": "jest", + "publish-sdk": "npm run build && npm publish --access public", + "build-web-scripts": "tsc && gulp" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/joshstevens19/ethereum-bloom-filters.git" + }, + "author": "joshstevens19@hotmail.co.uk", + "license": "MIT", + "bugs": { + "url": "https://github.com/joshstevens19/ethereum-bloom-filters/issues" + }, + "homepage": "https://github.com/joshstevens19/ethereum-bloom-filters#readme", + "keywords": [ + "ethereum", + "blockchain", + "blooms", + "bloom", + "bloom filters" + ], + "dependencies": { + "js-sha3": "^0.8.0" + }, + "devDependencies": { + "@types/jest": "^24.0.18", + "browserify": "^16.5.0", + "gulp": "^4.0.2", + "gulp-uglify-es": "^1.0.4", + "jest": "^24.9.0", + "ts-jest": "^24.1.0", + "tslint": "^5.20.0", + "typescript": "^3.6.4", + "vinyl-buffer": "^1.0.1", + "vinyl-source-stream": "^2.0.0" + } +} diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/LICENSE b/test/merkletreejs/node_modules/ethereum-cryptography/LICENSE new file mode 100644 index 0000000..29f02ab --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Patricio Palladino, Paul Miller, ethereum-cryptography 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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/README.md b/test/merkletreejs/node_modules/ethereum-cryptography/README.md new file mode 100644 index 0000000..fed06ac --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/README.md @@ -0,0 +1,508 @@ +# ethereum-cryptography + +[![npm version][1]][2] [![license][3]][4] + +[Audited](#security) pure JS library containing all Ethereum-related cryptographic primitives. + +Included algorithms, implemented with just 5 [noble & scure](https://paulmillr.com/noble/) dependencies: + +* [Hashes: SHA256, keccak-256, RIPEMD160, BLAKE2b](#hashes-sha256-keccak-256-ripemd160-blake2b) +* [KDFs: PBKDF2, Scrypt](#kdfs-pbkdf2-scrypt) +* [CSPRNG (Cryptographically Secure Pseudorandom Number Generator)](#csprng-cryptographically-strong-pseudorandom-number-generator) +* [secp256k1 elliptic curve](#secp256k1-curve) +* [BIP32 HD Keygen](#bip32-hd-keygen) +* [BIP39 Mnemonic phrases](#bip39-mnemonic-seed-phrase) +* [AES Encryption](#aes-encryption) + +**April 2023 update:** v2.0 is out, switching +[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1) to +[noble-curves](https://github.com/paulmillr/noble-curves), +which changes re-exported api of `secp256k1` submodule. +There have been no other changes. + +**January 2022 update:** v1.0 has been released. We've rewritten the library from +scratch and [audited](#security) it. It became **6x smaller:** ~5,000 lines of +code instead of ~24,000 (with all deps); 650KB instead of 10.2MB. +5 dependencies by 1 author are now used, instead of 38 by 5 authors. + +Check out [Upgrading](#upgrading) section and an article about the library: +[A safer, smaller, and faster Ethereum cryptography stack](https://medium.com/nomic-labs-blog/a-safer-smaller-and-faster-ethereum-cryptography-stack-5eeb47f62d79). + +## Usage + +Use NPM / Yarn in node.js / browser: + +```bash +# NPM +npm install ethereum-cryptography + +# Yarn +yarn add ethereum-cryptography +``` + +See [browser usage](#browser-usage) for information on using the package with major Javascript bundlers. It is +tested with **Webpack, Rollup, Parcel and Browserify**. + +This package has no single entry-point, but submodule for each cryptographic +primitive. Read each primitive's section of this document to learn how to use +them. + +The reason for this is that importing everything from a single file will lead to +huge bundles when using this package for the web. This could be avoided through +tree-shaking, but the possibility of it not working properly on one of +[the supported bundlers](#browser-usage) is too high. + +```js +// Hashes +import { sha256 } from "ethereum-cryptography/sha256.js"; +import { keccak256 } from "ethereum-cryptography/keccak.js"; +import { ripemd160 } from "ethereum-cryptography/ripemd160.js"; +import { blake2b } from "ethereum-cryptography/blake2b.js"; + +// KDFs +import { pbkdf2Sync } from "ethereum-cryptography/pbkdf2.js"; +import { scryptSync } from "ethereum-cryptography/scrypt.js"; + +// Random +import { getRandomBytesSync } from "ethereum-cryptography/random.js"; + +// AES encryption +import { encrypt } from "ethereum-cryptography/aes.js"; + +// secp256k1 elliptic curve operations +import { secp256k1 } from "ethereum-cryptography/secp256k1.js"; + +// BIP32 HD Keygen, BIP39 Mnemonic Phrases +import { HDKey } from "ethereum-cryptography/hdkey.js"; +import { generateMnemonic } from "ethereum-cryptography/bip39/index.js"; +import { wordlist } from "ethereum-cryptography/bip39/wordlists/english.js"; + +// utilities +import { hexToBytes, toHex, utf8ToBytes } from "ethereum-cryptography/utils.js"; +``` + +## Hashes: SHA256, keccak-256, RIPEMD160, BLAKE2b +```typescript +function sha256(msg: Uint8Array): Uint8Array; +function sha512(msg: Uint8Array): Uint8Array; +function keccak256(msg: Uint8Array): Uint8Array; +function ripemd160(msg: Uint8Array): Uint8Array; +function blake2b(msg: Uint8Array, outputLength = 64): Uint8Array; +``` + +Exposes following cryptographic hash functions: + +- SHA2 (SHA256, SHA512) +- keccak-256 variant of SHA3 (also `keccak224`, `keccak384`, +and `keccak512`) +- RIPEMD160 +- BLAKE2b + +```js +import { sha256 } from "ethereum-cryptography/sha256.js"; +import { sha512 } from "ethereum-cryptography/sha512.js"; +import { keccak256, keccak224, keccak384, keccak512 } from "ethereum-cryptography/keccak.js"; +import { ripemd160 } from "ethereum-cryptography/ripemd160.js"; +import { blake2b } from "ethereum-cryptography/blake2b.js"; + +sha256(Uint8Array.from([1, 2, 3])) + +// Can be used with strings +import { utf8ToBytes } from "ethereum-cryptography/utils.js"; +sha256(utf8ToBytes("abc")) + +// If you need hex +import { bytesToHex as toHex } from "ethereum-cryptography/utils.js"; +toHex(sha256(utf8ToBytes("abc"))) +``` + +## KDFs: PBKDF2, Scrypt + +```ts +function pbkdf2(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Promise; +function pbkdf2Sync(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Uint8Array; +function scrypt(password: Uint8Array, salt: Uint8Array, N: number, p: number, r: number, dkLen: number, onProgress?: (progress: number) => void): Promise; +function scryptSync(password: Uint8Array, salt: Uint8Array, N: number, p: number, r: number, dkLen: number, onProgress?: (progress: number) => void)): Uint8Array; +``` + +The `pbkdf2` submodule has two functions implementing the PBKDF2 key +derivation algorithm in synchronous and asynchronous ways. This algorithm is +very slow, and using the synchronous version in the browser is not recommended, +as it will block its main thread and hang your UI. The KDF supports `sha256` and `sha512` digests. + +The `scrypt` submodule has two functions implementing the Scrypt key +derivation algorithm in synchronous and asynchronous ways. This algorithm is +very slow, and using the synchronous version in the browser is not recommended, +as it will block its main thread and hang your UI. + +Encoding passwords is a frequent source of errors. Please read +[these notes](https://github.com/ricmoo/scrypt-js/tree/0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0#encoding-notes) +before using these submodules. + +```js +import { pbkdf2 } from "ethereum-cryptography/pbkdf2.js"; +import { utf8ToBytes } from "ethereum-cryptography/utils.js"; +// Pass Uint8Array, or convert strings to Uint8Array +console.log(await pbkdf2(utf8ToBytes("password"), utf8ToBytes("salt"), 131072, 32, "sha256")); +``` + +```js +import { scrypt } from "ethereum-cryptography/scrypt.js"; +import { utf8ToBytes } from "ethereum-cryptography/utils.js"; +console.log(await scrypt(utf8ToBytes("password"), utf8ToBytes("salt"), 262144, 8, 1, 32)); +``` + +## CSPRNG (Cryptographically strong pseudorandom number generator) + +```ts +function getRandomBytes(bytes: number): Promise; +function getRandomBytesSync(bytes: number): Uint8Array; +``` + +The `random` submodule has functions to generate cryptographically strong +pseudo-random data in synchronous and asynchronous ways. + +Backed by [`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) in browser and by [`crypto.randomBytes`](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback) in node.js. If backends are somehow not available, the module would throw an error and won't work, as keeping them working would be insecure. + +```js +import { getRandomBytesSync } from "ethereum-cryptography/random.js"; +console.log(getRandomBytesSync(32)); +``` + +## secp256k1 curve + +```ts +function getPublicKey(privateKey: Uint8Array, isCompressed = true): Uint8Array; +function sign(msgHash: Uint8Array, privateKey: Uint8Array): { r: bigint; s: bigint; recovery: number }; +function verify(signature: Uint8Array, msgHash: Uint8Array, publicKey: Uint8Array): boolean +function getSharedSecret(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array; +function utils.randomPrivateKey(): Uint8Array; +``` + +The `secp256k1` submodule provides a library for elliptic curve operations on +the curve secp256k1. For detailed documentation, follow [README of `noble-curves`](https://github.com/paulmillr/noble-curves), which the module uses as a backend. + +secp256k1 private keys need to be cryptographically secure random numbers with +certain characteristics. If this is not the case, the security of secp256k1 is +compromised. We strongly recommend using `utils.randomPrivateKey()` to generate them. + +```js +import { secp256k1 } from "ethereum-cryptography/secp256k1.js"; +(async () => { + // You pass either a hex string, or Uint8Array + const privateKey = "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e"; + const messageHash = "a33321f98e4ff1c283c76998f14f57447545d339b3db534c6d886decb4209f28"; + const publicKey = secp256k1.getPublicKey(privateKey); + const signature = secp256k1.sign(messageHash, privateKey); + const isSigned = secp256k1.verify(signature, messageHash, publicKey); +})(); +``` + +We're also providing a compatibility layer for users who want to upgrade +from `tiny-secp256k1` or `secp256k1` modules without hassle. +Check out [secp256k1 compatibility layer](#legacy-secp256k1-compatibility-layer). + +## BIP32 HD Keygen + +Hierarchical deterministic (HD) wallets that conform to BIP32 standard. +Also available as standalone package [scure-bip32](https://github.com/paulmillr/scure-bip32). + +This module exports a single class `HDKey`, which should be used like this: + +```ts +import { HDKey } from "ethereum-cryptography/hdkey.js"; +const hdkey1 = HDKey.fromMasterSeed(seed); +const hdkey2 = HDKey.fromExtendedKey(base58key); +const hdkey3 = HDKey.fromJSON({ xpriv: string }); + +// props +[hdkey1.depth, hdkey1.index, hdkey1.chainCode]; +console.log(hdkey2.privateKey, hdkey2.publicKey); +console.log(hdkey3.derive("m/0/2147483647'/1")); +const sig = hdkey3.sign(hash); +hdkey3.verify(hash, sig); +``` + +Note: `chainCode` property is essentially a private part +of a secret "master" key, it should be guarded from unauthorized access. + +The full API is: + +```ts +class HDKey { + public static HARDENED_OFFSET: number; + public static fromMasterSeed(seed: Uint8Array, versions: Versions): HDKey; + public static fromExtendedKey(base58key: string, versions: Versions): HDKey; + public static fromJSON(json: { xpriv: string }): HDKey; + + readonly versions: Versions; + readonly depth: number = 0; + readonly index: number = 0; + readonly chainCode: Uint8Array | null = null; + readonly parentFingerprint: number = 0; + + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + + derive(path: string): HDKey; + deriveChild(index: number): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; +} + +interface Versions { + private: number; + public: number; +} +``` + +The `hdkey` submodule provides a library for keys derivation according to +[BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). + +It has almost the exact same API than the version `1.x` of +[`hdkey` from cryptocoinjs](https://github.com/cryptocoinjs/hdkey), +but it's backed by this package's primitives, and has built-in TypeScript types. +Its only difference is that it has to be used with a named import. +The implementation is [loosely based on hdkey, which has MIT License](#LICENSE). + +## BIP39 Mnemonic Seed Phrase + +```ts +function generateMnemonic(wordlist: string[], strength: number = 128): string; +function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; +function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; +function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +async function mnemonicToSeed(mnemonic: string, passphrase: string = ""): Promise; +function mnemonicToSeedSync(mnemonic: string, passphrase: string = ""): Uint8Array; +``` + +The `bip39` submodule provides functions to generate, validate and use seed +recovery phrases according to [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). + +Also available as standalone package [scure-bip39](https://github.com/paulmillr/scure-bip39). + +```js +import { generateMnemonic } from "ethereum-cryptography/bip39/index.js"; +import { wordlist } from "ethereum-cryptography/bip39/wordlists/english.js"; +console.log(generateMnemonic(wordlist)); +``` + +This submodule also contains the word lists defined by BIP39 for Czech, English, +French, Italian, Japanese, Korean, Simplified and Traditional Chinese, and +Spanish. These are not imported by default, as that would increase bundle sizes +too much. Instead, you should import and use them explicitly. + +The word lists are exported as a `wordlist` variable in each of these submodules: + +* `ethereum-cryptography/bip39/wordlists/czech.js` +* `ethereum-cryptography/bip39/wordlists/english.js` +* `ethereum-cryptography/bip39/wordlists/french.js` +* `ethereum-cryptography/bip39/wordlists/italian.js` +* `ethereum-cryptography/bip39/wordlists/japanese.js` +* `ethereum-cryptography/bip39/wordlists/korean.js` +* `ethereum-cryptography/bip39/wordlists/simplified-chinese.js` +* `ethereum-cryptography/bip39/wordlists/spanish.js` +* `ethereum-cryptography/bip39/wordlists/traditional-chinese.js` + +## AES Encryption + +```ts +function encrypt(msg: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Promise; +function decrypt(cypherText: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Promise; +``` + +The `aes` submodule contains encryption and decryption functions implementing +the [Advanced Encryption Standard](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) +algorithm. + +### Encrypting with passwords + +AES is not supposed to be used directly with a password. Doing that will +compromise your users' security. + +The `key` parameters in this submodule are meant to be strong cryptographic +keys. If you want to obtain such a key from a password, please use a +[key derivation function](https://en.wikipedia.org/wiki/Key_derivation_function) +like [pbkdf2](#pbkdf2-submodule) or [scrypt](#scrypt-submodule). + +### Operation modes + +This submodule works with different [block cipher modes of operation](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation). If you are using this module in a new +application, we recommend using the default. + +While this module may work with any mode supported by OpenSSL, we only test it +with `aes-128-ctr`, `aes-128-cbc`, and `aes-256-cbc`. If you use another module +a warning will be printed in the console. + +We only recommend using `aes-128-cbc` and `aes-256-cbc` to decrypt already +encrypted data. + +### Padding plaintext messages + +Some operation modes require the plaintext message to be a multiple of `16`. If +that isn't the case, your message has to be padded. + +By default, this module automatically pads your messages according to [PKCS#7](https://tools.ietf.org/html/rfc2315). +Note that this padding scheme always adds at least 1 byte of padding. If you +are unsure what anything of this means, we **strongly** recommend you to use +the defaults. + +If you need to encrypt without padding or want to use another padding scheme, +you can disable PKCS#7 padding by passing `false` as the last argument and +handling padding yourself. Note that if you do this and your operation mode +requires padding, `encrypt` will throw if your plaintext message isn't a +multiple of `16`. + +This option is only present to enable the decryption of already encrypted data. +To encrypt new data, we recommend using the default. + +### How to use the IV parameter + +The `iv` parameter of the `encrypt` function must be unique, or the security +of the encryption algorithm can be compromised. + +You can generate a new `iv` using the `random` module. + +Note that to decrypt a value, you have to provide the same `iv` used to encrypt +it. + +### How to handle errors with this module + +Sensitive information can be leaked via error messages when using this module. +To avoid this, you should make sure that the errors you return don't +contain the exact reason for the error. Instead, errors must report general +encryption/decryption failures. + +Note that implementing this can mean catching all errors that can be thrown +when calling on of this module's functions, and just throwing a new generic +exception. + +### Example usage + +```js +import { encrypt } from "ethereum-cryptography/aes.js"; +import { hexToBytes, utf8ToBytes } from "ethereum-cryptography/utils.js"; + +console.log( + encrypt( + utf8ToBytes("message"), + hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"), + hexToBytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff") + ) +); +``` + +## Browser usage + +### Rollup setup + +Using this library with Rollup requires the following plugins: + +* [`@rollup/plugin-commonjs`](https://www.npmjs.com/package/@rollup/plugin-commonjs) +* [`@rollup/plugin-node-resolve`](https://www.npmjs.com/package/@rollup/plugin-node-resolve) + +These can be used by setting your `plugins` array like this: + +```js + plugins: [ + commonjs(), + resolve({ + browser: true, + preferBuiltins: false, + }), + ] +``` + +## Legacy secp256k1 compatibility layer + +**Warning:** use `secp256k1` instead. This module is only for users who upgraded +from ethereum-cryptography v0.1. It could be removed in the future. + +The API of `secp256k1-compat` is the same as [secp256k1-node](https://github.com/cryptocoinjs/secp256k1-node): + +```js +import { createPrivateKeySync, ecdsaSign } from "ethereum-cryptography/secp256k1-compat"; +const msgHash = Uint8Array.from( + "82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28", + "hex" +); +const privateKey = createPrivateKeySync(); +console.log(Uint8Array.from(ecdsaSign(msgHash, privateKey).signature)); +``` + +## Missing cryptographic primitives + +This package intentionally excludes the cryptographic primitives necessary +to implement the following EIPs: + +* [EIP 196: Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128](https://eips.ethereum.org/EIPS/eip-196) +* [EIP 197: Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128](https://eips.ethereum.org/EIPS/eip-197) +* [EIP 198: Big integer modular exponentiation](https://eips.ethereum.org/EIPS/eip-198) +* [EIP 152: Add Blake2 compression function `F` precompile](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-152.md) + +Feel free to open an issue if you want this decision to be reconsidered, or if +you found another primitive that is missing. + +## Upgrading + +Upgrading from 1.0 to 2.0: + +1. `secp256k1` module was changed massively: + before, it was using [noble-secp256k1 1.7](https://github.com/paulmillr/noble-secp256k1); + now it uses safer [noble-curves](https://github.com/paulmillr/noble-curves). Please refer + to [upgrading section from curves README](https://github.com/paulmillr/noble-curves#upgrading). + Main changes to keep in mind: a) `sign` now returns `Signature` instance + b) `recoverPublicKey` got moved onto a `Signature` instance +2. node.js 14 and older support was dropped. Upgrade to node.js 16 or later. + +Upgrading from 0.1 to 1.0: **Same functionality**, all old APIs remain the same except for the breaking changes: + +1. We return `Uint8Array` from all methods that worked with `Buffer` before. +`Buffer` has never been supported in browsers, while `Uint8Array`s are supported natively in both +browsers and node.js. +2. We target runtimes with [bigint](https://caniuse.com/bigint) support, +which is Chrome 67+, Edge 79+, Firefox 68+, Safari 14+, node.js 10+. If you need to support older runtimes, use `ethereum-cryptography@0.1` +3. If you've used `secp256k1`, [rename it to `secp256k1-compat`](#legacy-secp256k1-compatibility-layer) + +```js +import { sha256 } from "ethereum-cryptography/sha256.js"; + +// Old usage +const hasho = sha256(Buffer.from("string", "utf8")).toString("hex"); + +// New usage +import { toHex } from "ethereum-cryptography/utils.js"; +const hashn = toHex(sha256("string")); + +// If you have `Buffer` module and want to preserve it: +const hashb = Buffer.from(sha256("string")); +const hashbo = hashb.toString("hex"); +``` + +## Security + +Audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). + +## License + +`ethereum-cryptography` is released under The MIT License (MIT) + +Copyright (c) 2021 Patricio Palladino, Paul Miller, ethereum-cryptography contributors + +See [LICENSE](./LICENSE) file. + +`hdkey` is loosely based on [hdkey](https://github.com/cryptocoinjs/hdkey), +which had [MIT License](https://github.com/cryptocoinjs/hdkey/blob/3f3c0b5cedb98f971835b5116ebea05b3c09422a/LICENSE) + +Copyright (c) 2018 cryptocoinjs + +[1]: https://img.shields.io/npm/v/ethereum-cryptography.svg +[2]: https://www.npmjs.com/package/ethereum-cryptography +[3]: https://img.shields.io/npm/l/ethereum-cryptography +[4]: https://github.com/ethereum/js-ethereum-cryptography/blob/master/packages/ethereum-cryptography/LICENSE diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/aes.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/aes.d.ts new file mode 100644 index 0000000..bc69bae --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/aes.d.ts @@ -0,0 +1,2 @@ +export declare function encrypt(msg: Uint8Array, key: Uint8Array, iv: Uint8Array, mode?: string, pkcs7PaddingEnabled?: boolean): Promise; +export declare function decrypt(cypherText: Uint8Array, key: Uint8Array, iv: Uint8Array, mode?: string, pkcs7PaddingEnabled?: boolean): Promise; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/aes.js b/test/merkletreejs/node_modules/ethereum-cryptography/aes.js new file mode 100644 index 0000000..0cbe396 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/aes.js @@ -0,0 +1,98 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decrypt = exports.encrypt = void 0; +const crypto_1 = require("@noble/hashes/crypto"); +const utils_js_1 = require("./utils.js"); +const crypto = { web: crypto_1.crypto }; +function validateOpt(key, iv, mode) { + if (!mode.startsWith("aes-")) { + throw new Error(`AES submodule doesn't support mode ${mode}`); + } + if (iv.length !== 16) { + throw new Error("AES: wrong IV length"); + } + if ((mode.startsWith("aes-128") && key.length !== 16) || + (mode.startsWith("aes-256") && key.length !== 32)) { + throw new Error("AES: wrong key length"); + } +} +async function getBrowserKey(mode, key, iv) { + if (!crypto.web) { + throw new Error("Browser crypto not available."); + } + let keyMode; + if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) { + keyMode = "cbc"; + } + if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) { + keyMode = "ctr"; + } + if (!keyMode) { + throw new Error("AES: unsupported mode"); + } + const wKey = await crypto.web.subtle.importKey("raw", key, { name: `AES-${keyMode.toUpperCase()}`, length: key.length * 8 }, true, ["encrypt", "decrypt"]); + // node.js uses whole 128 bit as a counter, without nonce, instead of 64 bit + // recommended by NIST SP800-38A + return [wKey, { name: `aes-${keyMode}`, iv, counter: iv, length: 128 }]; +} +async function encrypt(msg, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) { + validateOpt(key, iv, mode); + if (crypto.web) { + const [wKey, wOpt] = await getBrowserKey(mode, key, iv); + const cipher = await crypto.web.subtle.encrypt(wOpt, wKey, msg); + // Remove PKCS7 padding on cbc mode by stripping end of message + let res = new Uint8Array(cipher); + if (!pkcs7PaddingEnabled && wOpt.name === "aes-cbc" && !(msg.length % 16)) { + res = res.slice(0, -16); + } + return res; + } + else if (crypto.node) { + const cipher = crypto.node.createCipheriv(mode, key, iv); + cipher.setAutoPadding(pkcs7PaddingEnabled); + return (0, utils_js_1.concatBytes)(cipher.update(msg), cipher.final()); + } + else { + throw new Error("The environment doesn't have AES module"); + } +} +exports.encrypt = encrypt; +async function getPadding(cypherText, key, iv, mode) { + const lastBlock = cypherText.slice(-16); + for (let i = 0; i < 16; i++) { + // Undo xor of iv and fill with lastBlock ^ padding (16) + lastBlock[i] ^= iv[i] ^ 16; + } + const res = await encrypt(lastBlock, key, iv, mode); + return res.slice(0, 16); +} +async function decrypt(cypherText, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) { + validateOpt(key, iv, mode); + if (crypto.web) { + const [wKey, wOpt] = await getBrowserKey(mode, key, iv); + // Add empty padding so Chrome will correctly decrypt message + if (!pkcs7PaddingEnabled && wOpt.name === "aes-cbc") { + const padding = await getPadding(cypherText, key, iv, mode); + cypherText = (0, utils_js_1.concatBytes)(cypherText, padding); + } + const msg = await crypto.web.subtle.decrypt(wOpt, wKey, cypherText); + const msgBytes = new Uint8Array(msg); + // Safari always ignores padding (if no padding -> broken message) + if (wOpt.name === "aes-cbc") { + const encrypted = await encrypt(msgBytes, key, iv, mode); + if (!(0, utils_js_1.equalsBytes)(encrypted, cypherText)) { + throw new Error("AES: wrong padding"); + } + } + return msgBytes; + } + else if (crypto.node) { + const decipher = crypto.node.createDecipheriv(mode, key, iv); + decipher.setAutoPadding(pkcs7PaddingEnabled); + return (0, utils_js_1.concatBytes)(decipher.update(cypherText), decipher.final()); + } + else { + throw new Error("The environment doesn't have AES module"); + } +} +exports.decrypt = decrypt; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/index.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/index.d.ts new file mode 100644 index 0000000..50c1c61 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/index.d.ts @@ -0,0 +1 @@ +export { generateMnemonic, mnemonicToEntropy, entropyToMnemonic, validateMnemonic, mnemonicToSeed, mnemonicToSeedSync } from "@scure/bip39"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/index.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/index.js new file mode 100644 index 0000000..5fb9218 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/index.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mnemonicToSeedSync = exports.mnemonicToSeed = exports.validateMnemonic = exports.entropyToMnemonic = exports.mnemonicToEntropy = exports.generateMnemonic = void 0; +var bip39_1 = require("@scure/bip39"); +Object.defineProperty(exports, "generateMnemonic", { enumerable: true, get: function () { return bip39_1.generateMnemonic; } }); +Object.defineProperty(exports, "mnemonicToEntropy", { enumerable: true, get: function () { return bip39_1.mnemonicToEntropy; } }); +Object.defineProperty(exports, "entropyToMnemonic", { enumerable: true, get: function () { return bip39_1.entropyToMnemonic; } }); +Object.defineProperty(exports, "validateMnemonic", { enumerable: true, get: function () { return bip39_1.validateMnemonic; } }); +Object.defineProperty(exports, "mnemonicToSeed", { enumerable: true, get: function () { return bip39_1.mnemonicToSeed; } }); +Object.defineProperty(exports, "mnemonicToSeedSync", { enumerable: true, get: function () { return bip39_1.mnemonicToSeedSync; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/czech.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/czech.d.ts new file mode 100644 index 0000000..a8cd030 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/czech.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/czech"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/czech.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/czech.js new file mode 100644 index 0000000..6e29e5a --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/czech.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var czech_1 = require("@scure/bip39/wordlists/czech"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return czech_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/english.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/english.d.ts new file mode 100644 index 0000000..77b99ba --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/english.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/english"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/english.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/english.js new file mode 100644 index 0000000..6167bcb --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/english.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var english_1 = require("@scure/bip39/wordlists/english"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return english_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/french.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/french.d.ts new file mode 100644 index 0000000..c95f532 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/french.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/french"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/french.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/french.js new file mode 100644 index 0000000..17c621c --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/french.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var french_1 = require("@scure/bip39/wordlists/french"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return french_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/italian.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/italian.d.ts new file mode 100644 index 0000000..75b7ebc --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/italian.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/italian"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/italian.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/italian.js new file mode 100644 index 0000000..7ea260c --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/italian.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var italian_1 = require("@scure/bip39/wordlists/italian"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return italian_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/japanese.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/japanese.d.ts new file mode 100644 index 0000000..f7b72c3 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/japanese.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/japanese"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/japanese.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/japanese.js new file mode 100644 index 0000000..a586e01 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/japanese.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var japanese_1 = require("@scure/bip39/wordlists/japanese"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return japanese_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/korean.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/korean.d.ts new file mode 100644 index 0000000..61b76bf --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/korean.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/korean"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/korean.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/korean.js new file mode 100644 index 0000000..1e25e5a --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/korean.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var korean_1 = require("@scure/bip39/wordlists/korean"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return korean_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/simplified-chinese.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/simplified-chinese.d.ts new file mode 100644 index 0000000..1aff712 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/simplified-chinese.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/simplified-chinese"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/simplified-chinese.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/simplified-chinese.js new file mode 100644 index 0000000..523c811 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/simplified-chinese.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var simplified_chinese_1 = require("@scure/bip39/wordlists/simplified-chinese"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return simplified_chinese_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/spanish.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/spanish.d.ts new file mode 100644 index 0000000..abf9af7 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/spanish.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/spanish"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/spanish.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/spanish.js new file mode 100644 index 0000000..6fc0c27 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/spanish.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var spanish_1 = require("@scure/bip39/wordlists/spanish"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return spanish_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/traditional-chinese.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/traditional-chinese.d.ts new file mode 100644 index 0000000..e2ff71c --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/traditional-chinese.d.ts @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/traditional-chinese"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/traditional-chinese.js b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/traditional-chinese.js new file mode 100644 index 0000000..a68e50a --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/bip39/wordlists/traditional-chinese.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlist = void 0; +var traditional_chinese_1 = require("@scure/bip39/wordlists/traditional-chinese"); +Object.defineProperty(exports, "wordlist", { enumerable: true, get: function () { return traditional_chinese_1.wordlist; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/blake2b.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/blake2b.d.ts new file mode 100644 index 0000000..f030965 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/blake2b.d.ts @@ -0,0 +1 @@ +export declare const blake2b: (msg: Uint8Array, outputLength?: number) => Uint8Array; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/blake2b.js b/test/merkletreejs/node_modules/ethereum-cryptography/blake2b.js new file mode 100644 index 0000000..6b60c3f --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/blake2b.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.blake2b = void 0; +const blake2b_1 = require("@noble/hashes/blake2b"); +const utils_js_1 = require("./utils.js"); +const blake2b = (msg, outputLength = 64) => { + (0, utils_js_1.assertBytes)(msg); + if (outputLength <= 0 || outputLength > 64) { + throw Error("Invalid outputLength"); + } + return (0, blake2b_1.blake2b)(msg, { dkLen: outputLength }); +}; +exports.blake2b = blake2b; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/aes.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/aes.js new file mode 100644 index 0000000..496dd83 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/aes.js @@ -0,0 +1,93 @@ +import { crypto as cr } from "@noble/hashes/crypto"; +import { concatBytes, equalsBytes } from "./utils.js"; +const crypto = { web: cr }; +function validateOpt(key, iv, mode) { + if (!mode.startsWith("aes-")) { + throw new Error(`AES submodule doesn't support mode ${mode}`); + } + if (iv.length !== 16) { + throw new Error("AES: wrong IV length"); + } + if ((mode.startsWith("aes-128") && key.length !== 16) || + (mode.startsWith("aes-256") && key.length !== 32)) { + throw new Error("AES: wrong key length"); + } +} +async function getBrowserKey(mode, key, iv) { + if (!crypto.web) { + throw new Error("Browser crypto not available."); + } + let keyMode; + if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) { + keyMode = "cbc"; + } + if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) { + keyMode = "ctr"; + } + if (!keyMode) { + throw new Error("AES: unsupported mode"); + } + const wKey = await crypto.web.subtle.importKey("raw", key, { name: `AES-${keyMode.toUpperCase()}`, length: key.length * 8 }, true, ["encrypt", "decrypt"]); + // node.js uses whole 128 bit as a counter, without nonce, instead of 64 bit + // recommended by NIST SP800-38A + return [wKey, { name: `aes-${keyMode}`, iv, counter: iv, length: 128 }]; +} +export async function encrypt(msg, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) { + validateOpt(key, iv, mode); + if (crypto.web) { + const [wKey, wOpt] = await getBrowserKey(mode, key, iv); + const cipher = await crypto.web.subtle.encrypt(wOpt, wKey, msg); + // Remove PKCS7 padding on cbc mode by stripping end of message + let res = new Uint8Array(cipher); + if (!pkcs7PaddingEnabled && wOpt.name === "aes-cbc" && !(msg.length % 16)) { + res = res.slice(0, -16); + } + return res; + } + else if (crypto.node) { + const cipher = crypto.node.createCipheriv(mode, key, iv); + cipher.setAutoPadding(pkcs7PaddingEnabled); + return concatBytes(cipher.update(msg), cipher.final()); + } + else { + throw new Error("The environment doesn't have AES module"); + } +} +async function getPadding(cypherText, key, iv, mode) { + const lastBlock = cypherText.slice(-16); + for (let i = 0; i < 16; i++) { + // Undo xor of iv and fill with lastBlock ^ padding (16) + lastBlock[i] ^= iv[i] ^ 16; + } + const res = await encrypt(lastBlock, key, iv, mode); + return res.slice(0, 16); +} +export async function decrypt(cypherText, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) { + validateOpt(key, iv, mode); + if (crypto.web) { + const [wKey, wOpt] = await getBrowserKey(mode, key, iv); + // Add empty padding so Chrome will correctly decrypt message + if (!pkcs7PaddingEnabled && wOpt.name === "aes-cbc") { + const padding = await getPadding(cypherText, key, iv, mode); + cypherText = concatBytes(cypherText, padding); + } + const msg = await crypto.web.subtle.decrypt(wOpt, wKey, cypherText); + const msgBytes = new Uint8Array(msg); + // Safari always ignores padding (if no padding -> broken message) + if (wOpt.name === "aes-cbc") { + const encrypted = await encrypt(msgBytes, key, iv, mode); + if (!equalsBytes(encrypted, cypherText)) { + throw new Error("AES: wrong padding"); + } + } + return msgBytes; + } + else if (crypto.node) { + const decipher = crypto.node.createDecipheriv(mode, key, iv); + decipher.setAutoPadding(pkcs7PaddingEnabled); + return concatBytes(decipher.update(cypherText), decipher.final()); + } + else { + throw new Error("The environment doesn't have AES module"); + } +} diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/index.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/index.js new file mode 100644 index 0000000..50c1c61 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/index.js @@ -0,0 +1 @@ +export { generateMnemonic, mnemonicToEntropy, entropyToMnemonic, validateMnemonic, mnemonicToSeed, mnemonicToSeedSync } from "@scure/bip39"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/czech.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/czech.js new file mode 100644 index 0000000..a8cd030 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/czech.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/czech"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/english.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/english.js new file mode 100644 index 0000000..77b99ba --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/english.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/english"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/french.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/french.js new file mode 100644 index 0000000..c95f532 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/french.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/french"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/italian.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/italian.js new file mode 100644 index 0000000..75b7ebc --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/italian.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/italian"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/japanese.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/japanese.js new file mode 100644 index 0000000..f7b72c3 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/japanese.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/japanese"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/korean.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/korean.js new file mode 100644 index 0000000..61b76bf --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/korean.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/korean"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/simplified-chinese.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/simplified-chinese.js new file mode 100644 index 0000000..1aff712 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/simplified-chinese.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/simplified-chinese"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/spanish.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/spanish.js new file mode 100644 index 0000000..abf9af7 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/spanish.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/spanish"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/traditional-chinese.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/traditional-chinese.js new file mode 100644 index 0000000..e2ff71c --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/bip39/wordlists/traditional-chinese.js @@ -0,0 +1 @@ +export { wordlist } from "@scure/bip39/wordlists/traditional-chinese"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/blake2b.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/blake2b.js new file mode 100644 index 0000000..19f2761 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/blake2b.js @@ -0,0 +1,9 @@ +import { blake2b as _blake2b } from "@noble/hashes/blake2b"; +import { assertBytes } from "./utils.js"; +export const blake2b = (msg, outputLength = 64) => { + assertBytes(msg); + if (outputLength <= 0 || outputLength > 64) { + throw Error("Invalid outputLength"); + } + return _blake2b(msg, { dkLen: outputLength }); +}; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/hdkey.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/hdkey.js new file mode 100644 index 0000000..79eab99 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/hdkey.js @@ -0,0 +1 @@ +export { HARDENED_OFFSET, HDKey } from "@scure/bip32"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/index.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/index.js new file mode 100644 index 0000000..6ac7bb3 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/index.js @@ -0,0 +1,2 @@ +"use strict"; +throw new Error("This package has no entry-point. Please consult the README.md to learn how to use it."); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/keccak.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/keccak.js new file mode 100644 index 0000000..b16b8ba --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/keccak.js @@ -0,0 +1,10 @@ +import { keccak_224, keccak_256, keccak_384, keccak_512 } from "@noble/hashes/sha3"; +import { wrapHash } from "./utils.js"; +export const keccak224 = wrapHash(keccak_224); +export const keccak256 = (() => { + const k = wrapHash(keccak_256); + k.create = keccak_256.create; + return k; +})(); +export const keccak384 = wrapHash(keccak_384); +export const keccak512 = wrapHash(keccak_512); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/package.json b/test/merkletreejs/node_modules/ethereum-cryptography/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/pbkdf2.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/pbkdf2.js new file mode 100644 index 0000000..69e1e1a --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/pbkdf2.js @@ -0,0 +1,26 @@ +import { pbkdf2 as _pbkdf2, pbkdf2Async as _pbkdf2Async } from "@noble/hashes/pbkdf2"; +import { sha256 } from "@noble/hashes/sha256"; +import { sha512 } from "@noble/hashes/sha512"; +import { assertBytes } from "./utils.js"; +export async function pbkdf2(password, salt, iterations, keylen, digest) { + if (!["sha256", "sha512"].includes(digest)) { + throw new Error("Only sha256 and sha512 are supported"); + } + assertBytes(password); + assertBytes(salt); + return _pbkdf2Async(digest === "sha256" ? sha256 : sha512, password, salt, { + c: iterations, + dkLen: keylen + }); +} +export function pbkdf2Sync(password, salt, iterations, keylen, digest) { + if (!["sha256", "sha512"].includes(digest)) { + throw new Error("Only sha256 and sha512 are supported"); + } + assertBytes(password); + assertBytes(salt); + return _pbkdf2(digest === "sha256" ? sha256 : sha512, password, salt, { + c: iterations, + dkLen: keylen + }); +} diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/random.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/random.js new file mode 100644 index 0000000..721bf09 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/random.js @@ -0,0 +1,7 @@ +import { randomBytes } from "@noble/hashes/utils"; +export function getRandomBytesSync(bytes) { + return randomBytes(bytes); +} +export async function getRandomBytes(bytes) { + return randomBytes(bytes); +} diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/ripemd160.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/ripemd160.js new file mode 100644 index 0000000..dd0fa5c --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/ripemd160.js @@ -0,0 +1,3 @@ +import { ripemd160 as _ripemd160 } from "@noble/hashes/ripemd160"; +import { wrapHash } from "./utils.js"; +export const ripemd160 = wrapHash(_ripemd160); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/scrypt.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/scrypt.js new file mode 100644 index 0000000..a03ecfe --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/scrypt.js @@ -0,0 +1,12 @@ +import { scrypt as _sync, scryptAsync as _async } from "@noble/hashes/scrypt"; +import { assertBytes } from "./utils.js"; +export async function scrypt(password, salt, n, p, r, dkLen, onProgress) { + assertBytes(password); + assertBytes(salt); + return _async(password, salt, { N: n, r, p, dkLen, onProgress }); +} +export function scryptSync(password, salt, n, p, r, dkLen, onProgress) { + assertBytes(password); + assertBytes(salt); + return _sync(password, salt, { N: n, r, p, dkLen, onProgress }); +} diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/secp256k1-compat.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/secp256k1-compat.js new file mode 100644 index 0000000..75b2f28 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/secp256k1-compat.js @@ -0,0 +1,254 @@ +import { sha256 } from "@noble/hashes/sha256"; +import { mod } from "@noble/curves/abstract/modular"; +import { secp256k1 } from "./secp256k1.js"; +import { assertBool, assertBytes, hexToBytes, toHex } from "./utils.js"; +// Use `secp256k1` module directly. +// This is a legacy compatibility layer for the npm package `secp256k1` via noble-secp256k1 +const Point = secp256k1.ProjectivePoint; +function hexToNumber(hex) { + if (typeof hex !== "string") { + throw new TypeError("hexToNumber: expected string, got " + typeof hex); + } + return BigInt(`0x${hex}`); +} +// Copy-paste from secp256k1, maybe export it? +const bytesToNumber = (bytes) => hexToNumber(toHex(bytes)); +const numberToHex = (num) => num.toString(16).padStart(64, "0"); +const numberToBytes = (num) => hexToBytes(numberToHex(num)); +const ORDER = secp256k1.CURVE.n; +function output(out = (len) => new Uint8Array(len), length, value) { + if (typeof out === "function") { + out = out(length); + } + assertBytes(out, length); + if (value) { + out.set(value); + } + return out; +} +function getSignature(signature) { + assertBytes(signature, 64); + return secp256k1.Signature.fromCompact(signature); +} +export function createPrivateKeySync() { + return secp256k1.utils.randomPrivateKey(); +} +export async function createPrivateKey() { + return createPrivateKeySync(); +} +export function privateKeyVerify(privateKey) { + assertBytes(privateKey, 32); + return secp256k1.utils.isValidPrivateKey(privateKey); +} +export function publicKeyCreate(privateKey, compressed = true, out) { + assertBytes(privateKey, 32); + assertBool(compressed); + const res = secp256k1.getPublicKey(privateKey, compressed); + return output(out, compressed ? 33 : 65, res); +} +export function publicKeyVerify(publicKey) { + assertBytes(publicKey, 33, 65); + try { + Point.fromHex(publicKey); + return true; + } + catch (e) { + return false; + } +} +export function publicKeyConvert(publicKey, compressed = true, out) { + assertBytes(publicKey, 33, 65); + assertBool(compressed); + const res = Point.fromHex(publicKey).toRawBytes(compressed); + return output(out, compressed ? 33 : 65, res); +} +export function ecdsaSign(msgHash, privateKey, options = { noncefn: undefined, data: undefined }, out) { + assertBytes(msgHash, 32); + assertBytes(privateKey, 32); + if (typeof options !== "object" || options === null) { + throw new TypeError("secp256k1.ecdsaSign: options should be object"); + } + // noble-secp256k1 uses hmac instead of hmac-drbg here + if (options && + (options.noncefn !== undefined || options.data !== undefined)) { + throw new Error("Secp256k1: noncefn && data is unsupported"); + } + const sig = secp256k1.sign(msgHash, privateKey); + const recid = sig.recovery; + return { signature: output(out, 64, sig.toCompactRawBytes()), recid }; +} +export function ecdsaRecover(signature, recid, msgHash, compressed = true, out) { + assertBytes(msgHash, 32); + assertBool(compressed); + const sign = getSignature(signature); + const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash); + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +export function ecdsaVerify(signature, msgHash, publicKey) { + assertBytes(signature, 64); + assertBytes(msgHash, 32); + assertBytes(publicKey, 33, 65); + assertBytes(signature, 64); + const r = bytesToNumber(signature.slice(0, 32)); + const s = bytesToNumber(signature.slice(32, 64)); + if (r >= ORDER || s >= ORDER) { + throw new Error("Cannot parse signature"); + } + const pub = Point.fromHex(publicKey); // can throw error + pub; // typescript + let sig; + try { + sig = getSignature(signature); + } + catch (error) { + return false; + } + return secp256k1.verify(sig, msgHash, publicKey); +} +export function privateKeyTweakAdd(privateKey, tweak) { + assertBytes(privateKey, 32); + assertBytes(tweak, 32); + let t = bytesToNumber(tweak); + if (t === 0n) { + throw new Error("Tweak must not be zero"); + } + if (t >= ORDER) { + throw new Error("Tweak bigger than curve order"); + } + t += bytesToNumber(privateKey); + if (t >= ORDER) { + t -= ORDER; + } + if (t === 0n) { + throw new Error("The tweak was out of range or the resulted private key is invalid"); + } + privateKey.set(hexToBytes(numberToHex(t))); + return privateKey; +} +export function privateKeyNegate(privateKey) { + assertBytes(privateKey, 32); + const bn = mod(-bytesToNumber(privateKey), ORDER); + privateKey.set(hexToBytes(numberToHex(bn))); + return privateKey; +} +export function publicKeyNegate(publicKey, compressed = true, out) { + assertBytes(publicKey, 33, 65); + assertBool(compressed); + const point = Point.fromHex(publicKey).negate(); + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +export function publicKeyCombine(publicKeys, compressed = true, out) { + if (!Array.isArray(publicKeys) || !publicKeys.length) { + throw new TypeError(`Expected array with one or more items, not ${publicKeys}`); + } + for (const publicKey of publicKeys) { + assertBytes(publicKey, 33, 65); + } + assertBool(compressed); + const combined = publicKeys + .map((pub) => Point.fromHex(pub)) + .reduce((res, curr) => res.add(curr), Point.ZERO); + // Prohibit returning ZERO point + if (combined.equals(Point.ZERO)) { + throw new Error("Combined result must not be zero"); + } + return output(out, compressed ? 33 : 65, combined.toRawBytes(compressed)); +} +export function publicKeyTweakAdd(publicKey, tweak, compressed = true, out) { + assertBytes(publicKey, 33, 65); + assertBytes(tweak, 32); + assertBool(compressed); + const p1 = Point.fromHex(publicKey); + const p2 = Point.fromPrivateKey(tweak); + const point = p1.add(p2); + if (p2.equals(Point.ZERO) || point.equals(Point.ZERO)) { + throw new Error("Tweak must not be zero"); + } + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +export function publicKeyTweakMul(publicKey, tweak, compressed = true, out) { + assertBytes(publicKey, 33, 65); + assertBytes(tweak, 32); + assertBool(compressed); + const bn = bytesToNumber(tweak); + if (bn === 0n) { + throw new Error("Tweak must not be zero"); + } + if (bn <= 1 || bn >= ORDER) { + throw new Error("Tweak is zero or bigger than curve order"); + } + const point = Point.fromHex(publicKey).multiply(bn); + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +export function privateKeyTweakMul(privateKey, tweak) { + assertBytes(privateKey, 32); + assertBytes(tweak, 32); + const bn = bytesToNumber(tweak); + if (bn <= 1 || bn >= ORDER) { + throw new Error("Tweak is zero or bigger than curve order"); + } + const res = mod(bn * bytesToNumber(privateKey), ORDER); + if (res === 0n) { + throw new Error("The tweak was out of range or the resulted private key is invalid"); + } + privateKey.set(hexToBytes(numberToHex(res))); + return privateKey; +} +// internal -> DER +export function signatureExport(signature, out) { + const res = getSignature(signature).toDERRawBytes(); + return output(out, 72, res.slice()).slice(0, res.length); +} +// DER -> internal +export function signatureImport(signature, out) { + assertBytes(signature); + const sig = secp256k1.Signature.fromDER(signature); + return output(out, 64, hexToBytes(sig.toCompactHex())); +} +export function signatureNormalize(signature) { + const res = getSignature(signature); + if (res.s > ORDER / 2n) { + signature.set(numberToBytes(ORDER - res.s), 32); + } + return signature; +} +export function ecdh(publicKey, privateKey, options = {}, out) { + assertBytes(publicKey, 33, 65); + assertBytes(privateKey, 32); + if (typeof options !== "object" || options === null) { + throw new TypeError("secp256k1.ecdh: options should be object"); + } + if (options.data !== undefined) { + assertBytes(options.data); + } + const point = Point.fromHex(secp256k1.getSharedSecret(privateKey, publicKey)); + if (options.hashfn === undefined) { + return output(out, 32, sha256(point.toRawBytes(true))); + } + if (typeof options.hashfn !== "function") { + throw new TypeError("secp256k1.ecdh: options.hashfn should be function"); + } + if (options.xbuf !== undefined) { + assertBytes(options.xbuf, 32); + } + if (options.ybuf !== undefined) { + assertBytes(options.ybuf, 32); + } + assertBytes(out, 32); + const { x, y } = point.toAffine(); + const xbuf = options.xbuf || new Uint8Array(32); + xbuf.set(numberToBytes(x)); + const ybuf = options.ybuf || new Uint8Array(32); + ybuf.set(numberToBytes(y)); + const hash = options.hashfn(xbuf, ybuf, options.data); + if (!(hash instanceof Uint8Array) || hash.length !== 32) { + throw new Error("secp256k1.ecdh: invalid options.hashfn output"); + } + return output(out, 32, hash); +} +export function contextRandomize(seed) { + if (seed !== null) { + assertBytes(seed, 32); + } + // There is no context to randomize +} diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/secp256k1.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/secp256k1.js new file mode 100644 index 0000000..28f4d1f --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/secp256k1.js @@ -0,0 +1 @@ +export { secp256k1 } from "@noble/curves/secp256k1"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/sha256.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/sha256.js new file mode 100644 index 0000000..44d9209 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/sha256.js @@ -0,0 +1,3 @@ +import { sha256 as _sha256 } from "@noble/hashes/sha256"; +import { wrapHash } from "./utils.js"; +export const sha256 = wrapHash(_sha256); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/sha512.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/sha512.js new file mode 100644 index 0000000..95e64cb --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/sha512.js @@ -0,0 +1,3 @@ +import { sha512 as _sha512 } from "@noble/hashes/sha512"; +import { wrapHash } from "./utils.js"; +export const sha512 = wrapHash(_sha512); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/esm/utils.js b/test/merkletreejs/node_modules/ethereum-cryptography/esm/utils.js new file mode 100644 index 0000000..8e771ea --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/esm/utils.js @@ -0,0 +1,47 @@ +import assert from "@noble/hashes/_assert"; +import { hexToBytes as _hexToBytes } from "@noble/hashes/utils"; +const assertBool = assert.bool; +const assertBytes = assert.bytes; +export { assertBool, assertBytes }; +export { bytesToHex, bytesToHex as toHex, concatBytes, createView, utf8ToBytes } from "@noble/hashes/utils"; +// buf.toString('utf8') -> bytesToUtf8(buf) +export function bytesToUtf8(data) { + if (!(data instanceof Uint8Array)) { + throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`); + } + return new TextDecoder().decode(data); +} +export function hexToBytes(data) { + const sliced = data.startsWith("0x") ? data.substring(2) : data; + return _hexToBytes(sliced); +} +// buf.equals(buf2) -> equalsBytes(buf, buf2) +export function equalsBytes(a, b) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} +// Internal utils +export function wrapHash(hash) { + return (msg) => { + assert.bytes(msg); + return hash(msg); + }; +} +// TODO(v3): switch away from node crypto, remove this unnecessary variable. +export const crypto = (() => { + const webCrypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined; + const nodeRequire = typeof module !== "undefined" && + typeof module.require === "function" && + module.require.bind(module); + return { + node: nodeRequire && !webCrypto ? nodeRequire("crypto") : undefined, + web: webCrypto + }; +})(); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/hdkey.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/hdkey.d.ts new file mode 100644 index 0000000..79eab99 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/hdkey.d.ts @@ -0,0 +1 @@ +export { HARDENED_OFFSET, HDKey } from "@scure/bip32"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/hdkey.js b/test/merkletreejs/node_modules/ethereum-cryptography/hdkey.js new file mode 100644 index 0000000..d7163ba --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/hdkey.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HDKey = exports.HARDENED_OFFSET = void 0; +var bip32_1 = require("@scure/bip32"); +Object.defineProperty(exports, "HARDENED_OFFSET", { enumerable: true, get: function () { return bip32_1.HARDENED_OFFSET; } }); +Object.defineProperty(exports, "HDKey", { enumerable: true, get: function () { return bip32_1.HDKey; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/index.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/index.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/index.js b/test/merkletreejs/node_modules/ethereum-cryptography/index.js new file mode 100644 index 0000000..6ac7bb3 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/index.js @@ -0,0 +1,2 @@ +"use strict"; +throw new Error("This package has no entry-point. Please consult the README.md to learn how to use it."); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/keccak.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/keccak.d.ts new file mode 100644 index 0000000..e16b1c4 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/keccak.d.ts @@ -0,0 +1,11 @@ +import { Keccak } from "@noble/hashes/sha3"; +import { Hash } from "@noble/hashes/utils"; +interface K256 { + (data: Uint8Array): Uint8Array; + create(): Hash; +} +export declare const keccak224: (msg: Uint8Array) => Uint8Array; +export declare const keccak256: K256; +export declare const keccak384: (msg: Uint8Array) => Uint8Array; +export declare const keccak512: (msg: Uint8Array) => Uint8Array; +export {}; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/keccak.js b/test/merkletreejs/node_modules/ethereum-cryptography/keccak.js new file mode 100644 index 0000000..a8c410e --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/keccak.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccak512 = exports.keccak384 = exports.keccak256 = exports.keccak224 = void 0; +const sha3_1 = require("@noble/hashes/sha3"); +const utils_js_1 = require("./utils.js"); +exports.keccak224 = (0, utils_js_1.wrapHash)(sha3_1.keccak_224); +exports.keccak256 = (() => { + const k = (0, utils_js_1.wrapHash)(sha3_1.keccak_256); + k.create = sha3_1.keccak_256.create; + return k; +})(); +exports.keccak384 = (0, utils_js_1.wrapHash)(sha3_1.keccak_384); +exports.keccak512 = (0, utils_js_1.wrapHash)(sha3_1.keccak_512); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/package.json b/test/merkletreejs/node_modules/ethereum-cryptography/package.json new file mode 100644 index 0000000..ad88cdc --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/package.json @@ -0,0 +1,364 @@ +{ + "name": "ethereum-cryptography", + "version": "2.1.2", + "description": "All the cryptographic primitives used in Ethereum", + "contributors": [ + { + "name": "Patricio Palladino", + "email": "patricio@nomiclabs.io" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "repository": "https://github.com/ethereum/js-ethereum-cryptography", + "license": "MIT", + "main": "./index.js", + "files": [ + "bip39/*.js", + "bip39/*.d.ts", + "bip39/wordlists/*.js", + "bip39/wordlists/*.d.ts", + "*.js", + "*.d.ts", + "esm" + ], + "dependencies": { + "@noble/curves": "1.1.0", + "@noble/hashes": "1.3.1", + "@scure/bip32": "1.3.1", + "@scure/bip39": "1.2.1" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./aes": { + "types": "./aes.d.ts", + "import": "./esm/aes.js", + "default": "./aes.js" + }, + "./bip39": { + "types": "./bip39/index.d.ts", + "import": "./esm/bip39/index.js", + "default": "./bip39/index.js" + }, + "./blake2b": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./hdkey": { + "types": "./hdkey.d.ts", + "import": "./esm/hdkey.js", + "default": "./hdkey.js" + }, + "./index": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./keccak": { + "types": "./keccak.d.ts", + "import": "./esm/keccak.js", + "default": "./keccak.js" + }, + "./pbkdf2": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./random": { + "types": "./random.d.ts", + "import": "./esm/random.js", + "default": "./random.js" + }, + "./ripemd160": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./secp256k1-compat": { + "types": "./secp256k1-compat.d.ts", + "import": "./esm/secp256k1-compat.js", + "default": "./secp256k1-compat.js" + }, + "./secp256k1": { + "types": "./secp256k1.d.ts", + "import": "./esm/secp256k1.js", + "default": "./secp256k1.js" + }, + "./sha256": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + }, + "./bip39/index": { + "types": "./bip39/index.d.ts", + "import": "./esm/bip39/index.js", + "default": "./bip39/index.js" + }, + "./bip39/wordlists/czech": { + "types": "./bip39/wordlists/czech.d.ts", + "import": "./esm/bip39/wordlists/czech.js", + "default": "./bip39/wordlists/czech.js" + }, + "./bip39/wordlists/english": { + "types": "./bip39/wordlists/english.d.ts", + "import": "./esm/bip39/wordlists/english.js", + "default": "./bip39/wordlists/english.js" + }, + "./bip39/wordlists/french": { + "types": "./bip39/wordlists/french.d.ts", + "import": "./esm/bip39/wordlists/french.js", + "default": "./bip39/wordlists/french.js" + }, + "./bip39/wordlists/italian": { + "types": "./bip39/wordlists/italian.d.ts", + "import": "./esm/bip39/wordlists/italian.js", + "default": "./bip39/wordlists/italian.js" + }, + "./bip39/wordlists/japanese": { + "types": "./bip39/wordlists/japanese.d.ts", + "import": "./esm/bip39/wordlists/japanese.js", + "default": "./bip39/wordlists/japanese.js" + }, + "./bip39/wordlists/korean": { + "types": "./bip39/wordlists/korean.d.ts", + "import": "./esm/bip39/wordlists/korean.js", + "default": "./bip39/wordlists/korean.js" + }, + "./bip39/wordlists/simplified-chinese": { + "types": "./bip39/wordlists/simplified-chinese.d.ts", + "import": "./esm/bip39/wordlists/simplified-chinese.js", + "default": "./bip39/wordlists/simplified-chinese.js" + }, + "./bip39/wordlists/spanish": { + "types": "./bip39/wordlists/spanish.d.ts", + "import": "./esm/bip39/wordlists/spanish.js", + "default": "./bip39/wordlists/spanish.js" + }, + "./bip39/wordlists/traditional-chinese": { + "types": "./bip39/wordlists/traditional-chinese.d.ts", + "import": "./esm/bip39/wordlists/traditional-chinese.js", + "default": "./bip39/wordlists/traditional-chinese.js" + }, + "./aes.js": { + "types": "./aes.d.ts", + "import": "./esm/aes.js", + "default": "./aes.js" + }, + "./bip39.js": { + "types": "./bip39/index.d.ts", + "import": "./esm/bip39/index.js", + "default": "./bip39/index.js" + }, + "./blake2b.js": { + "types": "./blake2b.d.ts", + "import": "./esm/blake2b.js", + "default": "./blake2b.js" + }, + "./hdkey.js": { + "types": "./hdkey.d.ts", + "import": "./esm/hdkey.js", + "default": "./hdkey.js" + }, + "./index.js": { + "types": "./index.d.ts", + "import": "./esm/index.js", + "default": "./index.js" + }, + "./keccak.js": { + "types": "./keccak.d.ts", + "import": "./esm/keccak.js", + "default": "./keccak.js" + }, + "./pbkdf2.js": { + "types": "./pbkdf2.d.ts", + "import": "./esm/pbkdf2.js", + "default": "./pbkdf2.js" + }, + "./random.js": { + "types": "./random.d.ts", + "import": "./esm/random.js", + "default": "./random.js" + }, + "./ripemd160.js": { + "types": "./ripemd160.d.ts", + "import": "./esm/ripemd160.js", + "default": "./ripemd160.js" + }, + "./scrypt.js": { + "types": "./scrypt.d.ts", + "import": "./esm/scrypt.js", + "default": "./scrypt.js" + }, + "./secp256k1-compat.js": { + "types": "./secp256k1-compat.d.ts", + "import": "./esm/secp256k1-compat.js", + "default": "./secp256k1-compat.js" + }, + "./secp256k1.js": { + "types": "./secp256k1.d.ts", + "import": "./esm/secp256k1.js", + "default": "./secp256k1.js" + }, + "./sha256.js": { + "types": "./sha256.d.ts", + "import": "./esm/sha256.js", + "default": "./sha256.js" + }, + "./sha512.js": { + "types": "./sha512.d.ts", + "import": "./esm/sha512.js", + "default": "./sha512.js" + }, + "./utils.js": { + "types": "./utils.d.ts", + "import": "./esm/utils.js", + "default": "./utils.js" + }, + "./bip39/index.js": { + "types": "./bip39/index.d.ts", + "import": "./esm/bip39/index.js", + "default": "./bip39/index.js" + }, + "./bip39/wordlists/czech.js": { + "types": "./bip39/wordlists/czech.d.ts", + "import": "./esm/bip39/wordlists/czech.js", + "default": "./bip39/wordlists/czech.js" + }, + "./bip39/wordlists/english.js": { + "types": "./bip39/wordlists/english.d.ts", + "import": "./esm/bip39/wordlists/english.js", + "default": "./bip39/wordlists/english.js" + }, + "./bip39/wordlists/french.js": { + "types": "./bip39/wordlists/french.d.ts", + "import": "./esm/bip39/wordlists/french.js", + "default": "./bip39/wordlists/french.js" + }, + "./bip39/wordlists/italian.js": { + "types": "./bip39/wordlists/italian.d.ts", + "import": "./esm/bip39/wordlists/italian.js", + "default": "./bip39/wordlists/italian.js" + }, + "./bip39/wordlists/japanese.js": { + "types": "./bip39/wordlists/japanese.d.ts", + "import": "./esm/bip39/wordlists/japanese.js", + "default": "./bip39/wordlists/japanese.js" + }, + "./bip39/wordlists/korean.js": { + "types": "./bip39/wordlists/korean.d.ts", + "import": "./esm/bip39/wordlists/korean.js", + "default": "./bip39/wordlists/korean.js" + }, + "./bip39/wordlists/simplified-chinese.js": { + "types": "./bip39/wordlists/simplified-chinese.d.ts", + "import": "./esm/bip39/wordlists/simplified-chinese.js", + "default": "./bip39/wordlists/simplified-chinese.js" + }, + "./bip39/wordlists/spanish.js": { + "types": "./bip39/wordlists/spanish.d.ts", + "import": "./esm/bip39/wordlists/spanish.js", + "default": "./bip39/wordlists/spanish.js" + }, + "./bip39/wordlists/traditional-chinese.js": { + "types": "./bip39/wordlists/traditional-chinese.d.ts", + "import": "./esm/bip39/wordlists/traditional-chinese.js", + "default": "./bip39/wordlists/traditional-chinese.js" + } + }, + "browser": { + "crypto": false + }, + "sideEffects": false, + "scripts": { + "prepare": "npm run build", + "build": "npm-run-all build:tsc", + "build:tsc": "tsc --project tsconfig.prod.json && tsc --project tsconfig.prod.esm.json", + "test": "npm-run-all test:node", + "test:node": "cd test && npm install && cd .. && mocha", + "clean": "rimraf test/test-builds bip39 '*.js' '*.js.map' '*.d.ts' '*.d.ts.map' 'src/**/*.js'", + "lint": "eslint", + "lint:fix": "eslint --fix", + "browser-tests": "npm-run-all browser-tests:build browser-tests:test", + "browser-tests:build": "bash -x ./scripts/build-browser-tests.sh", + "browser-tests:test": "npm-run-all browser-tests:test-parcel browser-tests:test-browserify browser-tests:test-webpack browser-tests:test-rollup", + "browser-tests:test-parcel": "karma start --single-run --browsers ChromeHeadless test/karma.parcel.conf.js", + "browser-tests:test-browserify": "karma start --single-run --browsers ChromeHeadless test/karma.browserify.conf.js", + "browser-tests:test-webpack": "karma start --single-run --browsers ChromeHeadless test/karma.webpack.conf.js", + "browser-tests:test-rollup": "karma start --single-run --browsers ChromeHeadless test/karma.rollup.conf.js" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "22.0.1", + "@rollup/plugin-node-resolve": "13.3.0", + "@types/estree": "1.0.0", + "@types/mocha": "9.1.1", + "@types/node": "18.15.11", + "@typescript-eslint/eslint-plugin": "5.30.6", + "@typescript-eslint/parser": "5.30.6", + "browserify": "17.0.0", + "eslint": "8.38.0", + "eslint-plugin-prettier": "4.2.1", + "karma": "6.4.0", + "karma-chrome-launcher": "3.1.1", + "karma-mocha": "2.0.1", + "karma-mocha-reporter": "2.2.5", + "mocha": "10.0.0", + "npm-run-all": "4.1.5", + "parcel": "2.6.2", + "prettier": "2.7.1", + "rimraf": "~3.0.2", + "rollup": "2.76.0", + "ts-node": "10.9.1", + "typescript": "5.0.2", + "webpack": "5.76.0", + "webpack-cli": "4.10.0" + }, + "keywords": [ + "ethereum", + "cryptography", + "digital signature", + "hash", + "encryption", + "prng", + "keccak", + "scrypt", + "pbkdf2", + "sha-256", + "ripemd-160", + "blake2b", + "aes", + "advanced encryption standard", + "secp256k1", + "ecdsa", + "bip32", + "hierarchical deterministic keys", + "hdwallet", + "hdkeys" + ], + "targets": { + "parcel_tests": { + "context": "browser" + } + } +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/pbkdf2.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/pbkdf2.d.ts new file mode 100644 index 0000000..28b2517 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/pbkdf2.d.ts @@ -0,0 +1,2 @@ +export declare function pbkdf2(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Promise; +export declare function pbkdf2Sync(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Uint8Array; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/pbkdf2.js b/test/merkletreejs/node_modules/ethereum-cryptography/pbkdf2.js new file mode 100644 index 0000000..7dbe02a --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/pbkdf2.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2Sync = exports.pbkdf2 = void 0; +const pbkdf2_1 = require("@noble/hashes/pbkdf2"); +const sha256_1 = require("@noble/hashes/sha256"); +const sha512_1 = require("@noble/hashes/sha512"); +const utils_js_1 = require("./utils.js"); +async function pbkdf2(password, salt, iterations, keylen, digest) { + if (!["sha256", "sha512"].includes(digest)) { + throw new Error("Only sha256 and sha512 are supported"); + } + (0, utils_js_1.assertBytes)(password); + (0, utils_js_1.assertBytes)(salt); + return (0, pbkdf2_1.pbkdf2Async)(digest === "sha256" ? sha256_1.sha256 : sha512_1.sha512, password, salt, { + c: iterations, + dkLen: keylen + }); +} +exports.pbkdf2 = pbkdf2; +function pbkdf2Sync(password, salt, iterations, keylen, digest) { + if (!["sha256", "sha512"].includes(digest)) { + throw new Error("Only sha256 and sha512 are supported"); + } + (0, utils_js_1.assertBytes)(password); + (0, utils_js_1.assertBytes)(salt); + return (0, pbkdf2_1.pbkdf2)(digest === "sha256" ? sha256_1.sha256 : sha512_1.sha512, password, salt, { + c: iterations, + dkLen: keylen + }); +} +exports.pbkdf2Sync = pbkdf2Sync; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/random.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/random.d.ts new file mode 100644 index 0000000..846ed97 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/random.d.ts @@ -0,0 +1,2 @@ +export declare function getRandomBytesSync(bytes: number): Uint8Array; +export declare function getRandomBytes(bytes: number): Promise; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/random.js b/test/merkletreejs/node_modules/ethereum-cryptography/random.js new file mode 100644 index 0000000..2edbb44 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/random.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRandomBytes = exports.getRandomBytesSync = void 0; +const utils_1 = require("@noble/hashes/utils"); +function getRandomBytesSync(bytes) { + return (0, utils_1.randomBytes)(bytes); +} +exports.getRandomBytesSync = getRandomBytesSync; +async function getRandomBytes(bytes) { + return (0, utils_1.randomBytes)(bytes); +} +exports.getRandomBytes = getRandomBytes; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/ripemd160.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/ripemd160.d.ts new file mode 100644 index 0000000..b71198e --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/ripemd160.d.ts @@ -0,0 +1 @@ +export declare const ripemd160: (msg: Uint8Array) => Uint8Array; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/ripemd160.js b/test/merkletreejs/node_modules/ethereum-cryptography/ripemd160.js new file mode 100644 index 0000000..44c19c7 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/ripemd160.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = void 0; +const ripemd160_1 = require("@noble/hashes/ripemd160"); +const utils_js_1 = require("./utils.js"); +exports.ripemd160 = (0, utils_js_1.wrapHash)(ripemd160_1.ripemd160); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/scrypt.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/scrypt.d.ts new file mode 100644 index 0000000..567e885 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/scrypt.d.ts @@ -0,0 +1,4 @@ +type OnProgressCallback = (progress: number) => void; +export declare function scrypt(password: Uint8Array, salt: Uint8Array, n: number, p: number, r: number, dkLen: number, onProgress?: OnProgressCallback): Promise; +export declare function scryptSync(password: Uint8Array, salt: Uint8Array, n: number, p: number, r: number, dkLen: number, onProgress?: OnProgressCallback): Uint8Array; +export {}; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/scrypt.js b/test/merkletreejs/node_modules/ethereum-cryptography/scrypt.js new file mode 100644 index 0000000..932646b --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/scrypt.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptSync = exports.scrypt = void 0; +const scrypt_1 = require("@noble/hashes/scrypt"); +const utils_js_1 = require("./utils.js"); +async function scrypt(password, salt, n, p, r, dkLen, onProgress) { + (0, utils_js_1.assertBytes)(password); + (0, utils_js_1.assertBytes)(salt); + return (0, scrypt_1.scryptAsync)(password, salt, { N: n, r, p, dkLen, onProgress }); +} +exports.scrypt = scrypt; +function scryptSync(password, salt, n, p, r, dkLen, onProgress) { + (0, utils_js_1.assertBytes)(password); + (0, utils_js_1.assertBytes)(salt); + return (0, scrypt_1.scrypt)(password, salt, { N: n, r, p, dkLen, onProgress }); +} +exports.scryptSync = scryptSync; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1-compat.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1-compat.d.ts new file mode 100644 index 0000000..9d22d9c --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1-compat.d.ts @@ -0,0 +1,35 @@ +type Output = Uint8Array | ((len: number) => Uint8Array); +interface Signature { + signature: Uint8Array; + recid: number; +} +export declare function createPrivateKeySync(): Uint8Array; +export declare function createPrivateKey(): Promise; +export declare function privateKeyVerify(privateKey: Uint8Array): boolean; +export declare function publicKeyCreate(privateKey: Uint8Array, compressed?: boolean, out?: Output): Uint8Array; +export declare function publicKeyVerify(publicKey: Uint8Array): boolean; +export declare function publicKeyConvert(publicKey: Uint8Array, compressed?: boolean, out?: Output): Uint8Array; +export declare function ecdsaSign(msgHash: Uint8Array, privateKey: Uint8Array, options?: { + noncefn: undefined; + data: undefined; +}, out?: Output): Signature; +export declare function ecdsaRecover(signature: Uint8Array, recid: number, msgHash: Uint8Array, compressed?: boolean, out?: Output): Uint8Array; +export declare function ecdsaVerify(signature: Uint8Array, msgHash: Uint8Array, publicKey: Uint8Array): boolean; +export declare function privateKeyTweakAdd(privateKey: Uint8Array, tweak: Uint8Array): Uint8Array; +export declare function privateKeyNegate(privateKey: Uint8Array): Uint8Array; +export declare function publicKeyNegate(publicKey: Uint8Array, compressed?: boolean, out?: Output): Uint8Array; +export declare function publicKeyCombine(publicKeys: Uint8Array[], compressed?: boolean, out?: Output): Uint8Array; +export declare function publicKeyTweakAdd(publicKey: Uint8Array, tweak: Uint8Array, compressed?: boolean, out?: Output): Uint8Array; +export declare function publicKeyTweakMul(publicKey: Uint8Array, tweak: Uint8Array, compressed?: boolean, out?: Output): Uint8Array; +export declare function privateKeyTweakMul(privateKey: Uint8Array, tweak: Uint8Array): Uint8Array; +export declare function signatureExport(signature: Uint8Array, out?: Output): Uint8Array; +export declare function signatureImport(signature: Uint8Array, out?: Output): Uint8Array; +export declare function signatureNormalize(signature: Uint8Array): Uint8Array; +export declare function ecdh(publicKey: Uint8Array, privateKey: Uint8Array, options?: { + xbuf?: Uint8Array; + ybuf?: Uint8Array; + data?: Uint8Array; + hashfn?: (x: Uint8Array, y: Uint8Array, data: Uint8Array) => Uint8Array; +}, out?: Output): Uint8Array; +export declare function contextRandomize(seed: Uint8Array): void; +export {}; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1-compat.js b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1-compat.js new file mode 100644 index 0000000..4075fd9 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1-compat.js @@ -0,0 +1,278 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.contextRandomize = exports.ecdh = exports.signatureNormalize = exports.signatureImport = exports.signatureExport = exports.privateKeyTweakMul = exports.publicKeyTweakMul = exports.publicKeyTweakAdd = exports.publicKeyCombine = exports.publicKeyNegate = exports.privateKeyNegate = exports.privateKeyTweakAdd = exports.ecdsaVerify = exports.ecdsaRecover = exports.ecdsaSign = exports.publicKeyConvert = exports.publicKeyVerify = exports.publicKeyCreate = exports.privateKeyVerify = exports.createPrivateKey = exports.createPrivateKeySync = void 0; +const sha256_1 = require("@noble/hashes/sha256"); +const modular_1 = require("@noble/curves/abstract/modular"); +const secp256k1_js_1 = require("./secp256k1.js"); +const utils_js_1 = require("./utils.js"); +// Use `secp256k1` module directly. +// This is a legacy compatibility layer for the npm package `secp256k1` via noble-secp256k1 +const Point = secp256k1_js_1.secp256k1.ProjectivePoint; +function hexToNumber(hex) { + if (typeof hex !== "string") { + throw new TypeError("hexToNumber: expected string, got " + typeof hex); + } + return BigInt(`0x${hex}`); +} +// Copy-paste from secp256k1, maybe export it? +const bytesToNumber = (bytes) => hexToNumber((0, utils_js_1.toHex)(bytes)); +const numberToHex = (num) => num.toString(16).padStart(64, "0"); +const numberToBytes = (num) => (0, utils_js_1.hexToBytes)(numberToHex(num)); +const ORDER = secp256k1_js_1.secp256k1.CURVE.n; +function output(out = (len) => new Uint8Array(len), length, value) { + if (typeof out === "function") { + out = out(length); + } + (0, utils_js_1.assertBytes)(out, length); + if (value) { + out.set(value); + } + return out; +} +function getSignature(signature) { + (0, utils_js_1.assertBytes)(signature, 64); + return secp256k1_js_1.secp256k1.Signature.fromCompact(signature); +} +function createPrivateKeySync() { + return secp256k1_js_1.secp256k1.utils.randomPrivateKey(); +} +exports.createPrivateKeySync = createPrivateKeySync; +async function createPrivateKey() { + return createPrivateKeySync(); +} +exports.createPrivateKey = createPrivateKey; +function privateKeyVerify(privateKey) { + (0, utils_js_1.assertBytes)(privateKey, 32); + return secp256k1_js_1.secp256k1.utils.isValidPrivateKey(privateKey); +} +exports.privateKeyVerify = privateKeyVerify; +function publicKeyCreate(privateKey, compressed = true, out) { + (0, utils_js_1.assertBytes)(privateKey, 32); + (0, utils_js_1.assertBool)(compressed); + const res = secp256k1_js_1.secp256k1.getPublicKey(privateKey, compressed); + return output(out, compressed ? 33 : 65, res); +} +exports.publicKeyCreate = publicKeyCreate; +function publicKeyVerify(publicKey) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + try { + Point.fromHex(publicKey); + return true; + } + catch (e) { + return false; + } +} +exports.publicKeyVerify = publicKeyVerify; +function publicKeyConvert(publicKey, compressed = true, out) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + (0, utils_js_1.assertBool)(compressed); + const res = Point.fromHex(publicKey).toRawBytes(compressed); + return output(out, compressed ? 33 : 65, res); +} +exports.publicKeyConvert = publicKeyConvert; +function ecdsaSign(msgHash, privateKey, options = { noncefn: undefined, data: undefined }, out) { + (0, utils_js_1.assertBytes)(msgHash, 32); + (0, utils_js_1.assertBytes)(privateKey, 32); + if (typeof options !== "object" || options === null) { + throw new TypeError("secp256k1.ecdsaSign: options should be object"); + } + // noble-secp256k1 uses hmac instead of hmac-drbg here + if (options && + (options.noncefn !== undefined || options.data !== undefined)) { + throw new Error("Secp256k1: noncefn && data is unsupported"); + } + const sig = secp256k1_js_1.secp256k1.sign(msgHash, privateKey); + const recid = sig.recovery; + return { signature: output(out, 64, sig.toCompactRawBytes()), recid }; +} +exports.ecdsaSign = ecdsaSign; +function ecdsaRecover(signature, recid, msgHash, compressed = true, out) { + (0, utils_js_1.assertBytes)(msgHash, 32); + (0, utils_js_1.assertBool)(compressed); + const sign = getSignature(signature); + const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash); + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +exports.ecdsaRecover = ecdsaRecover; +function ecdsaVerify(signature, msgHash, publicKey) { + (0, utils_js_1.assertBytes)(signature, 64); + (0, utils_js_1.assertBytes)(msgHash, 32); + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + (0, utils_js_1.assertBytes)(signature, 64); + const r = bytesToNumber(signature.slice(0, 32)); + const s = bytesToNumber(signature.slice(32, 64)); + if (r >= ORDER || s >= ORDER) { + throw new Error("Cannot parse signature"); + } + const pub = Point.fromHex(publicKey); // can throw error + pub; // typescript + let sig; + try { + sig = getSignature(signature); + } + catch (error) { + return false; + } + return secp256k1_js_1.secp256k1.verify(sig, msgHash, publicKey); +} +exports.ecdsaVerify = ecdsaVerify; +function privateKeyTweakAdd(privateKey, tweak) { + (0, utils_js_1.assertBytes)(privateKey, 32); + (0, utils_js_1.assertBytes)(tweak, 32); + let t = bytesToNumber(tweak); + if (t === 0n) { + throw new Error("Tweak must not be zero"); + } + if (t >= ORDER) { + throw new Error("Tweak bigger than curve order"); + } + t += bytesToNumber(privateKey); + if (t >= ORDER) { + t -= ORDER; + } + if (t === 0n) { + throw new Error("The tweak was out of range or the resulted private key is invalid"); + } + privateKey.set((0, utils_js_1.hexToBytes)(numberToHex(t))); + return privateKey; +} +exports.privateKeyTweakAdd = privateKeyTweakAdd; +function privateKeyNegate(privateKey) { + (0, utils_js_1.assertBytes)(privateKey, 32); + const bn = (0, modular_1.mod)(-bytesToNumber(privateKey), ORDER); + privateKey.set((0, utils_js_1.hexToBytes)(numberToHex(bn))); + return privateKey; +} +exports.privateKeyNegate = privateKeyNegate; +function publicKeyNegate(publicKey, compressed = true, out) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + (0, utils_js_1.assertBool)(compressed); + const point = Point.fromHex(publicKey).negate(); + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +exports.publicKeyNegate = publicKeyNegate; +function publicKeyCombine(publicKeys, compressed = true, out) { + if (!Array.isArray(publicKeys) || !publicKeys.length) { + throw new TypeError(`Expected array with one or more items, not ${publicKeys}`); + } + for (const publicKey of publicKeys) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + } + (0, utils_js_1.assertBool)(compressed); + const combined = publicKeys + .map((pub) => Point.fromHex(pub)) + .reduce((res, curr) => res.add(curr), Point.ZERO); + // Prohibit returning ZERO point + if (combined.equals(Point.ZERO)) { + throw new Error("Combined result must not be zero"); + } + return output(out, compressed ? 33 : 65, combined.toRawBytes(compressed)); +} +exports.publicKeyCombine = publicKeyCombine; +function publicKeyTweakAdd(publicKey, tweak, compressed = true, out) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + (0, utils_js_1.assertBytes)(tweak, 32); + (0, utils_js_1.assertBool)(compressed); + const p1 = Point.fromHex(publicKey); + const p2 = Point.fromPrivateKey(tweak); + const point = p1.add(p2); + if (p2.equals(Point.ZERO) || point.equals(Point.ZERO)) { + throw new Error("Tweak must not be zero"); + } + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +exports.publicKeyTweakAdd = publicKeyTweakAdd; +function publicKeyTweakMul(publicKey, tweak, compressed = true, out) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + (0, utils_js_1.assertBytes)(tweak, 32); + (0, utils_js_1.assertBool)(compressed); + const bn = bytesToNumber(tweak); + if (bn === 0n) { + throw new Error("Tweak must not be zero"); + } + if (bn <= 1 || bn >= ORDER) { + throw new Error("Tweak is zero or bigger than curve order"); + } + const point = Point.fromHex(publicKey).multiply(bn); + return output(out, compressed ? 33 : 65, point.toRawBytes(compressed)); +} +exports.publicKeyTweakMul = publicKeyTweakMul; +function privateKeyTweakMul(privateKey, tweak) { + (0, utils_js_1.assertBytes)(privateKey, 32); + (0, utils_js_1.assertBytes)(tweak, 32); + const bn = bytesToNumber(tweak); + if (bn <= 1 || bn >= ORDER) { + throw new Error("Tweak is zero or bigger than curve order"); + } + const res = (0, modular_1.mod)(bn * bytesToNumber(privateKey), ORDER); + if (res === 0n) { + throw new Error("The tweak was out of range or the resulted private key is invalid"); + } + privateKey.set((0, utils_js_1.hexToBytes)(numberToHex(res))); + return privateKey; +} +exports.privateKeyTweakMul = privateKeyTweakMul; +// internal -> DER +function signatureExport(signature, out) { + const res = getSignature(signature).toDERRawBytes(); + return output(out, 72, res.slice()).slice(0, res.length); +} +exports.signatureExport = signatureExport; +// DER -> internal +function signatureImport(signature, out) { + (0, utils_js_1.assertBytes)(signature); + const sig = secp256k1_js_1.secp256k1.Signature.fromDER(signature); + return output(out, 64, (0, utils_js_1.hexToBytes)(sig.toCompactHex())); +} +exports.signatureImport = signatureImport; +function signatureNormalize(signature) { + const res = getSignature(signature); + if (res.s > ORDER / 2n) { + signature.set(numberToBytes(ORDER - res.s), 32); + } + return signature; +} +exports.signatureNormalize = signatureNormalize; +function ecdh(publicKey, privateKey, options = {}, out) { + (0, utils_js_1.assertBytes)(publicKey, 33, 65); + (0, utils_js_1.assertBytes)(privateKey, 32); + if (typeof options !== "object" || options === null) { + throw new TypeError("secp256k1.ecdh: options should be object"); + } + if (options.data !== undefined) { + (0, utils_js_1.assertBytes)(options.data); + } + const point = Point.fromHex(secp256k1_js_1.secp256k1.getSharedSecret(privateKey, publicKey)); + if (options.hashfn === undefined) { + return output(out, 32, (0, sha256_1.sha256)(point.toRawBytes(true))); + } + if (typeof options.hashfn !== "function") { + throw new TypeError("secp256k1.ecdh: options.hashfn should be function"); + } + if (options.xbuf !== undefined) { + (0, utils_js_1.assertBytes)(options.xbuf, 32); + } + if (options.ybuf !== undefined) { + (0, utils_js_1.assertBytes)(options.ybuf, 32); + } + (0, utils_js_1.assertBytes)(out, 32); + const { x, y } = point.toAffine(); + const xbuf = options.xbuf || new Uint8Array(32); + xbuf.set(numberToBytes(x)); + const ybuf = options.ybuf || new Uint8Array(32); + ybuf.set(numberToBytes(y)); + const hash = options.hashfn(xbuf, ybuf, options.data); + if (!(hash instanceof Uint8Array) || hash.length !== 32) { + throw new Error("secp256k1.ecdh: invalid options.hashfn output"); + } + return output(out, 32, hash); +} +exports.ecdh = ecdh; +function contextRandomize(seed) { + if (seed !== null) { + (0, utils_js_1.assertBytes)(seed, 32); + } + // There is no context to randomize +} +exports.contextRandomize = contextRandomize; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1.d.ts new file mode 100644 index 0000000..28f4d1f --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1.d.ts @@ -0,0 +1 @@ +export { secp256k1 } from "@noble/curves/secp256k1"; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1.js b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1.js new file mode 100644 index 0000000..b8f0a26 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/secp256k1.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.secp256k1 = void 0; +var secp256k1_1 = require("@noble/curves/secp256k1"); +Object.defineProperty(exports, "secp256k1", { enumerable: true, get: function () { return secp256k1_1.secp256k1; } }); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/sha256.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/sha256.d.ts new file mode 100644 index 0000000..25124b8 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/sha256.d.ts @@ -0,0 +1 @@ +export declare const sha256: (msg: Uint8Array) => Uint8Array; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/sha256.js b/test/merkletreejs/node_modules/ethereum-cryptography/sha256.js new file mode 100644 index 0000000..6b6a885 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/sha256.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha256 = void 0; +const sha256_1 = require("@noble/hashes/sha256"); +const utils_js_1 = require("./utils.js"); +exports.sha256 = (0, utils_js_1.wrapHash)(sha256_1.sha256); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/sha512.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/sha512.d.ts new file mode 100644 index 0000000..a3545f2 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/sha512.d.ts @@ -0,0 +1 @@ +export declare const sha512: (msg: Uint8Array) => Uint8Array; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/sha512.js b/test/merkletreejs/node_modules/ethereum-cryptography/sha512.js new file mode 100644 index 0000000..83e0180 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/sha512.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha512 = void 0; +const sha512_1 = require("@noble/hashes/sha512"); +const utils_js_1 = require("./utils.js"); +exports.sha512 = (0, utils_js_1.wrapHash)(sha512_1.sha512); diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/utils.d.ts b/test/merkletreejs/node_modules/ethereum-cryptography/utils.d.ts new file mode 100644 index 0000000..18890a9 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/utils.d.ts @@ -0,0 +1,12 @@ +declare const assertBool: typeof import("@noble/hashes/_assert").bool; +declare const assertBytes: typeof import("@noble/hashes/_assert").bytes; +export { assertBool, assertBytes }; +export { bytesToHex, bytesToHex as toHex, concatBytes, createView, utf8ToBytes } from "@noble/hashes/utils"; +export declare function bytesToUtf8(data: Uint8Array): string; +export declare function hexToBytes(data: string): Uint8Array; +export declare function equalsBytes(a: Uint8Array, b: Uint8Array): boolean; +export declare function wrapHash(hash: (msg: Uint8Array) => Uint8Array): (msg: Uint8Array) => Uint8Array; +export declare const crypto: { + node?: any; + web?: any; +}; diff --git a/test/merkletreejs/node_modules/ethereum-cryptography/utils.js b/test/merkletreejs/node_modules/ethereum-cryptography/utils.js new file mode 100644 index 0000000..83d7e88 --- /dev/null +++ b/test/merkletreejs/node_modules/ethereum-cryptography/utils.js @@ -0,0 +1,63 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = exports.wrapHash = exports.equalsBytes = exports.hexToBytes = exports.bytesToUtf8 = exports.utf8ToBytes = exports.createView = exports.concatBytes = exports.toHex = exports.bytesToHex = exports.assertBytes = exports.assertBool = void 0; +const _assert_1 = __importDefault(require("@noble/hashes/_assert")); +const utils_1 = require("@noble/hashes/utils"); +const assertBool = _assert_1.default.bool; +exports.assertBool = assertBool; +const assertBytes = _assert_1.default.bytes; +exports.assertBytes = assertBytes; +var utils_2 = require("@noble/hashes/utils"); +Object.defineProperty(exports, "bytesToHex", { enumerable: true, get: function () { return utils_2.bytesToHex; } }); +Object.defineProperty(exports, "toHex", { enumerable: true, get: function () { return utils_2.bytesToHex; } }); +Object.defineProperty(exports, "concatBytes", { enumerable: true, get: function () { return utils_2.concatBytes; } }); +Object.defineProperty(exports, "createView", { enumerable: true, get: function () { return utils_2.createView; } }); +Object.defineProperty(exports, "utf8ToBytes", { enumerable: true, get: function () { return utils_2.utf8ToBytes; } }); +// buf.toString('utf8') -> bytesToUtf8(buf) +function bytesToUtf8(data) { + if (!(data instanceof Uint8Array)) { + throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`); + } + return new TextDecoder().decode(data); +} +exports.bytesToUtf8 = bytesToUtf8; +function hexToBytes(data) { + const sliced = data.startsWith("0x") ? data.substring(2) : data; + return (0, utils_1.hexToBytes)(sliced); +} +exports.hexToBytes = hexToBytes; +// buf.equals(buf2) -> equalsBytes(buf, buf2) +function equalsBytes(a, b) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} +exports.equalsBytes = equalsBytes; +// Internal utils +function wrapHash(hash) { + return (msg) => { + _assert_1.default.bytes(msg); + return hash(msg); + }; +} +exports.wrapHash = wrapHash; +// TODO(v3): switch away from node crypto, remove this unnecessary variable. +exports.crypto = (() => { + const webCrypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined; + const nodeRequire = typeof module !== "undefined" && + typeof module.require === "function" && + module.require.bind(module); + return { + node: nodeRequire && !webCrypto ? nodeRequire("crypto") : undefined, + web: webCrypto + }; +})(); diff --git a/test/merkletreejs/node_modules/ethjs-unit/CHANGELOG.md b/test/merkletreejs/node_modules/ethjs-unit/CHANGELOG.md new file mode 100644 index 0000000..2fd9e31 --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/CHANGELOG.md @@ -0,0 +1,28 @@ +# 0.1.5 -- update bn formatting + +1. Update bn formatting + +# 0.1.3 -- config fixes + +1. webpack config updates +2. build config updates + +# 0.1.2 -- removed BigNumber's, replaced with all BN.js + +1. new approach with BN.js and absolute precision +2. more coverage +3. more docs + +# 0.0.2 -- ethjs-unit + +1. More test coverage +2. Config +3. More docs + +# 0.0.1 -- ethjs-unit + +1. Basic testing +2. Basic docs +3. License +4. Linting +5. Basic exports diff --git a/test/merkletreejs/node_modules/ethjs-unit/LICENSE b/test/merkletreejs/node_modules/ethjs-unit/LICENSE new file mode 100644 index 0000000..37b6d29 --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nick Dodson + +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. diff --git a/test/merkletreejs/node_modules/ethjs-unit/README.md b/test/merkletreejs/node_modules/ethjs-unit/README.md new file mode 100644 index 0000000..5ad4b7e --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/README.md @@ -0,0 +1,181 @@ +## ethjs-unit + +
+ + + Dependency Status + + + + + devDependency Status + + + + + Build Status + + + + + NPM version + + + + + Test Coverage + + + + + js-airbnb-style + +
+ +
+ +A simple module for handling Ethereum unit convertion. + +## Install + +``` +npm install --save ethjs-unit +``` + +## Usage + +```js +const unit = require('ethjs-unit'); + +var val1 = unit.toWei(249824778, 'ether'); + +// result 249824778000000000000000000 + +var val2 = unit.fromWei('249824778000000000000000000', 'ether'); + +// result '249824778' +``` + +## About + +A port from the `web3.js` library, that just handles the unit convertion between the various types of Ethereum currency units. + +Note, the `toWei` returns a BN instance while `fromWei` always returns a string number. + +## Amorphic Data Formatting + +`ethjs-unit` uses the [number-to-bn](http://github.com/silentcicero/number-to-bn) module to format all number values (hex or otherwise) into digestable BN.js number instances. + +## Methods Available & Objects + +``` +unitMap { unitName: singleUnitWeiValue, ... } +getValueOfUnit +toWei +fromWei +``` + +## Supported Units + +``` +'wei': '1', +'kwei': '1000', +'Kwei': '1000', +'babbage': '1000', +'femtoether': '1000', +'mwei': '1000000', +'Mwei': '1000000', +'lovelace': '1000000', +'picoether': '1000000', +'gwei': '1000000000', +'Gwei': '1000000000', +'shannon': '1000000000', +'nanoether': '1000000000', +'nano': '1000000000', +'szabo': '1000000000000', +'microether': '1000000000000', +'micro': '1000000000000', +'finney': '1000000000000000', +'milliether': '1000000000000000', +'milli': '1000000000000000', +'ether': '1000000000000000000', +'kether': '1000000000000000000000', +'grand': '1000000000000000000000', +'mether': '1000000000000000000000000', +'gether': '1000000000000000000000000000', +'tether': '1000000000000000000000000000000' +``` + +## Why BN.js? + +`ethjs` has made a policy of using `BN.js` accross all of our modules. Here are some reasons why: + + 1. Lighter than alternatives (BigNumber.js) + 2. Faster than most alternatives, see [benchmarks](https://github.com/indutny/bn.js/issues/89) + 3. Used by the Ethereum foundation across all [`ethereumjs`](https://github.com/ethereumjs) repositories + 4. Is already used by a critical JS dependency of many ethereum packages, see package [`elliptic`](https://github.com/indutny/elliptic) + 5. Does not support decimals or floats (for greater precision), remember, the Ethereum blockchain cannot and will not support float values or decimal numbers + +## Contributing + +Please help better the ecosystem by submitting issues and pull requests to default. We need all the help we can get to build the absolute best linting standards and utilities. We follow the AirBNB linting standard and the unix philosophy. + +## Guides + +You'll find more detailed information on using `ethjs-unit` and tailoring it to your needs in our guides: + +- [User guide](docs/user-guide.md) - Usage, configuration, FAQ and complementary tools. +- [Developer guide](docs/developer-guide.md) - Contributing to `ethjs-unit`, writing coverage and updates. + +## Help out + +There is always a lot of work to do, and will have many rules to maintain. So please help out in any way that you can: + +- Create, enhance, and debug ethjs rules (see our guide to ["Working on rules"](./github/CONTRIBUTING.md)). +- Improve documentation. +- Chime in on any open issue or pull request. +- Open new issues about your ideas for making `ethjs-unit` better, and pull requests to show us how your idea works. +- Add new tests to *absolutely anything*. +- Create or contribute to ecosystem tools, like modules for encoding or contracts. +- Spread the word. + +Please consult our [Code of Conduct](CODE_OF_CONDUCT.md) docs before helping out. + +We communicate via [issues](https://github.com/ethjs/ethjs-unit/issues) and [pull requests](https://github.com/ethjs/ethjs-unit/pulls). + +## Important documents + +- [Changelog](CHANGELOG.md) +- [Code of Conduct](CODE_OF_CONDUCT.md) +- [License](https://raw.githubusercontent.com/ethjs/ethjs-unit/master/LICENSE) + +## Licence + +This project is licensed under the MIT license, Copyright (c) 2016 Nick Dodson. For more information see LICENSE.md. + +``` +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +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. +``` diff --git a/test/merkletreejs/node_modules/ethjs-unit/internals/webpack/webpack.config.js b/test/merkletreejs/node_modules/ethjs-unit/internals/webpack/webpack.config.js new file mode 100644 index 0000000..dcdcf4a --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/internals/webpack/webpack.config.js @@ -0,0 +1,58 @@ +var webpack = require('webpack'); // eslint-disable-line + +var env = process.env.NODE_ENV; // eslint-disable-line +var filename = 'ethjs-unit'; // eslint-disable-line +var library = 'ethUnit'; // eslint-disable-line +var config = { // eslint-disable-line + module: { + loaders: [ + { + test: /\.js$/, + loaders: ['babel-loader'], + exclude: /node_modules/, + }, + { + test: /\.json$/, + loader: 'json', + }, + ], + }, + devtool: 'cheap-module-source-map', + output: { + path: 'dist', + filename: filename + '.js', // eslint-disable-line + library: library, // eslint-disable-line + libraryTarget: 'umd', + umdNamedDefine: true, + }, + plugins: [ + new webpack.BannerPlugin({ banner: ' /* eslint-disable */ ', raw: true, entryOnly: true }), + new webpack.optimize.OccurrenceOrderPlugin(), + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify(env), + }), + ], +}; + +if (env === 'production') { + config.output.filename = filename + '.min.js'; // eslint-disable-line + config.plugins + .push(new webpack.optimize.UglifyJsPlugin({ + compressor: { + pure_getters: true, + unsafe: true, + unsafe_comps: true, + warnings: false, + screw_ie8: false, + }, + mangle: { + screw_ie8: false, + }, + output: { + screw_ie8: false, + }, + })); + config.plugins.push(new webpack.optimize.DedupePlugin()); +} + +module.exports = config; diff --git a/test/merkletreejs/node_modules/ethjs-unit/lib/index.js b/test/merkletreejs/node_modules/ethjs-unit/lib/index.js new file mode 100644 index 0000000..63a661d --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/lib/index.js @@ -0,0 +1,168 @@ +'use strict'; + +var BN = require('bn.js'); +var numberToBN = require('number-to-bn'); + +var zero = new BN(0); +var negative1 = new BN(-1); + +// complete ethereum unit map +var unitMap = { + 'noether': '0', // eslint-disable-line + 'wei': '1', // eslint-disable-line + 'kwei': '1000', // eslint-disable-line + 'Kwei': '1000', // eslint-disable-line + 'babbage': '1000', // eslint-disable-line + 'femtoether': '1000', // eslint-disable-line + 'mwei': '1000000', // eslint-disable-line + 'Mwei': '1000000', // eslint-disable-line + 'lovelace': '1000000', // eslint-disable-line + 'picoether': '1000000', // eslint-disable-line + 'gwei': '1000000000', // eslint-disable-line + 'Gwei': '1000000000', // eslint-disable-line + 'shannon': '1000000000', // eslint-disable-line + 'nanoether': '1000000000', // eslint-disable-line + 'nano': '1000000000', // eslint-disable-line + 'szabo': '1000000000000', // eslint-disable-line + 'microether': '1000000000000', // eslint-disable-line + 'micro': '1000000000000', // eslint-disable-line + 'finney': '1000000000000000', // eslint-disable-line + 'milliether': '1000000000000000', // eslint-disable-line + 'milli': '1000000000000000', // eslint-disable-line + 'ether': '1000000000000000000', // eslint-disable-line + 'kether': '1000000000000000000000', // eslint-disable-line + 'grand': '1000000000000000000000', // eslint-disable-line + 'mether': '1000000000000000000000000', // eslint-disable-line + 'gether': '1000000000000000000000000000', // eslint-disable-line + 'tether': '1000000000000000000000000000000' }; + +/** + * Returns value of unit in Wei + * + * @method getValueOfUnit + * @param {String} unit the unit to convert to, default ether + * @returns {BigNumber} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ +function getValueOfUnit(unitInput) { + var unit = unitInput ? unitInput.toLowerCase() : 'ether'; + var unitValue = unitMap[unit]; // eslint-disable-line + + if (typeof unitValue !== 'string') { + throw new Error('[ethjs-unit] the unit provided ' + unitInput + ' doesn\'t exists, please use the one of the following units ' + JSON.stringify(unitMap, null, 2)); + } + + return new BN(unitValue, 10); +} + +function numberToString(arg) { + if (typeof arg === 'string') { + if (!arg.match(/^-?[0-9.]+$/)) { + throw new Error('while converting number to string, invalid number value \'' + arg + '\', should be a number matching (^-?[0-9.]+).'); + } + return arg; + } else if (typeof arg === 'number') { + return String(arg); + } else if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) { + if (arg.toPrecision) { + return String(arg.toPrecision()); + } else { + // eslint-disable-line + return arg.toString(10); + } + } + throw new Error('while converting number to string, invalid number value \'' + arg + '\' type ' + typeof arg + '.'); +} + +function fromWei(weiInput, unit, optionsInput) { + var wei = numberToBN(weiInput); // eslint-disable-line + var negative = wei.lt(zero); // eslint-disable-line + var base = getValueOfUnit(unit); + var baseLength = unitMap[unit].length - 1 || 1; + var options = optionsInput || {}; + + if (negative) { + wei = wei.mul(negative1); + } + + var fraction = wei.mod(base).toString(10); // eslint-disable-line + + while (fraction.length < baseLength) { + fraction = '0' + fraction; + } + + if (!options.pad) { + fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + } + + var whole = wei.div(base).toString(10); // eslint-disable-line + + if (options.commify) { + whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ','); + } + + var value = '' + whole + (fraction == '0' ? '' : '.' + fraction); // eslint-disable-line + + if (negative) { + value = '-' + value; + } + + return value; +} + +function toWei(etherInput, unit) { + var ether = numberToString(etherInput); // eslint-disable-line + var base = getValueOfUnit(unit); + var baseLength = unitMap[unit].length - 1 || 1; + + // Is it negative? + var negative = ether.substring(0, 1) === '-'; // eslint-disable-line + if (negative) { + ether = ether.substring(1); + } + + if (ether === '.') { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, invalid value'); + } + + // Split it into a whole and fractional part + var comps = ether.split('.'); // eslint-disable-line + if (comps.length > 2) { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal points'); + } + + var whole = comps[0], + fraction = comps[1]; // eslint-disable-line + + if (!whole) { + whole = '0'; + } + if (!fraction) { + fraction = '0'; + } + if (fraction.length > baseLength) { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal places'); + } + + while (fraction.length < baseLength) { + fraction += '0'; + } + + whole = new BN(whole); + fraction = new BN(fraction); + var wei = whole.mul(base).add(fraction); // eslint-disable-line + + if (negative) { + wei = wei.mul(negative1); + } + + return new BN(wei.toString(10), 10); +} + +module.exports = { + unitMap: unitMap, + numberToString: numberToString, + getValueOfUnit: getValueOfUnit, + fromWei: fromWei, + toWei: toWei +}; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/ethjs-unit/lib/index.txt b/test/merkletreejs/node_modules/ethjs-unit/lib/index.txt new file mode 100644 index 0000000..005f3ba --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/lib/index.txt @@ -0,0 +1,146 @@ +const BigNumber = require('bignumber.js'); + +// complete ethereum unit map +const unitMap = { + 'noether': '0', // eslint-disable-line + 'wei': '1', // eslint-disable-line + 'kwei': '1000', // eslint-disable-line + 'Kwei': '1000', // eslint-disable-line + 'babbage': '1000', // eslint-disable-line + 'femtoether': '1000', // eslint-disable-line + 'mwei': '1000000', // eslint-disable-line + 'Mwei': '1000000', // eslint-disable-line + 'lovelace': '1000000', // eslint-disable-line + 'picoether': '1000000', // eslint-disable-line + 'gwei': '1000000000', // eslint-disable-line + 'Gwei': '1000000000', // eslint-disable-line + 'shannon': '1000000000', // eslint-disable-line + 'nanoether': '1000000000', // eslint-disable-line + 'nano': '1000000000', // eslint-disable-line + 'szabo': '1000000000000', // eslint-disable-line + 'microether': '1000000000000', // eslint-disable-line + 'micro': '1000000000000', // eslint-disable-line + 'finney': '1000000000000000', // eslint-disable-line + 'milliether': '1000000000000000', // eslint-disable-line + 'milli': '1000000000000000', // eslint-disable-line + 'ether': '1000000000000000000', // eslint-disable-line + 'kether': '1000000000000000000000', // eslint-disable-line + 'grand': '1000000000000000000000', // eslint-disable-line + 'mether': '1000000000000000000000000', // eslint-disable-line + 'gether': '1000000000000000000000000000', // eslint-disable-line + 'tether': '1000000000000000000000000000000', // eslint-disable-line +}; + +/** + * Returns value of unit in Wei + * + * @method getValueOfUnit + * @param {String} unit the unit to convert to, default ether + * @returns {BigNumber} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ +function getValueOfUnit(unitInput) { + const unit = unitInput ? unitInput.toLowerCase() : 'ether'; + var unitValue = unitMap[unit]; // eslint-disable-line + + if (typeof unitValue !== 'string') { + throw new Error(`This unit doesn't exists, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`); + } + + return new BigNumber(unitValue, 10); +} + +/** + * Takes a number of wei and converts it to any other ether unit. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method fromWei + * @param {Number|String} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert to, default ether + * @return {Object} When given a BigNumber object it returns one as well, otherwise a number +*/ +function fromWei(number, unit) { + const returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); + + return returnValue; +} + +/** + * Takes a number of a unit and converts it to wei. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method toWei + * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert from, default ether + * @return {Object} When given a BigNumber object it returns one as well, otherwise a number +*/ +function toWei(number, unit) { + const returnValue = toBigNumber(number).times(getValueOfUnit(unit)); + + return returnValue; +} + +/** + * Returns true if object is BigNumber, otherwise false + * + * @method isBigNumber + * @param {Object} + * @return {Boolean} + */ +function isBigNumber(object) { + return object instanceof BigNumber || (object && object.constructor && object.constructor.name === 'BigNumber'); +} + +/** + * Takes an input and transforms it into an bignumber + * + * @method toBigNumber + * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber + * @return {BigNumber} BigNumber +*/ +function toBigNumber(numberInput) { + const number = numberInput || 0; + + if (isBigNumber(number)) { + return number; + } + + if (typeof number === 'string' && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { + return new BigNumber(number.replace('0x', ''), 16); + } + + return new BigNumber(number.toString(10), 10); +} + +module.exports = { + unitMap, + isBigNumber, + toBigNumber, + toWei, + fromWei, +}; diff --git a/test/merkletreejs/node_modules/ethjs-unit/lib/tests/test.index.js b/test/merkletreejs/node_modules/ethjs-unit/lib/tests/test.index.js new file mode 100644 index 0000000..b3f0d41 --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/lib/tests/test.index.js @@ -0,0 +1,165 @@ +'use strict'; + +var units = require('../index.js'); // eslint-disable-line +var BigNumber = require('bn.js'); // eslint-disable-line +var ActualBigNumber = require('bignumber.js'); +var Web3 = require('web3'); // eslint-disable-line +var web3 = new Web3(); // eslint-disable-line +var assert = require('chai').assert; // eslint-disable-line +var totalTypes = Object.keys(units.unitMap).length; + +function testRandomValueAgainstWeb3ToWei(negative) { + var stringTestValue = '' + (negative ? '-' : '') + String(Math.floor(Math.random() * 100000000000000000 + 1)); + var randomunitsType = Object.keys(units.unitMap)[Math.floor(Math.random() * (totalTypes - 1) + 1)]; + var unitsValue = units.toWei(stringTestValue, randomunitsType); + var web3Value = new BigNumber(web3.toWei(stringTestValue, randomunitsType)); + + // it(`toWei should work like web3 val ${unitsValue.toString(10)} should equal ${web3Value.toString(10)}`, () => { + assert.deepEqual(unitsValue, web3Value); + // }); +} + +function testRandomValueAgainstWeb3FromWei(negative) { + var stringTestValue = '' + (negative ? '-' : '') + String(Math.floor(Math.random() * 100000000000000000 + 1)); + var randomunitsType = Object.keys(units.unitMap)[Math.floor(Math.random() * (totalTypes - 1) + 1)]; + var unitsValue = units.fromWei(stringTestValue, randomunitsType); + var web3Value = web3.fromWei(stringTestValue, randomunitsType); + + // it(`fromWei should work like web3 rounded val ${unitsValue.substr(0, web3Value.length - 1)} should equal ${web3Value.substr(0, web3Value.length - 1)} for unit type ${randomunitsType}`, () => { + assert.deepEqual(unitsValue.substr(0, web3Value.length - 1), web3Value.substr(0, web3Value.length - 1)); + // }); +} + +describe('getValueOfUnit', function () { + it('should throw when undefined or not string', function () { + function invalidFromWei() { + units.fromWei(1000000000000000000, 'something'); + } + assert.throws(invalidFromWei, Error); + }); +}); + +describe('toWei', function () { + it('should handle edge cases', function () { + assert.equal(units.toWei(0, 'wei').toString(10), '0'); + assert.equal(units.toWei('0.0', 'wei').toString(10), '0'); + assert.equal(units.toWei('.3', 'ether').toString(10), '300000000000000000'); + assert.throws(function () { + return units.toWei('.', 'wei'); + }, Error); + assert.throws(function () { + return units.toWei('1.243842387924387924897423897423', 'ether'); + }, Error); + assert.throws(function () { + return units.toWei('8723.98234.98234', 'ether'); + }, Error); + }); + + it('should return the correct value', function () { + assert.equal(units.toWei(1, 'wei').toString(10), '1'); + assert.equal(units.toWei(1, 'kwei').toString(10), '1000'); + assert.equal(units.toWei(1, 'Kwei').toString(10), '1000'); + assert.equal(units.toWei(1, 'babbage').toString(10), '1000'); + assert.equal(units.toWei(1, 'mwei').toString(10), '1000000'); + assert.equal(units.toWei(1, 'Mwei').toString(10), '1000000'); + assert.equal(units.toWei(1, 'lovelace').toString(10), '1000000'); + assert.equal(units.toWei(1, 'gwei').toString(10), '1000000000'); + assert.equal(units.toWei(1, 'Gwei').toString(10), '1000000000'); + assert.equal(units.toWei(1, 'shannon').toString(10), '1000000000'); + assert.equal(units.toWei(1, 'szabo').toString(10), '1000000000000'); + assert.equal(units.toWei(1, 'finney').toString(10), '1000000000000000'); + assert.equal(units.toWei(1, 'ether').toString(10), '1000000000000000000'); + assert.equal(units.toWei(1, 'kether').toString(10), '1000000000000000000000'); + assert.equal(units.toWei(1, 'grand').toString(10), '1000000000000000000000'); + assert.equal(units.toWei(1, 'mether').toString(10), '1000000000000000000000000'); + assert.equal(units.toWei(1, 'gether').toString(10), '1000000000000000000000000000'); + assert.equal(units.toWei(1, 'tether').toString(10), '1000000000000000000000000000000'); + + assert.equal(units.toWei(1, 'kwei').toString(10), units.toWei(1, 'femtoether').toString(10)); + assert.equal(units.toWei(1, 'szabo').toString(10), units.toWei(1, 'microether').toString(10)); + assert.equal(units.toWei(1, 'finney').toString(10), units.toWei(1, 'milliether').toString(10)); + assert.equal(units.toWei(1, 'milli').toString(10), units.toWei(1, 'milliether').toString(10)); + assert.equal(units.toWei(1, 'milli').toString(10), units.toWei(1000, 'micro').toString(10)); + + assert.throws(function () { + units.toWei(1, 'wei1'); + }, Error); + }); +}); + +describe('numberToString', function () { + it('should handle edge cases', function () { + // assert.throws(() => units.numberToString(null), Error); + assert.throws(function () { + return units.numberToString(undefined); + }, Error); + // assert.throws(() => units.numberToString(NaN), Error); + assert.throws(function () { + return units.numberToString({}); + }, Error); + assert.throws(function () { + return units.numberToString([]); + }, Error); + assert.throws(function () { + return units.numberToString('-1sdffsdsdf'); + }, Error); + assert.throws(function () { + return units.numberToString('-0..-...9'); + }, Error); + assert.throws(function () { + return units.numberToString('fds'); + }, Error); + assert.throws(function () { + return units.numberToString(''); + }, Error); + assert.throws(function () { + return units.numberToString('#'); + }, Error); + assert.equal(units.numberToString(55), '55'); + assert.equal(units.numberToString(1), '1'); + assert.equal(units.numberToString(-1), '-1'); + assert.equal(units.numberToString(0), '0'); + assert.equal(units.numberToString(-0), '0'); + assert.equal(units.numberToString(new ActualBigNumber(10.1)), '10.1'); + assert.equal(units.numberToString(new ActualBigNumber(10000)), '10000'); + assert.equal(units.numberToString(new BigNumber(10000)), '10000'); + assert.equal(units.numberToString(new BigNumber('-1')), '-1'); + assert.equal(units.numberToString(new BigNumber('1')), '1'); + assert.equal(units.numberToString(new BigNumber(0)), '0'); + }); +}); + +describe('fromWei', function () { + it('should handle options', function () { + assert.equal(units.fromWei(10000000, 'wei', { commify: true }), '10,000,000'); + }); + + it('should return the correct value', function () { + assert.equal(units.fromWei(1000000000000000000, 'wei'), '1000000000000000000'); + assert.equal(units.fromWei(1000000000000000000, 'kwei'), '1000000000000000'); + assert.equal(units.fromWei(1000000000000000000, 'mwei'), '1000000000000'); + assert.equal(units.fromWei(1000000000000000000, 'gwei'), '1000000000'); + assert.equal(units.fromWei(1000000000000000000, 'szabo'), '1000000'); + assert.equal(units.fromWei(1000000000000000000, 'finney'), '1000'); + assert.equal(units.fromWei(1000000000000000000, 'ether'), '1'); + assert.equal(units.fromWei(1000000000000000000, 'kether'), '0.001'); + assert.equal(units.fromWei(1000000000000000000, 'grand'), '0.001'); + assert.equal(units.fromWei(1000000000000000000, 'mether'), '0.000001'); + assert.equal(units.fromWei(1000000000000000000, 'gether'), '0.000000001'); + assert.equal(units.fromWei(1000000000000000000, 'tether'), '0.000000000001'); + }); +}); + +describe('units', function () { + describe('normal functionality', function () { + it('should be the same as web3', function () { + for (var i = 0; i < 15000; i++) { + // eslint-disable-line + testRandomValueAgainstWeb3ToWei(false); + testRandomValueAgainstWeb3ToWei(true); + testRandomValueAgainstWeb3FromWei(false); + testRandomValueAgainstWeb3FromWei(true); + } + }); + }); +}); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/ethjs-unit/package.json b/test/merkletreejs/node_modules/ethjs-unit/package.json new file mode 100644 index 0000000..05919b6 --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/package.json @@ -0,0 +1,238 @@ +{ + "name": "ethjs-unit", + "version": "0.1.6", + "description": "A simple module for handling Ethereum units (e.g. 'ether', 'wei', etc...)", + "main": "lib/index.js", + "files": [ + "dist", + "internals", + "lib", + "src" + ], + "scripts": { + "start": "npm test", + "release": "npmpub", + "pretest": "npm run lint", + "prepublish": "npm run build", + "prebuild": "npm run build:clean && npm run test", + "build:clean": "npm run test:clean && rimraf ./dist", + "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir lib --copy-files", + "build:umd": "cross-env BABEL_ENV=commonjs NODE_ENV=development webpack --config ./internals/webpack/webpack.config.js ./lib/index.js --progress", + "build:umd:min": "cross-env BABEL_ENV=commonjs NODE_ENV=production webpack --config ./internals/webpack/webpack.config.js ./lib/index.js --progress", + "build": "npm run build:commonjs && npm run test:lib && npm run build:umd && npm run build:umd:min", + "lint": "npm run lint:js", + "lint:eslint": "eslint --ignore-path .gitignore --ignore-pattern **/**.min.js", + "lint:js": "npm run lint:eslint -- . ", + "lint:staged": "lint-staged", + "test:clean": "rimraf ./coverage", + "test": "mocha ./src/tests/**/*.js -R spec --timeout 2000000", + "test:lib": "mocha ./lib/tests/**/*.js -R spec --timeout 2000000", + "test-travis": "node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- src/tests/**/*.js -R spec --timeout 2000000", + "coveralls": "npm run test-travis && cat ./coverage/lcov.info | coveralls" + }, + "engines": { + "npm": ">=3", + "node": ">=6.5.0" + }, + "babel": { + "plugins": [ + [ + "transform-es2015-template-literals", + { + "loose": true + } + ], + "transform-es2015-literals", + "transform-es2015-function-name", + "transform-es2015-arrow-functions", + "transform-es2015-block-scoped-functions", + [ + "transform-es2015-classes", + { + "loose": true + } + ], + "transform-es2015-object-super", + "transform-es2015-shorthand-properties", + [ + "transform-es2015-computed-properties", + { + "loose": true + } + ], + [ + "transform-es2015-for-of", + { + "loose": true + } + ], + "transform-es2015-sticky-regex", + "transform-es2015-unicode-regex", + "check-es2015-constants", + [ + "transform-es2015-spread", + { + "loose": true + } + ], + "transform-es2015-parameters", + [ + "transform-es2015-destructuring", + { + "loose": true + } + ], + "transform-es2015-block-scoping", + "transform-object-rest-spread", + "transform-es3-member-expression-literals", + "transform-es3-property-literals" + ], + "env": { + "commonjs": { + "plugins": [ + [ + "transform-es2015-modules-commonjs", + { + "loose": true + } + ] + ] + } + } + }, + "dependencies": { + "bn.js": "4.11.6", + "number-to-bn": "1.7.0" + }, + "devDependencies": { + "bignumber.js": "3.0.1", + "babel-cli": "6.18.0", + "babel-core": "6.18.2", + "babel-loader": "6.2.8", + "babel-plugin-check-es2015-constants": "6.8.0", + "babel-plugin-transform-es2015-arrow-functions": "6.8.0", + "babel-plugin-transform-es2015-block-scoped-functions": "6.8.0", + "babel-plugin-transform-es2015-block-scoping": "6.18.0", + "babel-plugin-transform-es2015-classes": "6.18.0", + "babel-plugin-transform-es2015-computed-properties": "6.8.0", + "babel-plugin-transform-es2015-destructuring": "6.19.0", + "babel-plugin-transform-es2015-for-of": "6.18.0", + "babel-plugin-transform-es2015-function-name": "6.9.0", + "babel-plugin-transform-es2015-literals": "6.8.0", + "babel-plugin-transform-es2015-modules-commonjs": "6.18.0", + "babel-plugin-transform-es2015-object-super": "6.8.0", + "babel-plugin-transform-es2015-parameters": "6.18.0", + "babel-plugin-transform-es2015-shorthand-properties": "6.18.0", + "babel-plugin-transform-es2015-spread": "6.8.0", + "babel-plugin-transform-es2015-sticky-regex": "6.8.0", + "babel-plugin-transform-es2015-template-literals": "6.8.0", + "babel-plugin-transform-es2015-unicode-regex": "6.11.0", + "babel-plugin-transform-es3-member-expression-literals": "6.5.0", + "babel-plugin-transform-es3-property-literals": "6.5.0", + "babel-plugin-transform-object-rest-spread": "6.19.0", + "babel-register": "6.18.0", + "check-es3-syntax-cli": "0.1.3", + "webpack": "2.1.0-beta.15", + "json-loader": "0.5.4", + "rimraf": "2.3.4", + "cross-env": "1.0.7", + "babel-eslint": "7.1.0", + "chai": "3.5.0", + "coveralls": "2.11.9", + "eslint": "2.10.1", + "istanbul": "0.4.5", + "eslint-config-airbnb": "9.0.1", + "eslint-import-resolver-webpack": "0.2.4", + "eslint-plugin-import": "1.8.0", + "eslint-plugin-jsx-a11y": "1.2.0", + "eslint-plugin-react": "5.1.1", + "eventsource-polyfill": "0.9.6", + "lint-staged": "1.0.1", + "mocha": "3.1.2", + "pre-commit": "1.1.3", + "web3": "0.17.0-beta" + }, + "keywords": [ + "ethereum", + "encoding", + "decoding" + ], + "author": "Nick Dodson ", + "contributors": [ + { + "name": "Richard Moore", + "email": "me@ricmoo.com", + "url": "https://ethers.io" + }, + { + "name": "Marek Kotewicz", + "email": "marek@ethdev.com", + "url": "https://github.com/debris" + }, + { + "name": "Fabian Vogelsteller", + "email": "fabian@ethdev.com", + "homepage": "http://frozeman.de" + }, + { + "name": "Marian Oancea", + "email": "marian@ethdev.com", + "url": "https://github.com/cubedro" + }, + { + "name": "Gav Wood", + "email": "g@ethdev.com", + "homepage": "http://gavwood.com" + }, + { + "name": "Jeffery Wilcke", + "email": "jeff@ethdev.com", + "url": "https://github.com/obscuren" + } + ], + "repository": { + "type": "git", + "url": "git://github.com/ethjs/ethjs-unit" + }, + "license": "MIT", + "lint-staged": { + "lint:eslint": "*.js" + }, + "eslintConfig": { + "parser": "babel-eslint", + "extends": "airbnb", + "env": { + "node": true, + "mocha": true, + "es6": true + }, + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module" + }, + "rules": { + "import/no-unresolved": 2, + "comma-dangle": [ + 2, + "always-multiline" + ], + "indent": [ + 2, + 2, + { + "SwitchCase": 1 + } + ], + "no-console": 1, + "max-len": 0, + "prefer-template": 2, + "no-use-before-define": 0, + "newline-per-chained-call": 0, + "arrow-body-style": [ + 2, + "as-needed" + ] + } + }, + "pre-commit": "build" +} diff --git a/test/merkletreejs/node_modules/ethjs-unit/src/index.js b/test/merkletreejs/node_modules/ethjs-unit/src/index.js new file mode 100644 index 0000000..c9cb89d --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/src/index.js @@ -0,0 +1,155 @@ +const BN = require('bn.js'); +const numberToBN = require('number-to-bn'); + +const zero = new BN(0); +const negative1 = new BN(-1); + +// complete ethereum unit map +const unitMap = { + 'noether': '0', // eslint-disable-line + 'wei': '1', // eslint-disable-line + 'kwei': '1000', // eslint-disable-line + 'Kwei': '1000', // eslint-disable-line + 'babbage': '1000', // eslint-disable-line + 'femtoether': '1000', // eslint-disable-line + 'mwei': '1000000', // eslint-disable-line + 'Mwei': '1000000', // eslint-disable-line + 'lovelace': '1000000', // eslint-disable-line + 'picoether': '1000000', // eslint-disable-line + 'gwei': '1000000000', // eslint-disable-line + 'Gwei': '1000000000', // eslint-disable-line + 'shannon': '1000000000', // eslint-disable-line + 'nanoether': '1000000000', // eslint-disable-line + 'nano': '1000000000', // eslint-disable-line + 'szabo': '1000000000000', // eslint-disable-line + 'microether': '1000000000000', // eslint-disable-line + 'micro': '1000000000000', // eslint-disable-line + 'finney': '1000000000000000', // eslint-disable-line + 'milliether': '1000000000000000', // eslint-disable-line + 'milli': '1000000000000000', // eslint-disable-line + 'ether': '1000000000000000000', // eslint-disable-line + 'kether': '1000000000000000000000', // eslint-disable-line + 'grand': '1000000000000000000000', // eslint-disable-line + 'mether': '1000000000000000000000000', // eslint-disable-line + 'gether': '1000000000000000000000000000', // eslint-disable-line + 'tether': '1000000000000000000000000000000', // eslint-disable-line +}; + +/** + * Returns value of unit in Wei + * + * @method getValueOfUnit + * @param {String} unit the unit to convert to, default ether + * @returns {BigNumber} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ +function getValueOfUnit(unitInput) { + const unit = unitInput ? unitInput.toLowerCase() : 'ether'; + var unitValue = unitMap[unit]; // eslint-disable-line + + if (typeof unitValue !== 'string') { + throw new Error(`[ethjs-unit] the unit provided ${unitInput} doesn't exists, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`); + } + + return new BN(unitValue, 10); +} + +function numberToString(arg) { + if (typeof arg === 'string') { + if (!arg.match(/^-?[0-9.]+$/)) { + throw new Error(`while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`); + } + return arg; + } else if (typeof arg === 'number') { + return String(arg); + } else if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) { + if (arg.toPrecision) { + return String(arg.toPrecision()); + } else { // eslint-disable-line + return arg.toString(10); + } + } + throw new Error(`while converting number to string, invalid number value '${arg}' type ${typeof arg}.`); +} + +function fromWei(weiInput, unit, optionsInput) { + var wei = numberToBN(weiInput); // eslint-disable-line + var negative = wei.lt(zero); // eslint-disable-line + const base = getValueOfUnit(unit); + const baseLength = unitMap[unit].length - 1 || 1; + const options = optionsInput || {}; + + if (negative) { + wei = wei.mul(negative1); + } + + var fraction = wei.mod(base).toString(10); // eslint-disable-line + + while (fraction.length < baseLength) { + fraction = `0${fraction}`; + } + + if (!options.pad) { + fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + } + + var whole = wei.div(base).toString(10); // eslint-disable-line + + if (options.commify) { + whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ','); + } + + var value = `${whole}${fraction == '0' ? '' : `.${fraction}`}`; // eslint-disable-line + + if (negative) { + value = `-${value}`; + } + + return value; +} + +function toWei(etherInput, unit) { + var ether = numberToString(etherInput); // eslint-disable-line + const base = getValueOfUnit(unit); + const baseLength = unitMap[unit].length - 1 || 1; + + // Is it negative? + var negative = (ether.substring(0, 1) === '-'); // eslint-disable-line + if (negative) { + ether = ether.substring(1); + } + + if (ether === '.') { throw new Error(`[ethjs-unit] while converting number ${etherInput} to wei, invalid value`); } + + // Split it into a whole and fractional part + var comps = ether.split('.'); // eslint-disable-line + if (comps.length > 2) { throw new Error(`[ethjs-unit] while converting number ${etherInput} to wei, too many decimal points`); } + + var whole = comps[0], fraction = comps[1]; // eslint-disable-line + + if (!whole) { whole = '0'; } + if (!fraction) { fraction = '0'; } + if (fraction.length > baseLength) { throw new Error(`[ethjs-unit] while converting number ${etherInput} to wei, too many decimal places`); } + + while (fraction.length < baseLength) { + fraction += '0'; + } + + whole = new BN(whole); + fraction = new BN(fraction); + var wei = (whole.mul(base)).add(fraction); // eslint-disable-line + + if (negative) { + wei = wei.mul(negative1); + } + + return new BN(wei.toString(10), 10); +} + +module.exports = { + unitMap, + numberToString, + getValueOfUnit, + fromWei, + toWei, +}; diff --git a/test/merkletreejs/node_modules/ethjs-unit/src/tests/test.index.js b/test/merkletreejs/node_modules/ethjs-unit/src/tests/test.index.js new file mode 100644 index 0000000..0397aa1 --- /dev/null +++ b/test/merkletreejs/node_modules/ethjs-unit/src/tests/test.index.js @@ -0,0 +1,138 @@ +const units = require('../index.js'); // eslint-disable-line +const BigNumber = require('bn.js'); // eslint-disable-line +const ActualBigNumber = require('bignumber.js'); +const Web3 = require('web3'); // eslint-disable-line +const web3 = new Web3(); // eslint-disable-line +const assert = require('chai').assert; // eslint-disable-line +const totalTypes = Object.keys(units.unitMap).length; + +function testRandomValueAgainstWeb3ToWei(negative) { + const stringTestValue = `${negative ? '-' : ''}${String(Math.floor((Math.random() * 100000000000000000) + 1))}`; + const randomunitsType = Object.keys(units.unitMap)[Math.floor((Math.random() * (totalTypes - 1)) + 1)]; + const unitsValue = units.toWei(stringTestValue, randomunitsType); + const web3Value = new BigNumber(web3.toWei(stringTestValue, randomunitsType)); + + // it(`toWei should work like web3 val ${unitsValue.toString(10)} should equal ${web3Value.toString(10)}`, () => { + assert.deepEqual(unitsValue, web3Value); + // }); +} + +function testRandomValueAgainstWeb3FromWei(negative) { + const stringTestValue = `${negative ? '-' : ''}${String(Math.floor((Math.random() * 100000000000000000) + 1))}`; + const randomunitsType = Object.keys(units.unitMap)[Math.floor((Math.random() * (totalTypes - 1)) + 1)]; + const unitsValue = units.fromWei(stringTestValue, randomunitsType); + const web3Value = web3.fromWei(stringTestValue, randomunitsType); + + // it(`fromWei should work like web3 rounded val ${unitsValue.substr(0, web3Value.length - 1)} should equal ${web3Value.substr(0, web3Value.length - 1)} for unit type ${randomunitsType}`, () => { + assert.deepEqual(unitsValue.substr(0, web3Value.length - 1), web3Value.substr(0, web3Value.length - 1)); + // }); +} + +describe('getValueOfUnit', () => { + it('should throw when undefined or not string', () => { + function invalidFromWei() { + units.fromWei(1000000000000000000, 'something'); + } + assert.throws(invalidFromWei, Error); + }); +}); + +describe('toWei', () => { + it('should handle edge cases', () => { + assert.equal(units.toWei(0, 'wei').toString(10), '0'); + assert.equal(units.toWei('0.0', 'wei').toString(10), '0'); + assert.equal(units.toWei('.3', 'ether').toString(10), '300000000000000000'); + assert.throws(() => units.toWei('.', 'wei'), Error); + assert.throws(() => units.toWei('1.243842387924387924897423897423', 'ether'), Error); + assert.throws(() => units.toWei('8723.98234.98234', 'ether'), Error); + }); + + it('should return the correct value', () => { + assert.equal(units.toWei(1, 'wei').toString(10), '1'); + assert.equal(units.toWei(1, 'kwei').toString(10), '1000'); + assert.equal(units.toWei(1, 'Kwei').toString(10), '1000'); + assert.equal(units.toWei(1, 'babbage').toString(10), '1000'); + assert.equal(units.toWei(1, 'mwei').toString(10), '1000000'); + assert.equal(units.toWei(1, 'Mwei').toString(10), '1000000'); + assert.equal(units.toWei(1, 'lovelace').toString(10), '1000000'); + assert.equal(units.toWei(1, 'gwei').toString(10), '1000000000'); + assert.equal(units.toWei(1, 'Gwei').toString(10), '1000000000'); + assert.equal(units.toWei(1, 'shannon').toString(10), '1000000000'); + assert.equal(units.toWei(1, 'szabo').toString(10), '1000000000000'); + assert.equal(units.toWei(1, 'finney').toString(10), '1000000000000000'); + assert.equal(units.toWei(1, 'ether').toString(10), '1000000000000000000'); + assert.equal(units.toWei(1, 'kether').toString(10), '1000000000000000000000'); + assert.equal(units.toWei(1, 'grand').toString(10), '1000000000000000000000'); + assert.equal(units.toWei(1, 'mether').toString(10), '1000000000000000000000000'); + assert.equal(units.toWei(1, 'gether').toString(10), '1000000000000000000000000000'); + assert.equal(units.toWei(1, 'tether').toString(10), '1000000000000000000000000000000'); + + assert.equal(units.toWei(1, 'kwei').toString(10), units.toWei(1, 'femtoether').toString(10)); + assert.equal(units.toWei(1, 'szabo').toString(10), units.toWei(1, 'microether').toString(10)); + assert.equal(units.toWei(1, 'finney').toString(10), units.toWei(1, 'milliether').toString(10)); + assert.equal(units.toWei(1, 'milli').toString(10), units.toWei(1, 'milliether').toString(10)); + assert.equal(units.toWei(1, 'milli').toString(10), units.toWei(1000, 'micro').toString(10)); + + assert.throws(() => { units.toWei(1, 'wei1'); }, Error); + }); +}); + +describe('numberToString', () => { + it('should handle edge cases', () => { + // assert.throws(() => units.numberToString(null), Error); + assert.throws(() => units.numberToString(undefined), Error); + // assert.throws(() => units.numberToString(NaN), Error); + assert.throws(() => units.numberToString({}), Error); + assert.throws(() => units.numberToString([]), Error); + assert.throws(() => units.numberToString('-1sdffsdsdf'), Error); + assert.throws(() => units.numberToString('-0..-...9'), Error); + assert.throws(() => units.numberToString('fds'), Error); + assert.throws(() => units.numberToString(''), Error); + assert.throws(() => units.numberToString('#'), Error); + assert.equal(units.numberToString(55), '55'); + assert.equal(units.numberToString(1), '1'); + assert.equal(units.numberToString(-1), '-1'); + assert.equal(units.numberToString(0), '0'); + assert.equal(units.numberToString(-0), '0'); + assert.equal(units.numberToString(new ActualBigNumber(10.1)), '10.1'); + assert.equal(units.numberToString(new ActualBigNumber(10000)), '10000'); + assert.equal(units.numberToString(new BigNumber(10000)), '10000'); + assert.equal(units.numberToString(new BigNumber('-1')), '-1'); + assert.equal(units.numberToString(new BigNumber('1')), '1'); + assert.equal(units.numberToString(new BigNumber(0)), '0'); + }); +}); + +describe('fromWei', () => { + it('should handle options', () => { + assert.equal(units.fromWei(10000000, 'wei', { commify: true }), '10,000,000'); + }); + + it('should return the correct value', () => { + assert.equal(units.fromWei(1000000000000000000, 'wei'), '1000000000000000000'); + assert.equal(units.fromWei(1000000000000000000, 'kwei'), '1000000000000000'); + assert.equal(units.fromWei(1000000000000000000, 'mwei'), '1000000000000'); + assert.equal(units.fromWei(1000000000000000000, 'gwei'), '1000000000'); + assert.equal(units.fromWei(1000000000000000000, 'szabo'), '1000000'); + assert.equal(units.fromWei(1000000000000000000, 'finney'), '1000'); + assert.equal(units.fromWei(1000000000000000000, 'ether'), '1'); + assert.equal(units.fromWei(1000000000000000000, 'kether'), '0.001'); + assert.equal(units.fromWei(1000000000000000000, 'grand'), '0.001'); + assert.equal(units.fromWei(1000000000000000000, 'mether'), '0.000001'); + assert.equal(units.fromWei(1000000000000000000, 'gether'), '0.000000001'); + assert.equal(units.fromWei(1000000000000000000, 'tether'), '0.000000000001'); + }); +}); + +describe('units', () => { + describe('normal functionality', () => { + it('should be the same as web3', () => { + for (var i = 0; i < 15000; i++) { // eslint-disable-line + testRandomValueAgainstWeb3ToWei(false); + testRandomValueAgainstWeb3ToWei(true); + testRandomValueAgainstWeb3FromWei(false); + testRandomValueAgainstWeb3FromWei(true); + } + }); + }); +}); diff --git a/test/merkletreejs/node_modules/for-each/.editorconfig b/test/merkletreejs/node_modules/for-each/.editorconfig new file mode 100644 index 0000000..ac29ade --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 120 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/test/merkletreejs/node_modules/for-each/.eslintrc b/test/merkletreejs/node_modules/for-each/.eslintrc new file mode 100644 index 0000000..2b8ea2a --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "indent": [2, 4], + "max-nested-callbacks": [2, 3], + "max-params": [2, 3], + "max-statements": [2, 14], + "no-invalid-this": [1], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + } +} diff --git a/test/merkletreejs/node_modules/for-each/.travis.yml b/test/merkletreejs/node_modules/for-each/.travis.yml new file mode 100644 index 0000000..e9e54bd --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/.travis.yml @@ -0,0 +1,45 @@ +language: node_js +os: + - linux +node_js: + - "8" + - "7" + - "6" + - "5" + - "4" + - "iojs" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "node" + env: PRETEST=true + - node_js: "node" + env: POSTTEST=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/test/merkletreejs/node_modules/for-each/LICENSE b/test/merkletreejs/node_modules/for-each/LICENSE new file mode 100644 index 0000000..53f19aa --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2012 Raynos. + +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. + diff --git a/test/merkletreejs/node_modules/for-each/README.md b/test/merkletreejs/node_modules/for-each/README.md new file mode 100644 index 0000000..16dfbb6 --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/README.md @@ -0,0 +1,43 @@ +# for-each [![build status][1]][2] + +[![browser support][3]][4] + +A better forEach. + +## Example + +Like `Array.prototype.forEach` but works on objects. + +```js +var forEach = require("for-each") + +forEach({ key: "value" }, function (value, key, object) { + /* code */ +}) +``` + +As a bonus, it's also a perfectly function shim/polyfill for arrays too! + +```js +var forEach = require("for-each") + +forEach([1, 2, 3], function (value, index, array) { + /* code */ +}) +``` + +## Installation + +`npm install for-each` + +## Contributors + + - Raynos + +## MIT Licenced + + [1]: https://secure.travis-ci.org/Raynos/for-each.png + [2]: http://travis-ci.org/Raynos/for-each + [3]: https://ci.testling.com/Raynos/for-each.png + [4]: https://ci.testling.com/Raynos/for-each + diff --git a/test/merkletreejs/node_modules/for-each/index.js b/test/merkletreejs/node_modules/for-each/index.js new file mode 100644 index 0000000..609ef9f --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/index.js @@ -0,0 +1,62 @@ +'use strict'; + +var isCallable = require('is-callable'); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; + +module.exports = forEach; diff --git a/test/merkletreejs/node_modules/for-each/package.json b/test/merkletreejs/node_modules/for-each/package.json new file mode 100644 index 0000000..f21d15e --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/package.json @@ -0,0 +1,65 @@ +{ + "name": "for-each", + "version": "0.3.3", + "description": "A better forEach", + "keywords": [], + "author": "Raynos ", + "repository": "git://github.com/Raynos/for-each.git", + "main": "index", + "homepage": "https://github.com/Raynos/for-each", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/for-each/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": { + "is-callable": "^1.1.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "eslint": "^4.19.1", + "nsp": "^3.2.1", + "tape": "^4.9.0" + }, + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/Raynos/for-each/raw/master/LICENSE" + } + ], + "scripts": { + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "node test/test", + "posttest": "npm run security", + "lint": "eslint *.js test/*.js", + "security": "nsp check" + }, + "testling": { + "files": "test/test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + } +} diff --git a/test/merkletreejs/node_modules/for-each/test/.eslintrc b/test/merkletreejs/node_modules/for-each/test/.eslintrc new file mode 100644 index 0000000..a6c04b9 --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/test/.eslintrc @@ -0,0 +1,8 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": 0, + "no-magic-numbers": 0, + } +} diff --git a/test/merkletreejs/node_modules/for-each/test/test.js b/test/merkletreejs/node_modules/for-each/test/test.js new file mode 100644 index 0000000..8c93787 --- /dev/null +++ b/test/merkletreejs/node_modules/for-each/test/test.js @@ -0,0 +1,182 @@ +'use strict'; + +/* globals window */ + +var test = require('tape'); +var forEach = require('../'); + +test('forEach calls each iterator', function (t) { + var count = 0; + t.plan(4); + forEach({ a: 1, b: 2 }, function (value, key) { + if (count === 0) { + t.equal(value, 1); + t.equal(key, 'a'); + } else { + t.equal(value, 2); + t.equal(key, 'b'); + } + count += 1; + }); +}); + +test('forEach calls iterator with correct this value', function (t) { + var thisValue = {}; + + t.plan(1); + + forEach([0], function () { + t.equal(this, thisValue); + }, thisValue); +}); + +test('second argument: iterator', function (t) { + var arr = []; + t['throws'](function () { forEach(arr); }, TypeError, 'undefined is not a function'); + t['throws'](function () { forEach(arr, null); }, TypeError, 'null is not a function'); + t['throws'](function () { forEach(arr, ''); }, TypeError, 'string is not a function'); + t['throws'](function () { forEach(arr, /a/); }, TypeError, 'regex is not a function'); + t['throws'](function () { forEach(arr, true); }, TypeError, 'true is not a function'); + t['throws'](function () { forEach(arr, false); }, TypeError, 'false is not a function'); + t['throws'](function () { forEach(arr, NaN); }, TypeError, 'NaN is not a function'); + t['throws'](function () { forEach(arr, 42); }, TypeError, '42 is not a function'); + t.doesNotThrow(function () { forEach(arr, function () {}); }, 'function is a function'); + t.doesNotThrow(function () { forEach(arr, setTimeout); }, 'setTimeout is a function'); + if (typeof window !== 'undefined') { + t.doesNotThrow(function () { forEach(arr, window.alert); }, 'alert is a function'); + } + t.end(); +}); + +test('array', function (t) { + var arr = [1, 2, 3]; + + t.test('iterates over every item', function (st) { + var index = 0; + forEach(arr, function () { index += 1; }); + st.equal(index, arr.length, 'iterates ' + arr.length + ' times'); + st.end(); + }); + + t.test('first iterator argument', function (st) { + var index = 0; + st.plan(arr.length); + forEach(arr, function (item) { + st.equal(arr[index], item, 'item ' + index + ' is passed as first argument'); + index += 1; + }); + st.end(); + }); + + t.test('second iterator argument', function (st) { + var counter = 0; + st.plan(arr.length); + forEach(arr, function (item, index) { + st.equal(counter, index, 'index ' + index + ' is passed as second argument'); + counter += 1; + }); + st.end(); + }); + + t.test('third iterator argument', function (st) { + st.plan(arr.length); + forEach(arr, function (item, index, array) { + st.deepEqual(arr, array, 'array is passed as third argument'); + }); + st.end(); + }); + + t.test('context argument', function (st) { + var context = {}; + forEach([], function () { + st.equal(this, context, '"this" is the passed context'); + }, context); + st.end(); + }); + + t.end(); +}); + +test('object', function (t) { + var obj = { + a: 1, + b: 2, + c: 3 + }; + var keys = ['a', 'b', 'c']; + + var F = function F() { + this.a = 1; + this.b = 2; + }; + F.prototype.c = 3; + var fKeys = ['a', 'b']; + + t.test('iterates over every object literal key', function (st) { + var counter = 0; + forEach(obj, function () { counter += 1; }); + st.equal(counter, keys.length, 'iterated ' + counter + ' times'); + st.end(); + }); + + t.test('iterates only over own keys', function (st) { + var counter = 0; + forEach(new F(), function () { counter += 1; }); + st.equal(counter, fKeys.length, 'iterated ' + fKeys.length + ' times'); + st.end(); + }); + + t.test('first iterator argument', function (st) { + var index = 0; + st.plan(keys.length); + forEach(obj, function (item) { + st.equal(obj[keys[index]], item, 'item at key ' + keys[index] + ' is passed as first argument'); + index += 1; + }); + st.end(); + }); + + t.test('second iterator argument', function (st) { + var counter = 0; + st.plan(keys.length); + forEach(obj, function (item, key) { + st.equal(keys[counter], key, 'key ' + key + ' is passed as second argument'); + counter += 1; + }); + st.end(); + }); + + t.test('third iterator argument', function (st) { + st.plan(keys.length); + forEach(obj, function (item, key, object) { + st.deepEqual(obj, object, 'object is passed as third argument'); + }); + st.end(); + }); + + t.test('context argument', function (st) { + var context = {}; + forEach({}, function () { + st.equal(this, context, '"this" is the passed context'); + }, context); + st.end(); + }); + + t.end(); +}); + +test('string', function (t) { + var str = 'str'; + t.test('second iterator argument', function (st) { + var counter = 0; + st.plan((str.length * 2) + 1); + forEach(str, function (item, index) { + st.equal(counter, index, 'index ' + index + ' is passed as second argument'); + st.equal(str.charAt(index), item); + counter += 1; + }); + st.equal(counter, str.length, 'iterates ' + str.length + ' times'); + st.end(); + }); + t.end(); +}); diff --git a/test/merkletreejs/node_modules/function-bind/.eslintrc b/test/merkletreejs/node_modules/function-bind/.eslintrc new file mode 100644 index 0000000..71a054f --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "no-new-func": [1], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], +} diff --git a/test/merkletreejs/node_modules/function-bind/.github/FUNDING.yml b/test/merkletreejs/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 0000000..7448219 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/function-bind/.github/SECURITY.md b/test/merkletreejs/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/test/merkletreejs/node_modules/function-bind/.nycrc b/test/merkletreejs/node_modules/function-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/function-bind/CHANGELOG.md b/test/merkletreejs/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 0000000..f9e6cc0 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license” field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/test/merkletreejs/node_modules/function-bind/LICENSE b/test/merkletreejs/node_modules/function-bind/LICENSE new file mode 100644 index 0000000..62d6d23 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +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. + diff --git a/test/merkletreejs/node_modules/function-bind/README.md b/test/merkletreejs/node_modules/function-bind/README.md new file mode 100644 index 0000000..814c20b --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/README.md @@ -0,0 +1,46 @@ +# function-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] + +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Implementation of function.prototype.bind + +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. + +## Example + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/test/merkletreejs/node_modules/function-bind/implementation.js b/test/merkletreejs/node_modules/function-bind/implementation.js new file mode 100644 index 0000000..fd4384c --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/test/merkletreejs/node_modules/function-bind/index.js b/test/merkletreejs/node_modules/function-bind/index.js new file mode 100644 index 0000000..3bb6b96 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/test/merkletreejs/node_modules/function-bind/package.json b/test/merkletreejs/node_modules/function-bind/package.json new file mode 100644 index 0000000..6185963 --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/package.json @@ -0,0 +1,87 @@ +{ + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "license": "MIT", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/function-bind/test/.eslintrc b/test/merkletreejs/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000..8a56d5b --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/test/merkletreejs/node_modules/function-bind/test/index.js b/test/merkletreejs/node_modules/function-bind/test/index.js new file mode 100644 index 0000000..2edecce --- /dev/null +++ b/test/merkletreejs/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/test/merkletreejs/node_modules/get-intrinsic/.eslintrc b/test/merkletreejs/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 0000000..8376636 --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/test/merkletreejs/node_modules/get-intrinsic/.github/FUNDING.yml b/test/merkletreejs/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 0000000..8e8da0d --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-intrinsic +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/get-intrinsic/.nycrc b/test/merkletreejs/node_modules/get-intrinsic/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/get-intrinsic/CHANGELOG.md b/test/merkletreejs/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 0000000..870b590 --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,125 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.2](https://github.com/ljharb/get-intrinsic/compare/v1.2.1...v1.2.2) - 2023-10-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `call-bind`, `es-abstract`, `mock-property`, `object-inspect`, `tape` [`f51bcf2`](https://github.com/ljharb/get-intrinsic/commit/f51bcf26412d58d17ce17c91c9afd0ad271f0762) +- [Refactor] use `hasown` instead of `has` [`18d14b7`](https://github.com/ljharb/get-intrinsic/commit/18d14b799bea6b5765e1cec91890830cbcdb0587) +- [Deps] update `function-bind` [`6e109c8`](https://github.com/ljharb/get-intrinsic/commit/6e109c81e03804cc5e7824fb64353cdc3d8ee2c7) + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/test/merkletreejs/node_modules/get-intrinsic/LICENSE b/test/merkletreejs/node_modules/get-intrinsic/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/get-intrinsic/README.md b/test/merkletreejs/node_modules/get-intrinsic/README.md new file mode 100644 index 0000000..3aa0bba --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/test/merkletreejs/node_modules/get-intrinsic/index.js b/test/merkletreejs/node_modules/get-intrinsic/index.js new file mode 100644 index 0000000..be180b0 --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/index.js @@ -0,0 +1,351 @@ +'use strict'; + +var undefined; + +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var hasProto = require('has-proto')(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/test/merkletreejs/node_modules/get-intrinsic/package.json b/test/merkletreejs/node_modules/get-intrinsic/package.json new file mode 100644 index 0000000..ffffe09 --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/package.json @@ -0,0 +1,93 @@ +{ + "name": "get-intrinsic", + "version": "1.2.2", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.5", + "es-abstract": "^1.22.2", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.0.2", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.2" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/get-intrinsic/test/GetIntrinsic.js b/test/merkletreejs/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 0000000..1cc08e0 --- /dev/null +++ b/test/merkletreejs/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bind/callBound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2021/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/gopd/.eslintrc b/test/merkletreejs/node_modules/gopd/.eslintrc new file mode 100644 index 0000000..e2550c0 --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/test/merkletreejs/node_modules/gopd/.github/FUNDING.yml b/test/merkletreejs/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000..94a44a8 --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/gopd/CHANGELOG.md b/test/merkletreejs/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000..f111eb1 --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/test/merkletreejs/node_modules/gopd/LICENSE b/test/merkletreejs/node_modules/gopd/LICENSE new file mode 100644 index 0000000..6abfe14 --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/gopd/README.md b/test/merkletreejs/node_modules/gopd/README.md new file mode 100644 index 0000000..784e56a --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/test/merkletreejs/node_modules/gopd/index.js b/test/merkletreejs/node_modules/gopd/index.js new file mode 100644 index 0000000..fb6d3bb --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/test/merkletreejs/node_modules/gopd/package.json b/test/merkletreejs/node_modules/gopd/package.json new file mode 100644 index 0000000..d5e1fa4 --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/package.json @@ -0,0 +1,71 @@ +{ + "name": "gopd", + "version": "1.0.1", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/gopd/test/index.js b/test/merkletreejs/node_modules/gopd/test/index.js new file mode 100644 index 0000000..0376bfb --- /dev/null +++ b/test/merkletreejs/node_modules/gopd/test/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-property-descriptors/.eslintrc b/test/merkletreejs/node_modules/has-property-descriptors/.eslintrc new file mode 100644 index 0000000..2fcc002 --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": ["GetIntrinsic"], + }], + }, +} diff --git a/test/merkletreejs/node_modules/has-property-descriptors/.github/FUNDING.yml b/test/merkletreejs/node_modules/has-property-descriptors/.github/FUNDING.yml new file mode 100644 index 0000000..817aacf --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-property-descriptors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/has-property-descriptors/.nycrc b/test/merkletreejs/node_modules/has-property-descriptors/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/has-property-descriptors/CHANGELOG.md b/test/merkletreejs/node_modules/has-property-descriptors/CHANGELOG.md new file mode 100644 index 0000000..2cec99c --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/inspect-js/has-property-descriptors/compare/v1.0.0...v1.0.1) - 2023-10-20 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`5bbf4da`](https://github.com/inspect-js/has-property-descriptors/commit/5bbf4dae1b58950d87bb3af508bee7513e640868) +- [actions] update rebase action to use reusable workflow [`3a5585b`](https://github.com/inspect-js/has-property-descriptors/commit/3a5585bf74988f71a8f59e67a07d594e62c51fd8) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`e5c1212`](https://github.com/inspect-js/has-property-descriptors/commit/e5c1212048a8fda549794c47863724ca60b89cae) +- [Dev Deps] update `aud`, `tape` [`e942917`](https://github.com/inspect-js/has-property-descriptors/commit/e942917b6c2f7c090d5623048989cf20d0834ebf) +- [Deps] update `get-intrinsic` [`f4a44ec`](https://github.com/inspect-js/has-property-descriptors/commit/f4a44ec6d94146fa6c550d3c15c31a2062c83ef4) +- [Deps] update `get-intrinsic` [`eeb275b`](https://github.com/inspect-js/has-property-descriptors/commit/eeb275b473e5d72ca843b61ca25cfcb06a5d4300) + +## v1.0.0 - 2022-04-14 + +### Commits + +- Initial implementation, tests [`303559f`](https://github.com/inspect-js/has-property-descriptors/commit/303559f2a72dfe7111573a1aec475ed4a184c35a) +- Initial commit [`3a7ca2d`](https://github.com/inspect-js/has-property-descriptors/commit/3a7ca2dc49f1fff0279a28bb16265e7615e14749) +- read me [`dd73dce`](https://github.com/inspect-js/has-property-descriptors/commit/dd73dce09d89d0f7a4a6e3b1e562a506f979a767) +- npm init [`c1e6557`](https://github.com/inspect-js/has-property-descriptors/commit/c1e655779de632d68cb944c50da6b71bcb7b8c85) +- Only apps should have lockfiles [`e72f7c6`](https://github.com/inspect-js/has-property-descriptors/commit/e72f7c68de534b2d273ee665f8b18d4ecc7f70b0) diff --git a/test/merkletreejs/node_modules/has-property-descriptors/LICENSE b/test/merkletreejs/node_modules/has-property-descriptors/LICENSE new file mode 100644 index 0000000..2e7b9a3 --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +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. diff --git a/test/merkletreejs/node_modules/has-property-descriptors/README.md b/test/merkletreejs/node_modules/has-property-descriptors/README.md new file mode 100644 index 0000000..d81fbd9 --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/README.md @@ -0,0 +1,43 @@ +# has-property-descriptors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD. + +## Example + +```js +var hasPropertyDescriptors = require('has-property-descriptors'); +var assert = require('assert'); + +assert.equal(hasPropertyDescriptors(), true); // will be `false` in IE 6-8, and ES5 engines + +// Arrays can not have their length `[[Defined]]` in some engines +assert.equal(hasPropertyDescriptors.hasArrayLengthDefineBug(), false); // will be `true` in Firefox 4-22, and node v0.6 +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-property-descriptors +[npm-version-svg]: https://versionbadg.es/inspect-js/has-property-descriptors.svg +[deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors.svg +[deps-url]: https://david-dm.org/inspect-js/has-property-descriptors +[dev-deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-property-descriptors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-property-descriptors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-property-descriptors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-property-descriptors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-property-descriptors +[codecov-image]: https://codecov.io/gh/inspect-js/has-property-descriptors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-property-descriptors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-property-descriptors +[actions-url]: https://github.com/inspect-js/has-property-descriptors/actions diff --git a/test/merkletreejs/node_modules/has-property-descriptors/index.js b/test/merkletreejs/node_modules/has-property-descriptors/index.js new file mode 100644 index 0000000..8e30683 --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/index.js @@ -0,0 +1,33 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + return true; + } catch (e) { + // IE 8 has a broken defineProperty + return false; + } + } + return false; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!hasPropertyDescriptors()) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; diff --git a/test/merkletreejs/node_modules/has-property-descriptors/package.json b/test/merkletreejs/node_modules/has-property-descriptors/package.json new file mode 100644 index 0000000..831e018 --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/package.json @@ -0,0 +1,77 @@ +{ + "name": "has-property-descriptors", + "version": "1.0.1", + "description": "Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-property-descriptors.git" + }, + "keywords": [ + "property", + "descriptors", + "has", + "environment", + "env", + "defineProperty", + "getOwnPropertyDescriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-property-descriptors/issues" + }, + "homepage": "https://github.com/inspect-js/has-property-descriptors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.2" + }, + "dependencies": { + "get-intrinsic": "^1.2.2" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/has-property-descriptors/test/index.js b/test/merkletreejs/node_modules/has-property-descriptors/test/index.js new file mode 100644 index 0000000..7f02bd3 --- /dev/null +++ b/test/merkletreejs/node_modules/has-property-descriptors/test/index.js @@ -0,0 +1,57 @@ +'use strict'; + +var test = require('tape'); + +var hasPropertyDescriptors = require('../'); + +var sentinel = {}; + +test('hasPropertyDescriptors', function (t) { + t.equal(typeof hasPropertyDescriptors, 'function', 'is a function'); + t.equal(typeof hasPropertyDescriptors.hasArrayLengthDefineBug, 'function', '`hasArrayLengthDefineBug` property is a function'); + + var yes = hasPropertyDescriptors(); + t.test('property descriptors', { skip: !yes }, function (st) { + var o = { a: sentinel }; + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: true, + value: sentinel, + writable: true + }, + 'has expected property descriptor' + ); + + Object.defineProperty(o, 'a', { enumerable: false, writable: false }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: false, + value: sentinel, + writable: false + }, + 'has expected property descriptor after [[Define]]' + ); + + st.end(); + }); + + var arrayBug = hasPropertyDescriptors.hasArrayLengthDefineBug(); + t.test('defining array lengths', { skip: !yes || arrayBug }, function (st) { + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + st.equal(arr.length, 3, 'array starts with length 3'); + + Object.defineProperty(arr, 'length', { value: 5 }); + + st.equal(arr.length, 5, 'array ends with length 5'); + + st.end(); + }); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-proto/.eslintrc b/test/merkletreejs/node_modules/has-proto/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/test/merkletreejs/node_modules/has-proto/.github/FUNDING.yml b/test/merkletreejs/node_modules/has-proto/.github/FUNDING.yml new file mode 100644 index 0000000..613705c --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/has-proto/CHANGELOG.md b/test/merkletreejs/node_modules/has-proto/CHANGELOG.md new file mode 100644 index 0000000..c350e80 --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/inspect-js/has-proto/compare/v1.0.0...v1.0.1) - 2022-12-21 + +### Commits + +- [meta] correct URLs and description [`ef34483`](https://github.com/inspect-js/has-proto/commit/ef34483ca0d35680f271b6b96e35526151b25dfc) +- [patch] add an additional criteria [`e81959e`](https://github.com/inspect-js/has-proto/commit/e81959ed7c7a77fbf459f00cb4ef824f1099497f) +- [Dev Deps] update `aud` [`2bec2c4`](https://github.com/inspect-js/has-proto/commit/2bec2c47b072b122ff5443fba0263f6dc649531f) + +## v1.0.0 - 2022-12-12 + +### Commits + +- Initial implementation, tests, readme [`6886fea`](https://github.com/inspect-js/has-proto/commit/6886fea578f67daf69a7920b2eb7637ea6ebb0bc) +- Initial commit [`99129c8`](https://github.com/inspect-js/has-proto/commit/99129c8f42471ac89cb681ba9cb9d52a583eb94f) +- npm init [`2844ad8`](https://github.com/inspect-js/has-proto/commit/2844ad8e75b84d66a46765b3bab9d2e8ea692e10) +- Only apps should have lockfiles [`c65bc5e`](https://github.com/inspect-js/has-proto/commit/c65bc5e40b9004463f7336d47c67245fb139a36a) diff --git a/test/merkletreejs/node_modules/has-proto/LICENSE b/test/merkletreejs/node_modules/has-proto/LICENSE new file mode 100644 index 0000000..2e7b9a3 --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +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. diff --git a/test/merkletreejs/node_modules/has-proto/README.md b/test/merkletreejs/node_modules/has-proto/README.md new file mode 100644 index 0000000..1456765 --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/README.md @@ -0,0 +1,38 @@ +# has-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does this environment have the ability to set the [[Prototype]] of an object on creation with `__proto__`? + +## Example + +```js +var hasProto = require('has-proto'); +var assert = require('assert'); + +assert.equal(typeof hasProto(), 'boolean'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-proto +[npm-version-svg]: https://versionbadg.es/inspect-js/has-proto.svg +[deps-svg]: https://david-dm.org/inspect-js/has-proto.svg +[deps-url]: https://david-dm.org/inspect-js/has-proto +[dev-deps-svg]: https://david-dm.org/inspect-js/has-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-proto +[codecov-image]: https://codecov.io/gh/inspect-js/has-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-proto +[actions-url]: https://github.com/inspect-js/has-proto/actions diff --git a/test/merkletreejs/node_modules/has-proto/index.js b/test/merkletreejs/node_modules/has-proto/index.js new file mode 100644 index 0000000..d3e4be4 --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = { + foo: {} +}; + +var $Object = Object; + +module.exports = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); +}; diff --git a/test/merkletreejs/node_modules/has-proto/package.json b/test/merkletreejs/node_modules/has-proto/package.json new file mode 100644 index 0000000..706f951 --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/package.json @@ -0,0 +1,74 @@ +{ + "name": "has-proto", + "version": "1.0.1", + "description": "Does this environment have the ability to get the [[Prototype]] of an object on creation with `__proto__`?", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-proto.git" + }, + "keywords": [ + "prototype", + "proto", + "set", + "get", + "__proto__", + "getPrototypeOf", + "setPrototypeOf", + "has" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-proto/issues" + }, + "homepage": "https://github.com/inspect-js/has-proto#readme", + "testling": { + "files": "test/index.js" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/has-proto/test/index.js b/test/merkletreejs/node_modules/has-proto/test/index.js new file mode 100644 index 0000000..5da1a3a --- /dev/null +++ b/test/merkletreejs/node_modules/has-proto/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); +var hasProto = require('../'); + +test('hasProto', function (t) { + var result = hasProto(); + t.equal(typeof result, 'boolean', 'returns a boolean (' + result + ')'); + + var obj = { __proto__: null }; + if (result) { + t.notOk('toString' in obj, 'null object lacks toString'); + } else { + t.ok('toString' in obj, 'without proto, null object has toString'); + t.equal(obj.__proto__, null); // eslint-disable-line no-proto + } + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-symbols/.eslintrc b/test/merkletreejs/node_modules/has-symbols/.eslintrc new file mode 100644 index 0000000..2d9a66a --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/test/merkletreejs/node_modules/has-symbols/.github/FUNDING.yml b/test/merkletreejs/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 0000000..04cf87e --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-symbols +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/has-symbols/.nycrc b/test/merkletreejs/node_modules/has-symbols/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/has-symbols/CHANGELOG.md b/test/merkletreejs/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 0000000..cd532a2 --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,75 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/test/merkletreejs/node_modules/has-symbols/LICENSE b/test/merkletreejs/node_modules/has-symbols/LICENSE new file mode 100644 index 0000000..df31cbf --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/has-symbols/README.md b/test/merkletreejs/node_modules/has-symbols/README.md new file mode 100644 index 0000000..33905f0 --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/test/merkletreejs/node_modules/has-symbols/index.js b/test/merkletreejs/node_modules/has-symbols/index.js new file mode 100644 index 0000000..17044fa --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/test/merkletreejs/node_modules/has-symbols/package.json b/test/merkletreejs/node_modules/has-symbols/package.json new file mode 100644 index 0000000..fe7004a --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/package.json @@ -0,0 +1,101 @@ +{ + "name": "has-symbols", + "version": "1.0.3", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "greenkeeper": { + "ignore": [ + "core-js" + ] + } +} diff --git a/test/merkletreejs/node_modules/has-symbols/shams.js b/test/merkletreejs/node_modules/has-symbols/shams.js new file mode 100644 index 0000000..1285210 --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/shams.js @@ -0,0 +1,42 @@ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/test/merkletreejs/node_modules/has-symbols/test/index.js b/test/merkletreejs/node_modules/has-symbols/test/index.js new file mode 100644 index 0000000..352129c --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-symbols/test/shams/core-js.js b/test/merkletreejs/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 0000000..df5365c --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/test/merkletreejs/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..9191b24 --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-symbols/test/tests.js b/test/merkletreejs/node_modules/has-symbols/test/tests.js new file mode 100644 index 0000000..89edd12 --- /dev/null +++ b/test/merkletreejs/node_modules/has-symbols/test/tests.js @@ -0,0 +1,56 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax + for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/test/merkletreejs/node_modules/has-tostringtag/.eslintrc b/test/merkletreejs/node_modules/has-tostringtag/.eslintrc new file mode 100644 index 0000000..2d9a66a --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/test/merkletreejs/node_modules/has-tostringtag/.github/FUNDING.yml b/test/merkletreejs/node_modules/has-tostringtag/.github/FUNDING.yml new file mode 100644 index 0000000..7a450e7 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-tostringtag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/has-tostringtag/CHANGELOG.md b/test/merkletreejs/node_modules/has-tostringtag/CHANGELOG.md new file mode 100644 index 0000000..39fb77c --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2021-08-05 + +### Commits + +- Tests [`6b6f573`](https://github.com/inspect-js/has-tostringtag/commit/6b6f5734dc2058badb300ff0783efdad95fe1a65) +- Initial commit [`2f8190e`](https://github.com/inspect-js/has-tostringtag/commit/2f8190e799fac32ba9b95a076c0255e01d7ce475) +- [meta] do not publish github action workflow files [`6e08cc4`](https://github.com/inspect-js/has-tostringtag/commit/6e08cc4e0fea7ec71ef66e70734b2af2c4a8b71b) +- readme [`94bed6c`](https://github.com/inspect-js/has-tostringtag/commit/94bed6c9560cbbfda034f8d6c260bb7b0db33c1a) +- npm init [`be67840`](https://github.com/inspect-js/has-tostringtag/commit/be67840ab92ee7adb98bcc65261975543f815fa5) +- Implementation [`c4914ec`](https://github.com/inspect-js/has-tostringtag/commit/c4914ecc51ddee692c85b471ae0a5d8123030fbf) +- [meta] use `auto-changelog` [`4aaf768`](https://github.com/inspect-js/has-tostringtag/commit/4aaf76895ae01d7b739f2b19f967ef2372506cd7) +- Only apps should have lockfiles [`bc4d99e`](https://github.com/inspect-js/has-tostringtag/commit/bc4d99e4bf494afbaa235c5f098df6e642edf724) +- [meta] add `safe-publish-latest` [`6523c05`](https://github.com/inspect-js/has-tostringtag/commit/6523c05c9b87140f3ae74c9daf91633dd9ff4e1f) diff --git a/test/merkletreejs/node_modules/has-tostringtag/LICENSE b/test/merkletreejs/node_modules/has-tostringtag/LICENSE new file mode 100644 index 0000000..7948bc0 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Inspect JS + +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. diff --git a/test/merkletreejs/node_modules/has-tostringtag/README.md b/test/merkletreejs/node_modules/has-tostringtag/README.md new file mode 100644 index 0000000..67a5e92 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/README.md @@ -0,0 +1,46 @@ +# has-tostringtag [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams. + +## Example + +```js +var hasSymbolToStringTag = require('has-tostringtag'); + +hasSymbolToStringTag() === true; // if the environment has native Symbol.toStringTag support. Not polyfillable, not forgeable. + +var hasSymbolToStringTagKinda = require('has-tostringtag/shams'); +hasSymbolToStringTagKinda() === true; // if the environment has a Symbol.toStringTag sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-tostringtag +[2]: https://versionbadg.es/inspect-js/has-tostringtag.svg +[5]: https://david-dm.org/inspect-js/has-tostringtag.svg +[6]: https://david-dm.org/inspect-js/has-tostringtag +[7]: https://david-dm.org/inspect-js/has-tostringtag/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-tostringtag#info=devDependencies +[11]: https://nodei.co/npm/has-tostringtag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-tostringtag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-tostringtag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-tostringtag +[codecov-image]: https://codecov.io/gh/inspect-js/has-tostringtag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-tostringtag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-tostringtag +[actions-url]: https://github.com/inspect-js/has-tostringtag/actions diff --git a/test/merkletreejs/node_modules/has-tostringtag/index.js b/test/merkletreejs/node_modules/has-tostringtag/index.js new file mode 100644 index 0000000..d626b7a --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/index.js @@ -0,0 +1,7 @@ +'use strict'; + +var hasSymbols = require('has-symbols'); + +module.exports = function hasToStringTag() { + return hasSymbols() && typeof Symbol.toStringTag === 'symbol'; +}; diff --git a/test/merkletreejs/node_modules/has-tostringtag/package.json b/test/merkletreejs/node_modules/has-tostringtag/package.json new file mode 100644 index 0000000..9c74d64 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/package.json @@ -0,0 +1,84 @@ +{ + "name": "has-tostringtag", + "version": "1.0.0", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams.", + "license": "MIT", + "main": "index.js", + "exports": { + ".": "./index.js", + "./shams": "./shams.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-tostringtag.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/has-tostringtag/issues" + }, + "homepage": "https://github.com/inspect-js/has-tostringtag#readme", + "keywords": [ + "javascript", + "ecmascript", + "symbol", + "symbols", + "tostringtag", + "Symbol.toStringTag" + ], + "dependencies": { + "has-symbols": "^1.0.2" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^2.6.12", + "eslint": "^7.32.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/test/merkletreejs/node_modules/has-tostringtag/shams.js b/test/merkletreejs/node_modules/has-tostringtag/shams.js new file mode 100644 index 0000000..8b7e401 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/shams.js @@ -0,0 +1,7 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams'); + +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; diff --git a/test/merkletreejs/node_modules/has-tostringtag/test/index.js b/test/merkletreejs/node_modules/has-tostringtag/test/index.js new file mode 100644 index 0000000..0679afd --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/test/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('tape'); +var hasSymbolToStringTag = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbolToStringTag, 'function', 'is a function'); + t.equal(typeof hasSymbolToStringTag(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbol.toStringTag exists', { skip: !hasSymbolToStringTag() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbol.toStringTag does not exist', { skip: hasSymbolToStringTag() }, function (t) { + t.equal(typeof Symbol === 'undefined' ? 'undefined' : typeof Symbol.toStringTag, 'undefined', 'global Symbol.toStringTag is undefined'); + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-tostringtag/test/shams/core-js.js b/test/merkletreejs/node_modules/has-tostringtag/test/shams/core-js.js new file mode 100644 index 0000000..692b86e --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol') { + test('has native Symbol.toStringTag support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol.toStringTag, 'symbol'); + t.end(); + }); + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js b/test/merkletreejs/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..489fe83 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/test/merkletreejs/node_modules/has-tostringtag/test/tests.js b/test/merkletreejs/node_modules/has-tostringtag/test/tests.js new file mode 100644 index 0000000..0dae885 --- /dev/null +++ b/test/merkletreejs/node_modules/has-tostringtag/test/tests.js @@ -0,0 +1,14 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + t.ok(Symbol.toStringTag, 'Symbol.toStringTag exists'); + + if (typeof Symbol !== 'function' || !Symbol.toStringTag) { return false; } + + var obj = {}; + obj[Symbol.toStringTag] = 'test'; + + t.equal(Object.prototype.toString.call(obj), '[object test]'); +}; diff --git a/test/merkletreejs/node_modules/hasown/.eslintrc b/test/merkletreejs/node_modules/hasown/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/test/merkletreejs/node_modules/hasown/.github/FUNDING.yml b/test/merkletreejs/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 0000000..d68c8b7 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/hasown +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/test/merkletreejs/node_modules/hasown/.nycrc b/test/merkletreejs/node_modules/hasown/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/hasown/CHANGELOG.md b/test/merkletreejs/node_modules/hasown/CHANGELOG.md new file mode 100644 index 0000000..1cbd1f5 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/test/merkletreejs/node_modules/hasown/LICENSE b/test/merkletreejs/node_modules/hasown/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and 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. diff --git a/test/merkletreejs/node_modules/hasown/README.md b/test/merkletreejs/node_modules/hasown/README.md new file mode 100644 index 0000000..f759b8a --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/test/merkletreejs/node_modules/hasown/index.d.ts b/test/merkletreejs/node_modules/hasown/index.d.ts new file mode 100644 index 0000000..caf4a06 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare const _exports: (o: {}, p: PropertyKey) => p is never; +export = _exports; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/hasown/index.d.ts.map b/test/merkletreejs/node_modules/hasown/index.d.ts.map new file mode 100644 index 0000000..d40068a --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"4BAMe,EAAE,KAAK,WAAW"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/hasown/index.js b/test/merkletreejs/node_modules/hasown/index.js new file mode 100644 index 0000000..3b91618 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {(o: {}, p: PropertyKey) => p is keyof o} */ +module.exports = bind.call(call, $hasOwn); diff --git a/test/merkletreejs/node_modules/hasown/package.json b/test/merkletreejs/node_modules/hasown/package.json new file mode 100644 index 0000000..9545006 --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/package.json @@ -0,0 +1,91 @@ +{ + "name": "hasown", + "version": "2.0.0", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated && npm run emit-types", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "preemit-types": "rm -f *.ts *.ts.map test/*.ts test/*.ts.map", + "emit-types": "npm run tsc -- --noEmit false --emitDeclarationOnly", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/function-bind": "^1.1.9", + "@types/mock-property": "^1.0.1", + "@types/tape": "^5.6.3", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.2", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1", + "typescript": "^5.3.0-dev.20231019" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test", + "!*.d.ts", + "!*.d.ts.map" + ] + } +} diff --git a/test/merkletreejs/node_modules/hasown/tsconfig.json b/test/merkletreejs/node_modules/hasown/tsconfig.json new file mode 100644 index 0000000..fdab34f --- /dev/null +++ b/test/merkletreejs/node_modules/hasown/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + //"skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/test/merkletreejs/node_modules/inherits/LICENSE b/test/merkletreejs/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/test/merkletreejs/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/test/merkletreejs/node_modules/inherits/README.md b/test/merkletreejs/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/test/merkletreejs/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/test/merkletreejs/node_modules/inherits/inherits.js b/test/merkletreejs/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/test/merkletreejs/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/test/merkletreejs/node_modules/inherits/inherits_browser.js b/test/merkletreejs/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/test/merkletreejs/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/test/merkletreejs/node_modules/inherits/package.json b/test/merkletreejs/node_modules/inherits/package.json new file mode 100644 index 0000000..37b4366 --- /dev/null +++ b/test/merkletreejs/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/test/merkletreejs/node_modules/is-arguments/.editorconfig b/test/merkletreejs/node_modules/is-arguments/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/test/merkletreejs/node_modules/is-arguments/.eslintignore b/test/merkletreejs/node_modules/is-arguments/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/test/merkletreejs/node_modules/is-arguments/.eslintrc b/test/merkletreejs/node_modules/is-arguments/.eslintrc new file mode 100644 index 0000000..6d42c6e --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": [2, { "min": 1, "max": 25 }], + "operator-linebreak": [2, "after"] + } +} diff --git a/test/merkletreejs/node_modules/is-arguments/.github/FUNDING.yml b/test/merkletreejs/node_modules/is-arguments/.github/FUNDING.yml new file mode 100644 index 0000000..d29bb40 --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-arguments +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/is-arguments/.nycrc b/test/merkletreejs/node_modules/is-arguments/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/is-arguments/CHANGELOG.md b/test/merkletreejs/node_modules/is-arguments/CHANGELOG.md new file mode 100644 index 0000000..a1ddafe --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/CHANGELOG.md @@ -0,0 +1,179 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.1](https://github.com/inspect-js/is-arguments/compare/v1.1.0...v1.1.1) - 2021-08-05 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`dd28b30`](https://github.com/inspect-js/is-arguments/commit/dd28b30f4237fac722f2ce05b0c1d7e63c4a81e4) +- [meta] do not publish github action workflow files [`87e489c`](https://github.com/inspect-js/is-arguments/commit/87e489cc77b709b96e73aaf9f9b2cd6da48f4960) +- [readme] fix repo URLs [`e2c2c6e`](https://github.com/inspect-js/is-arguments/commit/e2c2c6ee34ca21be4b19d282d96dd7ab75b63ae3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`b9ae62b`](https://github.com/inspect-js/is-arguments/commit/b9ae62b3a08a5fe84519865192e6287d5b6966f7) +- [readme] add github actions/codecov badges [`504c0a5`](https://github.com/inspect-js/is-arguments/commit/504c0a508dc313eae5942b1e35b2d031948de143) +- [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams [`dc29e52`](https://github.com/inspect-js/is-arguments/commit/dc29e521d71da420414110919a1e0fde8ec6eba3) +- [Dev Deps] update `auto-changelog`, `eslint`, `tape` [`a966d25`](https://github.com/inspect-js/is-arguments/commit/a966d25535c5f050ca5ce43a1559f93698a7130b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1218944`](https://github.com/inspect-js/is-arguments/commit/12189445a195558fdccebe099c699272d2082aa8) +- [meta] use `prepublishOnly` script for npm 7+ [`757dbee`](https://github.com/inspect-js/is-arguments/commit/757dbee3ec6f6225d4c7c91582e045cc1183dbd8) +- [Deps] update `call-bind` [`b206f05`](https://github.com/inspect-js/is-arguments/commit/b206f059571c430375c632e40dd29249fa76a8fd) +- [actions] update workflows [`b89b2f1`](https://github.com/inspect-js/is-arguments/commit/b89b2f1ab98bedebdf97d2397246030a1132c84e) + +## [v1.1.0](https://github.com/inspect-js/is-arguments/compare/v1.0.4...v1.1.0) - 2020-12-04 + +### Commits + +- [Tests] use shared travis-ci configs [`fd59a37`](https://github.com/inspect-js/is-arguments/commit/fd59a3779f004f36ea8e5ac90b0de9b97ff60755) +- [Tests] migrate tests to Github Actions [`982a0d6`](https://github.com/inspect-js/is-arguments/commit/982a0d68495b68e2b6ca8f4caa9f8a909ec56755) +- [Tests] remove `jscs` [`927d4b5`](https://github.com/inspect-js/is-arguments/commit/927d4b5c17b12c40f445491e52a11d5bed311ef6) +- [meta] add `auto-changelog` [`ef0634b`](https://github.com/inspect-js/is-arguments/commit/ef0634b0c07a12d9144c4db168cb79963326ec6d) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`1689f8b`](https://github.com/inspect-js/is-arguments/commit/1689f8bf533c8ab8cd95caf953905e3a204c0cdc) +- [Tests] up to `node` `v11.7`, `v10.15`, `v8.15`, `v6.16` [`145aaeb`](https://github.com/inspect-js/is-arguments/commit/145aaeb5a35e7abd3a8a5c9ec87c6e37f16ed068) +- [readme] fix repo URLs, remove defunct badges [`cc484a3`](https://github.com/inspect-js/is-arguments/commit/cc484a3ae787125eccc30a05c63b7ff6a1581591) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`c888738`](https://github.com/inspect-js/is-arguments/commit/c888738ef1cf84b973169bbe6219b795de4acfc2) +- [Tests] run `nyc` on all tests [`0de8efb`](https://github.com/inspect-js/is-arguments/commit/0de8efb8091a3dd5708812cd26ad541f7dca773a) +- [actions] add automatic rebasing / merge commit blocking [`818775a`](https://github.com/inspect-js/is-arguments/commit/818775aa0c66064965517be554c3bcc57ec0d721) +- [Robustness] use `call-bind` [`31d0199`](https://github.com/inspect-js/is-arguments/commit/31d0199c1a560f113ff099a2f43068cdfe0af79e) +- [actions] add "Allow Edits" workflow [`0c55f7d`](https://github.com/inspect-js/is-arguments/commit/0c55f7d254ff335291d9cee39501b247f7248fb9) +- [meta] create FUNDING.yml [`ca7ed59`](https://github.com/inspect-js/is-arguments/commit/ca7ed597bac29790ac6233ff1bdff7704b870e96) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`1ae5053`](https://github.com/inspect-js/is-arguments/commit/1ae505390efff099c50d0bc786a3ecc8d5303b04) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `safe-publish-latest` [`433f4a5`](https://github.com/inspect-js/is-arguments/commit/433f4a5573810fe689c5e56ad9fe69b6a2229b8c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`78ea4e8`](https://github.com/inspect-js/is-arguments/commit/78ea4e8261bc326c1ae7e9e50bb655e8bf128c6b) +- [Tests] use `npm audit` instead of `nsp` [`07fb85b`](https://github.com/inspect-js/is-arguments/commit/07fb85bf396880648c2d4285273968d478df4711) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`2204add`](https://github.com/inspect-js/is-arguments/commit/2204add22fcc15b1ee6aaae90578595b4f6d9647) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` [`ce150c0`](https://github.com/inspect-js/is-arguments/commit/ce150c0c47504779ce812b1aefe044fcad1286af) +- [Tests] fix tests from 0de8efb [`ee45fc3`](https://github.com/inspect-js/is-arguments/commit/ee45fc387b655de6feac101c478af111d488e144) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`03a312c`](https://github.com/inspect-js/is-arguments/commit/03a312cdae0aa058cfd094c996acb2af4e785484) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`25d2ef8`](https://github.com/inspect-js/is-arguments/commit/25d2ef8da0b90c834d1fa6b83410205832e271d4) +- [Dev Deps] update `auto-changelog`, `tape` [`0fe60b7`](https://github.com/inspect-js/is-arguments/commit/0fe60b74b7f1254c386e14d0ea6d9cc074fdf12c) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a9cbd0`](https://github.com/inspect-js/is-arguments/commit/4a9cbd0c91fd945ccc97c219d34e0840b0965586) +- [Dev Deps] update `auto-changelog`; add `aud` [`d9ff7d5`](https://github.com/inspect-js/is-arguments/commit/d9ff7d5f521eec5942019b1d7b38ace475da142f) +- [meta] add `funding` field [`adec2d2`](https://github.com/inspect-js/is-arguments/commit/adec2d293022ee3ec87479eaeae81bfec1ea1b18) +- [Tests] only audit prod deps [`f474960`](https://github.com/inspect-js/is-arguments/commit/f474960795eeb6087fc79eed8b787aa067b22ab1) + +## [v1.0.4](https://github.com/inspect-js/is-arguments/compare/v1.0.3...v1.0.4) - 2018-11-05 + +### Commits + +- [Fix] Fix errors about `in` operator. [`4d12e23`](https://github.com/inspect-js/is-arguments/commit/4d12e23fab8701207b7715fe7502db35c6edd3dd) + +## [v1.0.3](https://github.com/inspect-js/is-arguments/compare/v1.0.2...v1.0.3) - 2018-11-02 + +### Fixed + +- [Fix] add awareness of Symbol.toStringTag [`#20`](https://github.com/inspect-js/is-arguments/issues/20) + +### Commits + +- [Tests] up to `node` `v8.1`; `v7.10`, `v6.11`, `v4.8`; improve matrix; newer npm fails on older node [`ea5f23c`](https://github.com/inspect-js/is-arguments/commit/ea5f23c322234e18248b0acafe0f45333d5d78ec) +- [Tests] up to `node` `v9.1`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS. [`697a0a1`](https://github.com/inspect-js/is-arguments/commit/697a0a143d3b82f84956e4cca407c7eea228526b) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`40045c5`](https://github.com/inspect-js/is-arguments/commit/40045c5fe6ebb86f96125da96f7bfb9637579ce4) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `jscs`, `tape` [`08abc0d`](https://github.com/inspect-js/is-arguments/commit/08abc0d2e31c34514a58711f6203e41d06c3b81f) +- [Tests] up to `node` `v11.1`, `v10.13`, `v8.12` [`bf8d275`](https://github.com/inspect-js/is-arguments/commit/bf8d275ecf855c40c9c3f9c3ccf76874d4ce2497) +- [Tests] up to `node` `v7.0`, `v6.9`, `v4.6`; improve test matrix [`f813d86`](https://github.com/inspect-js/is-arguments/commit/f813d86b38f10d2e1f495597ca2a58d25a21339e) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`e4f9aee`](https://github.com/inspect-js/is-arguments/commit/e4f9aee64f0f7f2f9d8132992b81d133b5d3c9c7) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`6c98d11`](https://github.com/inspect-js/is-arguments/commit/6c98d1171a043a4ab21d70b813379a4162ac3702) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8e3178d`](https://github.com/inspect-js/is-arguments/commit/8e3178db172bc3ac889343aa3e38c24cc92aed08) +- package.json: use object form of "author", add "contributors" [`decc4fe`](https://github.com/inspect-js/is-arguments/commit/decc4feb9b31bd9f68b7a5f67aed39d32c9a6ab3) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`514902a`](https://github.com/inspect-js/is-arguments/commit/514902abde6b7d9397c9dbcd90f19fd78b70725a) +- [Tests] up to `node` `v5.6`, `v4.3` [`f11f47c`](https://github.com/inspect-js/is-arguments/commit/f11f47c5c1dae8adfda7ba1319de3b6e03db7925) +- [Dev Deps] add `npm run security` [`4adf82c`](https://github.com/inspect-js/is-arguments/commit/4adf82c0c9259eb81db18848a314b36db1c48d36) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`f587aeb`](https://github.com/inspect-js/is-arguments/commit/f587aeb3ec04f2d22c2a8fd7686a2153d0fd50d2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape` [`4f587bb`](https://github.com/inspect-js/is-arguments/commit/4f587bb7a2c499b1aa2e2aea60da8c0ee91c9df2) +- [Tests] up to `node` `v6.2`, `v5.11` [`36939c5`](https://github.com/inspect-js/is-arguments/commit/36939c5e1d8ce56c356a3f2144983839d86b3ae8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape` [`d779cc8`](https://github.com/inspect-js/is-arguments/commit/d779cc875bd6fa15d861a134065d629159051331) +- Only apps should have lockfiles [`f50ce65`](https://github.com/inspect-js/is-arguments/commit/f50ce65fe94728b6f127a0c11f2efc6473f56cf3) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`3025559`](https://github.com/inspect-js/is-arguments/commit/30255597cf578068e5a28d7a6e29076355132c87) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`3b9ddee`](https://github.com/inspect-js/is-arguments/commit/3b9ddeef740608d84d2b825b9a90e4adf049c905) +- [Tests] up to `v5.8`, `v4.4` [`d4902cf`](https://github.com/inspect-js/is-arguments/commit/d4902cfb07e0bfaa0788a7847fcaaba91c8e3435) +- [Tests] fix npm upgrades for older nodes [`c617dd3`](https://github.com/inspect-js/is-arguments/commit/c617dd3a7b6a70162cbeb985009620acd69c029d) +- [Tests] up to `node` `v5.3` [`cdd2a61`](https://github.com/inspect-js/is-arguments/commit/cdd2a617c3d1810149683596fe90024ae9dcc549) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7719172`](https://github.com/inspect-js/is-arguments/commit/77191721ef92ce9dc72fdae8e1cfdc2ec74317d9) +- [Dev Deps] update `es5-shim`, `tape`, `nsp`, `eslint` [`6a5f82b`](https://github.com/inspect-js/is-arguments/commit/6a5f82bc6d9407e64fc4c7794d546e4db8ab61ed) +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` [`c896c1c`](https://github.com/inspect-js/is-arguments/commit/c896c1c4629ff3c8cda25e0c3e607d2950ff4ba9) +- [Tests] Use `pretest` for running the linter. [`83db117`](https://github.com/inspect-js/is-arguments/commit/83db1173fde93c2d8a490663ce850321b018eab2) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint` [`57fdc63`](https://github.com/inspect-js/is-arguments/commit/57fdc636dea2f5c641e2d0c0dfbe0ac589acb69a) +- [Tests] up to `node` `v7.2` [`aa3eacf`](https://github.com/inspect-js/is-arguments/commit/aa3eacf27001a92aab4874f7d29f693ed6221b4a) +- [Tests] up to `node` `v5.10` [`94ff6d7`](https://github.com/inspect-js/is-arguments/commit/94ff6d72c095cae00a4df06043976dc3e414f49b) +- [Tests] on `node` `v4.2` [`cdb1fb5`](https://github.com/inspect-js/is-arguments/commit/cdb1fb5babe08c845570cbae218c0b96753c1152) + +## [v1.0.2](https://github.com/inspect-js/is-arguments/compare/v1.0.1...v1.0.2) - 2015-09-21 + +### Commits + +- Update `eslint`, use my personal shared config. [`8e211f4`](https://github.com/inspect-js/is-arguments/commit/8e211f46b17ae8d89aa5484b4b3b853d3d1b3fa9) +- In modern engines, only export the "is standard arguments" check. [`e8aa23f`](https://github.com/inspect-js/is-arguments/commit/e8aa23fc19f6d1c3c952174391a4903d90fcd622) +- Update `jscs`, `eslint`, `@ljharb/eslint-config` [`8a90bca`](https://github.com/inspect-js/is-arguments/commit/8a90bcad88025736a7c127123f1473af35bae6f7) +- Update `eslint` [`2214b5d`](https://github.com/inspect-js/is-arguments/commit/2214b5dac911e1eb949179f9034aa37ba7c079d7) +- Update `eslint` [`ca97c5b`](https://github.com/inspect-js/is-arguments/commit/ca97c5b22e7cf4f30d90ee1519988ecd4bf36887) +- [Dev Deps] update `jscs` [`ca6a477`](https://github.com/inspect-js/is-arguments/commit/ca6a477c16c70c0e5f29d56713237703ab610fdf) +- Update `covert`, `jscs`, `eslint` [`232d92a`](https://github.com/inspect-js/is-arguments/commit/232d92ab1dff7b0ad64024726cda437b32ce1906) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`460d700`](https://github.com/inspect-js/is-arguments/commit/460d700bdb5d8b261995e3d8f3e6b3eda4f91bcf) +- Test up to `io.js` `v2.3` [`7ef2293`](https://github.com/inspect-js/is-arguments/commit/7ef229388819ae1f1c1d55dbe741c90977cc3a3f) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`29f3d71`](https://github.com/inspect-js/is-arguments/commit/29f3d71eb516326409bd24bc7e6d4ebb6a872d01) +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` [`1c79a85`](https://github.com/inspect-js/is-arguments/commit/1c79a85d670d8dc5dbb1831ee0de0c8858a94775) +- `toString` as a variable name breaks in some older browsers. [`1e59f2b`](https://github.com/inspect-js/is-arguments/commit/1e59f2bf79454188145de5275a64996eafc94420) +- Update `tape`, `eslint` [`1efbefd`](https://github.com/inspect-js/is-arguments/commit/1efbefd84df6ae802245ebe6371cd15255ee23e7) +- Test up to `io.js` `v2.5` [`0760acc`](https://github.com/inspect-js/is-arguments/commit/0760acc3139d1930efebc4321c1f96ba1406e2de) +- Test up to `io.js` `v2.1` [`4c2245f`](https://github.com/inspect-js/is-arguments/commit/4c2245f3deccdb3ec70e4f79e5e8aac697f35d08) +- [Dev Deps] update `tape` [`348980e`](https://github.com/inspect-js/is-arguments/commit/348980e1666b66724e37c9df63d18d540a51d5fe) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`91d8c4f`](https://github.com/inspect-js/is-arguments/commit/91d8c4fd4516aae483fa2dd9c4a5b44c48e773f0) +- Update `tape` [`ec9b92a`](https://github.com/inspect-js/is-arguments/commit/ec9b92a244f7a077fe1df58af89f56a39d4d2600) +- Update `tape` [`6bc8969`](https://github.com/inspect-js/is-arguments/commit/6bc8969c40b2b2cd1c767933b7ef3d8ff65bf67f) +- Test on `io.js` `v3.0` [`33d9578`](https://github.com/inspect-js/is-arguments/commit/33d957814d515855583e98e652624e5920cc9496) + +## [v1.0.1](https://github.com/inspect-js/is-arguments/compare/v1.0.0...v1.0.1) - 2015-04-29 + +### Commits + +- Update `jscs`, add `npm run eslint` [`13a5f01`](https://github.com/inspect-js/is-arguments/commit/13a5f015aa67cb2402b5fdb21c68180ff7036a14) +- Using my standard jscs.json file [`d669fc4`](https://github.com/inspect-js/is-arguments/commit/d669fc49c0db56457eb55a77a2f9c40916ad6361) +- Adding `npm run lint` [`ece5d05`](https://github.com/inspect-js/is-arguments/commit/ece5d0581fadcff99b181d67b54eacb4869cfb98) +- Test on latest `io.js` [`908b092`](https://github.com/inspect-js/is-arguments/commit/908b092912fa9c89c20a41fdd117b21e857bfc84) +- Adding license and downloads badges [`05fd28b`](https://github.com/inspect-js/is-arguments/commit/05fd28b28d857ecb2220d0ac6267f36ec1e65eae) +- Make sure old and unstable nodes don't break Travis [`16ee7ea`](https://github.com/inspect-js/is-arguments/commit/16ee7eae70015864a8b3f2fe03463ecb4d707451) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`9846c79`](https://github.com/inspect-js/is-arguments/commit/9846c79d1999432538ea757c0dbf61ab3f0d54cd) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`27c014d`](https://github.com/inspect-js/is-arguments/commit/27c014d217d41d33b0bb1735e38184b871d86311) +- Use SVG instead of PNG badges [`ea01e68`](https://github.com/inspect-js/is-arguments/commit/ea01e68896722351c63912e37cc37541f9b78780) +- Remove unused links in README [`f5baaff`](https://github.com/inspect-js/is-arguments/commit/f5baaff1931bb9d48b20270a94d99121a3176dba) +- Test on latest `io.js` versions [`293e2c4`](https://github.com/inspect-js/is-arguments/commit/293e2c4d1edfdf9c6db88663314599ecde08a945) +- Update `tape`, `jscs` [`d72ab08`](https://github.com/inspect-js/is-arguments/commit/d72ab08147ab5256e1efd61c01b719796699faf0) +- Update `jscs` [`5f6e6d4`](https://github.com/inspect-js/is-arguments/commit/5f6e6d42645845b5663b5fef716e2963686aad8d) +- Update `tape`, `jscs` [`39ae55b`](https://github.com/inspect-js/is-arguments/commit/39ae55b6ef0c3d6206116bd7500bc601485d8698) +- Update `tape`, `jscs` [`594d928`](https://github.com/inspect-js/is-arguments/commit/594d92852cf7a4d93c8ff5ac157fdae9dbefc133) +- Updating dependencies [`183ac15`](https://github.com/inspect-js/is-arguments/commit/183ac151d27032fce4aaf3fa095cce9b086eb651) +- Update `tape` [`77b9cea`](https://github.com/inspect-js/is-arguments/commit/77b9ceae8dcb2c2e73d85f512d0d0309427c4011) +- Lock covert to v1.0.0. [`28d9052`](https://github.com/inspect-js/is-arguments/commit/28d9052eaa99f36ca5c61f35645b5e14ddf6f8f9) +- Updating tape [`d9ee2ac`](https://github.com/inspect-js/is-arguments/commit/d9ee2ac24045fa81ffed356410cfc2d878bc8b4b) +- Updating jscs [`c0cab8f`](https://github.com/inspect-js/is-arguments/commit/c0cab8fd6c0509153142a3cc79a7a4dceba322be) +- Updating jscs [`c59352a`](https://github.com/inspect-js/is-arguments/commit/c59352ae99c0d813168c19b9c888182ea11ae17a) +- Run linter as part of tests [`8b8154e`](https://github.com/inspect-js/is-arguments/commit/8b8154ef5b2566250baed70807affdbba93c3bcf) +- Oops, properly running code coverage checks during tests. [`cc441d0`](https://github.com/inspect-js/is-arguments/commit/cc441d0c488486c688e513f7d129f4f8ea2ee323) +- Updating covert. [`142db90`](https://github.com/inspect-js/is-arguments/commit/142db90aa3448995232c419419523b67a953b012) +- Updating tape [`265fd0f`](https://github.com/inspect-js/is-arguments/commit/265fd0ff3ee71ab8aa3d2d90be74066c1aa7c9c0) +- Updating tape [`7e9aec6`](https://github.com/inspect-js/is-arguments/commit/7e9aec654b8f5fe0bb2f8c940c84da8ec29a2102) +- Updating covert [`d96860a`](https://github.com/inspect-js/is-arguments/commit/d96860ab520ae62a37e80ad259b936ace09954d9) +- Updating tape [`1ec32a0`](https://github.com/inspect-js/is-arguments/commit/1ec32a0c02f53192a94521d63d4cf8fbb567fc84) +- Run code coverage as part of tests [`155ab22`](https://github.com/inspect-js/is-arguments/commit/155ab227902287c5eec653c25bec2cc4b530e635) +- Coverage does not work currently on node 0.6. [`9acf696`](https://github.com/inspect-js/is-arguments/commit/9acf696a1f3e202990fea494615377b40a380b79) +- Testing node 0.6 again [`a23ca07`](https://github.com/inspect-js/is-arguments/commit/a23ca07427cf3801b82e6a93d9a8904f392f4b20) + +## [v1.0.0](https://github.com/inspect-js/is-arguments/compare/v0.1.0...v1.0.0) - 2014-01-07 + +### Commits + +- :metal: 1.0.0 [`fc08874`](https://github.com/inspect-js/is-arguments/commit/fc08874107ac74fca91bd678843dbf7ea3a4c54a) + +## v0.1.0 - 2014-01-07 + +### Commits + +- package.json [`c547055`](https://github.com/inspect-js/is-arguments/commit/c54705585e907f1ef22473bff656904e49d22db2) +- read me! [`72ed639`](https://github.com/inspect-js/is-arguments/commit/72ed639c5db9c8732073ec1d30f14b493bb976da) +- Initial commit [`d2e0264`](https://github.com/inspect-js/is-arguments/commit/d2e0264bed7948b6c4f7bfde12ab351bffbf4cc1) +- Tests. [`032ed16`](https://github.com/inspect-js/is-arguments/commit/032ed16abf54466a75333e1da2ceef780fb58c1e) +- Implementation. [`71c312d`](https://github.com/inspect-js/is-arguments/commit/71c312d76d3b4b99cf7a1e0b442e9492069fba2b) +- Travis CI [`5500a66`](https://github.com/inspect-js/is-arguments/commit/5500a664de6b4484850f02b74641baa6e7d74c50) +- Running code coverage as part of tests. [`88ad34a`](https://github.com/inspect-js/is-arguments/commit/88ad34a133188cea28aa26a9f583653ea3a0260e) diff --git a/test/merkletreejs/node_modules/is-arguments/LICENSE b/test/merkletreejs/node_modules/is-arguments/LICENSE new file mode 100644 index 0000000..47b7b50 --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/is-arguments/README.md b/test/merkletreejs/node_modules/is-arguments/README.md new file mode 100644 index 0000000..b312512 --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/README.md @@ -0,0 +1,47 @@ +# is-arguments [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this an arguments object? It's a harder question than you think. + +## Example + +```js +var isArguments = require('is-arguments'); +var assert = require('assert'); + +assert.equal(isArguments({}), false); +assert.equal(isArguments([]), false); +(function () { + assert.equal(isArguments(arguments), true); +}()) +``` + +## Caveats +If you have modified an actual `arguments` object by giving it a `Symbol.toStringTag` property, then this package will return `false`. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-arguments +[2]: https://versionbadg.es/inspect-js/is-arguments.svg +[5]: https://david-dm.org/inspect-js/is-arguments.svg +[6]: https://david-dm.org/inspect-js/is-arguments +[7]: https://david-dm.org/inspect-js/is-arguments/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-arguments#info=devDependencies +[11]: https://nodei.co/npm/is-arguments.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-arguments.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-arguments.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-arguments +[codecov-image]: https://codecov.io/gh/inspect-js/is-arguments/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-arguments/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-arguments +[actions-url]: https://github.com/inspect-js/is-arguments/actions diff --git a/test/merkletreejs/node_modules/is-arguments/index.js b/test/merkletreejs/node_modules/is-arguments/index.js new file mode 100644 index 0000000..e17e906 --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/index.js @@ -0,0 +1,33 @@ +'use strict'; + +var hasToStringTag = require('has-tostringtag/shams')(); +var callBound = require('call-bind/callBound'); + +var $toString = callBound('Object.prototype.toString'); + +var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { + return false; + } + return $toString(value) === '[object Arguments]'; +}; + +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + $toString(value) !== '[object Array]' && + $toString(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; diff --git a/test/merkletreejs/node_modules/is-arguments/package.json b/test/merkletreejs/node_modules/is-arguments/package.json new file mode 100644 index 0000000..b4ba9ae --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/package.json @@ -0,0 +1,91 @@ +{ + "name": "is-arguments", + "version": "1.1.1", + "description": "Is this an arguments object? It's a harder question than you think.", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx aud --production", + "lint": "eslint .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-arguments.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/is-arguments/issues" + }, + "homepage": "https://github.com/inspect-js/is-arguments", + "keywords": [ + "arguments", + "js", + "javascript", + "is-arguments", + "is", + "object" + ], + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^7.32.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/test/merkletreejs/node_modules/is-arguments/test/index.js b/test/merkletreejs/node_modules/is-arguments/test/index.js new file mode 100644 index 0000000..6d7cd5a --- /dev/null +++ b/test/merkletreejs/node_modules/is-arguments/test/index.js @@ -0,0 +1,44 @@ +'use strict'; + +var test = require('tape'); +var isArguments = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('primitives', function (t) { + t.notOk(isArguments([]), 'array is not arguments'); + t.notOk(isArguments({}), 'object is not arguments'); + t.notOk(isArguments(''), 'empty string is not arguments'); + t.notOk(isArguments('foo'), 'string is not arguments'); + t.notOk(isArguments({ length: 2 }), 'naive array-like is not arguments'); + t.end(); +}); + +test('arguments object', function (t) { + t.ok(isArguments(arguments), 'arguments is arguments'); + t.notOk(isArguments(Array.prototype.slice.call(arguments)), 'sliced arguments is not arguments'); + t.end(); +}); + +test('old-style arguments object', function (t) { + var isLegacyArguments = isArguments.isLegacyArguments || isArguments; + var fakeOldArguments = { + callee: function () {}, + length: 3 + }; + t.ok(isLegacyArguments(fakeOldArguments), 'old-style arguments is arguments'); + t.end(); +}); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + var obj = {}; + obj[Symbol.toStringTag] = 'Arguments'; + t.notOk(isArguments(obj), 'object with faked toStringTag is not arguments'); + + var args = (function () { + return arguments; + }()); + args[Symbol.toStringTag] = 'Arguments'; + t.notOk(isArguments(obj), 'real arguments with faked toStringTag is not arguments'); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/is-callable/.editorconfig b/test/merkletreejs/node_modules/is-callable/.editorconfig new file mode 100644 index 0000000..f5f5679 --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/.editorconfig @@ -0,0 +1,31 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 +max_line_length = off + +[README.md] +indent_style = off +indent_size = off +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[coverage*/**/*] +indent_style = off +indent_size = off +max_line_length = off diff --git a/test/merkletreejs/node_modules/is-callable/.eslintrc b/test/merkletreejs/node_modules/is-callable/.eslintrc new file mode 100644 index 0000000..ce033bf --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-statements-per-line": [2, { "max": 2 }], + }, +} diff --git a/test/merkletreejs/node_modules/is-callable/.github/FUNDING.yml b/test/merkletreejs/node_modules/is-callable/.github/FUNDING.yml new file mode 100644 index 0000000..0fdebd0 --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-callable +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/is-callable/.nycrc b/test/merkletreejs/node_modules/is-callable/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/is-callable/CHANGELOG.md b/test/merkletreejs/node_modules/is-callable/CHANGELOG.md new file mode 100644 index 0000000..32788cd --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/CHANGELOG.md @@ -0,0 +1,158 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.7](https://github.com/inspect-js/is-callable/compare/v1.2.6...v1.2.7) - 2022-09-23 + +### Commits + +- [Fix] recognize `document.all` in IE 6-10 [`06c1db2`](https://github.com/inspect-js/is-callable/commit/06c1db2b9b2e0f28428e1293eb572f8f93871ec7) +- [Tests] improve logic for FF 20-35 [`0f7d9b9`](https://github.com/inspect-js/is-callable/commit/0f7d9b9c7fe149ca87e71f0a125ade251a6a578c) +- [Fix] handle `document.all` in FF 27 (and +, probably) [`696c661`](https://github.com/inspect-js/is-callable/commit/696c661b8c0810c2d05ab172f1607f4e77ddf81e) +- [Tests] fix proxy tests in FF 42-63 [`985df0d`](https://github.com/inspect-js/is-callable/commit/985df0dd36f8cfe6f1993657b7c0f4cfc19dae30) +- [readme] update tested browsers [`389e919`](https://github.com/inspect-js/is-callable/commit/389e919493b1cb2010126b0411e5291bf76169bd) +- [Fix] detect `document.all` in Opera 12.16 [`b9f1022`](https://github.com/inspect-js/is-callable/commit/b9f1022b3d7e466b7f09080bd64c253caf644325) +- [Fix] HTML elements: properly report as callable in Opera 12.16 [`17391fe`](https://github.com/inspect-js/is-callable/commit/17391fe02b895777c4337be28dca3b364b743b34) +- [Tests] fix inverted logic in FF3 test [`056ebd4`](https://github.com/inspect-js/is-callable/commit/056ebd48790f46ca18ff5b12f51b44c08ccc3595) + +## [v1.2.6](https://github.com/inspect-js/is-callable/compare/v1.2.5...v1.2.6) - 2022-09-14 + +### Commits + +- [Fix] work for `document.all` in Firefox 3 and IE 6-8 [`015132a`](https://github.com/inspect-js/is-callable/commit/015132aaef886ec777b5b3593ef4ce461dd0c7d4) +- [Test] skip function toString check for nullish values [`8698116`](https://github.com/inspect-js/is-callable/commit/8698116f95eb59df8b48ec8e4585fc1cdd8cae9f) +- [readme] add "supported engines" section [`0442207`](https://github.com/inspect-js/is-callable/commit/0442207a89a1554d41ba36daf21862ef7ccbd500) +- [Tests] skip one of the fixture objects in FF 3.6 [`a501141`](https://github.com/inspect-js/is-callable/commit/a5011410bc6edb276c6ec8b47ce5c5d83c4bee15) +- [Tests] allow `class` constructor tests to fail in FF v45 - v54, which has undetectable classes [`b12e4a4`](https://github.com/inspect-js/is-callable/commit/b12e4a4d8c438678bd7710f9f896680150766b51) +- [Fix] Safari 4: regexes should not be considered callable [`4b732ff`](https://github.com/inspect-js/is-callable/commit/4b732ffa34346db3f0193ea4e46b7d4e637e6c82) +- [Fix] properly recognize `document.all` in Safari 4 [`3193735`](https://github.com/inspect-js/is-callable/commit/319373525dc4603346661641840cd9a3e0613136) + +## [v1.2.5](https://github.com/inspect-js/is-callable/compare/v1.2.4...v1.2.5) - 2022-09-11 + +### Commits + +- [actions] reuse common workflows [`5bb4b32`](https://github.com/inspect-js/is-callable/commit/5bb4b32dc93987328ab4f396601f751c4a7abd62) +- [meta] better `eccheck` command [`b9bd597`](https://github.com/inspect-js/is-callable/commit/b9bd597322b6e3a24c74c09881ca73e1d9f9f485) +- [meta] use `npmignore` to autogenerate an npmignore file [`3192d38`](https://github.com/inspect-js/is-callable/commit/3192d38527c7fc461d05d5aa93d47628e658bc45) +- [Fix] for HTML constructors, always use `tryFunctionObject` even in pre-toStringTag browsers [`3076ea2`](https://github.com/inspect-js/is-callable/commit/3076ea21d1f6ecc1cb711dcf1da08f257892c72b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `available-typed-arrays`, `object-inspect`, `safe-publish-latest`, `tape` [`8986746`](https://github.com/inspect-js/is-callable/commit/89867464c42adc5cd375ee074a4574b0295442cb) +- [meta] add `auto-changelog` [`7dda9d0`](https://github.com/inspect-js/is-callable/commit/7dda9d04e670a69ae566c8fa596da4ff4371e615) +- [Fix] properly report `document.all` [`da90b2b`](https://github.com/inspect-js/is-callable/commit/da90b2b68dc4f33702c2e01ad07b4f89bcb60984) +- [actions] update codecov uploader [`c8f847c`](https://github.com/inspect-js/is-callable/commit/c8f847c90e04e54ff73c7cfae86e96e94990e324) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`899ae00`](https://github.com/inspect-js/is-callable/commit/899ae00b6abd10d81fc8bc7f02b345fd885d5f56) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-value-fixtures`, `object-inspect`, `tape` [`344e913`](https://github.com/inspect-js/is-callable/commit/344e913b149609bf741aa7345fa32dc0b90d8893) +- [meta] remove greenkeeper config [`737dce5`](https://github.com/inspect-js/is-callable/commit/737dce5590b1abb16183a63cb9d7d26920b3b394) +- [meta] npmignore coverage output [`680a883`](https://github.com/inspect-js/is-callable/commit/680a8839071bf36a419fe66e1ced7a3303c27b28) + + +1.2.4 / 2021-08-05 +================= + * [Fix] use `has-tostringtag` approach to behave correctly in the presence of symbol shams + * [readme] fix repo URLs + * [readme] add actions and codecov badges + * [readme] remove defunct badges + * [meta] ignore eclint checking coverage output + * [meta] use `prepublishOnly` script for npm 7+ + * [actions] use `node/install` instead of `node/run`; use `codecov` action + * [actions] remove unused workflow file + * [Tests] run `nyc` on all tests; use `tape` runner + * [Tests] use `available-typed-arrays`, `for-each`, `has-symbols`, `object-inspect` + * [Dev Deps] update `available-typed-arrays`, `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + +1.2.3 / 2021-01-31 +================= + * [Fix] `document.all` is callable (do not use `document.all`!) + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` + * [Tests] migrate tests to Github Actions + * [actions] add "Allow Edits" workflow + * [actions] switch Automatic Rebase workflow to `pull_request_target` event + +1.2.2 / 2020-09-21 +================= + * [Fix] include actual fix from 579179e + * [Dev Deps] update `eslint` + +1.2.1 / 2020-09-09 +================= + * [Fix] phantomjs‘ Reflect.apply does not throw properly on a bad array-like + * [Dev Deps] update `eslint`, `@ljharb/eslint-config` + * [meta] fix eclint error + +1.2.0 / 2020-06-02 +================= + * [New] use `Reflect.apply`‑based callability detection + * [readme] add install instructions (#55) + * [meta] only run `aud` on prod deps + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `make-arrow-function`, `make-generator-function`; add `aud`, `safe-publish-latest`, `make-async-function` + * [Tests] add tests for function proxies (#53, #25) + +1.1.5 / 2019-12-18 +================= + * [meta] remove unused Makefile and associated utilities + * [meta] add `funding` field; add FUNDING.yml + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape`, `covert`, `rimraf` + * [Tests] use shared travis configs + * [Tests] use `eccheck` over `editorconfig-tools` + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + * [Tests] remove `jscs` + * [actions] add automatic rebasing / merge commit blocking + +1.1.4 / 2018-07-02 +================= + * [Fix] improve `class` and arrow function detection (#30, #31) + * [Tests] on all latest node minors; improve matrix + * [Dev Deps] update all dev deps + +1.1.3 / 2016-02-27 +================= + * [Fix] ensure “class “ doesn’t screw up “class” detection + * [Tests] up to `node` `v5.7`, `v4.3` + * [Dev Deps] update to `eslint` v2, `@ljharb/eslint-config`, `jscs` + +1.1.2 / 2016-01-15 +================= + * [Fix] Make sure comments don’t screw up “class” detection (#4) + * [Tests] up to `node` `v5.3` + * [Tests] Add `parallelshell`, run both `--es-staging` and stock tests at once + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Refactor] convert `isNonES6ClassFn` into `isES6ClassFn` + +1.1.1 / 2015-11-30 +================= + * [Fix] do not throw when a non-function has a function in its [[Prototype]] (#2) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `semver` + * [Tests] up to `node` `v5.1` + * [Tests] no longer allow node 0.8 to fail. + * [Tests] fix npm upgrades in older nodes + +1.1.0 / 2015-10-02 +================= + * [Fix] Some browsers report TypedArray constructors as `typeof object` + * [New] return false for "class" constructors, when possible. + * [Tests] up to `io.js` `v3.3`, `node` `v4.1` + * [Dev Deps] update `eslint`, `editorconfig-tools`, `nsp`, `tape`, `semver`, `jscs`, `covert`, `make-arrow-function` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + +1.0.4 / 2015-01-30 +================= + * If @@toStringTag is not present, use the old-school Object#toString test. + +1.0.3 / 2015-01-29 +================= + * Add tests to ensure arrow functions are callable. + * Refactor to aid optimization of non-try/catch code. + +1.0.2 / 2015-01-29 +================= + * Fix broken package.json + +1.0.1 / 2015-01-29 +================= + * Add early exit for typeof not "function" + +1.0.0 / 2015-01-29 +================= + * Initial release. diff --git a/test/merkletreejs/node_modules/is-callable/LICENSE b/test/merkletreejs/node_modules/is-callable/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +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. + diff --git a/test/merkletreejs/node_modules/is-callable/README.md b/test/merkletreejs/node_modules/is-callable/README.md new file mode 100644 index 0000000..4f2b6d6 --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/README.md @@ -0,0 +1,83 @@ +# is-callable [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag. + +## Supported engines +Automatically tested in every minor version of node. + +Manually tested in: + - Safari: v4 - v15 (4, 5, 5.1, 6.0.5, 6.2, 7.1, 8, 9.1.3, 10.1.2, 11.1.2, 12.1, 13.1.2, 14.1.2, 15.3, 15.6.1) + - Note: Safari 9 has `class`, but `Function.prototype.toString` hides that progeny and makes them look like functions, so `class` constructors will be reported by this package as callable, when they are not in fact callable. + - Chrome: v15 - v81, v83 - v106(every integer version) + - Note: This includes Edge v80+ and Opera v15+, which matches Chrome + - Firefox: v3, v3.6, v4 - v105 (every integer version) + - Note: v45 - v54 has `class`, but `Function.prototype.toString` hides that progeny and makes them look like functions, so `class` constructors will be reported by this package as callable, when they are not in fact callable. + - Note: in v42 - v63, `Function.prototype.toString` throws on HTML element constructors, or a Proxy to a function + - Note: in v20 - v35, HTML element constructors are not callable, despite having typeof `function`. + - Note: in v19, `document.all` is not callable. + - IE: v6 - v11(every integer version + - Opera: v11.1, v11.5, v11.6, v12.1, v12.14, v12.15, v12.16, v15+ v15+ matches Chrome + +## Example + +```js +var isCallable = require('is-callable'); +var assert = require('assert'); + +assert.notOk(isCallable(undefined)); +assert.notOk(isCallable(null)); +assert.notOk(isCallable(false)); +assert.notOk(isCallable(true)); +assert.notOk(isCallable([])); +assert.notOk(isCallable({})); +assert.notOk(isCallable(/a/g)); +assert.notOk(isCallable(new RegExp('a', 'g'))); +assert.notOk(isCallable(new Date())); +assert.notOk(isCallable(42)); +assert.notOk(isCallable(NaN)); +assert.notOk(isCallable(Infinity)); +assert.notOk(isCallable(new Number(42))); +assert.notOk(isCallable('foo')); +assert.notOk(isCallable(Object('foo'))); + +assert.ok(isCallable(function () {})); +assert.ok(isCallable(function* () {})); +assert.ok(isCallable(x => x * x)); +``` + +## Install + +Install with + +``` +npm install is-callable +``` + +## Tests + +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-callable +[2]: https://versionbadg.es/inspect-js/is-callable.svg +[5]: https://david-dm.org/inspect-js/is-callable.svg +[6]: https://david-dm.org/inspect-js/is-callable +[7]: https://david-dm.org/inspect-js/is-callable/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-callable#info=devDependencies +[11]: https://nodei.co/npm/is-callable.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-callable.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-callable.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-callable +[codecov-image]: https://codecov.io/gh/inspect-js/is-callable/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-callable/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-callable +[actions-url]: https://github.com/inspect-js/is-callable/actions diff --git a/test/merkletreejs/node_modules/is-callable/index.js b/test/merkletreejs/node_modules/is-callable/index.js new file mode 100644 index 0000000..f2a89f8 --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/index.js @@ -0,0 +1,101 @@ +'use strict'; + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; diff --git a/test/merkletreejs/node_modules/is-callable/package.json b/test/merkletreejs/node_modules/is-callable/package.json new file mode 100644 index 0000000..aa3e8df --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/package.json @@ -0,0 +1,106 @@ +{ + "name": "is-callable", + "version": "1.2.7", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only --", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs ." + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-callable.git" + }, + "keywords": [ + "Function", + "function", + "callable", + "generator", + "generator function", + "arrow", + "arrow function", + "ES6", + "toStringTag", + "@@toStringTag" + ], + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "available-typed-arrays": "^1.0.5", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "has-tostringtag": "^1.0.0", + "make-arrow-function": "^1.2.0", + "make-async-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.2", + "rimraf": "^2.7.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "v1.2.5" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/is-callable/test/index.js b/test/merkletreejs/node_modules/is-callable/test/index.js new file mode 100644 index 0000000..bfe5db5 --- /dev/null +++ b/test/merkletreejs/node_modules/is-callable/test/index.js @@ -0,0 +1,244 @@ +'use strict'; + +/* eslint no-magic-numbers: 1 */ + +var test = require('tape'); +var isCallable = require('../'); +var hasToStringTag = require('has-tostringtag/shams')(); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var typedArrayNames = require('available-typed-arrays')(); +var generators = require('make-generator-function')(); +var arrows = require('make-arrow-function').list(); +var asyncs = require('make-async-function').list(); +var weirdlyCommentedArrowFn; +try { + /* eslint-disable no-new-func */ + weirdlyCommentedArrowFn = Function('return cl/*/**/=>/**/ass - 1;')(); + /* eslint-enable no-new-func */ +} catch (e) { /**/ } + +var isIE68 = !(0 in [undefined]); +var isFirefox = typeof window !== 'undefined' && ('netscape' in window) && (/ rv:/).test(navigator.userAgent); +var fnToStringCoerces; +try { + Function.prototype.toString.call(v.uncoercibleFnObject); + fnToStringCoerces = true; +} catch (e) { + fnToStringCoerces = false; +} + +var noop = function () {}; +var classFake = function classFake() { }; // eslint-disable-line func-name-matching +var returnClass = function () { return ' class '; }; +var return3 = function () { return 3; }; +/* for coverage */ +noop(); +classFake(); +returnClass(); +return3(); +/* end for coverage */ + +var proxy; +if (typeof Proxy === 'function') { + try { + proxy = new Proxy(function () {}, {}); + // for coverage + proxy(); + String(proxy); + } catch (_) { + // Older engines throw a `TypeError` when `Function.prototype.toString` is called on a Proxy object. + proxy = null; + } +} + +var invokeFunction = function invokeFunctionString(str) { + var result; + try { + /* eslint-disable no-new-func */ + var fn = Function(str); + /* eslint-enable no-new-func */ + result = fn(); + } catch (e) {} + return result; +}; + +var classConstructor = invokeFunction('"use strict"; return class Foo {}'); +var hasDetectableClasses = classConstructor && Function.prototype.toString.call(classConstructor) === 'class Foo {}'; + +var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}'); +var commentedClassOneLine = invokeFunction('"use strict"; return class/**/A{}'); +var classAnonymous = invokeFunction('"use strict"; return class{}'); +var classAnonymousCommentedOneLine = invokeFunction('"use strict"; return class/*/*/{}'); + +test('not callables', function (t) { + t.notOk(isCallable(), 'implicit undefined is not callable'); + + forEach(v.nonFunctions.concat([ + Object(42), + Object('foo'), + NaN, + [], + /a/g, + new RegExp('a', 'g'), + new Date() + ]), function (nonFunction) { + if (fnToStringCoerces && nonFunction === v.coercibleFnObject) { + t.comment('FF 3.6 has a Function toString that coerces its receiver, so this test is skipped'); + return; + } + if (nonFunction != null) { // eslint-disable-line eqeqeq + if (isFirefox) { + // Firefox 3 throws some kind of *object* here instead of a proper error + t['throws']( + function () { Function.prototype.toString.call(nonFunction); }, + inspect(nonFunction) + ' can not be used with Function toString' + ); + } else { + t['throws']( + function () { Function.prototype.toString.call(nonFunction); }, + TypeError, + inspect(nonFunction) + ' can not be used with Function toString' + ); + } + } + t.equal(isCallable(nonFunction), false, inspect(nonFunction) + ' is not callable'); + }); + + t.test('non-function with function in its [[Prototype]] chain', function (st) { + var Foo = function Bar() {}; + Foo.prototype = noop; + st.equal(isCallable(Foo), true, 'sanity check: Foo is callable'); + st.equal(isCallable(new Foo()), false, 'instance of Foo is not callable'); + st.end(); + }); + + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var fakeFunction = { + toString: function () { return String(return3); }, + valueOf: return3 + }; + fakeFunction[Symbol.toStringTag] = 'Function'; + t.equal(String(fakeFunction), String(return3)); + t.equal(Number(fakeFunction), return3()); + t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable'); + t.end(); +}); + +test('Functions', function (t) { + t.ok(isCallable(noop), 'function is callable'); + t.ok(isCallable(classFake), 'function with name containing "class" is callable'); + t.ok(isCallable(returnClass), 'function with string " class " is callable'); + t.ok(isCallable(isCallable), 'isCallable is callable'); + t.end(); +}); + +test('Typed Arrays', { skip: typedArrayNames.length === 0 }, function (st) { + forEach(typedArrayNames, function (typedArray) { + st.ok(isCallable(global[typedArray]), typedArray + ' is callable'); + }); + st.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.ok(isCallable(genFn), 'generator function ' + genFn + ' is callable'); + }); + t.end(); +}); + +test('Arrow functions', { skip: arrows.length === 0 }, function (t) { + forEach(arrows, function (arrowFn) { + t.ok(isCallable(arrowFn), 'arrow function ' + arrowFn + ' is callable'); + }); + t.ok(isCallable(weirdlyCommentedArrowFn), 'weirdly commented arrow functions are callable'); + t.end(); +}); + +test('"Class" constructors', { + skip: !classConstructor || !commentedClass || !commentedClassOneLine || !classAnonymous, todo: !hasDetectableClasses +}, function (t) { + if (!hasDetectableClasses) { + t.comment('WARNING: This engine does not support detectable classes'); + } + t.notOk(isCallable(classConstructor), 'class constructors are not callable'); + t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable'); + t.notOk(isCallable(commentedClassOneLine), 'one-line class constructors with comments in the signature are not callable'); + t.notOk(isCallable(classAnonymous), 'anonymous class constructors are not callable'); + t.notOk(isCallable(classAnonymousCommentedOneLine), 'anonymous one-line class constructors with comments in the signature are not callable'); + t.end(); +}); + +test('`async function`s', { skip: asyncs.length === 0 }, function (t) { + forEach(asyncs, function (asyncFn) { + t.ok(isCallable(asyncFn), '`async function` ' + asyncFn + ' is callable'); + }); + t.end(); +}); + +test('proxies of functions', { skip: !proxy }, function (t) { + t.equal(isCallable(proxy), true, 'proxies of functions are callable'); + t.end(); +}); + +test('throwing functions', function (t) { + t.plan(1); + + var thrower = function (a) { return a.b; }; + t.ok(isCallable(thrower), 'a function that throws is callable'); +}); + +test('DOM', function (t) { + /* eslint-env browser */ + + t.test('document.all', { skip: typeof document !== 'object' }, function (st) { + st.notOk(isCallable(document), 'document is not callable'); + + var all = document.all; + var isFF3 = !isIE68 && Object.prototype.toString(all) === Object.prototype.toString.call(document.all); // this test is true in IE 6-8 also + var expected = false; + if (!isFF3) { + try { + expected = document.all('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + st.equal(isCallable(document.all), expected, 'document.all is ' + (isFF3 ? 'not ' : '') + 'callable'); + + st.end(); + }); + + forEach([ + 'HTMLElement', + 'HTMLAnchorElement' + ], function (name) { + var constructor = global[name]; + + t.test(name, { skip: !constructor }, function (st) { + st.match(typeof constructor, /^(?:function|object)$/, name + ' is a function or object'); + + var callable = isCallable(constructor); + st.equal(typeof callable, 'boolean'); + + if (callable) { + st.doesNotThrow( + function () { Function.prototype.toString.call(constructor); }, + 'anything this library claims is callable should be accepted by Function toString' + ); + } else { + st['throws']( + function () { Function.prototype.toString.call(constructor); }, + TypeError, + 'anything this library claims is not callable should not be accepted by Function toString' + ); + } + + st.end(); + }); + }); + + t.end(); +}); diff --git a/test/merkletreejs/node_modules/is-generator-function/.eslintignore b/test/merkletreejs/node_modules/is-generator-function/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/test/merkletreejs/node_modules/is-generator-function/.eslintrc b/test/merkletreejs/node_modules/is-generator-function/.eslintrc new file mode 100644 index 0000000..d7f41a5 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "no-new-func": 1 + }, +} diff --git a/test/merkletreejs/node_modules/is-generator-function/.nvmrc b/test/merkletreejs/node_modules/is-generator-function/.nvmrc new file mode 100644 index 0000000..64f5a0a --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/.nvmrc @@ -0,0 +1 @@ +node diff --git a/test/merkletreejs/node_modules/is-generator-function/.nycrc b/test/merkletreejs/node_modules/is-generator-function/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/is-generator-function/CHANGELOG.md b/test/merkletreejs/node_modules/is-generator-function/CHANGELOG.md new file mode 100644 index 0000000..25b705c --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/CHANGELOG.md @@ -0,0 +1,216 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.10](https://github.com/inspect-js/is-generator-function/compare/v1.0.9...v1.0.10) - 2021-08-05 + +### Commits + +- [Dev Deps] update `eslint`, `auto-changelog`, `core-js`, `tape` [`63cd935`](https://github.com/inspect-js/is-generator-function/commit/63cd9353eead5ad5eb8cf581fc4129841641bb43) +- [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams [`8c3fe76`](https://github.com/inspect-js/is-generator-function/commit/8c3fe76b546fbc5085381df65800e4fc67e25ede) +- [Dev Deps] unpin `core-js` v3 [`ebf2885`](https://github.com/inspect-js/is-generator-function/commit/ebf2885bc202b59f37e074f28951639873c6f38e) + +## [v1.0.9](https://github.com/inspect-js/is-generator-function/compare/v1.0.8...v1.0.9) - 2021-05-05 + +### Fixed + +- [Fix] avoid calling `Function` until absolutely necessary [`#41`](https://github.com/inspect-js/is-generator-function/issues/41) + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`612862b`](https://github.com/inspect-js/is-generator-function/commit/612862b5fefc2dc1c7e1f5e7478563a5b53f7b23) +- [meta] do not publish github action workflow files [`c13855d`](https://github.com/inspect-js/is-generator-function/commit/c13855dc11947589ed7314840a9cc5ae04db90f4) +- [readme] fix repo URLs; remove travis badge [`bd11a2a`](https://github.com/inspect-js/is-generator-function/commit/bd11a2af1b644cfa352346dcbf6f4cec48b00b78) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`23f54d4`](https://github.com/inspect-js/is-generator-function/commit/23f54d49da035c1ca79227faee9bacfde2d46884) +- [readme] add actions and codecov badges [`9e759ef`](https://github.com/inspect-js/is-generator-function/commit/9e759ef8e8f098fe1fa3cd9cca98f79f9e8b8b22) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`6305f8d`](https://github.com/inspect-js/is-generator-function/commit/6305f8d71ccfa4656bdd280c2616e88fc5ca184b) +- [meta] remove explicit audit level config [`db4391c`](https://github.com/inspect-js/is-generator-function/commit/db4391c68cf8162245d32734685be7c73c2f03c7) +- [meta] use `prepublishOnly` script for npm 7+ [`82c5b18`](https://github.com/inspect-js/is-generator-function/commit/82c5b183a605f1d25af15ec8242c8a8f88a26bfa) +- [Dev Deps] pin `core-js` v3 to < v3.9 [`5f6cc2a`](https://github.com/inspect-js/is-generator-function/commit/5f6cc2ac94a65d7d592775bac6dce573220ccea2) +- [Tests] avoid running harmony tests on node 16+ [`c41526b`](https://github.com/inspect-js/is-generator-function/commit/c41526b8cd1d376f9ca73b56a5ee076db0f9f1c1) +- [actions] update workflows [`a348c5d`](https://github.com/inspect-js/is-generator-function/commit/a348c5d6d4b06041ae0ece9f3765dc13ec9df354) + +## [v1.0.8](https://github.com/inspect-js/is-generator-function/compare/v1.0.7...v1.0.8) - 2020-12-02 + +### Fixed + +- [Refactor] improve performance in non-toStringTag envs [`#9`](https://github.com/inspect-js/is-generator-function/issues/9) + +### Commits + +- [Tests] use shared travis-ci configs [`98c84ec`](https://github.com/inspect-js/is-generator-function/commit/98c84ecd38d7d64b2aa070fa2c240be4373be131) +- [Tests] migrate tests to Github Actions [`52ea2e2`](https://github.com/inspect-js/is-generator-function/commit/52ea2e2e14da2278c7844a18af4aaef1cc8bb3bb) +- [meta] add `auto-changelog` [`a31c8d9`](https://github.com/inspect-js/is-generator-function/commit/a31c8d9e8fe4f397e1f8da5b1297050542cd00c3) +- [Tests] remove `jscs` [`c30694e`](https://github.com/inspect-js/is-generator-function/commit/c30694e5e1739a37c455b8bfae4cc7c4347292de) +- [meta] remove unused Makefile and associated utilities [`23a8dd7`](https://github.com/inspect-js/is-generator-function/commit/23a8dd75ea554642aadb1313c1cbbd11fe69eb1d) +- [Tests] up to `node` `v11.4`, `v10.14`, `v8.14`, `v6.15` [`9711495`](https://github.com/inspect-js/is-generator-function/commit/9711495e58fa9477167d7dbc582749981c3f5ee5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `make-generator-function`; add `safe-publish-latest` [`3afb4d0`](https://github.com/inspect-js/is-generator-function/commit/3afb4d033587eeddfd2dc840ff98c10f3abea48e) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`f1e9b0f`](https://github.com/inspect-js/is-generator-function/commit/f1e9b0f150e77357ecd4afac5873a3bd3ada7b02) +- [Tests] up to `node` `v11.13`, `v10.15`, `v8.15`, `v6.17` [`433ca64`](https://github.com/inspect-js/is-generator-function/commit/433ca64d5500371516598bebb19fc00370e7c9c7) +- [Tests] run `nyc` on all tests [`84d8e18`](https://github.com/inspect-js/is-generator-function/commit/84d8e18c441c4c181e51a339559040f95adc4d94) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ec51a9f`](https://github.com/inspect-js/is-generator-function/commit/ec51a9f2e6f5da5ae5e8b446e0112eeaa0853954) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape` [`180fb0d`](https://github.com/inspect-js/is-generator-function/commit/180fb0dbd1a9d6975344d2deb4338c9071e865b1) +- [actions] add automatic rebasing / merge commit blocking [`7e0f94b`](https://github.com/inspect-js/is-generator-function/commit/7e0f94b055308abc8469e526980991a12a87cfaf) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `replace`, `semver`, `core-js` [`75768b3`](https://github.com/inspect-js/is-generator-function/commit/75768b30b7d4c92231ed53ec72d2f4ae81274d4c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `replace`, `semver`, `tape` [`d6413cd`](https://github.com/inspect-js/is-generator-function/commit/d6413cd0bfc27c924619200efe39d9956d6fb638) +- [actions] add "Allow Edits" workflow [`e73fec7`](https://github.com/inspect-js/is-generator-function/commit/e73fec71e5d1c99246a6f905091e133860931245) +- [Dev Deps] update `core-js`, `eslint`, `nsp`, `semver`, `tape` [`6746c73`](https://github.com/inspect-js/is-generator-function/commit/6746c733fa535f724700726356a9156d491b54ae) +- [Tests] switch from `nsp` to `npm audit`; allow it to fail for now [`301aa25`](https://github.com/inspect-js/is-generator-function/commit/301aa2557b4b99962a0e48191c4719c5a95eb69b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`d978937`](https://github.com/inspect-js/is-generator-function/commit/d978937e3c86b3e239e0ceecc2324134806e0a32) +- Revert "[Refactor] improve performance in non-toStringTag envs" [`3892c18`](https://github.com/inspect-js/is-generator-function/commit/3892c18f95a8b5ea57f9893e6d8dce89fec4af30) +- [Tests] test on both core-js 3 and 2 [`fac5447`](https://github.com/inspect-js/is-generator-function/commit/fac54476693d1b8573cbd36bc3c6eb74cbeb7468) +- [Tests] use `npx aud` instead of `npm audit` with hoops [`e12897f`](https://github.com/inspect-js/is-generator-function/commit/e12897feae0185f89592dfe1a02a2a4520180313) +- [meta] add `funding` field [`60711d1`](https://github.com/inspect-js/is-generator-function/commit/60711d122a4ef7ab6a9bee6044a26352ba7f86bd) +- [Fix] `Object.getPrototypeOf` does not exist in all engines [`7484531`](https://github.com/inspect-js/is-generator-function/commit/7484531c55a61fdb7e8d819ce9aa363f29b2c704) +- [Dev Deps] update `auto-changelog`, `tape` [`fe92b74`](https://github.com/inspect-js/is-generator-function/commit/fe92b743baaf206e3ee849c551171f0a56b7fa23) +- [Dev Deps] update `eslint`, `tape` [`2f16f77`](https://github.com/inspect-js/is-generator-function/commit/2f16f77aae4c9aafe65fb29854f46b783d853c58) +- [Dev Deps] update `core-js`, `replace` [`c67825a`](https://github.com/inspect-js/is-generator-function/commit/c67825a62b7bad7911a1bdb5af237d86229aa4bc) +- [Tests] on `node` `v10.1` [`b00dbcc`](https://github.com/inspect-js/is-generator-function/commit/b00dbcce7a9f6df4fb35e99fac79560389a9a272) +- [actions] update rebase action to use checkout v2 [`85c7947`](https://github.com/inspect-js/is-generator-function/commit/85c7947d7474468a5e6dd30b00f632e43f45c21d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`d2fd827`](https://github.com/inspect-js/is-generator-function/commit/d2fd827cf87a90d647d93185f6d5e332fb7b1bb4) +- [Dev Deps] update `@ljharb/eslint-config` [`791766e`](https://github.com/inspect-js/is-generator-function/commit/791766e4f12a96d3b9949128f813dadd428d0891) + +## [v1.0.7](https://github.com/inspect-js/is-generator-function/compare/v1.0.6...v1.0.7) - 2017-12-27 + +### Fixed + +- [Tests] run tests with uglify-register [`#16`](https://github.com/inspect-js/is-generator-function/issues/16) +- Exclude `testling.html` from npm package. [`#8`](https://github.com/inspect-js/is-generator-function/issues/8) + +### Commits + +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node; remove osx builds [`365004b`](https://github.com/inspect-js/is-generator-function/commit/365004b20b302dceb7bd2cee91814f0a55ae3253) +- [Tests] up to `node` `v9.2`, `v8.9`, `v6.12`; pin included builds to LTS [`33916ea`](https://github.com/inspect-js/is-generator-function/commit/33916eadddccf2a39c8cf0160f82c9a5d4a20ecb) +- [Dev Deps] update `core-js`, `eslint`, `nsp` [`b4ce014`](https://github.com/inspect-js/is-generator-function/commit/b4ce0144a8b56fc3089b96f1b8818c6e793e552f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `nsp`, `semver`, `tape` [`e4b499f`](https://github.com/inspect-js/is-generator-function/commit/e4b499fbe2e5e24593eb25bd63dfc2a1520aaa04) +- [Tests] up to `node` `v7.4`, `v4.7` [`ce642b6`](https://github.com/inspect-js/is-generator-function/commit/ce642b63f0f9c4f56ca3daefbf8b0d4cbda8c0a4) +- Only apps should have lockfiles. [`ea4dfb1`](https://github.com/inspect-js/is-generator-function/commit/ea4dfb15554de3a22656415cda985ceaf449be00) +- [Tests] on `node` `v9.3` [`307d9c1`](https://github.com/inspect-js/is-generator-function/commit/307d9c144fed8a4aec412d3e9ccc117d1c08e167) +- fix: example code missing ) after argument list [`05f62c7`](https://github.com/inspect-js/is-generator-function/commit/05f62c712a9ca08b0efcabe883affd7c0734f51c) +- [Tests] update `uglify-register` [`7376bec`](https://github.com/inspect-js/is-generator-function/commit/7376bec6c3c8ee16cf16feb285798be23e6c2c89) +- [Dev Deps] update `eslint` [`c3f5895`](https://github.com/inspect-js/is-generator-function/commit/c3f58952033c93918aa5b5ac527520b26c2460f8) + +## [v1.0.6](https://github.com/inspect-js/is-generator-function/compare/v1.0.5...v1.0.6) - 2016-12-20 + +### Fixed + +- [Fix] fix `is-generator-function` in an env without native generators, with core-js. [`#33`](https://github.com/ljharb/is-equal/issues/33) + +### Commits + +- [Tests] fix linting errors. [`9d12cdb`](https://github.com/inspect-js/is-generator-function/commit/9d12cdb4bb43c63801173635a7db92ced8f720d8) + +## [v1.0.5](https://github.com/inspect-js/is-generator-function/compare/v1.0.4...v1.0.5) - 2016-12-19 + +### Commits + +- Update `tape`, `semver`, `eslint`; use my personal shared `eslint` config. [`3a1192c`](https://github.com/inspect-js/is-generator-function/commit/3a1192cbf25ee5a1ca64e64c20d169c643ceb860) +- Add `npm run eslint` [`ae191b6`](https://github.com/inspect-js/is-generator-function/commit/ae191b61d3ec65de63bcd7b2c1ab08f2f9a94ead) +- [Tests] improve test matrix [`0d0837f`](https://github.com/inspect-js/is-generator-function/commit/0d0837fe00bed00ced94ef5a7bfdbd7e8e295656) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config`, `semver`, `nsp` [`6523655`](https://github.com/inspect-js/is-generator-function/commit/652365556b5f8eea69b4612a183b5026c952e776) +- Update `jscs`, `tape`, `semver` [`c185388`](https://github.com/inspect-js/is-generator-function/commit/c185388111ee6c0df1498a76d9c565167b5d20cd) +- Update `eslint` [`9959dbc`](https://github.com/inspect-js/is-generator-function/commit/9959dbc1450214658dc4789574b68de826ec33a7) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`5945497`](https://github.com/inspect-js/is-generator-function/commit/5945497bc564655ed5ea1bb6f12610a9afc33a33) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`1754eae`](https://github.com/inspect-js/is-generator-function/commit/1754eaec79e43835bd154c81fba064b558f7ad1b) +- Update `eslint`, `semver`, `nsp` [`a40f7af`](https://github.com/inspect-js/is-generator-function/commit/a40f7afab3f6ba43193e5464faf51692f6f2199d) +- Update `covert`, `jscs`, `eslint`, `semver` [`f7c3504`](https://github.com/inspect-js/is-generator-function/commit/f7c35049406adc784b23b6b0fbfdd34b4ca8c183) +- [Fix] account for Safari 10 which reports the wrong toString on generator functions. [`3a3a52b`](https://github.com/inspect-js/is-generator-function/commit/3a3a52bdba46e03ae333af9519bf471207bf6cec) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config`, `semver`, `nsp` [`aaab6c3`](https://github.com/inspect-js/is-generator-function/commit/aaab6c3a331c8c8793f8f43aa1d452cc12b92c0d) +- [Dev Deps] update `jscs` [`e24641c`](https://github.com/inspect-js/is-generator-function/commit/e24641ca69ae3ee232837e9153c8b43b046cfe69) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`c43c5ad`](https://github.com/inspect-js/is-generator-function/commit/c43c5ade8b3b62fa27fac3e5104ab3df93278878) +- Add `npm run security` via `nsp` [`24256ca`](https://github.com/inspect-js/is-generator-function/commit/24256ca5f5308930e86c3dc75b70bbfe1033e9b6) +- Test up to `io.js` `v2.3` [`730233f`](https://github.com/inspect-js/is-generator-function/commit/730233f0ca376887c698c01799b60ee54424bf9f) +- [Tests] use pretest/posttest for linting/security [`3e6b860`](https://github.com/inspect-js/is-generator-function/commit/3e6b8603453e4d127cd1acef720f1ce214d8f69a) +- [Refactor] remove useless `Object#toString` check. [`9d4d7ac`](https://github.com/inspect-js/is-generator-function/commit/9d4d7ac23f6f2f75098903b4fe4f74e1d39a2226) +- [Dev Deps] Update `tape`, `eslint` [`34673b8`](https://github.com/inspect-js/is-generator-function/commit/34673b86aecddf149284bd8bbca5ab54e6e59694) +- Test up to `io.js` `v2.1` [`1e91585`](https://github.com/inspect-js/is-generator-function/commit/1e915850246cbd691606567850f35665a650e490) +- Test on two latest `io.js` versions. [`8702608`](https://github.com/inspect-js/is-generator-function/commit/87026087a1e3b43ba9f8dc7a5b6c2b58d572ff25) +- Test on `iojs-v1.5` and `iojs-v1.6` [`c74935e`](https://github.com/inspect-js/is-generator-function/commit/c74935ec9c187e9640f862607873aa096ddcf9fc) +- Latest `node` now supports generators. [`beb3bfe`](https://github.com/inspect-js/is-generator-function/commit/beb3bfe3d425cc0ece9a02e286727e36d53f5050) +- [Dev Deps] update `tape` [`c6e6587`](https://github.com/inspect-js/is-generator-function/commit/c6e658765c94b9edc282848f13e7bce882711c8c) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`0039875`](https://github.com/inspect-js/is-generator-function/commit/0039875e6c587255470088c7867cfa314713626b) +- Test on `io.js` `v2.5` [`0017408`](https://github.com/inspect-js/is-generator-function/commit/001740801d2a29f9a25a8824b064286910601e8c) +- Test on `io.js` `v2.4` [`bc013e2`](https://github.com/inspect-js/is-generator-function/commit/bc013e20b99a89b3f592038196d69f871b39caf0) +- Test on `io.js` `v3.0` [`e195030`](https://github.com/inspect-js/is-generator-function/commit/e1950306f4e0a107101e9aeae89cfac2c18e33de) + +## [v1.0.4](https://github.com/inspect-js/is-generator-function/compare/v1.0.3...v1.0.4) - 2015-03-03 + +### Fixed + +- Add support for detecting concise generator methods. [`#2`](https://github.com/inspect-js/is-generator-function/issues/2) + +### Commits + +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`6562e80`](https://github.com/inspect-js/is-generator-function/commit/6562e8015cf318056522a39d7a8e6ad121f9cf4c) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`592f768`](https://github.com/inspect-js/is-generator-function/commit/592f76853bcc5b46351d8842df7fd1483214d870) +- Test on latest `io.js` [`edca329`](https://github.com/inspect-js/is-generator-function/commit/edca329a4b3ddc19b5ac9491f7678240a73f4e0b) +- Forgot to add `replace` in 209fac444b4bd90eaa8df279457c4a15e6bba6d2 [`3ebfb38`](https://github.com/inspect-js/is-generator-function/commit/3ebfb380c73e29447689f0924248a5c801260371) +- Update `semver` [`c21baa5`](https://github.com/inspect-js/is-generator-function/commit/c21baa5acfe51e6bbe324c13ce5d4b6770ecfb27) +- Update `jscs` [`71a68f4`](https://github.com/inspect-js/is-generator-function/commit/71a68f47044af23ed2cd819d122202a59c2e6967) +- Update `tape` [`32c03cf`](https://github.com/inspect-js/is-generator-function/commit/32c03cf5701634f47c8d47fc383c97365adb3bb3) + +## [v1.0.3](https://github.com/inspect-js/is-generator-function/compare/v1.0.2...v1.0.3) - 2015-01-31 + +### Commits + +- `make release` [`209fac4`](https://github.com/inspect-js/is-generator-function/commit/209fac444b4bd90eaa8df279457c4a15e6bba6d2) +- Run tests against a faked @@toStringTag [`c9ba1ea`](https://github.com/inspect-js/is-generator-function/commit/c9ba1ea8163bd2e7a0f537da8fbaead0efa96a24) +- Add `sudo: false` to speed up travis-ci tests. [`a4b41e1`](https://github.com/inspect-js/is-generator-function/commit/a4b41e1b9c3856c671922f64bf5b7b41eb9ec0d6) +- Bail out early when typeof is not "function" [`a62e7a5`](https://github.com/inspect-js/is-generator-function/commit/a62e7a547307f5ba62a39e374f2cc2f46705eabc) + +## [v1.0.2](https://github.com/inspect-js/is-generator-function/compare/v1.0.1...v1.0.2) - 2015-01-20 + +### Commits + +- Update `tape`, `jscs` [`354d343`](https://github.com/inspect-js/is-generator-function/commit/354d3437426c274221ad21a2a580e9f31bfb07e3) +- Update `jscs` [`e0b6203`](https://github.com/inspect-js/is-generator-function/commit/e0b620323be47b3925fe3cd660c063a06cfde4aa) +- Fix tests in newer v8 (and io.js) [`36f0545`](https://github.com/inspect-js/is-generator-function/commit/36f054590d4f5fa994af5f2e7d592840bf9f9d27) + +## [v1.0.1](https://github.com/inspect-js/is-generator-function/compare/v1.0.0...v1.0.1) - 2014-12-14 + +### Commits + +- Use my standard jscs.json file. [`7624ca3`](https://github.com/inspect-js/is-generator-function/commit/7624ca3053cacec69d9a58e40c54e6635d8f980b) +- Use `make-generator-function` instead of a local module. [`9234a57`](https://github.com/inspect-js/is-generator-function/commit/9234a5771a3237baf3fe609540e74ce982fe6932) +- Adding license and downloads badges [`9463b6a`](https://github.com/inspect-js/is-generator-function/commit/9463b6a0c6bf254e213a2f5306f37e9849c8bb1a) +- Using single quotes exclusively. [`4b4d71f`](https://github.com/inspect-js/is-generator-function/commit/4b4d71f9e0d3753b6f2bd764ae910601352ff19e) +- Use SVG badges instead of PNG [`eaaaf41`](https://github.com/inspect-js/is-generator-function/commit/eaaaf41900c2e69c801062e8c7bb247bd3d2e402) +- Updating jscs. [`780758e`](https://github.com/inspect-js/is-generator-function/commit/780758ef1ae5e6a7a422fc8e3ac1265f53e33135) +- Update `tape`, `jscs` [`6b8f959`](https://github.com/inspect-js/is-generator-function/commit/6b8f95928274d770e9b66359e38c982a2b161e74) +- Update `tape`, `jscs` [`6e1334d`](https://github.com/inspect-js/is-generator-function/commit/6e1334d12899bed116ab3c4e82994fdfc8f8c279) +- Lock covert to v1.0.0. [`3dd5c74`](https://github.com/inspect-js/is-generator-function/commit/3dd5c74921a59481d5a699444a879ef0f80ef7c5) +- Updating `tape` [`99f61a3`](https://github.com/inspect-js/is-generator-function/commit/99f61a30692b7c00d06a6d29ac3022b242d4f1d4) +- Updating jscs [`171d96d`](https://github.com/inspect-js/is-generator-function/commit/171d96deef2bff8a840b0ef9563ad9366c8fcd98) +- Updating jscs [`847795e`](https://github.com/inspect-js/is-generator-function/commit/847795e9f951f5d28195f0bdb85ec26b427d2d33) +- Updating jscs [`cad09d8`](https://github.com/inspect-js/is-generator-function/commit/cad09d88873f2595545977f0ce9ed8ccde78b625) +- Updating covert [`8617860`](https://github.com/inspect-js/is-generator-function/commit/86178604dccea5b73ad2b386b275657366735529) +- Adding an .nvmrc file. [`1fa3ea4`](https://github.com/inspect-js/is-generator-function/commit/1fa3ea4f04139fdc28e2c0e553efd917be1f5744) + +## [v1.0.0](https://github.com/inspect-js/is-generator-function/compare/v0.0.0...v1.0.0) - 2014-08-09 + +### Commits + +- Adding `npm run lint` [`ed9cf0a`](https://github.com/inspect-js/is-generator-function/commit/ed9cf0a240ae8b3c4bf682e5ff37757d9eb6cffc) +- Make sure old and unstable nodes don't break Travis [`80a7ee7`](https://github.com/inspect-js/is-generator-function/commit/80a7ee782dc832869bccf857213ef76685303738) +- Updating tape [`d5f141f`](https://github.com/inspect-js/is-generator-function/commit/d5f141f0017aefb003911a1eb9c9b615069f1cf0) +- Fix npm upgrading on node 0.8 [`2ee0f08`](https://github.com/inspect-js/is-generator-function/commit/2ee0f08a56f493fb5d4299c7bda9cd52c41a98a2) +- Updating dependencies [`accf688`](https://github.com/inspect-js/is-generator-function/commit/accf688e8c20f05d0f24c1ff8efdaa24def0882c) +- Updating covert [`38d22e6`](https://github.com/inspect-js/is-generator-function/commit/38d22e6cdc939bb3f2cbfc5fff41473a694d4fe5) +- Updating tape [`49c1f00`](https://github.com/inspect-js/is-generator-function/commit/49c1f00cf5c66c87a8678d9c78a6b411cf1af986) +- Updating tape [`75cb7df`](https://github.com/inspect-js/is-generator-function/commit/75cb7dfef5254f4a9941a3bd77471cb783bb6fbd) +- Updating tape [`4142cc0`](https://github.com/inspect-js/is-generator-function/commit/4142cc092e157b92a6107112b2c3f3dc9b154367) +- Better code coverage [`1831d64`](https://github.com/inspect-js/is-generator-function/commit/1831d64d859ae8d45cc9aea30248d8cabc3d1e1d) + +## v0.0.0 - 2014-02-09 + +### Commits + +- Tests. [`f46e936`](https://github.com/inspect-js/is-generator-function/commit/f46e9368db04e0725a56e2bd0a246ab52123ed35) +- package.json [`189db32`](https://github.com/inspect-js/is-generator-function/commit/189db324e627257de94b68d1e6005c21ba74ebad) +- Initial commit [`8096cee`](https://github.com/inspect-js/is-generator-function/commit/8096ceedf7c9caece9acfd0ff4a0bd6eafa5dfdf) +- README. [`9eda97f`](https://github.com/inspect-js/is-generator-function/commit/9eda97fbc33113a519121a6515e777985730f3f7) +- Implementation. [`c5c3a8d`](https://github.com/inspect-js/is-generator-function/commit/c5c3a8d5dccae465c69958fc38c4ceba8b1354cc) +- Adding Travis CI [`9a6503e`](https://github.com/inspect-js/is-generator-function/commit/9a6503ebce8c9521c82e8ed1ec1b79bc856d0c5c) diff --git a/test/merkletreejs/node_modules/is-generator-function/LICENSE b/test/merkletreejs/node_modules/is-generator-function/LICENSE new file mode 100644 index 0000000..47b7b50 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +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. diff --git a/test/merkletreejs/node_modules/is-generator-function/README.md b/test/merkletreejs/node_modules/is-generator-function/README.md new file mode 100644 index 0000000..519a423 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/README.md @@ -0,0 +1,40 @@ +# is-generator-function [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this a native generator function? + +## Example + +```js +var isGeneratorFunction = require('is-generator-function'); +assert(!isGeneratorFunction(function () {})); +assert(!isGeneratorFunction(null)); +assert(isGeneratorFunction(function* () { yield 42; return Infinity; })); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-generator-function +[2]: https://versionbadg.es/inspect-js/is-generator-function.svg +[5]: https://david-dm.org/inspect-js/is-generator-function.svg +[6]: https://david-dm.org/inspect-js/is-generator-function +[7]: https://david-dm.org/inspect-js/is-generator-function/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-generator-function#info=devDependencies +[11]: https://nodei.co/npm/is-generator-function.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-generator-function.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-generator-function.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-generator-function +[codecov-image]: https://codecov.io/gh/inspect-js/is-generator-function/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-generator-function/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-generator-function +[actions-url]: https://github.com/inspect-js/is-generator-function/actions diff --git a/test/merkletreejs/node_modules/is-generator-function/index.js b/test/merkletreejs/node_modules/is-generator-function/index.js new file mode 100644 index 0000000..9064e91 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/index.js @@ -0,0 +1,38 @@ +'use strict'; + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = require('has-tostringtag/shams')(); +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var GeneratorFunction; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + if (!getProto) { + return false; + } + if (typeof GeneratorFunction === 'undefined') { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; + } + return getProto(fn) === GeneratorFunction; +}; diff --git a/test/merkletreejs/node_modules/is-generator-function/package.json b/test/merkletreejs/node_modules/is-generator-function/package.json new file mode 100644 index 0000000..d013d43 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/package.json @@ -0,0 +1,87 @@ +{ + "name": "is-generator-function", + "version": "1.0.10", + "description": "Determine if a function is a native generator function.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc npm run test:all", + "test:all": "npm run test:index && npm run test:corejs && npm run test:uglified", + "test:harmony": "node --es-staging --harmony test && node --es-staging --harmony test/corejs && node --es-staging --harmony test/uglified", + "test:index": "node test", + "test:corejs": "node test/corejs", + "test:uglified": "node test/uglified", + "posttest": "aud --production", + "lint": "eslint .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-generator-function.git" + }, + "keywords": [ + "generator", + "generator function", + "es6", + "es2015", + "yield", + "function", + "function*" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-generator-function/issues" + }, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "core-js": "^2.6.5 || ^3.16.0", + "eslint": "^7.32.0", + "make-generator-function": "^2.0.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.3.0", + "uglify-register": "^1.0.1" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/test/merkletreejs/node_modules/is-generator-function/test/corejs.js b/test/merkletreejs/node_modules/is-generator-function/test/corejs.js new file mode 100644 index 0000000..73f0c89 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/test/corejs.js @@ -0,0 +1,5 @@ +'use strict'; + +require('core-js'); + +require('./'); diff --git a/test/merkletreejs/node_modules/is-generator-function/test/index.js b/test/merkletreejs/node_modules/is-generator-function/test/index.js new file mode 100644 index 0000000..cbaab5d --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/test/index.js @@ -0,0 +1,83 @@ +'use strict'; + +/* globals window */ + +var test = require('tape'); +var isGeneratorFunction = require('../index'); +var generatorFuncs = require('make-generator-function')(); +var hasToStringTag = require('has-tostringtag/shams')(); + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +test('returns false for non-functions', function (t) { + var nonFuncs = [ + true, + false, + null, + undefined, + {}, + [], + /a/g, + 'string', + 42, + new Date() + ]; + t.plan(nonFuncs.length); + forEach(nonFuncs, function (nonFunc) { + t.notOk(isGeneratorFunction(nonFunc), nonFunc + ' is not a function'); + }); + t.end(); +}); + +test('returns false for non-generator functions', function (t) { + var func = function () {}; + t.notOk(isGeneratorFunction(func), 'anonymous function is not an generator function'); + + var namedFunc = function foo() {}; + t.notOk(isGeneratorFunction(namedFunc), 'named function is not an generator function'); + + if (typeof window === 'undefined') { + t.skip('window.alert is not an generator function'); + } else { + t.notOk(isGeneratorFunction(window.alert), 'window.alert is not an generator function'); + } + t.end(); +}); + +var fakeToString = function () { return 'function* () { return "TOTALLY REAL I SWEAR!"; }'; }; + +test('returns false for non-generator function with faked toString', function (t) { + var func = function () {}; + func.toString = fakeToString; + + t.notEqual(String(func), Function.prototype.toString.apply(func), 'faked toString is not real toString'); + t.notOk(isGeneratorFunction(func), 'anonymous function with faked toString is not a generator function'); + t.end(); +}); + +test('returns false for non-generator function with faked @@toStringTag', { skip: !hasToStringTag || generatorFuncs.length === 0 }, function (t) { + var generatorFunc = generatorFuncs[0]; + var fakeGenFunction = { + toString: function () { return String(generatorFunc); }, + valueOf: function () { return generatorFunc; } + }; + fakeGenFunction[Symbol.toStringTag] = 'GeneratorFunction'; + t.notOk(isGeneratorFunction(fakeGenFunction), 'fake GeneratorFunction with @@toStringTag "GeneratorFunction" is not a generator function'); + t.end(); +}); + +test('returns true for generator functions', function (t) { + if (generatorFuncs.length > 0) { + forEach(generatorFuncs, function (generatorFunc) { + t.ok(isGeneratorFunction(generatorFunc), generatorFunc + ' is generator function'); + }); + } else { + t.skip('generator function is generator function - this environment does not support ES6 generator functions. Please run `node --harmony`, or use a supporting browser.'); + } + t.end(); +}); diff --git a/test/merkletreejs/node_modules/is-generator-function/test/uglified.js b/test/merkletreejs/node_modules/is-generator-function/test/uglified.js new file mode 100644 index 0000000..fd82b55 --- /dev/null +++ b/test/merkletreejs/node_modules/is-generator-function/test/uglified.js @@ -0,0 +1,8 @@ +'use strict'; + +require('uglify-register/api').register({ + exclude: [/\/node_modules\//, /\/test\//], + uglify: { mangle: true } +}); + +require('./'); diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/.editorconfig b/test/merkletreejs/node_modules/is-hex-prefixed/.editorconfig new file mode 100644 index 0000000..d4eed84 --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/.editorconfig @@ -0,0 +1,7 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = false +indent_style = space +indent_size = 2 diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/.gitattributes b/test/merkletreejs/node_modules/is-hex-prefixed/.gitattributes new file mode 100644 index 0000000..a29125a --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/.gitattributes @@ -0,0 +1,106 @@ +# From https://github.com/Danimoth/gitattributes/blob/master/Web.gitattributes + +# Handle line endings automatically for files detected as text +# and leave all files detected as binary untouched. +* text=auto + +# +# The above will handle all files NOT found below +# + +# +## These files are text and should be normalized (Convert crlf => lf) +# + +# source code +*.php text +*.css text +*.sass text +*.scss text +*.less text +*.styl text +*.js text eol=lf +*.coffee text +*.json text +*.htm text +*.html text +*.xml text +*.svg text +*.txt text +*.ini text +*.inc text +*.pl text +*.rb text +*.py text +*.scm text +*.sql text +*.sh text +*.bat text + +# templates +*.ejs text +*.hbt text +*.jade text +*.haml text +*.hbs text +*.dot text +*.tmpl text +*.phtml text + +# server config +.htaccess text + +# git config +.gitattributes text +.gitignore text +.gitconfig text + +# code analysis config +.jshintrc text +.jscsrc text +.jshintignore text +.csslintrc text + +# misc config +*.yaml text +*.yml text +.editorconfig text + +# build config +*.npmignore text +*.bowerrc text + +# Heroku +Procfile text +.slugignore text + +# Documentation +*.md text +LICENSE text +AUTHORS text + + +# +## These files are binary and should be left untouched +# + +# (binary is a macro for -text -diff) +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.mov binary +*.mp4 binary +*.mp3 binary +*.flv binary +*.fla binary +*.swf binary +*.gz binary +*.zip binary +*.7z binary +*.ttf binary +*.eot binary +*.woff binary +*.pyc binary +*.pdf binary diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/.npmignore b/test/merkletreejs/node_modules/is-hex-prefixed/.npmignore new file mode 100644 index 0000000..3260b1f --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/.npmignore @@ -0,0 +1,8 @@ +# Don't check auto-generated stuff into git +node_modules +coverage +lib + +# Cruft +.DS_Store +npm-debug.log diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/.travis.yml b/test/merkletreejs/node_modules/is-hex-prefixed/.travis.yml new file mode 100644 index 0000000..baeeccb --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/.travis.yml @@ -0,0 +1,5 @@ +sudo: true +language: node_js +node_js: + - "6" +after_success: npm run coveralls diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/CHANGELOG.md b/test/merkletreejs/node_modules/is-hex-prefixed/CHANGELOG.md new file mode 100644 index 0000000..b01c88d --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/CHANGELOG.md @@ -0,0 +1,7 @@ +# 0.0.1 -- is-hex-prefixed + +1. Basic testing +2. Basic docs +3. License +4. linting +5. basic exports diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/LICENSE b/test/merkletreejs/node_modules/is-hex-prefixed/LICENSE new file mode 100644 index 0000000..b231a71 --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +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. diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/README.md b/test/merkletreejs/node_modules/is-hex-prefixed/README.md new file mode 100644 index 0000000..20cf37b --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/README.md @@ -0,0 +1,101 @@ +## is-hex-prefixed + +
+ + + Dependency Status + + + + + devDependency Status + + + + + Build Status + + + + + NPM version + + + + + Test Coverage + + + + + js-airbnb-style + +
+ +
+ +A simple method to check if a string is hex prefixed. + +## Install + +``` +npm install --save is-hex-prefixed +``` + +## Usage + +```js +const isHexPrefixed = require('is-hex-prefixed'); + +console.log(isHexPrefixed('0x..')); + +// result true + +console.log(isHexPrefixed('dfsk')); + +// result false + +console.log(isHexPrefixed({})); + +// result throw new Error + +console.log(isHexPrefixed('-0x')); + +// result false +``` + +## Important documents + +- [Changelog](CHANGELOG.md) +- [License](https://raw.githubusercontent.com/silentcicero/is-hex-prefixed/master/LICENSE) + +## Licence + +This project is licensed under the MIT license, Copyright (c) 2016 Nick Dodson. For more information see LICENSE.md. + +``` +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +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. +``` diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/package.json b/test/merkletreejs/node_modules/is-hex-prefixed/package.json new file mode 100644 index 0000000..02ebb9d --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/package.json @@ -0,0 +1,39 @@ +{ + "name": "is-hex-prefixed", + "version": "1.0.0", + "description": "A simple method to check if a string is hex prefixed.", + "main": "src/index.js", + "scripts": { + "test": "mocha src/tests/**/**.js", + "test-travis": "node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- src/tests/**/*.js", + "coveralls": "npm run test-travis && cat ./coverage/lcov.info | coveralls" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/SilentCicero/is-hex-prefixed.git" + }, + "engines": { + "npm": ">=3", + "node": ">=6.5.0" + }, + "keywords": [ + "is", + "hex", + "prefixed", + "prefix", + "checker", + "method" + ], + "author": "Nick Dodson ", + "license": "MIT", + "bugs": { + "url": "https://github.com/SilentCicero/is-hex-prefixed/issues" + }, + "homepage": "https://github.com/SilentCicero/is-hex-prefixed#readme", + "devDependencies": { + "chai": "3.5.0", + "mocha": "3.2.0", + "istanbul": "0.4.5", + "coveralls": "2.11.9" + } +} diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/src/index.js b/test/merkletreejs/node_modules/is-hex-prefixed/src/index.js new file mode 100644 index 0000000..dab0fa7 --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/src/index.js @@ -0,0 +1,13 @@ +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param {String} str the string input value + * @return {Boolean} a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +module.exports = function isHexPrefixed(str) { + if (typeof str !== 'string') { + throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); + } + + return str.slice(0, 2) === '0x'; +} diff --git a/test/merkletreejs/node_modules/is-hex-prefixed/src/tests/test.index.js b/test/merkletreejs/node_modules/is-hex-prefixed/src/tests/test.index.js new file mode 100644 index 0000000..07775a0 --- /dev/null +++ b/test/merkletreejs/node_modules/is-hex-prefixed/src/tests/test.index.js @@ -0,0 +1,66 @@ +const isHexPrefixed = require('../index.js'); +const assert = require('chai').assert; + +describe("isHexPrefixed", () => { + describe("constructor", () => { + it("should have the method exported", () => { + assert.equal(typeof isHexPrefixed, 'function'); + }); + }); + + describe("should function normall", () => { + it('should isHexPrefixed check if hex is prefixed', () => { + assert.equal(isHexPrefixed('0xsdffsd'), true); + assert.equal(isHexPrefixed('0x'), true); + assert.equal(isHexPrefixed('0x3982349284'), true); + assert.equal(isHexPrefixed('0x824723894jshdksjdhks'), true); + }); + + it('should isHexPrefixed check if hex is prefixed not prefixed', () => { + assert.equal(isHexPrefixed('sdffsd'), false); + assert.equal(isHexPrefixed(''), false); + assert.equal(isHexPrefixed('3982349284'), false); + assert.equal(isHexPrefixed('824723894jshdksjdhks'), false); + }); + + it('should isHexPrefixed throw as expected string got buffer', () => { + try { + isHexPrefixed(new Buffer()); + } catch (error) { + assert.equal(typeof error, 'object'); + } + }); + + it('should isHexPrefixed throw as expected string got empty object', () => { + try { + isHexPrefixed({}); + } catch (error) { + assert.equal(typeof error, 'object'); + } + }); + + it('should isHexPrefixed throw as expected string got number', () => { + try { + isHexPrefixed(823947243994); + } catch (error) { + assert.equal(typeof error, 'object'); + } + }); + + it('should isHexPrefixed throw as expected string got undefined', () => { + try { + isHexPrefixed(undefined); + } catch (error) { + assert.equal(typeof error, 'object'); + } + }); + + it('should isHexPrefixed throw as expected string got null', () => { + try { + isHexPrefixed(null); + } catch (error) { + assert.equal(typeof error, 'object'); + } + }); + }); +}); diff --git a/test/merkletreejs/node_modules/is-typed-array/.editorconfig b/test/merkletreejs/node_modules/is-typed-array/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/test/merkletreejs/node_modules/is-typed-array/.eslintrc b/test/merkletreejs/node_modules/is-typed-array/.eslintrc new file mode 100644 index 0000000..34a6262 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "globals": { + "globalThis": false + }, + + "rules": { + "max-statements-per-line": [2, { "max": 2 }] + }, +} diff --git a/test/merkletreejs/node_modules/is-typed-array/.github/FUNDING.yml b/test/merkletreejs/node_modules/is-typed-array/.github/FUNDING.yml new file mode 100644 index 0000000..7dd24b9 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/is-typed-array +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/is-typed-array/.nycrc b/test/merkletreejs/node_modules/is-typed-array/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/is-typed-array/CHANGELOG.md b/test/merkletreejs/node_modules/is-typed-array/CHANGELOG.md new file mode 100644 index 0000000..b139d2d --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/CHANGELOG.md @@ -0,0 +1,134 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.12](https://github.com/inspect-js/is-typed-array/compare/v1.1.11...v1.1.12) - 2023-07-17 + +### Commits + +- [Refactor] use `which-typed-array` for all internals [`7619405`](https://github.com/inspect-js/is-typed-array/commit/761940532de595f6721fed101b02814dcfa7fe4e) + +## [v1.1.11](https://github.com/inspect-js/is-typed-array/compare/v1.1.10...v1.1.11) - 2023-07-17 + +### Commits + +- [Fix] `node < v0.6` lacks proper Object toString behavior [`c94b90d`](https://github.com/inspect-js/is-typed-array/commit/c94b90dc6bc457783d6f8cc208415a49da0933b7) +- [Robustness] use `call-bind` [`573b00b`](https://github.com/inspect-js/is-typed-array/commit/573b00b8deec42ac1ac262415e442ea0b7e1c96b) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`c88c2d4`](https://github.com/inspect-js/is-typed-array/commit/c88c2d479976110478fa4038fe8921251c06a163) + +## [v1.1.10](https://github.com/inspect-js/is-typed-array/compare/v1.1.9...v1.1.10) - 2022-11-02 + +### Commits + +- [meta] add `auto-changelog` [`cf6d86b`](https://github.com/inspect-js/is-typed-array/commit/cf6d86bf2f693eca357439d4d12e76d641f91f92) +- [actions] update rebase action to use reusable workflow [`8da51a5`](https://github.com/inspect-js/is-typed-array/commit/8da51a5dce6d2442ae31ccbc2be136f2e04d6bef) +- [Dev Deps] update `aud`, `is-callable`, `object-inspect`, `tape` [`554e3de`](https://github.com/inspect-js/is-typed-array/commit/554e3deec59dec926d0badc628e589ab363e465b) +- [Refactor] use `gopd` instead of an `es-abstract` helper` [`cdaa465`](https://github.com/inspect-js/is-typed-array/commit/cdaa465d5f94bfc9e32475e31209e1c2458a9603) +- [Deps] update `es-abstract` [`677ae4b`](https://github.com/inspect-js/is-typed-array/commit/677ae4b3c8323b59d6650a9254ab945045c33f79) + + + +1.1.9 / 2022-05-13 +================= + * [Refactor] use `foreach` instead of `for-each` + * [readme] markdown URL cleanup + * [Deps] update `es-abstract` + * [meta] use `npmignore` to autogenerate an npmignore file + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `safe-publish-latest`, `tape` + * [actions] reuse common workflows + * [actions] update codecov uploader + +1.1.8 / 2021-08-30 +================= + * [Refactor] use `globalThis` if available (#53) + * [Deps] update `available-typed-arrays` + * [Dev Deps] update `@ljharb/eslint-config` + +1.1.7 / 2021-08-07 +================= + * [Fix] if Symbol.toStringTag exists but is not present, use Object.prototype.toString + * [Dev Deps] update `is-callable`, `tape` + +1.1.6 / 2021-08-05 +================= + * [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams + * [readme] add actions and codecov badges + * [meta] use `prepublishOnly` script for npm 7+ + * [Deps] update `available-typed-arrays`, `es-abstract` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + * [actions] use `node/install` instead of `node/run`; use `codecov` action + +1.1.5 / 2021-02-14 +================= + * [meta] do not publish github action workflow files or nyc output + * [Deps] update `call-bind`, `es-abstract` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `is-callable`, `tape` + +1.1.4 / 2020-12-05 +================= + * [readme] fix repo URLs, remove defunct badges + * [Deps] update `available-typed-arrays`, `es-abstract`; use `call-bind` where applicable + * [meta] gitignore nyc output + * [meta] only audit prod deps + * [actions] add "Allow Edits" workflow + * [actions] switch Automatic Rebase workflow to `pull_request_target` event + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `make-arrow-function`, `make-generator-function`, `object-inspect`, `tape`; add `aud` + * [Tests] migrate tests to Github Actions + * [Tests] run `nyc` on all tests + +1.1.3 / 2020-01-24 +================= + * [Refactor] use `es-abstract`’s `callBound`, `available-typed-arrays`, `has-symbols` + +1.1.2 / 2020-01-20 +================= + * [Fix] in envs without Symbol.toStringTag, dc8a8cc made arrays return `true` + * [Tests] add `evalmd` to `prelint` + +1.1.1 / 2020-01-18 +================= + * [Robustness] don’t rely on Array.prototype.indexOf existing + * [meta] remove unused Makefile and associated utilities + * [meta] add `funding` field; create FUNDING.yml + * [actions] add automatic rebasing / merge commit blocking + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `replace`, `semver`, `tape`; add `safe-publish-latest` + * [Tests] use shared travis-ci configs + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + +1.1.0 / 2019-02-16 +================= + * [New] add `BigInt64Array` and `BigUint64Array` + * [Refactor] use an array instead of an object for storing Typed Array names + * [meta] ignore `test.html` + * [Tests] up to `node` `v11.10`, `v10.15`, `v8.15`, `v7.10`, `v6.16`, `v5.10`, `v4.9` + * [Tests] remove `jscs` + * [Tests] use `npm audit` instead of `nsp` + * [Dev Deps] update `eslint`,` @ljharb/eslint-config`, `is-callable`, `tape`, `replace`, `semver` + * [Dev Deps] remove unused eccheck script + dep + +1.0.4 / 2016-03-19 +================= + * [Fix] `Symbol.toStringTag` is on the super-`[[Prototype]]` of Float32Array, not the `[[Prototype]]` (#3) + * [Tests] up to `node` `v5.9`, `v4.4` + * [Tests] use pretest/posttest for linting/security + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `is-callable` + +1.0.3 / 2015-10-13 +================= + * [Deps] Add missing `foreach` dependency (#1) + +1.0.2 / 2015-10-05 +================= + * [Deps] Remove unneeded "isarray" dependency + * [Dev Deps] update `eslint`, `@ljharb/eslint-config` + +1.0.1 / 2015-10-02 +================= + * Rerelease: avoid instanceof and the constructor property; work cross-realm; work with Symbol.toStringTag. + +1.0.0 / 2015-05-06 +================= + * Initial release. diff --git a/test/merkletreejs/node_modules/is-typed-array/LICENSE b/test/merkletreejs/node_modules/is-typed-array/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +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. + diff --git a/test/merkletreejs/node_modules/is-typed-array/README.md b/test/merkletreejs/node_modules/is-typed-array/README.md new file mode 100644 index 0000000..5075257 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/README.md @@ -0,0 +1,70 @@ +# is-typed-array [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag. + +## Example + +```js +var isTypedArray = require('is-typed-array'); +var assert = require('assert'); + +assert.equal(false, isTypedArray(undefined)); +assert.equal(false, isTypedArray(null)); +assert.equal(false, isTypedArray(false)); +assert.equal(false, isTypedArray(true)); +assert.equal(false, isTypedArray([])); +assert.equal(false, isTypedArray({})); +assert.equal(false, isTypedArray(/a/g)); +assert.equal(false, isTypedArray(new RegExp('a', 'g'))); +assert.equal(false, isTypedArray(new Date())); +assert.equal(false, isTypedArray(42)); +assert.equal(false, isTypedArray(NaN)); +assert.equal(false, isTypedArray(Infinity)); +assert.equal(false, isTypedArray(new Number(42))); +assert.equal(false, isTypedArray('foo')); +assert.equal(false, isTypedArray(Object('foo'))); +assert.equal(false, isTypedArray(function () {})); +assert.equal(false, isTypedArray(function* () {})); +assert.equal(false, isTypedArray(x => x * x)); +assert.equal(false, isTypedArray([])); + +assert.ok(isTypedArray(new Int8Array())); +assert.ok(isTypedArray(new Uint8Array())); +assert.ok(isTypedArray(new Uint8ClampedArray())); +assert.ok(isTypedArray(new Int16Array())); +assert.ok(isTypedArray(new Uint16Array())); +assert.ok(isTypedArray(new Int32Array())); +assert.ok(isTypedArray(new Uint32Array())); +assert.ok(isTypedArray(new Float32Array())); +assert.ok(isTypedArray(new Float64Array())); +assert.ok(isTypedArray(new BigInt64Array())); +assert.ok(isTypedArray(new BigUint64Array())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/is-typed-array +[npm-version-svg]: https://versionbadg.es/inspect-js/is-typed-array.svg +[deps-svg]: https://david-dm.org/inspect-js/is-typed-array.svg +[deps-url]: https://david-dm.org/inspect-js/is-typed-array +[dev-deps-svg]: https://david-dm.org/inspect-js/is-typed-array/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/is-typed-array#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/is-typed-array.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-typed-array.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-typed-array.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-typed-array +[codecov-image]: https://codecov.io/gh/inspect-js/is-typed-array/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-typed-array/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-typed-array +[actions-url]: https://github.com/inspect-js/is-typed-array/actions diff --git a/test/merkletreejs/node_modules/is-typed-array/index.js b/test/merkletreejs/node_modules/is-typed-array/index.js new file mode 100644 index 0000000..08c3163 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/index.js @@ -0,0 +1,7 @@ +'use strict'; + +var whichTypedArray = require('which-typed-array'); + +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; diff --git a/test/merkletreejs/node_modules/is-typed-array/package.json b/test/merkletreejs/node_modules/is-typed-array/package.json new file mode 100644 index 0000000..e2fc302 --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/package.json @@ -0,0 +1,116 @@ +{ + "name": "is-typed-array", + "version": "1.1.12", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run --silent lint", + "test": "npm run tests-only && npm run test:harmony", + "tests-only": "nyc tape test", + "test:harmony": "nyc node --harmony --es-staging test", + "posttest": "npx aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/is-typed-array.git" + }, + "keywords": [ + "array", + "TypedArray", + "typed array", + "is", + "typed", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "ES6", + "toStringTag", + "Symbol.toStringTag", + "@@toStringTag" + ], + "dependencies": { + "which-typed-array": "^1.1.11" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "has-tostringtag": "^1.0.0", + "in-publish": "^2.0.1", + "is-callable": "^1.2.7", + "make-arrow-function": "^1.2.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.5" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "1.1.10" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/is-typed-array/test/index.js b/test/merkletreejs/node_modules/is-typed-array/test/index.js new file mode 100644 index 0000000..8e7a16b --- /dev/null +++ b/test/merkletreejs/node_modules/is-typed-array/test/index.js @@ -0,0 +1,103 @@ +'use strict'; + +var test = require('tape'); +var isTypedArray = require('../'); +var isCallable = require('is-callable'); +var hasToStringTag = require('has-tostringtag/shams')(); +var generators = require('make-generator-function')(); +var arrowFn = require('make-arrow-function')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var typedArrayNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; + +test('not arrays', function (t) { + t.test('non-number/string primitives', function (st) { + st.notOk(isTypedArray(), 'undefined is not typed array'); + st.notOk(isTypedArray(null), 'null is not typed array'); + st.notOk(isTypedArray(false), 'false is not typed array'); + st.notOk(isTypedArray(true), 'true is not typed array'); + st.end(); + }); + + t.notOk(isTypedArray({}), 'object is not typed array'); + t.notOk(isTypedArray(/a/g), 'regex literal is not typed array'); + t.notOk(isTypedArray(new RegExp('a', 'g')), 'regex object is not typed array'); + t.notOk(isTypedArray(new Date()), 'new Date() is not typed array'); + + t.test('numbers', function (st) { + st.notOk(isTypedArray(42), 'number is not typed array'); + st.notOk(isTypedArray(Object(42)), 'number object is not typed array'); + st.notOk(isTypedArray(NaN), 'NaN is not typed array'); + st.notOk(isTypedArray(Infinity), 'Infinity is not typed array'); + st.end(); + }); + + t.test('strings', function (st) { + st.notOk(isTypedArray('foo'), 'string primitive is not typed array'); + st.notOk(isTypedArray(Object('foo')), 'string object is not typed array'); + st.end(); + }); + + t.end(); +}); + +test('Functions', function (t) { + t.notOk(isTypedArray(function () {}), 'function is not typed array'); + t.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.notOk(isTypedArray(genFn), 'generator function ' + inspect(genFn) + ' is not typed array'); + }); + t.end(); +}); + +test('Arrow functions', { skip: !arrowFn }, function (t) { + t.notOk(isTypedArray(arrowFn), 'arrow function is not typed array'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + forEach(typedArrayNames, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var fakeTypedArray = []; + fakeTypedArray[Symbol.toStringTag] = typedArray; + t.notOk(isTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); + +test('non-Typed Arrays', function (t) { + t.notOk(isTypedArray([]), '[] is not typed array'); + t.end(); +}); + +test('Typed Arrays', function (t) { + forEach(typedArrayNames, function (typedArray) { + var TypedArray = global[typedArray]; + if (isCallable(TypedArray)) { + var arr = new TypedArray(10); + t.ok(isTypedArray(arr), 'new ' + typedArray + '(10) is typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); diff --git a/test/merkletreejs/node_modules/isomorphic-ws/LICENSE b/test/merkletreejs/node_modules/isomorphic-ws/LICENSE new file mode 100644 index 0000000..5db5d0b --- /dev/null +++ b/test/merkletreejs/node_modules/isomorphic-ws/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Zejin Zhuang + +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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/isomorphic-ws/README.md b/test/merkletreejs/node_modules/isomorphic-ws/README.md new file mode 100644 index 0000000..f7ad278 --- /dev/null +++ b/test/merkletreejs/node_modules/isomorphic-ws/README.md @@ -0,0 +1,59 @@ +# isomorphic-ws + +Isomorphic implementation of WebSocket. + +It uses: +- [ws](https://github.com/websockets/ws) on Node +- [global.WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) in browsers + +## Limitations + +Before using this module you should know that +[`ws`](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket) +is not perfectly API compatible with +[WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), +you should always test your code against both Node and browsers. + +Some major differences: + +- no `Server` implementation in browsers +- no support for the constructor + [`options`](https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketaddress-protocols-options) + argument in browsers + +## Usage + +You need to install both this package and [ws](https://github.com/websockets/ws): + +``` +> npm i isomorphic-ws ws +``` + +Then just require this package: + +```js +const WebSocket = require('isomorphic-ws'); + +const ws = new WebSocket('wss://echo.websocket.org/'); + +ws.onopen = function open() { + console.log('connected'); + ws.send(Date.now()); +}; + +ws.onclose = function close() { + console.log('disconnected'); +}; + +ws.onmessage = function incoming(data) { + console.log(`Roundtrip time: ${Date.now() - data.data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}; +``` + +## License + +[MIT](LICENSE) diff --git a/test/merkletreejs/node_modules/isomorphic-ws/browser.js b/test/merkletreejs/node_modules/isomorphic-ws/browser.js new file mode 100644 index 0000000..f59be2d --- /dev/null +++ b/test/merkletreejs/node_modules/isomorphic-ws/browser.js @@ -0,0 +1,17 @@ +// https://github.com/maxogden/websocket-stream/blob/48dc3ddf943e5ada668c31ccd94e9186f02fafbd/ws-fallback.js + +var ws = null + +if (typeof WebSocket !== 'undefined') { + ws = WebSocket +} else if (typeof MozWebSocket !== 'undefined') { + ws = MozWebSocket +} else if (typeof global !== 'undefined') { + ws = global.WebSocket || global.MozWebSocket +} else if (typeof window !== 'undefined') { + ws = window.WebSocket || window.MozWebSocket +} else if (typeof self !== 'undefined') { + ws = self.WebSocket || self.MozWebSocket +} + +export default ws diff --git a/test/merkletreejs/node_modules/isomorphic-ws/index.d.ts b/test/merkletreejs/node_modules/isomorphic-ws/index.d.ts new file mode 100644 index 0000000..de923a9 --- /dev/null +++ b/test/merkletreejs/node_modules/isomorphic-ws/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for isomorphic-ws +// Run `npm install @types/ws` before using this. +// Fix for https://github.com/heineiuo/isomorphic-ws/issues/8 +// If there is still something wrong, welcome issue. + +import WebSocket = require('ws') + +export = WebSocket \ No newline at end of file diff --git a/test/merkletreejs/node_modules/isomorphic-ws/node.js b/test/merkletreejs/node_modules/isomorphic-ws/node.js new file mode 100644 index 0000000..4fef4d2 --- /dev/null +++ b/test/merkletreejs/node_modules/isomorphic-ws/node.js @@ -0,0 +1,3 @@ +"use strict"; + +module.exports = require('ws'); \ No newline at end of file diff --git a/test/merkletreejs/node_modules/isomorphic-ws/package.json b/test/merkletreejs/node_modules/isomorphic-ws/package.json new file mode 100644 index 0000000..fcea2d3 --- /dev/null +++ b/test/merkletreejs/node_modules/isomorphic-ws/package.json @@ -0,0 +1,35 @@ +{ + "name": "isomorphic-ws", + "version": "5.0.0", + "description": "Isomorphic implementation of WebSocket", + "main": "node.js", + "types": "index.d.ts", + "browser": "browser.js", + "repository": { + "type": "git", + "url": "git+https://github.com/heineiuo/isomorphic-ws.git" + }, + "keywords": [ + "browser", + "browsers", + "isomorphic", + "node", + "websocket", + "ws" + ], + "author": "@heineiuo", + "license": "MIT", + "bugs": { + "url": "https://github.com/heineiuo/isomorphic-ws/issues" + }, + "homepage": "https://github.com/heineiuo/isomorphic-ws#readme", + "peerDependencies": { + "ws": "*" + }, + "files": [ + "index.d.ts", + "node.js", + "browser.js", + "README.md" + ] +} diff --git a/test/merkletreejs/node_modules/js-sha3/CHANGELOG.md b/test/merkletreejs/node_modules/js-sha3/CHANGELOG.md new file mode 100644 index 0000000..0812bdd --- /dev/null +++ b/test/merkletreejs/node_modules/js-sha3/CHANGELOG.md @@ -0,0 +1,106 @@ +# Change Log + +## v0.8.0 / 2018-08-05 +### Added +- TypeScript definitions. + +### Changed +- throw error if update after finalize + +## v0.7.0 / 2017-12-01 +### Added +- AMD support. +- support for web worker. #13 + +### Changed +- throw error if input type is incorrect when cSHAKE and KMAC. +- freeze hash after finalize. + +## v0.6.1 / 2017-07-03 +### Fixed +- Typo on variable kmac_256 type definition. #12 + +## v0.6.0 / 2017-06-15 +### Added +- cSHAKE method. +- KMAC method. +- alias methods without underscore like shake128, keccak512. + +### Changed +- throw error if input type is incorrect. + +## v0.5.7 / 2016-12-30 +### Fixed +- ArrayBuffer detection in old browsers. + +## v0.5.6 / 2016-12-29 +### Fixed +- ArrayBuffer dosen't work in Webpack. + +## v0.5.5 / 2016-09-26 +### Added +- TypeScript support. +- ArrayBuffer method. + +### Deprecated +- Buffer method. + +## v0.5.4 / 2016-09-12 +### Fixed +- CommonJS detection. + +## v0.5.3 / 2016-09-08 +### Added +- Some missing files to npm package. + +## v0.5.2 / 2016-06-06 +### Fixed +- Shake output incorrect in the special length. + +## v0.5.1 / 2015-10-27 +### Fixed +- Version in package.json and bower.json. + +## v0.5.0 / 2015-09-23 +### Added +- Hash object with create/update interface. + +## v0.4.1 / 2015-09-18 +### Added +- Integer array output. + +### Fixed +- Shake output incorrect when it's greater than 1088. + +## v0.4.0 / 2015-09-17 +### Added +- ArrayBuffer output. +- Shake alogirthms. + +## v0.3.1 / 2015-05-22 +### Fixed +- Some bugs. + +## v0.3.0 / 2015-05-21 +### Added +- Integer array input. +- ArrayBuffer input. + +## v0.2.0 / 2015-04-04 +### Added +- NIST's May 2014 SHA-3 version. + +### Changed +- Rename original methods to keccak. + +## v0.1.2 / 2015-02-27 +### Changed +- Improve performance. + +## v0.1.1 / 2015-02-26 +### Changed +- Improve performance. + +## v0.1.0 / 2015-02-23 +### Added +- First version implementation. diff --git a/test/merkletreejs/node_modules/js-sha3/LICENSE.txt b/test/merkletreejs/node_modules/js-sha3/LICENSE.txt new file mode 100644 index 0000000..968ee90 --- /dev/null +++ b/test/merkletreejs/node_modules/js-sha3/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2015-2018 Chen, Yi-Cyuan + +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. diff --git a/test/merkletreejs/node_modules/js-sha3/README.md b/test/merkletreejs/node_modules/js-sha3/README.md new file mode 100644 index 0000000..a675ae7 --- /dev/null +++ b/test/merkletreejs/node_modules/js-sha3/README.md @@ -0,0 +1,241 @@ +# js-sha3 + +[![Build Status](https://travis-ci.org/emn178/js-sha3.svg?branch=master)](https://travis-ci.org/emn178/js-sha3) +[![Coverage Status](https://coveralls.io/repos/emn178/js-sha3/badge.svg?branch=master)](https://coveralls.io/r/emn178/js-sha3?branch=master) +[![NPM](https://nodei.co/npm/js-sha3.png?stars&downloads)](https://nodei.co/npm/js-sha3/) + +A simple SHA-3 / Keccak / Shake hash function for JavaScript supports UTF-8 encoding. + +## Notice +* v0.8.0+ will throw an error if try to update hash after finalize. +* Sha3 methods has been renamed to keccak since v0.2.0. It means that sha3 methods of v0.1.x are equal to keccak methods of v0.2.x and later. +* `buffer` method is deprecated. This maybe confuse with Buffer in node.js. Please use `arrayBuffer` instead. + +## Demo +[SHA3-512 Online](http://emn178.github.io/online-tools/sha3_512.html) +[SHA3-384 Online](http://emn178.github.io/online-tools/sha3_384.html) +[SHA3-256 Online](http://emn178.github.io/online-tools/sha3_256.html) +[SHA3-224 Online](http://emn178.github.io/online-tools/sha3_224.html) +[Keccak-512 Online](http://emn178.github.io/online-tools/keccak_512.html) +[Keccak-384 Online](http://emn178.github.io/online-tools/keccak_384.html) +[Keccak-256 Online](http://emn178.github.io/online-tools/keccak_256.html) +[Keccak-224 Online](http://emn178.github.io/online-tools/keccak_224.html) +[Shake128 Online](http://emn178.github.io/online-tools/shake_128.html) +[Shake256 Online](http://emn178.github.io/online-tools/shake_256.html) + +## Download +[Compress](https://raw.github.com/emn178/js-sha3/master/build/sha3.min.js) +[Uncompress](https://raw.github.com/emn178/js-sha3/master/src/sha3.js) + +## Installation +You can also install js-sha3 by using Bower. + + bower install js-sha3 + +For node.js, you can use this command to install: + + npm install js-sha3 + +## Usage +You could use like this: +```JavaScript +sha3_512('Message to hash'); +sha3_384('Message to hash'); +sha3_256('Message to hash'); +sha3_224('Message to hash'); +keccak512('Message to hash'); +keccak384('Message to hash'); +keccak256('Message to hash'); +keccak224('Message to hash'); +shake128('Message to hash', 256); +shake256('Message to hash', 512); +cshake128('Message to hash', 256, 'function name', 'customization'); +cshake256('Message to hash', 512, 'function name', 'customization'); +kmac128('key', 'Message to hash', 256, 'customization'); +kmac256('key', 'Message to hash', 512, 'customization'); + +// Support ArrayBuffer output +var arrayBuffer = keccak224.arrayBuffer('Message to hash'); + +// Support Array output +var bytes = keccak224.digest('Message to hash'); +var bytes = keccak224.array('Message to hash'); + +// update hash +sha3_512.update('Message ').update('to ').update('hash').hex(); +// specify shake output bits at first update +shake128.update('Message ', 256).update('to ').update('hash').hex(); + +// or to use create +var hash = sha3_512.create(); +hash.update('...'); +hash.update('...'); +hash.hex(); + +// specify shake output bits when creating +var hash = shake128.create(256); +hash.update('...'); +hash.update('...'); +hash.hex(); + +// specify cshake output bits, function name and customization when creating +var hash = cshake128.create(256, 'function name', 'customization'); + +// specify kmac key, output bits and customization when creating +var hash = kmac128.create('key', 256, 'customization'); +``` +If you use node.js, you should require the module first: +```JavaScript +sha3_512 = require('js-sha3').sha3_512; +sha3_384 = require('js-sha3').sha3_384; +sha3_256 = require('js-sha3').sha3_256; +sha3_224 = require('js-sha3').sha3_224; +keccak512 = require('js-sha3').keccak512; +keccak384 = require('js-sha3').keccak384; +keccak256 = require('js-sha3').keccak256; +keccak224 = require('js-sha3').keccak224; +shake128 = require('js-sha3').shake128; +shake256 = require('js-sha3').shake256; +cshake128 = require('js-sha3').cshake128; +cshake256 = require('js-sha3').cshake256; +kmac128 = require('js-sha3').kmac128; +kmac256 = require('js-sha3').kmac256; +``` +If you use TypeScript, you can import like this: +```TypeScript +import { sha3_512 } from 'js-sha3'; +``` + +## Example +Code +```JavaScript +sha3_512(''); +// a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26 + +sha3_512('The quick brown fox jumps over the lazy dog'); +// 01dedd5de4ef14642445ba5f5b97c15e47b9ad931326e4b0727cd94cefc44fff23f07bf543139939b49128caf436dc1bdee54fcb24023a08d9403f9b4bf0d450 + +sha3_512('The quick brown fox jumps over the lazy dog.'); +// 18f4f4bd419603f95538837003d9d254c26c23765565162247483f65c50303597bc9ce4d289f21d1c2f1f458828e33dc442100331b35e7eb031b5d38ba6460f8 + +sha3_384(''); +// 0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004 + +sha3_384('The quick brown fox jumps over the lazy dog'); +// 7063465e08a93bce31cd89d2e3ca8f602498696e253592ed26f07bf7e703cf328581e1471a7ba7ab119b1a9ebdf8be41 + +sha3_384('The quick brown fox jumps over the lazy dog.'); +// 1a34d81695b622df178bc74df7124fe12fac0f64ba5250b78b99c1273d4b080168e10652894ecad5f1f4d5b965437fb9 + +sha3_256(''); +// a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a + +sha3_256('The quick brown fox jumps over the lazy dog'); +// 69070dda01975c8c120c3aada1b282394e7f032fa9cf32f4cb2259a0897dfc04 + +sha3_256('The quick brown fox jumps over the lazy dog.'); +// a80f839cd4f83f6c3dafc87feae470045e4eb0d366397d5c6ce34ba1739f734d + +sha3_224(''); +// 6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7 + +sha3_224('The quick brown fox jumps over the lazy dog'); +// d15dadceaa4d5d7bb3b48f446421d542e08ad8887305e28d58335795 + +sha3_224('The quick brown fox jumps over the lazy dog.'); +// 2d0708903833afabdd232a20201176e8b58c5be8a6fe74265ac54db0 + +keccak512(''); +// 0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e + +keccak512('The quick brown fox jumps over the lazy dog'); +// d135bb84d0439dbac432247ee573a23ea7d3c9deb2a968eb31d47c4fb45f1ef4422d6c531b5b9bd6f449ebcc449ea94d0a8f05f62130fda612da53c79659f609 + +keccak512('The quick brown fox jumps over the lazy dog.'); +// ab7192d2b11f51c7dd744e7b3441febf397ca07bf812cceae122ca4ded6387889064f8db9230f173f6d1ab6e24b6e50f065b039f799f5592360a6558eb52d760 + +keccak384(''); +// 2c23146a63a29acf99e73b88f8c24eaa7dc60aa771780ccc006afbfa8fe2479b2dd2b21362337441ac12b515911957ff + +keccak384('The quick brown fox jumps over the lazy dog'); +// 283990fa9d5fb731d786c5bbee94ea4db4910f18c62c03d173fc0a5e494422e8a0b3da7574dae7fa0baf005e504063b3 + +keccak384('The quick brown fox jumps over the lazy dog.'); +// 9ad8e17325408eddb6edee6147f13856ad819bb7532668b605a24a2d958f88bd5c169e56dc4b2f89ffd325f6006d820b + +keccak256(''); +// c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 + +keccak256('The quick brown fox jumps over the lazy dog'); +// 4d741b6f1eb29cb2a9b9911c82f56fa8d73b04959d3d9d222895df6c0b28aa15 + +keccak256('The quick brown fox jumps over the lazy dog.'); +// 578951e24efd62a3d63a86f7cd19aaa53c898fe287d2552133220370240b572d + +keccak224(''); +// f71837502ba8e10837bdd8d365adb85591895602fc552b48b7390abd + +keccak224('The quick brown fox jumps over the lazy dog'); +// 310aee6b30c47350576ac2873fa89fd190cdc488442f3ef654cf23fe + +keccak224('The quick brown fox jumps over the lazy dog.'); +// c59d4eaeac728671c635ff645014e2afa935bebffdb5fbd207ffdeab + +shake128('', 256); +// 7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26 + +shake256('', 512); +// 46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762fd75dc4ddd8c0f200cb05019d67b592f6fc821c49479ab48640292eacb3b7c4be +``` +It also supports UTF-8 encoding: + +Code +```JavaScript +sha3_512('中文'); +// 059bbe2efc50cc30e4d8ec5a96be697e2108fcbf9193e1296192eddabc13b143c0120d059399a13d0d42651efe23a6c1ce2d1efb576c5b207fa2516050505af7 + +sha3_384('中文'); +// 9fb5b99e3c546f2738dcd50a14e9aef9c313800c1bf8cf76bc9b2c3a23307841364c5a2d0794702662c5796fb72f5432 + +sha3_256('中文'); +// ac5305da3d18be1aed44aa7c70ea548da243a59a5fd546f489348fd5718fb1a0 + +sha3_224('中文'); +// 106d169e10b61c2a2a05554d3e631ec94467f8316640f29545d163ee + +keccak512('中文'); +// 2f6a1bd50562230229af34b0ccf46b8754b89d23ae2c5bf7840b4acfcef86f87395edc0a00b2bfef53bafebe3b79de2e3e01cbd8169ddbb08bde888dcc893524 + +keccak384('中文'); +// 743f64bb7544c6ed923be4741b738dde18b7cee384a3a09c4e01acaaac9f19222cdee137702bd3aa05dc198373d87d6c + +keccak256('中文'); +// 70a2b6579047f0a977fcb5e9120a4e07067bea9abb6916fbc2d13ffb9a4e4eee + +keccak224('中文'); +// f71837502ba8e10837bdd8d365adb85591895602fc552b48b7390abd +``` + +It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` input: + +Code +```JavaScript +sha3_512([]); +// a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26 + +sha3_512(new Uint8Array([])); +// a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26 + +// ... +``` + +## Benchmark +[UTF8](http://jsperf.com/sha3/5) +[ASCII](http://jsperf.com/sha3/4) + +## License +The project is released under the [MIT license](http://www.opensource.org/licenses/MIT). + +## Contact +The project's website is located at https://github.com/emn178/js-sha3 +Author: Chen, Yi-Cyuan (emn178@gmail.com) diff --git a/test/merkletreejs/node_modules/js-sha3/build/sha3.min.js b/test/merkletreejs/node_modules/js-sha3/build/sha3.min.js new file mode 100644 index 0000000..965b779 --- /dev/null +++ b/test/merkletreejs/node_modules/js-sha3/build/sha3.min.js @@ -0,0 +1,9 @@ +/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */ +!function(){"use strict";function t(t,e,r){this.blocks=[],this.s=[],this.padding=e,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(t<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function e(e,r,n){t.call(this,e,r,n)}var r="input is invalid type",n="object"==typeof window,i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var o=!n&&"object"==typeof self;!i.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?i=global:o&&(i=self);var a=!i.JS_SHA3_NO_COMMON_JS&&"object"==typeof module&&module.exports,s="function"==typeof define&&define.amd,u=!i.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,f="0123456789abcdef".split(""),c=[4,1024,262144,67108864],h=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],d=[224,256,384,512],l=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136};!i.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),!u||!i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(t){return"object"==typeof t&&t.buffer&&t.buffer.constructor===ArrayBuffer});for(var A=function(e,r,n){return function(i){return new t(e,r,e).update(i)[n]()}},w=function(e,r,n){return function(i,o){return new t(e,r,o).update(i)[n]()}},v=function(t,e,r){return function(e,n,i,o){return S["cshake"+t].update(e,n,i,o)[r]()}},B=function(t,e,r){return function(e,n,i,o){return S["kmac"+t].update(e,n,i,o)[r]()}},g=function(t,e,r,n){for(var i=0;i>2]|=t[p]<>2]|=o<>2]|=(192|o>>6)<>2]|=(128|63&o)<=57344?(a[i>>2]|=(224|o>>12)<>2]|=(128|o>>6&63)<>2]|=(128|63&o)<>2]|=(240|o>>18)<>2]|=(128|o>>12&63)<>2]|=(128|o>>6&63)<>2]|=(128|63&o)<=s){for(this.start=i-s,this.block=a[c],i=0;i>=8);r>0;)i.unshift(r),r=255&(t>>=8),++n;return e?i.push(n):i.unshift(n),this.update(i),i.length},t.prototype.encodeString=function(t){var e,n=typeof t;if("string"!==n){if("object"!==n)throw new Error(r);if(null===t)throw new Error(r);if(u&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!(Array.isArray(t)||u&&ArrayBuffer.isView(t)))throw new Error(r);e=!0}var i=0,o=t.length;if(e)i=o;else for(var a=0;a=57344?i+=3:(s=65536+((1023&s)<<10|1023&t.charCodeAt(++a)),i+=4)}return i+=this.encode(8*i),this.update(t),i},t.prototype.bytepad=function(t,e){for(var r=this.encode(e),n=0;n>2]|=this.padding[3&e],this.lastByteIndex===this.byteCount)for(t[0]=t[r],e=1;e>4&15]+f[15&t]+f[t>>12&15]+f[t>>8&15]+f[t>>20&15]+f[t>>16&15]+f[t>>28&15]+f[t>>24&15];a%e==0&&(j(r),o=0)}return i&&(t=r[o],s+=f[t>>4&15]+f[15&t],i>1&&(s+=f[t>>12&15]+f[t>>8&15]),i>2&&(s+=f[t>>20&15]+f[t>>16&15])),s},t.prototype.arrayBuffer=function(){this.finalize();var t,e=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,a=0,s=this.outputBits>>3;t=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(s);for(var u=new Uint32Array(t);a>8&255,u[t+2]=e>>16&255,u[t+3]=e>>24&255;s%r==0&&j(n)}return o&&(t=s<<2,e=n[a],u[t]=255&e,o>1&&(u[t+1]=e>>8&255),o>2&&(u[t+2]=e>>16&255)),u},(e.prototype=new t).finalize=function(){return this.encode(this.outputBits,!0),t.prototype.finalize.call(this)};var j=function(t){var e,r,n,i,o,a,s,u,f,c,h,d,l,y,b,A,w,v,B,g,_,k,S,C,x,m,E,O,z,N,j,J,M,H,I,R,U,V,F,D,W,Y,K,q,G,L,P,Q,T,X,Z,$,tt,et,rt,nt,it,ot,at,st,ut,ft,ct;for(n=0;n<48;n+=2)i=t[0]^t[10]^t[20]^t[30]^t[40],o=t[1]^t[11]^t[21]^t[31]^t[41],a=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],u=t[4]^t[14]^t[24]^t[34]^t[44],f=t[5]^t[15]^t[25]^t[35]^t[45],c=t[6]^t[16]^t[26]^t[36]^t[46],h=t[7]^t[17]^t[27]^t[37]^t[47],e=(d=t[8]^t[18]^t[28]^t[38]^t[48])^(a<<1|s>>>31),r=(l=t[9]^t[19]^t[29]^t[39]^t[49])^(s<<1|a>>>31),t[0]^=e,t[1]^=r,t[10]^=e,t[11]^=r,t[20]^=e,t[21]^=r,t[30]^=e,t[31]^=r,t[40]^=e,t[41]^=r,e=i^(u<<1|f>>>31),r=o^(f<<1|u>>>31),t[2]^=e,t[3]^=r,t[12]^=e,t[13]^=r,t[22]^=e,t[23]^=r,t[32]^=e,t[33]^=r,t[42]^=e,t[43]^=r,e=a^(c<<1|h>>>31),r=s^(h<<1|c>>>31),t[4]^=e,t[5]^=r,t[14]^=e,t[15]^=r,t[24]^=e,t[25]^=r,t[34]^=e,t[35]^=r,t[44]^=e,t[45]^=r,e=u^(d<<1|l>>>31),r=f^(l<<1|d>>>31),t[6]^=e,t[7]^=r,t[16]^=e,t[17]^=r,t[26]^=e,t[27]^=r,t[36]^=e,t[37]^=r,t[46]^=e,t[47]^=r,e=c^(i<<1|o>>>31),r=h^(o<<1|i>>>31),t[8]^=e,t[9]^=r,t[18]^=e,t[19]^=r,t[28]^=e,t[29]^=r,t[38]^=e,t[39]^=r,t[48]^=e,t[49]^=r,y=t[0],b=t[1],L=t[11]<<4|t[10]>>>28,P=t[10]<<4|t[11]>>>28,O=t[20]<<3|t[21]>>>29,z=t[21]<<3|t[20]>>>29,st=t[31]<<9|t[30]>>>23,ut=t[30]<<9|t[31]>>>23,Y=t[40]<<18|t[41]>>>14,K=t[41]<<18|t[40]>>>14,H=t[2]<<1|t[3]>>>31,I=t[3]<<1|t[2]>>>31,A=t[13]<<12|t[12]>>>20,w=t[12]<<12|t[13]>>>20,Q=t[22]<<10|t[23]>>>22,T=t[23]<<10|t[22]>>>22,N=t[33]<<13|t[32]>>>19,j=t[32]<<13|t[33]>>>19,ft=t[42]<<2|t[43]>>>30,ct=t[43]<<2|t[42]>>>30,et=t[5]<<30|t[4]>>>2,rt=t[4]<<30|t[5]>>>2,R=t[14]<<6|t[15]>>>26,U=t[15]<<6|t[14]>>>26,v=t[25]<<11|t[24]>>>21,B=t[24]<<11|t[25]>>>21,X=t[34]<<15|t[35]>>>17,Z=t[35]<<15|t[34]>>>17,J=t[45]<<29|t[44]>>>3,M=t[44]<<29|t[45]>>>3,C=t[6]<<28|t[7]>>>4,x=t[7]<<28|t[6]>>>4,nt=t[17]<<23|t[16]>>>9,it=t[16]<<23|t[17]>>>9,V=t[26]<<25|t[27]>>>7,F=t[27]<<25|t[26]>>>7,g=t[36]<<21|t[37]>>>11,_=t[37]<<21|t[36]>>>11,$=t[47]<<24|t[46]>>>8,tt=t[46]<<24|t[47]>>>8,q=t[8]<<27|t[9]>>>5,G=t[9]<<27|t[8]>>>5,m=t[18]<<20|t[19]>>>12,E=t[19]<<20|t[18]>>>12,ot=t[29]<<7|t[28]>>>25,at=t[28]<<7|t[29]>>>25,D=t[38]<<8|t[39]>>>24,W=t[39]<<8|t[38]>>>24,k=t[48]<<14|t[49]>>>18,S=t[49]<<14|t[48]>>>18,t[0]=y^~A&v,t[1]=b^~w&B,t[10]=C^~m&O,t[11]=x^~E&z,t[20]=H^~R&V,t[21]=I^~U&F,t[30]=q^~L&Q,t[31]=G^~P&T,t[40]=et^~nt&ot,t[41]=rt^~it&at,t[2]=A^~v&g,t[3]=w^~B&_,t[12]=m^~O&N,t[13]=E^~z&j,t[22]=R^~V&D,t[23]=U^~F&W,t[32]=L^~Q&X,t[33]=P^~T&Z,t[42]=nt^~ot&st,t[43]=it^~at&ut,t[4]=v^~g&k,t[5]=B^~_&S,t[14]=O^~N&J,t[15]=z^~j&M,t[24]=V^~D&Y,t[25]=F^~W&K,t[34]=Q^~X&$,t[35]=T^~Z&tt,t[44]=ot^~st&ft,t[45]=at^~ut&ct,t[6]=g^~k&y,t[7]=_^~S&b,t[16]=N^~J&C,t[17]=j^~M&x,t[26]=D^~Y&H,t[27]=W^~K&I,t[36]=X^~$&q,t[37]=Z^~tt&G,t[46]=st^~ft&et,t[47]=ut^~ct&rt,t[8]=k^~y&A,t[9]=S^~b&w,t[18]=J^~C&m,t[19]=M^~x&E,t[28]=Y^~H&R,t[29]=K^~I&U,t[38]=$^~q&L,t[39]=tt^~G&P,t[48]=ft^~et&nt,t[49]=ct^~rt&it,t[0]^=p[n],t[1]^=p[n+1]};if(a)module.exports=S;else{for(x=0;x", + "homepage": "https://github.com/emn178/js-sha3", + "bugs": { + "url": "https://github.com/emn178/js-sha3/issues" + }, + "nyc": { + "exclude": [ + "tests" + ] + } +} diff --git a/test/merkletreejs/node_modules/js-sha3/src/sha3.js b/test/merkletreejs/node_modules/js-sha3/src/sha3.js new file mode 100644 index 0000000..f9a8d9c --- /dev/null +++ b/test/merkletreejs/node_modules/js-sha3/src/sha3.js @@ -0,0 +1,656 @@ +/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */ +/*jslint bitwise: true */ +(function () { + 'use strict'; + + var INPUT_ERROR = 'input is invalid type'; + var FINALIZE_ERROR = 'finalize already called'; + var WINDOW = typeof window === 'object'; + var root = WINDOW ? window : {}; + if (root.JS_SHA3_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === 'object'; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = global; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports; + var AMD = typeof define === 'function' && define.amd; + var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; + var HEX_CHARS = '0123456789abcdef'.split(''); + var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; + var CSHAKE_PADDING = [4, 1024, 262144, 67108864]; + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var PADDING = [6, 1536, 393216, 100663296]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, + 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, + 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, + 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, + 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + var BITS = [224, 256, 384, 512]; + var SHAKE_BITS = [128, 256]; + var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest']; + var CSHAKE_BYTEPAD = { + '128': 168, + '256': 136 + }; + + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + } + + if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function (obj) { + return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; + + var createCshakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits, n, s) { + return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); + }; + }; + + var createKmacOutputMethod = function (bits, padding, outputType) { + return function (key, message, outputBits, s) { + return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); + }; + }; + + var createOutputMethods = function (method, createMethod, bits, padding) { + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createMethod(bits, padding, type); + } + return method; + }; + + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits, padding); + }; + + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits, padding); + }; + + var createCshakeMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createCshakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits, n, s) { + if (!n && !s) { + return methods['shake' + bits].create(outputBits); + } else { + return new Keccak(bits, padding, outputBits).bytepad([n, s], w); + } + }; + method.update = function (message, outputBits, n, s) { + return method.create(outputBits, n, s).update(message); + }; + return createOutputMethods(method, createCshakeOutputMethod, bits, padding); + }; + + var createKmacMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createKmacOutputMethod(bits, padding, 'hex'); + method.create = function (key, outputBits, s) { + return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w); + }; + method.update = function (key, message, outputBits, s) { + return method.create(key, outputBits, s).update(message); + }; + return createOutputMethods(method, createKmacOutputMethod, bits, padding); + }; + + var algorithms = [ + { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, + { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod }, + { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod }, + { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod }, + { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod } + ]; + + var methods = {}, methodNames = []; + + for (var i = 0; i < algorithms.length; ++i) { + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for (var j = 0; j < bits.length; ++j) { + var methodName = algorithm.name + '_' + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + if (algorithm.name !== 'sha3') { + var newMethodName = algorithm.name + bits[j]; + methodNames.push(newMethodName); + methods[newMethodName] = methods[methodName]; + } + } + } + + function Keccak(bits, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.finalized = false; + this.block = 0; + this.start = 0; + this.blockCount = (1600 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } + + Keccak.prototype.update = function (message) { + if (this.finalized) { + throw new Error(FINALIZE_ERROR); + } + var notString, type = typeof message; + if (type !== 'string') { + if (type === 'object') { + if (message === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; + } else { + this.start = i; + } + } + return this; + }; + + Keccak.prototype.encode = function (x, right) { + var o = x & 255, n = 1; + var bytes = [o]; + x = x >> 8; + o = x & 255; + while (o > 0) { + bytes.unshift(o); + x = x >> 8; + o = x & 255; + ++n; + } + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); + } + this.update(bytes); + return bytes.length; + }; + + Keccak.prototype.encodeString = function (str) { + var notString, type = typeof str; + if (type !== 'string') { + if (type === 'object') { + if (str === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { + str = new Uint8Array(str); + } else if (!Array.isArray(str)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for (var i = 0; i < str.length; ++i) { + var code = str.charCodeAt(i); + if (code < 0x80) { + bytes += 1; + } else if (code < 0x800) { + bytes += 2; + } else if (code < 0xd800 || code >= 0xe000) { + bytes += 3; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); + bytes += 4; + } + } + } + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; + }; + + Keccak.prototype.bytepad = function (strs, w) { + var bytes = this.encode(w); + for (var i = 0; i < strs.length; ++i) { + bytes += this.encodeString(strs[i]); + } + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; + }; + + Keccak.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + }; + + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + if (extraBytes) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } + } + return hex; + }; + + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer((outputBlocks + 1) << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; + } + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; + } + } + return array; + }; + + function Kmac(bits, padding, outputBits) { + Keccak.call(this, bits, padding, outputBits); + } + + Kmac.prototype = new Keccak(); + + Kmac.prototype.finalize = function () { + this.encode(this.outputBits, true); + return Keccak.prototype.finalize.call(this); + }; + + var f = function (s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, + b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, + b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); + l = c9 ^ ((c3 << 1) | (c2 >>> 31)); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ ((c4 << 1) | (c5 >>> 31)); + l = c1 ^ ((c5 << 1) | (c4 >>> 31)); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ ((c6 << 1) | (c7 >>> 31)); + l = c3 ^ ((c7 << 1) | (c6 >>> 31)); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ ((c8 << 1) | (c9 >>> 31)); + l = c5 ^ ((c9 << 1) | (c8 >>> 31)); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ ((c0 << 1) | (c1 >>> 31)); + l = c7 ^ ((c1 << 1) | (c0 >>> 31)); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = (s[11] << 4) | (s[10] >>> 28); + b33 = (s[10] << 4) | (s[11] >>> 28); + b14 = (s[20] << 3) | (s[21] >>> 29); + b15 = (s[21] << 3) | (s[20] >>> 29); + b46 = (s[31] << 9) | (s[30] >>> 23); + b47 = (s[30] << 9) | (s[31] >>> 23); + b28 = (s[40] << 18) | (s[41] >>> 14); + b29 = (s[41] << 18) | (s[40] >>> 14); + b20 = (s[2] << 1) | (s[3] >>> 31); + b21 = (s[3] << 1) | (s[2] >>> 31); + b2 = (s[13] << 12) | (s[12] >>> 20); + b3 = (s[12] << 12) | (s[13] >>> 20); + b34 = (s[22] << 10) | (s[23] >>> 22); + b35 = (s[23] << 10) | (s[22] >>> 22); + b16 = (s[33] << 13) | (s[32] >>> 19); + b17 = (s[32] << 13) | (s[33] >>> 19); + b48 = (s[42] << 2) | (s[43] >>> 30); + b49 = (s[43] << 2) | (s[42] >>> 30); + b40 = (s[5] << 30) | (s[4] >>> 2); + b41 = (s[4] << 30) | (s[5] >>> 2); + b22 = (s[14] << 6) | (s[15] >>> 26); + b23 = (s[15] << 6) | (s[14] >>> 26); + b4 = (s[25] << 11) | (s[24] >>> 21); + b5 = (s[24] << 11) | (s[25] >>> 21); + b36 = (s[34] << 15) | (s[35] >>> 17); + b37 = (s[35] << 15) | (s[34] >>> 17); + b18 = (s[45] << 29) | (s[44] >>> 3); + b19 = (s[44] << 29) | (s[45] >>> 3); + b10 = (s[6] << 28) | (s[7] >>> 4); + b11 = (s[7] << 28) | (s[6] >>> 4); + b42 = (s[17] << 23) | (s[16] >>> 9); + b43 = (s[16] << 23) | (s[17] >>> 9); + b24 = (s[26] << 25) | (s[27] >>> 7); + b25 = (s[27] << 25) | (s[26] >>> 7); + b6 = (s[36] << 21) | (s[37] >>> 11); + b7 = (s[37] << 21) | (s[36] >>> 11); + b38 = (s[47] << 24) | (s[46] >>> 8); + b39 = (s[46] << 24) | (s[47] >>> 8); + b30 = (s[8] << 27) | (s[9] >>> 5); + b31 = (s[9] << 27) | (s[8] >>> 5); + b12 = (s[18] << 20) | (s[19] >>> 12); + b13 = (s[19] << 20) | (s[18] >>> 12); + b44 = (s[29] << 7) | (s[28] >>> 25); + b45 = (s[28] << 7) | (s[29] >>> 25); + b26 = (s[38] << 8) | (s[39] >>> 24); + b27 = (s[39] << 8) | (s[38] >>> 24); + b8 = (s[48] << 14) | (s[49] >>> 18); + b9 = (s[49] << 14) | (s[48] >>> 18); + + s[0] = b0 ^ (~b2 & b4); + s[1] = b1 ^ (~b3 & b5); + s[10] = b10 ^ (~b12 & b14); + s[11] = b11 ^ (~b13 & b15); + s[20] = b20 ^ (~b22 & b24); + s[21] = b21 ^ (~b23 & b25); + s[30] = b30 ^ (~b32 & b34); + s[31] = b31 ^ (~b33 & b35); + s[40] = b40 ^ (~b42 & b44); + s[41] = b41 ^ (~b43 & b45); + s[2] = b2 ^ (~b4 & b6); + s[3] = b3 ^ (~b5 & b7); + s[12] = b12 ^ (~b14 & b16); + s[13] = b13 ^ (~b15 & b17); + s[22] = b22 ^ (~b24 & b26); + s[23] = b23 ^ (~b25 & b27); + s[32] = b32 ^ (~b34 & b36); + s[33] = b33 ^ (~b35 & b37); + s[42] = b42 ^ (~b44 & b46); + s[43] = b43 ^ (~b45 & b47); + s[4] = b4 ^ (~b6 & b8); + s[5] = b5 ^ (~b7 & b9); + s[14] = b14 ^ (~b16 & b18); + s[15] = b15 ^ (~b17 & b19); + s[24] = b24 ^ (~b26 & b28); + s[25] = b25 ^ (~b27 & b29); + s[34] = b34 ^ (~b36 & b38); + s[35] = b35 ^ (~b37 & b39); + s[44] = b44 ^ (~b46 & b48); + s[45] = b45 ^ (~b47 & b49); + s[6] = b6 ^ (~b8 & b0); + s[7] = b7 ^ (~b9 & b1); + s[16] = b16 ^ (~b18 & b10); + s[17] = b17 ^ (~b19 & b11); + s[26] = b26 ^ (~b28 & b20); + s[27] = b27 ^ (~b29 & b21); + s[36] = b36 ^ (~b38 & b30); + s[37] = b37 ^ (~b39 & b31); + s[46] = b46 ^ (~b48 & b40); + s[47] = b47 ^ (~b49 & b41); + s[8] = b8 ^ (~b0 & b2); + s[9] = b9 ^ (~b1 & b3); + s[18] = b18 ^ (~b10 & b12); + s[19] = b19 ^ (~b11 & b13); + s[28] = b28 ^ (~b20 & b22); + s[29] = b29 ^ (~b21 & b23); + s[38] = b38 ^ (~b30 & b32); + s[39] = b39 ^ (~b31 & b33); + s[48] = b48 ^ (~b40 & b42); + s[49] = b49 ^ (~b41 & b43); + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + if (COMMON_JS) { + module.exports = methods; + } else { + for (i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + if (AMD) { + define(function () { + return methods; + }); + } + } +})(); diff --git a/test/merkletreejs/node_modules/merkletreejs/LICENSE b/test/merkletreejs/node_modules/merkletreejs/LICENSE new file mode 100755 index 0000000..eb0736f --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/LICENSE @@ -0,0 +1,21 @@ +MIT license + +Copyright (C) 2015 Miguel Mota + +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. diff --git a/test/merkletreejs/node_modules/merkletreejs/README.md b/test/merkletreejs/node_modules/merkletreejs/README.md new file mode 100644 index 0000000..a2f5240 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/README.md @@ -0,0 +1,209 @@ +

+
+ merkletree.js logo +
+
+
+

+ +# MerkleTree.js + +> Construct [Merkle Trees](https://en.wikipedia.org/wiki/Merkle_tree) and verify proofs in JavaScript. + +[![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/miguelmota/merkletreejs/master/LICENSE) +[![Documentation](https://img.shields.io/badge/documentation-latest-blue.svg)](https://github.com/miguelmota/merkletreejs/tree/master/docs) +[![Build Status](https://travis-ci.org/miguelmota/merkletreejs.svg?branch=master)](https://travis-ci.org/miguelmota/merkletreejs) +[![dependencies Status](https://david-dm.org/miguelmota/merkletreejs/status.svg)](https://david-dm.org/miguelmota/merkletreejs) +[![NPM version](https://badge.fury.io/js/merkletreejs.svg)](http://badge.fury.io/js/merkletreejs) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#contributing) + +## Contents + +- [Install](#install) +- [Example](#example) +- [Getting started](#Getting-started) +- [Diagrams](#diagrams) +- [Documentation](#documentation) +- [Test](#test) +- [FAQ](#faq) +- [Notes](#notes) +- [Resources](#resources) +- [Contributing](#contributing) +- [License](#license) + +## Install + +From [NPM](https://www.npmjs.com/package/merkletreejs): + +```bash +npm install merkletreejs +``` + +Import as ES6 module + +```js +import { MerkleTree } from 'merkletreejs' +``` + +Import as CommonJs + +```js +const { MerkleTree } = require('merkletreejs') +``` + +### CDN + +Available on [jsDelivr](https://www.jsdelivr.com/) CDN: + +```html + +``` + +The exported classes will be available on `window` object, e.g. `window.MerkleTree` + +## Example + +[https://lab.miguelmota.com/merkletreejs](https://lab.miguelmota.com/merkletreejs) + +## Getting started + +Construct tree, generate proof, and verify proof: + +```js +const { MerkleTree } = require('merkletreejs') +const SHA256 = require('crypto-js/sha256') + +const leaves = ['a', 'b', 'c'].map(x => SHA256(x)) +const tree = new MerkleTree(leaves, SHA256) +const root = tree.getRoot().toString('hex') +const leaf = SHA256('a') +const proof = tree.getProof(leaf) +console.log(tree.verify(proof, leaf, root)) // true + + +const badLeaves = ['a', 'x', 'c'].map(x => SHA256(x)) +const badTree = new MerkleTree(badLeaves, SHA256) +const badLeaf = SHA256('x') +const badProof = badTree.getProof(badLeaf) +console.log(badTree.verify(badProof, badLeaf, root)) // false +``` + +Print tree to console: + +```js +console.log(tree.toString()) +``` + +Output: + +```bash +└─ 7075152d03a5cd92104887b476862778ec0c87be5c2fa1c0a90f87c49fad6eff + ├─ e5a01fee14e0ed5c48714f22180f25ad8365b53f9779f79dc4a3d7e93963f94a + │ ├─ ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb + │ └─ 3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d + └─ 2e7d2c03a9507ae265ecf5b5356885a53393a2029d241394997265a1a25aefc6 + └─ 2e7d2c03a9507ae265ecf5b5356885a53393a2029d241394997265a1a25aefc6 +``` + +## Diagrams + +▾ Visualization of Merkle Tree + +Merkle Tree + +▾ Visualization of Merkle Tree Proof + +Merkle Tree Proof + +▾ Visualization of Invalid Merkle Tree Proofs + +Merkle Tree Proof + +▾ Visualization of Bitcoin Merkle Tree + +Merkle Tree Proof + +## Documentation + +See [documentation](docs/classes/_src_merkletree_.merkletree.md) (under [docs/](docs/)) + +## Test + +```bash +npm test +``` + +## FAQ + +- Q: How do you verify merkle proofs in Solidity? + - A: Check out the example repo [merkletreejs-solidity](https://github.com/miguelmota/merkletreejs-solidity) on how to generate merkle proofs with this library and verify them in Solidity. + +- Q: How do you verify merkle [multiproofs](https://github.com/ethereum/eth2.0-specs/blob/dev/ssz/merkle-proofs.md#merkle-multiproofs) in Solidity? + - A: Check out the example repo [merkletreejs-multiproof-solidity](https://github.com/miguelmota/merkletreejs-multiproof-solidity) on how to generate merkle multiproofs with this library and verify them in Solidity. + +- Q: Is there an NFT whitelist example in Solidity? + - A: Check out the example repo [merkletreejs-nft-whitelist](https://github.com/miguelmota/merkletreejs-nft-whitelist) on how to generate merkle root of whitelisted accounts and merkle proofs with this library and verify them in Solidity. + +- Q: What other types of merkle trees are supported? + + - Besides standard `MerkleTree`, there's also `MerkleMountainRange`, `MerkleSumTree`, and `IncrementalMerkleTree` implemenation classes available. + +- Q: Is there a CLI version of this library? + + - Yes, see [merkletreejs-cli](https://github.com/miguelmota/merkletreejs-cli). + +- Q: Is there a way to visualize the merkle trees in the browser? + + - Yes, see [merkletree-viz](https://github.com/miguelmota/merkletree-viz). + +## Notes + +As is, this implemenation is vulnerable to a [second pre-image attack](https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack). Use a difference hashing function for leaves and nodes, so that `H(x) != H'(x)`. + +Also, as is, this implementation is vulnerable to a forgery attack for an unbalanced tree, where the last leaf node can be duplicated to create an artificial balanced tree, resulting in the same Merkle root hash. Do not accept unbalanced tree to prevent this. More info [here](https://bitcointalk.org/?topic=102395). + +Please use the library [`@openzeppelin/merkle-tree`](https://github.com/OpenZeppelin/merkle-tree) if you're integrating with OpenZeppelin contracts or using multiproofs. There are known issues with the current multiproof implementation as pointed out in [issues](https://github.com/merkletreejs/merkletreejs/issues/63). + +### Disclaimer + +This library was created for my own purposes and is provided as-is. Use at your own risk. + +## Resources + +- [Bitcoin mining the hard way: the algorithms, protocols, and bytes](http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html) + +- [Bitcoin Talk - Merkle Trees](https://bitcointalk.org/index.php?topic=403231.msg9054025#msg9054025) + +- [How Log Proofs Work](https://www.certificate-transparency.org/log-proofs-work) + +- [Raiden Merkle Tree Implemenation](https://github.com/raiden-network/raiden/blob/f9cf12571891cdf54feb4667cd2fffcb3d5daa89/raiden/mtree.py) + +- [Why aren't Solidity sha3 hashes not matching what other sha3 libraries produce?](https://ethereum.stackexchange.com/questions/559/why-arent-solidity-sha3-hashes-not-matching-what-other-sha3-libraries-produce) + +- [What is the purpose of using different hash functions for the leaves and internals of a hash tree?](https://crypto.stackexchange.com/questions/2106/what-is-the-purpose-of-using-different-hash-functions-for-the-leaves-and-interna) + +- [Why is the full Merkle path needed to verify a transaction?](https://bitcoin.stackexchange.com/questions/50674/why-is-the-full-merkle-path-needed-to-verify-a-transaction) + +- [Where is Double hashing performed in Bitcoin?](https://bitcoin.stackexchange.com/questions/8443/where-is-double-hashing-performed-in-bitcoin) + +- [Compact Merkle Multiproofs](https://arxiv.org/pdf/2002.07648.pdf) + +- [Eth 2.0 specs - Merkle Multiproofs](https://github.com/ethereum/eth2.0-specs/blob/dev/ssz/merkle-proofs.md#merkle-multiproofs) + +- [What is complete binary tree?](https://xlinux.nist.gov/dads/HTML/completeBinaryTree.html) + +- [What is perfect binary tree?](https://xlinux.nist.gov/dads/HTML/perfectBinaryTree.html) + +## Contributing + +Pull requests are welcome! + +For contributions please create a new branch and submit a pull request for review. + +_Many thanks to all the [contributors](https://github.com/miguelmota/merkletreejs/graphs/contributors) that made this library better._ + +## License + +Released under the [MIT](./LICENSE) license. + +© [Miguel Mota](https://github.com/miguelmota) diff --git a/test/merkletreejs/node_modules/merkletreejs/merkletree.js b/test/merkletreejs/node_modules/merkletreejs/merkletree.js new file mode 100644 index 0000000..cda590c --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/merkletree.js @@ -0,0 +1 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i2&&arguments[2]!==undefined?arguments[2]:false;if(isSorted){return this.binarySearch(array,element,buffer_1.Buffer.compare)}var eqChecker=function eqChecker(buffer1,buffer2){return buffer1.equals(buffer2)};return this.linearSearch(array,element,eqChecker)}},{key:"binarySearch",value:function binarySearch(array,element,compareFunction){return Base.binarySearch(array,element,compareFunction)}},{key:"linearSearch",value:function linearSearch(array,element,eqChecker){return Base.linearSearch(array,element,eqChecker)}},{key:"bigNumberify",value:function bigNumberify(value){return Base.bigNumberify(value)}},{key:"bufferToHex",value:function bufferToHex(value){var withPrefix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return Base.bufferToHex(value,withPrefix)}},{key:"bufferify",value:function bufferify(value){return Base.bufferify(value)}},{key:"bufferifyFn",value:function bufferifyFn(f){var _this=this;return function(value){var v=f(value);if(buffer_1.Buffer.isBuffer(v)){return v}if(_this.isHexString(v)){return buffer_1.Buffer.from(v.replace("0x",""),"hex")}if(typeof v==="string"){return buffer_1.Buffer.from(v)}if(typeof v==="bigint"){return buffer_1.Buffer.from(value.toString(16),"hex")}if(ArrayBuffer.isView(v)){return buffer_1.Buffer.from(v.buffer,v.byteOffset,v.byteLength)}return buffer_1.Buffer.from(f(crypto_js_1["default"].enc.Hex.parse(value.toString("hex"))).toString(crypto_js_1["default"].enc.Hex),"hex")}}},{key:"isHexString",value:function isHexString(value){return Base.isHexString(value)}},{key:"log2",value:function log2(n){return n===1?0:1+this.log2(n/2|0)}},{key:"zip",value:function zip(a,b){return a.map(function(e,i){return[e,b[i]]})}}],[{key:"binarySearch",value:function binarySearch(array,element,compareFunction){var start=0;var end=array.length-1;while(start<=end){var mid=Math.floor((start+end)/2);var ordering=compareFunction(array[mid],element);if(ordering===0){for(var i=mid-1;i>=0;i--){if(compareFunction(array[i],element)===0)continue;return i+1}return 0}else if(ordering<0){start=mid+1}else{end=mid-1}}return-1}},{key:"linearSearch",value:function linearSearch(array,element,eqChecker){for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:true;return"".concat(withPrefix?"0x":"").concat((value||buffer_1.Buffer.alloc(0)).toString("hex"))}},{key:"hexZeroPad",value:function hexZeroPad(hexStr,length){return"0x"+hexStr.replace("0x","").padStart(length,"0")}}]);return Base}();exports.Base=Base;exports["default"]=Base},{buffer:10,"crypto-js":21}],2:[function(require,module,exports){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i=this.getMaxLeaves()){throw new Error("tree is full")}}var node=leaf;var index=this.nodes[0].length;for(var level=0;level=this.nodes[0].length){throw new Error("out of bounds")}var node=newLeaf;for(var level=0;level=layers[level].length){layers[level][_i]=this.zeroes[level]}}index=Math.floor(index/this.arity)}}layers.push([this.root]);return layers}},{key:"getHexLayers",value:function getHexLayers(){var _this2=this;return this.getLayers().reduce(function(acc,item){if(Array.isArray(item)){acc.push(item.map(function(layer){return _this2.bufferToHex(_this2.bufferify(layer))}))}else{acc.push(item)}return acc},[])}},{key:"getLayersAsObject",value:function getLayersAsObject(){var _this3=this;var layers=this.getLayers().map(function(layer){return layer.map(function(value){return _this3.bufferToHex(_this3.bufferify(value),false)})});var objs=[];for(var i=0;i=this.nodes[0].length){throw new Error("The leaf does not exist in this tree")}var siblings=[];var pathIndices=[];var leafIndex=index;for(var level=0;level=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i0&&arguments[0]!==undefined?arguments[0]:sha256_1["default"];var leaves=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var hashLeafFn=arguments.length>2?arguments[2]:undefined;var peakBaggingFn=arguments.length>3?arguments[3]:undefined;var hashBranchFn=arguments.length>4?arguments[4]:undefined;_classCallCheck(this,MerkleMountainRange);_this=_super.call(this);_this.root=buffer_1.Buffer.alloc(0);_this.size=0;_this.width=0;_this.hashes={};_this.data={};leaves=leaves.map(_this.bufferify);_this.hashFn=_this.bufferifyFn(hashFn);_this.hashLeafFn=hashLeafFn;_this.peakBaggingFn=peakBaggingFn;_this.hashBranchFn=hashBranchFn;var _iterator=_createForOfIteratorHelper(leaves),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var leaf=_step.value;_this.append(leaf)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return _this}_createClass(MerkleMountainRange,[{key:"append",value:function append(data){data=this.bufferify(data);var dataHash=this.hashFn(data);var dataHashHex=this.bufferToHex(dataHash);if(!this.data[dataHashHex]||this.bufferToHex(this.hashFn(this.data[dataHashHex]))!==dataHashHex){this.data[dataHashHex]=data}var leaf=this.hashLeaf(this.size+1,dataHash);this.hashes[this.size+1]=leaf;this.width+=1;var peakIndexes=this.getPeakIndexes(this.width);this.size=this.getSize(this.width);var peaks=[];for(var i=0;i0;i--){if((width&1<=numPeaks){break}}}if(count!==peakIndexes.length){throw new Error("invalid bit calculation")}return peakIndexes}},{key:"numOfPeaks",value:function numOfPeaks(width){var bits=width;var num=0;while(bits>0){if(bits%2===1){num++}bits=bits>>1}return num}},{key:"peakBagging",value:function peakBagging(width,peaks){var size=this.getSize(width);if(this.numOfPeaks(width)!==peaks.length){throw new Error("received invalid number of peaks")}if(width===0&&!peaks.length){return buffer_1.Buffer.alloc(0)}if(this.peakBaggingFn){return this.bufferify(this.peakBaggingFn(size,peaks))}return this.hashFn(buffer_1.Buffer.concat([this.bufferify(size)].concat(_toConsumableArray(peaks.map(this.bufferify)))))}},{key:"getSize",value:function getSize(width){return(width<<1)-this.numOfPeaks(width)}},{key:"getRoot",value:function getRoot(){return this.root}},{key:"getHexRoot",value:function getHexRoot(){return this.bufferToHex(this.getRoot())}},{key:"getNode",value:function getNode(index){return this.hashes[index]}},{key:"mountainHeight",value:function mountainHeight(size){var height=1;while(1<peakIndex){reducedIndex-=(1<this.size){throw new Error("out of range")}if(!this.isLeaf(index)){throw new Error("not a leaf")}var root=this.root;var width=this.width;var peaks=this.getPeakIndexes(this.width);var peakBagging=[];var cursor=0;for(var i=0;i=index&&cursor===0){cursor=peaks[i]}}var left=0;var right=0;var height=this.heightAt(cursor);var siblings=[];while(cursor!==index){height--;var _this$getChildren=this.getChildren(cursor);var _this$getChildren2=_slicedToArray(_this$getChildren,2);left=_this$getChildren2[0];right=_this$getChildren2[1];cursor=index<=left?left:right;siblings[height-1]=this.hashes[index<=left?right:left]}return{root:root,width:width,peakBagging:peakBagging,siblings:siblings}}},{key:"verify",value:function verify(root,width,index,value,peaks,siblings){value=this.bufferify(value);var size=this.getSize(width);if(size=index){targetPeak=peaks[i];cursor=peakIndexes[i];break}}if(!targetPeak){throw new Error("target not found")}var height=siblings.length+1;var path=new Array(height);var left=0;var right=0;while(height>0){path[--height]=cursor;if(cursor===index){break}else{var _this$getChildren3=this.getChildren(cursor);var _this$getChildren4=_slicedToArray(_this$getChildren3,2);left=_this$getChildren4[0];right=_this$getChildren4[1];cursor=index>left?right:left;continue}}var node;while(heightthis.size){throw new Error("out of range")}if(!this.hashes[index]){var _this$getChildren5=this.getChildren(index),_this$getChildren6=_slicedToArray(_this$getChildren5,2),leftIndex=_this$getChildren6[0],rightIndex=_this$getChildren6[1];var leftHash=this._getOrCreateNode(leftIndex);var rightHash=this._getOrCreateNode(rightIndex);this.hashes[index]=this.hashBranch(index,leftHash,rightHash)}return this.hashes[index]}}]);return MerkleMountainRange}(Base_1["default"]);exports.MerkleMountainRange=MerkleMountainRange;if(typeof window!=="undefined"){window.MerkleMountainRange=MerkleMountainRange}exports["default"]=MerkleMountainRange},{"./Base":1,buffer:10,"crypto-js/sha256":41}],4:[function(require,module,exports){(function(Buffer){(function(){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i=2){var b1=buckets.shift();var b2=buckets.shift();var size=b1.size+b2.size;var hashed=_this.hashFn(Buffer.concat([_this.sizeToBuffer(b1.size),_this.bufferify(b1.hashed),_this.sizeToBuffer(b2.size),_this.bufferify(b2.hashed)]));var b=new Bucket(size,hashed);b2.parent=b;b1.parent=b2.parent;b1.right=b2;b2.left=b1;newBuckets.push(b)}else{newBuckets.push(buckets.shift())}}buckets=newBuckets}_this.root=buckets[0];return _this}_createClass(MerkleSumTree,[{key:"sizeToBuffer",value:function sizeToBuffer(size){var buf=Buffer.alloc(8);var view=new DataView(buf.buffer);view.setBigInt64(0,BigInt(size),false);return buf}},{key:"getProof",value:function getProof(index){var curr=this.buckets[Number(index)];var proof=[];while(curr&&curr.parent){var right=!!curr.right;var bucket=curr.right?curr.right:curr.left;curr=curr.parent;proof.push(new ProofStep(bucket,right))}return proof}},{key:"sum",value:function sum(arr){var total=BigInt(0);var _iterator3=_createForOfIteratorHelper(arr),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var value=_step3.value;total+=BigInt(value)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}return total}},{key:"verifyProof",value:function verifyProof(root,leaf,proof){var rng=[this.sum(proof.filter(function(x){return!x.right}).map(function(x){return x.bucket.size})),BigInt(root.size)-this.sum(proof.filter(function(x){return x.right}).map(function(x){return x.bucket.size}))];if(!(rng[0]===leaf.rng[0]&&rng[1]===leaf.rng[1])){return false}var curr=leaf.getBucket();var hashed;var _iterator4=_createForOfIteratorHelper(proof),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var step=_step4.value;if(step.right){hashed=this.hashFn(Buffer.concat([this.sizeToBuffer(curr.size),this.bufferify(curr.hashed),this.sizeToBuffer(step.bucket.size),this.bufferify(step.bucket.hashed)]))}else{hashed=this.hashFn(Buffer.concat([this.sizeToBuffer(step.bucket.size),this.bufferify(step.bucket.hashed),this.sizeToBuffer(curr.size),this.bufferify(curr.hashed)]))}curr=new Bucket(BigInt(curr.size)+BigInt(step.bucket.size),hashed)}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}return curr.size===root.size&&curr.hashed.toString("hex")===root.hashed.toString("hex")}}],[{key:"checkConsecutive",value:function checkConsecutive(leaves){var curr=BigInt(0);var _iterator5=_createForOfIteratorHelper(leaves),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var leaf=_step5.value;if(leaf.rng[0]!==curr){throw new Error("leaf ranges are invalid")}curr=BigInt(leaf.rng[1])}}catch(err){_iterator5.e(err)}finally{_iterator5.f()}}}]);return MerkleSumTree}(Base_1.Base);exports.MerkleSumTree=MerkleSumTree;if(typeof window!=="undefined"){window.MerkleSumTree=MerkleSumTree}exports["default"]=MerkleSumTree}).call(this)}).call(this,require("buffer").Buffer)},{"./Base":1,buffer:10}],5:[function(require,module,exports){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t["return"]&&(u=t["return"](),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i1&&arguments[1]!==undefined?arguments[1]:sha256_1["default"];var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};_classCallCheck(this,MerkleTree);_this=_super.call(this);_this.duplicateOdd=false;_this.concatenator=buffer_1.Buffer.concat;_this.hashLeaves=false;_this.isBitcoinTree=false;_this.leaves=[];_this.layers=[];_this.sortLeaves=false;_this.sortPairs=false;_this.sort=false;_this.fillDefaultHash=null;_this.complete=false;if(options.complete){if(options.isBitcoinTree){throw new Error('option "complete" is incompatible with "isBitcoinTree"')}if(options.duplicateOdd){throw new Error('option "complete" is incompatible with "duplicateOdd"')}}_this.isBitcoinTree=!!options.isBitcoinTree;_this.hashLeaves=!!options.hashLeaves;_this.sortLeaves=!!options.sortLeaves;_this.sortPairs=!!options.sortPairs;_this.complete=!!options.complete;if(options.fillDefaultHash){if(typeof options.fillDefaultHash==="function"){_this.fillDefaultHash=options.fillDefaultHash}else if(buffer_1.Buffer.isBuffer(options.fillDefaultHash)||typeof options.fillDefaultHash==="string"){_this.fillDefaultHash=function(idx,hashFn){return options.fillDefaultHash}}else{throw new Error('method "fillDefaultHash" must be a function, Buffer, or string')}}_this.sort=!!options.sort;if(_this.sort){_this.sortLeaves=true;_this.sortPairs=true}_this.duplicateOdd=!!options.duplicateOdd;if(options.concatenator){_this.concatenator=options.concatenator}_this.hashFn=_this.bufferifyFn(hashFn);_this.processLeaves(leaves);return _this}_createClass(MerkleTree,[{key:"getOptions",value:function getOptions(){var _a,_b;return{complete:this.complete,isBitcoinTree:this.isBitcoinTree,hashLeaves:this.hashLeaves,sortLeaves:this.sortLeaves,sortPairs:this.sortPairs,sort:this.sort,fillDefaultHash:(_b=(_a=this.fillDefaultHash)===null||_a===void 0?void 0:_a.toString())!==null&&_b!==void 0?_b:null,duplicateOdd:this.duplicateOdd}}},{key:"processLeaves",value:function processLeaves(leaves){if(this.hashLeaves){leaves=leaves.map(this.hashFn)}this.leaves=leaves.map(this.bufferify);if(this.sortLeaves){this.leaves=this.leaves.sort(buffer_1.Buffer.compare)}if(this.fillDefaultHash){for(var i=this.leaves.length;i1){var layerIndex=this.layers.length;this.layers.push([]);var layerLimit=this.complete&&layerIndex===1&&!Number.isInteger(Math.log2(nodes.length))?2*nodes.length-Math.pow(2,Math.ceil(Math.log2(nodes.length))):nodes.length;for(var i=0;i=layerLimit){var _this$layers$layerInd;(_this$layers$layerInd=this.layers[layerIndex]).push.apply(_this$layers$layerInd,_toConsumableArray(nodes.slice(layerLimit)));break}else if(i+1===nodes.length){if(nodes.length%2===1){var data=nodes[nodes.length-1];var _hash=data;if(this.isBitcoinTree){_hash=this.hashFn(this.concatenator([buffer_reverse_1["default"](data),buffer_reverse_1["default"](data)]));_hash=buffer_reverse_1["default"](this.hashFn(_hash));this.layers[layerIndex].push(_hash);continue}else{if(this.duplicateOdd){}else{this.layers[layerIndex].push(nodes[i]);continue}}}}var left=nodes[i];var right=i+1===nodes.length?left:nodes[i+1];var combined=null;if(this.isBitcoinTree){combined=[buffer_reverse_1["default"](left),buffer_reverse_1["default"](right)]}else{combined=[left,right]}if(this.sortPairs){combined.sort(buffer_1.Buffer.compare)}var hash=this.hashFn(this.concatenator(combined));if(this.isBitcoinTree){hash=buffer_reverse_1["default"](this.hashFn(hash))}this.layers[layerIndex].push(hash)}nodes=this.layers[layerIndex]}}},{key:"addLeaf",value:function addLeaf(leaf){var shouldHash=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(shouldHash){leaf=this.hashFn(leaf)}this.processLeaves(this.leaves.concat(leaf))}},{key:"addLeaves",value:function addLeaves(leaves){var shouldHash=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(shouldHash){leaves=leaves.map(this.hashFn)}this.processLeaves(this.leaves.concat(leaves))}},{key:"getLeaves",value:function getLeaves(values){var _this2=this;if(Array.isArray(values)){if(this.hashLeaves){values=values.map(this.hashFn);if(this.sortLeaves){values=values.sort(buffer_1.Buffer.compare)}}return this.leaves.filter(function(leaf){return _this2.bufferIndexOf(values,leaf,_this2.sortLeaves)!==-1})}return this.leaves}},{key:"getLeaf",value:function getLeaf(index){if(index<0||index>this.leaves.length-1){return buffer_1.Buffer.from([])}return this.leaves[index]}},{key:"getLeafIndex",value:function getLeafIndex(target){target=this.bufferify(target);var leaves=this.getLeaves();for(var i=0;i=this.layers[currentLayer].length)return;var layer=this.layers[currentLayer];var pairIndex=isRightNode?index-1:index+1;var pushed=false;if(pairIndex1){maximalIndices.add(x^1);x=x/2|0}}}catch(err){_iterator.e(err)}finally{_iterator.f()}var a=treeIndices.map(function(index){return leafCount+index});var b=Array.from(maximalIndices).sort(function(a,b){return a-b}).reverse();maximalIndices=a.concat(b);var redundantIndices=new Set;var proof=[];var _iterator2=_createForOfIteratorHelper(maximalIndices),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var _index=_step2.value;if(!redundantIndices.has(_index)){proof.push(_index);while(_index>1){redundantIndices.add(_index);if(!redundantIndices.has(_index^1))break;_index=_index/2|0}}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}return proof.filter(function(index){return!treeIndices.includes(index-leafCount)})}},{key:"getProofIndicesForUnevenTree",value:function getProofIndicesForUnevenTree(sortedLeafIndices,leavesCount){var depth=Math.ceil(Math.log2(leavesCount));var unevenLayers=[];for(var index=0;indexb?1:-1});if(!ids.every(function(idx){return idx!==-1})){throw new Error("Element does not exist in Merkle tree")}var hashes=[];var proof=[];var nextIds=[];for(var i=0;ib?1:-1})}else{ids=leaves.map(function(el){return _this11.bufferIndexOf(_this11.leaves,el,_this11.sortLeaves)}).sort(function(a,b){return a===b?0:a>b?1:-1})}if(!ids.every(function(idx){return idx!==-1})){throw new Error("Element does not exist in Merkle tree")}var _proofs=proofs.map(function(item){return _this11.bufferify(item)});var tested=[];var flags=[];var _loop2=function _loop2(){var layer=_this11.layers[index];ids=ids.reduce(function(ids,idx){var skipped=tested.includes(layer[idx]);if(!skipped){var pairElement=_this11.getPairNode(layer,idx);var proofUsed=_proofs.includes(layer[idx])||_proofs.includes(pairElement);pairElement&&flags.push(!proofUsed);tested.push(layer[idx]);tested.push(pairElement)}ids.push(idx/2|0);return ids},[])};for(var index=0;index=2&&{}.hasOwnProperty.call(tree,index^1)){var pair=[tree[index-index%2],tree[index-index%2+1]];if(this.sortPairs){pair=pair.sort(buffer_1.Buffer.compare)}var hash=pair[1]?this.hashFn(this.concatenator(pair)):pair[0];tree[index/2|0]=hash;indexqueue.push(index/2|0)}i+=1}return!proofIndices.length||{}.hasOwnProperty.call(tree,1)&&tree[1].equals(root)}},{key:"verifyMultiProofWithFlags",value:function verifyMultiProofWithFlags(root,leaves,proofs,proofFlag){root=this.bufferify(root);leaves=leaves.map(this.bufferify);proofs=proofs.map(this.bufferify);var leavesLen=leaves.length;var totalHashes=proofFlag.length;var hashes=[];var leafPos=0;var hashPos=0;var proofPos=0;for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:sha256_1["default"];var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var parsed=null;if(typeof jsonStr==="string"){parsed=JSON.parse(jsonStr)}else if(jsonStr instanceof Object){parsed=jsonStr}else{throw new Error("Expected type of string or object")}if(!parsed){throw new Error("could not parse json")}options=Object.assign({},parsed.options||{},options);return new MerkleTree(parsed.leaves,hashFn,options)}},{key:"verify",value:function verify(proof,targetNode,root){var hashFn=arguments.length>3&&arguments[3]!==undefined?arguments[3]:sha256_1["default"];var options=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var tree=new MerkleTree([],hashFn,options);return tree.verify(proof,targetNode,root)}},{key:"getMultiProof",value:function getMultiProof(tree,indices){var t=new MerkleTree([]);return t.getMultiProof(tree,indices)}}]);return MerkleTree}(Base_1["default"]);exports.MerkleTree=MerkleTree;if(typeof window!=="undefined"){window.MerkleTree=MerkleTree}exports["default"]=MerkleTree},{"./Base":1,buffer:10,"buffer-reverse":9,"crypto-js/sha256":41,treeify:48}],6:[function(require,module,exports){"use strict";var __importDefault=void 0&&(void 0).__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.MerkleTree=void 0;var MerkleTree_1=__importDefault(require("./MerkleTree"));exports.MerkleTree=MerkleTree_1["default"];var MerkleMountainRange_1=require("./MerkleMountainRange");Object.defineProperty(exports,"MerkleMountainRange",{enumerable:true,get:function get(){return MerkleMountainRange_1.MerkleMountainRange}});var IncrementalMerkleTree_1=require("./IncrementalMerkleTree");Object.defineProperty(exports,"IncrementalMerkleTree",{enumerable:true,get:function get(){return IncrementalMerkleTree_1.IncrementalMerkleTree}});var MerkleSumTree_1=require("./MerkleSumTree");Object.defineProperty(exports,"MerkleSumTree",{enumerable:true,get:function get(){return MerkleSumTree_1.MerkleSumTree}});exports["default"]=MerkleTree_1["default"]},{"./IncrementalMerkleTree":2,"./MerkleMountainRange":3,"./MerkleSumTree":4,"./MerkleTree":5}],7:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],8:[function(require,module,exports){},{}],9:[function(require,module,exports){(function(Buffer){(function(){module.exports=function reverse(src){var buffer=new Buffer(src.length);for(var i=0,j=src.length-1;i<=j;++i,--j){buffer[i]=src[j];buffer[j]=src[i]}return buffer}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:10}],10:[function(require,module,exports){(function(Buffer){(function(){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;imax)str+=" ... ";return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":7,buffer:10,ieee754:47}],11:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./enc-base64"),require("./md5"),require("./evpkdf"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var BlockCipher=C_lib.BlockCipher;var C_algo=C.algo;var SBOX=[];var INV_SBOX=[];var SUB_MIX_0=[];var SUB_MIX_1=[];var SUB_MIX_2=[];var SUB_MIX_3=[];var INV_SUB_MIX_0=[];var INV_SUB_MIX_1=[];var INV_SUB_MIX_2=[];var INV_SUB_MIX_3=[];(function(){var d=[];for(var i=0;i<256;i++){if(i<128){d[i]=i<<1}else{d[i]=i<<1^283}}var x=0;var xi=0;for(var i=0;i<256;i++){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&255^99;SBOX[x]=sx;INV_SBOX[sx]=x;var x2=d[x];var x4=d[x2];var x8=d[x4];var t=d[sx]*257^sx*16843008;SUB_MIX_0[x]=t<<24|t>>>8;SUB_MIX_1[x]=t<<16|t>>>16;SUB_MIX_2[x]=t<<8|t>>>24;SUB_MIX_3[x]=t;var t=x8*16843009^x4*65537^x2*257^x*16843008;INV_SUB_MIX_0[sx]=t<<24|t>>>8;INV_SUB_MIX_1[sx]=t<<16|t>>>16;INV_SUB_MIX_2[sx]=t<<8|t>>>24;INV_SUB_MIX_3[sx]=t;if(!x){x=xi=1}else{x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]]}}})();var RCON=[0,1,2,4,8,16,32,64,128,27,54];var AES=C_algo.AES=BlockCipher.extend({_doReset:function(){var t;if(this._nRounds&&this._keyPriorReset===this._key){return}var key=this._keyPriorReset=this._key;var keyWords=key.words;var keySize=key.sigBytes/4;var nRounds=this._nRounds=keySize+6;var ksRows=(nRounds+1)*4;var keySchedule=this._keySchedule=[];for(var ksRow=0;ksRow>>24;t=SBOX[t>>>24]<<24|SBOX[t>>>16&255]<<16|SBOX[t>>>8&255]<<8|SBOX[t&255];t^=RCON[ksRow/keySize|0]<<24}else if(keySize>6&&ksRow%keySize==4){t=SBOX[t>>>24]<<24|SBOX[t>>>16&255]<<16|SBOX[t>>>8&255]<<8|SBOX[t&255]}keySchedule[ksRow]=keySchedule[ksRow-keySize]^t}}var invKeySchedule=this._invKeySchedule=[];for(var invKsRow=0;invKsRow>>24]]^INV_SUB_MIX_1[SBOX[t>>>16&255]]^INV_SUB_MIX_2[SBOX[t>>>8&255]]^INV_SUB_MIX_3[SBOX[t&255]]}}},encryptBlock:function(M,offset){this._doCryptBlock(M,offset,this._keySchedule,SUB_MIX_0,SUB_MIX_1,SUB_MIX_2,SUB_MIX_3,SBOX)},decryptBlock:function(M,offset){var t=M[offset+1];M[offset+1]=M[offset+3];M[offset+3]=t;this._doCryptBlock(M,offset,this._invKeySchedule,INV_SUB_MIX_0,INV_SUB_MIX_1,INV_SUB_MIX_2,INV_SUB_MIX_3,INV_SBOX);var t=M[offset+1];M[offset+1]=M[offset+3];M[offset+3]=t},_doCryptBlock:function(M,offset,keySchedule,SUB_MIX_0,SUB_MIX_1,SUB_MIX_2,SUB_MIX_3,SBOX){var nRounds=this._nRounds;var s0=M[offset]^keySchedule[0];var s1=M[offset+1]^keySchedule[1];var s2=M[offset+2]^keySchedule[2];var s3=M[offset+3]^keySchedule[3];var ksRow=4;for(var round=1;round>>24]^SUB_MIX_1[s1>>>16&255]^SUB_MIX_2[s2>>>8&255]^SUB_MIX_3[s3&255]^keySchedule[ksRow++];var t1=SUB_MIX_0[s1>>>24]^SUB_MIX_1[s2>>>16&255]^SUB_MIX_2[s3>>>8&255]^SUB_MIX_3[s0&255]^keySchedule[ksRow++];var t2=SUB_MIX_0[s2>>>24]^SUB_MIX_1[s3>>>16&255]^SUB_MIX_2[s0>>>8&255]^SUB_MIX_3[s1&255]^keySchedule[ksRow++];var t3=SUB_MIX_0[s3>>>24]^SUB_MIX_1[s0>>>16&255]^SUB_MIX_2[s1>>>8&255]^SUB_MIX_3[s2&255]^keySchedule[ksRow++];s0=t0;s1=t1;s2=t2;s3=t3}var t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++];var t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++];var t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++];var t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++];M[offset]=t0;M[offset+1]=t1;M[offset+2]=t2;M[offset+3]=t3},keySize:256/32});C.AES=BlockCipher._createHelper(AES)})();return CryptoJS.AES})},{"./cipher-core":13,"./core":14,"./enc-base64":15,"./evpkdf":18,"./md5":23}],12:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./enc-base64"),require("./md5"),require("./evpkdf"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var BlockCipher=C_lib.BlockCipher;var C_algo=C.algo;const N=16;const ORIG_P=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731];const ORIG_S=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var BLOWFISH_CTX={pbox:[],sbox:[]};function F(ctx,x){let a=x>>24&255;let b=x>>16&255;let c=x>>8&255;let d=x&255;let y=ctx.sbox[0][a]+ctx.sbox[1][b];y=y^ctx.sbox[2][c];y=y+ctx.sbox[3][d];return y}function BlowFish_Encrypt(ctx,left,right){let Xl=left;let Xr=right;let temp;for(let i=0;i1;--i){Xl=Xl^ctx.pbox[i];Xr=F(ctx,Xl)^Xr;temp=Xl;Xl=Xr;Xr=temp}temp=Xl;Xl=Xr;Xr=temp;Xr=Xr^ctx.pbox[1];Xl=Xl^ctx.pbox[0];return{left:Xl,right:Xr}}function BlowFishInit(ctx,key,keysize){for(let Row=0;Row<4;Row++){ctx.sbox[Row]=[];for(let Col=0;Col<256;Col++){ctx.sbox[Row][Col]=ORIG_S[Row][Col]}}let keyIndex=0;for(let index=0;index=keysize){keyIndex=0}}let Data1=0;let Data2=0;let res=0;for(let i=0;i>>2]&255;data.sigBytes-=nPaddingBytes}};var BlockCipher=C_lib.BlockCipher=Cipher.extend({cfg:Cipher.cfg.extend({mode:CBC,padding:Pkcs7}),reset:function(){var modeCreator;Cipher.reset.call(this);var cfg=this.cfg;var iv=cfg.iv;var mode=cfg.mode;if(this._xformMode==this._ENC_XFORM_MODE){modeCreator=mode.createEncryptor}else{modeCreator=mode.createDecryptor;this._minBufferSize=1}if(this._mode&&this._mode.__creator==modeCreator){this._mode.init(this,iv&&iv.words)}else{this._mode=modeCreator.call(mode,this,iv&&iv.words);this._mode.__creator=modeCreator}},_doProcessBlock:function(words,offset){this._mode.processBlock(words,offset)},_doFinalize:function(){var finalProcessedBlocks;var padding=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){padding.pad(this._data,this.blockSize);finalProcessedBlocks=this._process(!!"flush")}else{finalProcessedBlocks=this._process(!!"flush");padding.unpad(finalProcessedBlocks)}return finalProcessedBlocks},blockSize:128/32});var CipherParams=C_lib.CipherParams=Base.extend({init:function(cipherParams){this.mixIn(cipherParams)},toString:function(formatter){return(formatter||this.formatter).stringify(this)}});var C_format=C.format={};var OpenSSLFormatter=C_format.OpenSSL={stringify:function(cipherParams){var wordArray;var ciphertext=cipherParams.ciphertext;var salt=cipherParams.salt;if(salt){wordArray=WordArray.create([1398893684,1701076831]).concat(salt).concat(ciphertext)}else{wordArray=ciphertext}return wordArray.toString(Base64)},parse:function(openSSLStr){var salt;var ciphertext=Base64.parse(openSSLStr);var ciphertextWords=ciphertext.words;if(ciphertextWords[0]==1398893684&&ciphertextWords[1]==1701076831){salt=WordArray.create(ciphertextWords.slice(2,4));ciphertextWords.splice(0,4);ciphertext.sigBytes-=16}return CipherParams.create({ciphertext:ciphertext,salt:salt})}};var SerializableCipher=C_lib.SerializableCipher=Base.extend({cfg:Base.extend({format:OpenSSLFormatter}),encrypt:function(cipher,message,key,cfg){cfg=this.cfg.extend(cfg);var encryptor=cipher.createEncryptor(key,cfg);var ciphertext=encryptor.finalize(message);var cipherCfg=encryptor.cfg;return CipherParams.create({ciphertext:ciphertext,key:key,iv:cipherCfg.iv,algorithm:cipher,mode:cipherCfg.mode,padding:cipherCfg.padding,blockSize:cipher.blockSize,formatter:cfg.format})},decrypt:function(cipher,ciphertext,key,cfg){cfg=this.cfg.extend(cfg);ciphertext=this._parse(ciphertext,cfg.format);var plaintext=cipher.createDecryptor(key,cfg).finalize(ciphertext.ciphertext);return plaintext},_parse:function(ciphertext,format){if(typeof ciphertext=="string"){return format.parse(ciphertext,this)}else{return ciphertext}}});var C_kdf=C.kdf={};var OpenSSLKdf=C_kdf.OpenSSL={execute:function(password,keySize,ivSize,salt,hasher){if(!salt){salt=WordArray.random(64/8)}if(!hasher){var key=EvpKDF.create({keySize:keySize+ivSize}).compute(password,salt)}else{var key=EvpKDF.create({keySize:keySize+ivSize,hasher:hasher}).compute(password,salt)}var iv=WordArray.create(key.words.slice(keySize),ivSize*4);key.sigBytes=keySize*4;return CipherParams.create({key:key,iv:iv,salt:salt})}};var PasswordBasedCipher=C_lib.PasswordBasedCipher=SerializableCipher.extend({cfg:SerializableCipher.cfg.extend({kdf:OpenSSLKdf}),encrypt:function(cipher,message,password,cfg){cfg=this.cfg.extend(cfg);var derivedParams=cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,cfg.salt,cfg.hasher);cfg.iv=derivedParams.iv;var ciphertext=SerializableCipher.encrypt.call(this,cipher,message,derivedParams.key,cfg);ciphertext.mixIn(derivedParams);return ciphertext},decrypt:function(cipher,ciphertext,password,cfg){cfg=this.cfg.extend(cfg);ciphertext=this._parse(ciphertext,cfg.format);var derivedParams=cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,ciphertext.salt,cfg.hasher);cfg.iv=derivedParams.iv;var plaintext=SerializableCipher.decrypt.call(this,cipher,ciphertext,derivedParams.key,cfg);return plaintext}})}()})},{"./core":14,"./evpkdf":18}],14:[function(require,module,exports){(function(global){(function(){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory()}else if(typeof define==="function"&&define.amd){define([],factory)}else{root.CryptoJS=factory()}})(this,function(){var CryptoJS=CryptoJS||function(Math,undefined){var crypto;if(typeof window!=="undefined"&&window.crypto){crypto=window.crypto}if(typeof self!=="undefined"&&self.crypto){crypto=self.crypto}if(typeof globalThis!=="undefined"&&globalThis.crypto){crypto=globalThis.crypto}if(!crypto&&typeof window!=="undefined"&&window.msCrypto){crypto=window.msCrypto}if(!crypto&&typeof global!=="undefined"&&global.crypto){crypto=global.crypto}if(!crypto&&typeof require==="function"){try{crypto=require("crypto")}catch(err){}}var cryptoSecureRandomInt=function(){if(crypto){if(typeof crypto.getRandomValues==="function"){try{return crypto.getRandomValues(new Uint32Array(1))[0]}catch(err){}}if(typeof crypto.randomBytes==="function"){try{return crypto.randomBytes(4).readInt32LE()}catch(err){}}}throw new Error("Native crypto module could not be used to get secure random number.")};var create=Object.create||function(){function F(){}return function(obj){var subtype;F.prototype=obj;subtype=new F;F.prototype=null;return subtype}}();var C={};var C_lib=C.lib={};var Base=C_lib.Base=function(){return{extend:function(overrides){var subtype=create(this);if(overrides){subtype.mixIn(overrides)}if(!subtype.hasOwnProperty("init")||this.init===subtype.init){subtype.init=function(){subtype.$super.init.apply(this,arguments)}}subtype.init.prototype=subtype;subtype.$super=this;return subtype},create:function(){var instance=this.extend();instance.init.apply(instance,arguments);return instance},init:function(){},mixIn:function(properties){for(var propertyName in properties){if(properties.hasOwnProperty(propertyName)){this[propertyName]=properties[propertyName]}}if(properties.hasOwnProperty("toString")){this.toString=properties.toString}},clone:function(){return this.init.prototype.extend(this)}}}();var WordArray=C_lib.WordArray=Base.extend({init:function(words,sigBytes){words=this.words=words||[];if(sigBytes!=undefined){this.sigBytes=sigBytes}else{this.sigBytes=words.length*4}},toString:function(encoder){return(encoder||Hex).stringify(this)},concat:function(wordArray){var thisWords=this.words;var thatWords=wordArray.words;var thisSigBytes=this.sigBytes;var thatSigBytes=wordArray.sigBytes;this.clamp();if(thisSigBytes%4){for(var i=0;i>>2]>>>24-i%4*8&255;thisWords[thisSigBytes+i>>>2]|=thatByte<<24-(thisSigBytes+i)%4*8}}else{for(var j=0;j>>2]=thatWords[j>>>2]}}this.sigBytes+=thatSigBytes;return this},clamp:function(){var words=this.words;var sigBytes=this.sigBytes;words[sigBytes>>>2]&=4294967295<<32-sigBytes%4*8;words.length=Math.ceil(sigBytes/4)},clone:function(){var clone=Base.clone.call(this);clone.words=this.words.slice(0);return clone},random:function(nBytes){var words=[];for(var i=0;i>>2]>>>24-i%4*8&255;hexChars.push((bite>>>4).toString(16));hexChars.push((bite&15).toString(16))}return hexChars.join("")},parse:function(hexStr){var hexStrLength=hexStr.length;var words=[];for(var i=0;i>>3]|=parseInt(hexStr.substr(i,2),16)<<24-i%8*4}return new WordArray.init(words,hexStrLength/2)}};var Latin1=C_enc.Latin1={stringify:function(wordArray){var words=wordArray.words;var sigBytes=wordArray.sigBytes;var latin1Chars=[];for(var i=0;i>>2]>>>24-i%4*8&255;latin1Chars.push(String.fromCharCode(bite))}return latin1Chars.join("")},parse:function(latin1Str){var latin1StrLength=latin1Str.length;var words=[];for(var i=0;i>>2]|=(latin1Str.charCodeAt(i)&255)<<24-i%4*8}return new WordArray.init(words,latin1StrLength)}};var Utf8=C_enc.Utf8={stringify:function(wordArray){try{return decodeURIComponent(escape(Latin1.stringify(wordArray)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(utf8Str){return Latin1.parse(unescape(encodeURIComponent(utf8Str)))}};var BufferedBlockAlgorithm=C_lib.BufferedBlockAlgorithm=Base.extend({reset:function(){this._data=new WordArray.init;this._nDataBytes=0},_append:function(data){if(typeof data=="string"){data=Utf8.parse(data)}this._data.concat(data);this._nDataBytes+=data.sigBytes},_process:function(doFlush){var processedWords;var data=this._data;var dataWords=data.words;var dataSigBytes=data.sigBytes;var blockSize=this.blockSize;var blockSizeBytes=blockSize*4;var nBlocksReady=dataSigBytes/blockSizeBytes;if(doFlush){nBlocksReady=Math.ceil(nBlocksReady)}else{nBlocksReady=Math.max((nBlocksReady|0)-this._minBufferSize,0)}var nWordsReady=nBlocksReady*blockSize;var nBytesReady=Math.min(nWordsReady*4,dataSigBytes);if(nWordsReady){for(var offset=0;offset>>2]>>>24-i%4*8&255;var byte2=words[i+1>>>2]>>>24-(i+1)%4*8&255;var byte3=words[i+2>>>2]>>>24-(i+2)%4*8&255;var triplet=byte1<<16|byte2<<8|byte3;for(var j=0;j<4&&i+j*.75>>6*(3-j)&63))}}var paddingChar=map.charAt(64);if(paddingChar){while(base64Chars.length%4){base64Chars.push(paddingChar)}}return base64Chars.join("")},parse:function(base64Str){var base64StrLength=base64Str.length;var map=this._map;var reverseMap=this._reverseMap;if(!reverseMap){reverseMap=this._reverseMap=[];for(var j=0;j>>6-i%4*2;var bitsCombined=bits1|bits2;words[nBytes>>>2]|=bitsCombined<<24-nBytes%4*8;nBytes++}}return WordArray.create(words,nBytes)}})();return CryptoJS.enc.Base64})},{"./core":14}],16:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var C_enc=C.enc;var Base64url=C_enc.Base64url={stringify:function(wordArray,urlSafe){if(urlSafe===undefined){urlSafe=true}var words=wordArray.words;var sigBytes=wordArray.sigBytes;var map=urlSafe?this._safe_map:this._map;wordArray.clamp();var base64Chars=[];for(var i=0;i>>2]>>>24-i%4*8&255;var byte2=words[i+1>>>2]>>>24-(i+1)%4*8&255;var byte3=words[i+2>>>2]>>>24-(i+2)%4*8&255;var triplet=byte1<<16|byte2<<8|byte3;for(var j=0;j<4&&i+j*.75>>6*(3-j)&63))}}var paddingChar=map.charAt(64);if(paddingChar){while(base64Chars.length%4){base64Chars.push(paddingChar)}}return base64Chars.join("")},parse:function(base64Str,urlSafe){if(urlSafe===undefined){urlSafe=true}var base64StrLength=base64Str.length;var map=urlSafe?this._safe_map:this._map;var reverseMap=this._reverseMap;if(!reverseMap){reverseMap=this._reverseMap=[];for(var j=0;j>>6-i%4*2;var bitsCombined=bits1|bits2;words[nBytes>>>2]|=bitsCombined<<24-nBytes%4*8;nBytes++}}return WordArray.create(words,nBytes)}})();return CryptoJS.enc.Base64url})},{"./core":14}],17:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var C_enc=C.enc;var Utf16BE=C_enc.Utf16=C_enc.Utf16BE={stringify:function(wordArray){var words=wordArray.words;var sigBytes=wordArray.sigBytes;var utf16Chars=[];for(var i=0;i>>2]>>>16-i%4*8&65535;utf16Chars.push(String.fromCharCode(codePoint))}return utf16Chars.join("")},parse:function(utf16Str){var utf16StrLength=utf16Str.length;var words=[];for(var i=0;i>>1]|=utf16Str.charCodeAt(i)<<16-i%2*16}return WordArray.create(words,utf16StrLength*2)}};C_enc.Utf16LE={stringify:function(wordArray){var words=wordArray.words;var sigBytes=wordArray.sigBytes;var utf16Chars=[];for(var i=0;i>>2]>>>16-i%4*8&65535);utf16Chars.push(String.fromCharCode(codePoint))}return utf16Chars.join("")},parse:function(utf16Str){var utf16StrLength=utf16Str.length;var words=[];for(var i=0;i>>1]|=swapEndian(utf16Str.charCodeAt(i)<<16-i%2*16)}return WordArray.create(words,utf16StrLength*2)}};function swapEndian(word){return word<<8&4278255360|word>>>8&16711935}})();return CryptoJS.enc.Utf16})},{"./core":14}],18:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./sha1"),require("./hmac"))}else if(typeof define==="function"&&define.amd){define(["./core","./sha1","./hmac"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var Base=C_lib.Base;var WordArray=C_lib.WordArray;var C_algo=C.algo;var MD5=C_algo.MD5;var EvpKDF=C_algo.EvpKDF=Base.extend({cfg:Base.extend({keySize:128/32,hasher:MD5,iterations:1}),init:function(cfg){this.cfg=this.cfg.extend(cfg)},compute:function(password,salt){var block;var cfg=this.cfg;var hasher=cfg.hasher.create();var derivedKey=WordArray.create();var derivedKeyWords=derivedKey.words;var keySize=cfg.keySize;var iterations=cfg.iterations;while(derivedKeyWords.lengthhasherBlockSizeBytes){key=hasher.finalize(key)}key.clamp();var oKey=this._oKey=key.clone();var iKey=this._iKey=key.clone();var oKeyWords=oKey.words;var iKeyWords=iKey.words;for(var i=0;i>>2]|=typedArray[i]<<24-i%4*8}superInit.call(this,words,typedArrayByteLength)}else{superInit.apply(this,arguments)}};subInit.prototype=WordArray})();return CryptoJS.lib.WordArray})},{"./core":14}],23:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(Math){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;var T=[];(function(){for(var i=0;i<64;i++){T[i]=Math.abs(Math.sin(i+1))*4294967296|0}})();var MD5=C_algo.MD5=Hasher.extend({_doReset:function(){this._hash=new WordArray.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var H=this._hash.words;var M_offset_0=M[offset+0];var M_offset_1=M[offset+1];var M_offset_2=M[offset+2];var M_offset_3=M[offset+3];var M_offset_4=M[offset+4];var M_offset_5=M[offset+5];var M_offset_6=M[offset+6];var M_offset_7=M[offset+7];var M_offset_8=M[offset+8];var M_offset_9=M[offset+9];var M_offset_10=M[offset+10];var M_offset_11=M[offset+11];var M_offset_12=M[offset+12];var M_offset_13=M[offset+13];var M_offset_14=M[offset+14];var M_offset_15=M[offset+15];var a=H[0];var b=H[1];var c=H[2];var d=H[3];a=FF(a,b,c,d,M_offset_0,7,T[0]);d=FF(d,a,b,c,M_offset_1,12,T[1]);c=FF(c,d,a,b,M_offset_2,17,T[2]);b=FF(b,c,d,a,M_offset_3,22,T[3]);a=FF(a,b,c,d,M_offset_4,7,T[4]);d=FF(d,a,b,c,M_offset_5,12,T[5]);c=FF(c,d,a,b,M_offset_6,17,T[6]);b=FF(b,c,d,a,M_offset_7,22,T[7]);a=FF(a,b,c,d,M_offset_8,7,T[8]);d=FF(d,a,b,c,M_offset_9,12,T[9]);c=FF(c,d,a,b,M_offset_10,17,T[10]);b=FF(b,c,d,a,M_offset_11,22,T[11]);a=FF(a,b,c,d,M_offset_12,7,T[12]);d=FF(d,a,b,c,M_offset_13,12,T[13]);c=FF(c,d,a,b,M_offset_14,17,T[14]);b=FF(b,c,d,a,M_offset_15,22,T[15]);a=GG(a,b,c,d,M_offset_1,5,T[16]);d=GG(d,a,b,c,M_offset_6,9,T[17]);c=GG(c,d,a,b,M_offset_11,14,T[18]);b=GG(b,c,d,a,M_offset_0,20,T[19]);a=GG(a,b,c,d,M_offset_5,5,T[20]);d=GG(d,a,b,c,M_offset_10,9,T[21]);c=GG(c,d,a,b,M_offset_15,14,T[22]);b=GG(b,c,d,a,M_offset_4,20,T[23]);a=GG(a,b,c,d,M_offset_9,5,T[24]);d=GG(d,a,b,c,M_offset_14,9,T[25]);c=GG(c,d,a,b,M_offset_3,14,T[26]);b=GG(b,c,d,a,M_offset_8,20,T[27]);a=GG(a,b,c,d,M_offset_13,5,T[28]);d=GG(d,a,b,c,M_offset_2,9,T[29]);c=GG(c,d,a,b,M_offset_7,14,T[30]);b=GG(b,c,d,a,M_offset_12,20,T[31]);a=HH(a,b,c,d,M_offset_5,4,T[32]);d=HH(d,a,b,c,M_offset_8,11,T[33]);c=HH(c,d,a,b,M_offset_11,16,T[34]);b=HH(b,c,d,a,M_offset_14,23,T[35]);a=HH(a,b,c,d,M_offset_1,4,T[36]);d=HH(d,a,b,c,M_offset_4,11,T[37]);c=HH(c,d,a,b,M_offset_7,16,T[38]);b=HH(b,c,d,a,M_offset_10,23,T[39]);a=HH(a,b,c,d,M_offset_13,4,T[40]);d=HH(d,a,b,c,M_offset_0,11,T[41]);c=HH(c,d,a,b,M_offset_3,16,T[42]);b=HH(b,c,d,a,M_offset_6,23,T[43]);a=HH(a,b,c,d,M_offset_9,4,T[44]);d=HH(d,a,b,c,M_offset_12,11,T[45]);c=HH(c,d,a,b,M_offset_15,16,T[46]);b=HH(b,c,d,a,M_offset_2,23,T[47]);a=II(a,b,c,d,M_offset_0,6,T[48]);d=II(d,a,b,c,M_offset_7,10,T[49]);c=II(c,d,a,b,M_offset_14,15,T[50]);b=II(b,c,d,a,M_offset_5,21,T[51]);a=II(a,b,c,d,M_offset_12,6,T[52]);d=II(d,a,b,c,M_offset_3,10,T[53]);c=II(c,d,a,b,M_offset_10,15,T[54]);b=II(b,c,d,a,M_offset_1,21,T[55]);a=II(a,b,c,d,M_offset_8,6,T[56]);d=II(d,a,b,c,M_offset_15,10,T[57]);c=II(c,d,a,b,M_offset_6,15,T[58]);b=II(b,c,d,a,M_offset_13,21,T[59]);a=II(a,b,c,d,M_offset_4,6,T[60]);d=II(d,a,b,c,M_offset_11,10,T[61]);c=II(c,d,a,b,M_offset_2,15,T[62]);b=II(b,c,d,a,M_offset_9,21,T[63]);H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0},_doFinalize:function(){var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;var nBitsTotalH=Math.floor(nBitsTotal/4294967296);var nBitsTotalL=nBitsTotal;dataWords[(nBitsLeft+64>>>9<<4)+15]=(nBitsTotalH<<8|nBitsTotalH>>>24)&16711935|(nBitsTotalH<<24|nBitsTotalH>>>8)&4278255360;dataWords[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotalL<<8|nBitsTotalL>>>24)&16711935|(nBitsTotalL<<24|nBitsTotalL>>>8)&4278255360;data.sigBytes=(dataWords.length+1)*4;this._process();var hash=this._hash;var H=hash.words;for(var i=0;i<4;i++){var H_i=H[i];H[i]=(H_i<<8|H_i>>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}return hash},clone:function(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone}});function FF(a,b,c,d,x,s,t){var n=a+(b&c|~b&d)+x+t;return(n<>>32-s)+b}function GG(a,b,c,d,x,s,t){var n=a+(b&d|c&~d)+x+t;return(n<>>32-s)+b}function HH(a,b,c,d,x,s,t){var n=a+(b^c^d)+x+t;return(n<>>32-s)+b}function II(a,b,c,d,x,s,t){var n=a+(c^(b|~d))+x+t;return(n<>>32-s)+b}C.MD5=Hasher._createHelper(MD5);C.HmacMD5=Hasher._createHmacHelper(MD5)})(Math);return CryptoJS.MD5})},{"./core":14}],24:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){CryptoJS.mode.CFB=function(){var CFB=CryptoJS.lib.BlockCipherMode.extend();CFB.Encryptor=CFB.extend({processBlock:function(words,offset){var cipher=this._cipher;var blockSize=cipher.blockSize;generateKeystreamAndEncrypt.call(this,words,offset,blockSize,cipher);this._prevBlock=words.slice(offset,offset+blockSize)}});CFB.Decryptor=CFB.extend({processBlock:function(words,offset){var cipher=this._cipher;var blockSize=cipher.blockSize;var thisBlock=words.slice(offset,offset+blockSize);generateKeystreamAndEncrypt.call(this,words,offset,blockSize,cipher);this._prevBlock=thisBlock}});function generateKeystreamAndEncrypt(words,offset,blockSize,cipher){var keystream;var iv=this._iv;if(iv){keystream=iv.slice(0);this._iv=undefined}else{keystream=this._prevBlock}cipher.encryptBlock(keystream,0);for(var i=0;i>24&255)===255){var b1=word>>16&255;var b2=word>>8&255;var b3=word&255;if(b1===255){b1=0;if(b2===255){b2=0;if(b3===255){b3=0}else{++b3}}else{++b2}}else{++b1}word=0;word+=b1<<16;word+=b2<<8;word+=b3}else{word+=1<<24}return word}function incCounter(counter){if((counter[0]=incWord(counter[0]))===0){counter[1]=incWord(counter[1])}return counter}var Encryptor=CTRGladman.Encryptor=CTRGladman.extend({processBlock:function(words,offset){var cipher=this._cipher;var blockSize=cipher.blockSize;var iv=this._iv;var counter=this._counter;if(iv){counter=this._counter=iv.slice(0);this._iv=undefined}incCounter(counter);var keystream=counter.slice(0);cipher.encryptBlock(keystream,0);for(var i=0;i>>2]|=nPaddingBytes<<24-lastBytePos%4*8;data.sigBytes+=nPaddingBytes},unpad:function(data){var nPaddingBytes=data.words[data.sigBytes-1>>>2]&255;data.sigBytes-=nPaddingBytes}};return CryptoJS.pad.Ansix923})},{"./cipher-core":13,"./core":14}],30:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){CryptoJS.pad.Iso10126={pad:function(data,blockSize){var blockSizeBytes=blockSize*4;var nPaddingBytes=blockSizeBytes-data.sigBytes%blockSizeBytes;data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes-1)).concat(CryptoJS.lib.WordArray.create([nPaddingBytes<<24],1))},unpad:function(data){var nPaddingBytes=data.words[data.sigBytes-1>>>2]&255;data.sigBytes-=nPaddingBytes}};return CryptoJS.pad.Iso10126})},{"./cipher-core":13,"./core":14}],31:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){CryptoJS.pad.Iso97971={pad:function(data,blockSize){data.concat(CryptoJS.lib.WordArray.create([2147483648],1));CryptoJS.pad.ZeroPadding.pad(data,blockSize)},unpad:function(data){CryptoJS.pad.ZeroPadding.unpad(data);data.sigBytes--}};return CryptoJS.pad.Iso97971})},{"./cipher-core":13,"./core":14}],32:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){CryptoJS.pad.NoPadding={pad:function(){},unpad:function(){}};return CryptoJS.pad.NoPadding})},{"./cipher-core":13,"./core":14}],33:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){CryptoJS.pad.ZeroPadding={pad:function(data,blockSize){var blockSizeBytes=blockSize*4;data.clamp();data.sigBytes+=blockSizeBytes-(data.sigBytes%blockSizeBytes||blockSizeBytes)},unpad:function(data){var dataWords=data.words;var i=data.sigBytes-1;for(var i=data.sigBytes-1;i>=0;i--){if(dataWords[i>>>2]>>>24-i%4*8&255){data.sigBytes=i+1;break}}}};return CryptoJS.pad.ZeroPadding})},{"./cipher-core":13,"./core":14}],34:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./sha256"),require("./hmac"))}else if(typeof define==="function"&&define.amd){define(["./core","./sha256","./hmac"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var Base=C_lib.Base;var WordArray=C_lib.WordArray;var C_algo=C.algo;var SHA256=C_algo.SHA256;var HMAC=C_algo.HMAC;var PBKDF2=C_algo.PBKDF2=Base.extend({cfg:Base.extend({keySize:128/32,hasher:SHA256,iterations:25e4}),init:function(cfg){this.cfg=this.cfg.extend(cfg)},compute:function(password,salt){var cfg=this.cfg;var hmac=HMAC.create(cfg.hasher,password);var derivedKey=WordArray.create();var blockIndex=WordArray.create([1]);var derivedKeyWords=derivedKey.words;var blockIndexWords=blockIndex.words;var keySize=cfg.keySize;var iterations=cfg.iterations;while(derivedKeyWords.length>>16,K[1],K[0]<<16|K[3]>>>16,K[2],K[1]<<16|K[0]>>>16,K[3],K[2]<<16|K[1]>>>16];var C=this._C=[K[2]<<16|K[2]>>>16,K[0]&4294901760|K[1]&65535,K[3]<<16|K[3]>>>16,K[1]&4294901760|K[2]&65535,K[0]<<16|K[0]>>>16,K[2]&4294901760|K[3]&65535,K[1]<<16|K[1]>>>16,K[3]&4294901760|K[0]&65535];this._b=0;for(var i=0;i<4;i++){nextState.call(this)}for(var i=0;i<8;i++){C[i]^=X[i+4&7]}if(iv){var IV=iv.words;var IV_0=IV[0];var IV_1=IV[1];var i0=(IV_0<<8|IV_0>>>24)&16711935|(IV_0<<24|IV_0>>>8)&4278255360;var i2=(IV_1<<8|IV_1>>>24)&16711935|(IV_1<<24|IV_1>>>8)&4278255360;var i1=i0>>>16|i2&4294901760;var i3=i2<<16|i0&65535;C[0]^=i0;C[1]^=i1;C[2]^=i2;C[3]^=i3;C[4]^=i0;C[5]^=i1;C[6]^=i2;C[7]^=i3;for(var i=0;i<4;i++){nextState.call(this)}}},_doProcessBlock:function(M,offset){var X=this._X;nextState.call(this);S[0]=X[0]^X[5]>>>16^X[3]<<16;S[1]=X[2]^X[7]>>>16^X[5]<<16;S[2]=X[4]^X[1]>>>16^X[7]<<16;S[3]=X[6]^X[3]>>>16^X[1]<<16;for(var i=0;i<4;i++){S[i]=(S[i]<<8|S[i]>>>24)&16711935|(S[i]<<24|S[i]>>>8)&4278255360;M[offset+i]^=S[i]}},blockSize:128/32,ivSize:64/32});function nextState(){var X=this._X;var C=this._C;for(var i=0;i<8;i++){C_[i]=C[i]}C[0]=C[0]+1295307597+this._b|0;C[1]=C[1]+3545052371+(C[0]>>>0>>0?1:0)|0;C[2]=C[2]+886263092+(C[1]>>>0>>0?1:0)|0;C[3]=C[3]+1295307597+(C[2]>>>0>>0?1:0)|0;C[4]=C[4]+3545052371+(C[3]>>>0>>0?1:0)|0;C[5]=C[5]+886263092+(C[4]>>>0>>0?1:0)|0;C[6]=C[6]+1295307597+(C[5]>>>0>>0?1:0)|0;C[7]=C[7]+3545052371+(C[6]>>>0>>0?1:0)|0;this._b=C[7]>>>0>>0?1:0;for(var i=0;i<8;i++){var gx=X[i]+C[i];var ga=gx&65535;var gb=gx>>>16;var gh=((ga*ga>>>17)+ga*gb>>>15)+gb*gb;var gl=((gx&4294901760)*gx|0)+((gx&65535)*gx|0);G[i]=gh^gl}X[0]=G[0]+(G[7]<<16|G[7]>>>16)+(G[6]<<16|G[6]>>>16)|0;X[1]=G[1]+(G[0]<<8|G[0]>>>24)+G[7]|0;X[2]=G[2]+(G[1]<<16|G[1]>>>16)+(G[0]<<16|G[0]>>>16)|0;X[3]=G[3]+(G[2]<<8|G[2]>>>24)+G[1]|0;X[4]=G[4]+(G[3]<<16|G[3]>>>16)+(G[2]<<16|G[2]>>>16)|0;X[5]=G[5]+(G[4]<<8|G[4]>>>24)+G[3]|0;X[6]=G[6]+(G[5]<<16|G[5]>>>16)+(G[4]<<16|G[4]>>>16)|0;X[7]=G[7]+(G[6]<<8|G[6]>>>24)+G[5]|0}C.RabbitLegacy=StreamCipher._createHelper(RabbitLegacy)})();return CryptoJS.RabbitLegacy})},{"./cipher-core":13,"./core":14,"./enc-base64":15,"./evpkdf":18,"./md5":23}],36:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./enc-base64"),require("./md5"),require("./evpkdf"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var StreamCipher=C_lib.StreamCipher;var C_algo=C.algo;var S=[];var C_=[];var G=[];var Rabbit=C_algo.Rabbit=StreamCipher.extend({_doReset:function(){var K=this._key.words;var iv=this.cfg.iv;for(var i=0;i<4;i++){K[i]=(K[i]<<8|K[i]>>>24)&16711935|(K[i]<<24|K[i]>>>8)&4278255360}var X=this._X=[K[0],K[3]<<16|K[2]>>>16,K[1],K[0]<<16|K[3]>>>16,K[2],K[1]<<16|K[0]>>>16,K[3],K[2]<<16|K[1]>>>16];var C=this._C=[K[2]<<16|K[2]>>>16,K[0]&4294901760|K[1]&65535,K[3]<<16|K[3]>>>16,K[1]&4294901760|K[2]&65535,K[0]<<16|K[0]>>>16,K[2]&4294901760|K[3]&65535,K[1]<<16|K[1]>>>16,K[3]&4294901760|K[0]&65535];this._b=0;for(var i=0;i<4;i++){nextState.call(this)}for(var i=0;i<8;i++){C[i]^=X[i+4&7]}if(iv){var IV=iv.words;var IV_0=IV[0];var IV_1=IV[1];var i0=(IV_0<<8|IV_0>>>24)&16711935|(IV_0<<24|IV_0>>>8)&4278255360;var i2=(IV_1<<8|IV_1>>>24)&16711935|(IV_1<<24|IV_1>>>8)&4278255360;var i1=i0>>>16|i2&4294901760;var i3=i2<<16|i0&65535;C[0]^=i0;C[1]^=i1;C[2]^=i2;C[3]^=i3;C[4]^=i0;C[5]^=i1;C[6]^=i2;C[7]^=i3;for(var i=0;i<4;i++){nextState.call(this)}}},_doProcessBlock:function(M,offset){var X=this._X;nextState.call(this);S[0]=X[0]^X[5]>>>16^X[3]<<16;S[1]=X[2]^X[7]>>>16^X[5]<<16;S[2]=X[4]^X[1]>>>16^X[7]<<16;S[3]=X[6]^X[3]>>>16^X[1]<<16;for(var i=0;i<4;i++){S[i]=(S[i]<<8|S[i]>>>24)&16711935|(S[i]<<24|S[i]>>>8)&4278255360;M[offset+i]^=S[i]}},blockSize:128/32,ivSize:64/32});function nextState(){var X=this._X;var C=this._C;for(var i=0;i<8;i++){C_[i]=C[i]}C[0]=C[0]+1295307597+this._b|0;C[1]=C[1]+3545052371+(C[0]>>>0>>0?1:0)|0;C[2]=C[2]+886263092+(C[1]>>>0>>0?1:0)|0;C[3]=C[3]+1295307597+(C[2]>>>0>>0?1:0)|0;C[4]=C[4]+3545052371+(C[3]>>>0>>0?1:0)|0;C[5]=C[5]+886263092+(C[4]>>>0>>0?1:0)|0;C[6]=C[6]+1295307597+(C[5]>>>0>>0?1:0)|0;C[7]=C[7]+3545052371+(C[6]>>>0>>0?1:0)|0;this._b=C[7]>>>0>>0?1:0;for(var i=0;i<8;i++){var gx=X[i]+C[i];var ga=gx&65535;var gb=gx>>>16;var gh=((ga*ga>>>17)+ga*gb>>>15)+gb*gb;var gl=((gx&4294901760)*gx|0)+((gx&65535)*gx|0);G[i]=gh^gl}X[0]=G[0]+(G[7]<<16|G[7]>>>16)+(G[6]<<16|G[6]>>>16)|0;X[1]=G[1]+(G[0]<<8|G[0]>>>24)+G[7]|0;X[2]=G[2]+(G[1]<<16|G[1]>>>16)+(G[0]<<16|G[0]>>>16)|0;X[3]=G[3]+(G[2]<<8|G[2]>>>24)+G[1]|0;X[4]=G[4]+(G[3]<<16|G[3]>>>16)+(G[2]<<16|G[2]>>>16)|0;X[5]=G[5]+(G[4]<<8|G[4]>>>24)+G[3]|0;X[6]=G[6]+(G[5]<<16|G[5]>>>16)+(G[4]<<16|G[4]>>>16)|0;X[7]=G[7]+(G[6]<<8|G[6]>>>24)+G[5]|0}C.Rabbit=StreamCipher._createHelper(Rabbit)})();return CryptoJS.Rabbit})},{"./cipher-core":13,"./core":14,"./enc-base64":15,"./evpkdf":18,"./md5":23}],37:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./enc-base64"),require("./md5"),require("./evpkdf"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var StreamCipher=C_lib.StreamCipher;var C_algo=C.algo;var RC4=C_algo.RC4=StreamCipher.extend({_doReset:function(){var key=this._key;var keyWords=key.words;var keySigBytes=key.sigBytes;var S=this._S=[];for(var i=0;i<256;i++){S[i]=i}for(var i=0,j=0;i<256;i++){var keyByteIndex=i%keySigBytes;var keyByte=keyWords[keyByteIndex>>>2]>>>24-keyByteIndex%4*8&255;j=(j+S[i]+keyByte)%256;var t=S[i];S[i]=S[j];S[j]=t}this._i=this._j=0},_doProcessBlock:function(M,offset){M[offset]^=generateKeystreamWord.call(this)},keySize:256/32,ivSize:0});function generateKeystreamWord(){var S=this._S;var i=this._i;var j=this._j;var keystreamWord=0;for(var n=0;n<4;n++){i=(i+1)%256;j=(j+S[i])%256;var t=S[i];S[i]=S[j];S[j]=t;keystreamWord|=S[(S[i]+S[j])%256]<<24-n*8}this._i=i;this._j=j;return keystreamWord}C.RC4=StreamCipher._createHelper(RC4);var RC4Drop=C_algo.RC4Drop=RC4.extend({cfg:RC4.cfg.extend({drop:192}),_doReset:function(){RC4._doReset.call(this);for(var i=this.cfg.drop;i>0;i--){generateKeystreamWord.call(this)}}});C.RC4Drop=StreamCipher._createHelper(RC4Drop)})();return CryptoJS.RC4})},{"./cipher-core":13,"./core":14,"./enc-base64":15,"./evpkdf":18,"./md5":23}],38:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(Math){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;var _zl=WordArray.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]);var _zr=WordArray.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]);var _sl=WordArray.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]);var _sr=WordArray.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]);var _hl=WordArray.create([0,1518500249,1859775393,2400959708,2840853838]);var _hr=WordArray.create([1352829926,1548603684,1836072691,2053994217,0]);var RIPEMD160=C_algo.RIPEMD160=Hasher.extend({_doReset:function(){this._hash=WordArray.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var H=this._hash.words;var hl=_hl.words;var hr=_hr.words;var zl=_zl.words;var zr=_zr.words;var sl=_sl.words;var sr=_sr.words;var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(var i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t},_doFinalize:function(){var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;dataWords[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;data.sigBytes=(dataWords.length+1)*4;this._process();var hash=this._hash;var H=hash.words;for(var i=0;i<5;i++){var H_i=H[i];H[i]=(H_i<<8|H_i>>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}return hash},clone:function(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone}});function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}C.RIPEMD160=Hasher._createHelper(RIPEMD160);C.HmacRIPEMD160=Hasher._createHmacHelper(RIPEMD160)})(Math);return CryptoJS.RIPEMD160})},{"./core":14}],39:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;var W=[];var SHA1=C_algo.SHA1=Hasher.extend({_doReset:function(){this._hash=new WordArray.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(M,offset){var H=this._hash.words;var a=H[0];var b=H[1];var c=H[2];var d=H[3];var e=H[4];for(var i=0;i<80;i++){if(i<16){W[i]=M[offset+i]|0}else{var n=W[i-3]^W[i-8]^W[i-14]^W[i-16];W[i]=n<<1|n>>>31}var t=(a<<5|a>>>27)+e+W[i];if(i<20){t+=(b&c|~b&d)+1518500249}else if(i<40){t+=(b^c^d)+1859775393}else if(i<60){t+=(b&c|b&d|c&d)-1894007588}else{t+=(b^c^d)-899497514}e=d;d=c;c=b<<30|b>>>2;b=a;a=t}H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0;H[4]=H[4]+e|0},_doFinalize:function(){var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;dataWords[(nBitsLeft+64>>>9<<4)+14]=Math.floor(nBitsTotal/4294967296);dataWords[(nBitsLeft+64>>>9<<4)+15]=nBitsTotal;data.sigBytes=dataWords.length*4;this._process();return this._hash},clone:function(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone}});C.SHA1=Hasher._createHelper(SHA1);C.HmacSHA1=Hasher._createHmacHelper(SHA1)})();return CryptoJS.SHA1})},{"./core":14}],40:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./sha256"))}else if(typeof define==="function"&&define.amd){define(["./core","./sha256"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var C_algo=C.algo;var SHA256=C_algo.SHA256;var SHA224=C_algo.SHA224=SHA256.extend({_doReset:function(){this._hash=new WordArray.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var hash=SHA256._doFinalize.call(this);hash.sigBytes-=4;return hash}});C.SHA224=SHA256._createHelper(SHA224);C.HmacSHA224=SHA256._createHmacHelper(SHA224)})();return CryptoJS.SHA224})},{"./core":14,"./sha256":41}],41:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(Math){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;var H=[];var K=[];(function(){function isPrime(n){var sqrtN=Math.sqrt(n);for(var factor=2;factor<=sqrtN;factor++){if(!(n%factor)){return false}}return true}function getFractionalBits(n){return(n-(n|0))*4294967296|0}var n=2;var nPrime=0;while(nPrime<64){if(isPrime(n)){if(nPrime<8){H[nPrime]=getFractionalBits(Math.pow(n,1/2))}K[nPrime]=getFractionalBits(Math.pow(n,1/3));nPrime++}n++}})();var W=[];var SHA256=C_algo.SHA256=Hasher.extend({_doReset:function(){this._hash=new WordArray.init(H.slice(0))},_doProcessBlock:function(M,offset){var H=this._hash.words;var a=H[0];var b=H[1];var c=H[2];var d=H[3];var e=H[4];var f=H[5];var g=H[6];var h=H[7];for(var i=0;i<64;i++){if(i<16){W[i]=M[offset+i]|0}else{var gamma0x=W[i-15];var gamma0=(gamma0x<<25|gamma0x>>>7)^(gamma0x<<14|gamma0x>>>18)^gamma0x>>>3;var gamma1x=W[i-2];var gamma1=(gamma1x<<15|gamma1x>>>17)^(gamma1x<<13|gamma1x>>>19)^gamma1x>>>10;W[i]=gamma0+W[i-7]+gamma1+W[i-16]}var ch=e&f^~e&g;var maj=a&b^a&c^b&c;var sigma0=(a<<30|a>>>2)^(a<<19|a>>>13)^(a<<10|a>>>22);var sigma1=(e<<26|e>>>6)^(e<<21|e>>>11)^(e<<7|e>>>25);var t1=h+sigma1+ch+K[i]+W[i];var t2=sigma0+maj;h=g;g=f;f=e;e=d+t1|0;d=c;c=b;b=a;a=t1+t2|0}H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0;H[4]=H[4]+e|0;H[5]=H[5]+f|0;H[6]=H[6]+g|0;H[7]=H[7]+h|0},_doFinalize:function(){var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;dataWords[(nBitsLeft+64>>>9<<4)+14]=Math.floor(nBitsTotal/4294967296);dataWords[(nBitsLeft+64>>>9<<4)+15]=nBitsTotal;data.sigBytes=dataWords.length*4;this._process();return this._hash},clone:function(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone}});C.SHA256=Hasher._createHelper(SHA256);C.HmacSHA256=Hasher._createHmacHelper(SHA256)})(Math);return CryptoJS.SHA256})},{"./core":14}],42:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./x64-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./x64-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(Math){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_x64=C.x64;var X64Word=C_x64.Word;var C_algo=C.algo;var RHO_OFFSETS=[];var PI_INDEXES=[];var ROUND_CONSTANTS=[];(function(){var x=1,y=0;for(var t=0;t<24;t++){RHO_OFFSETS[x+5*y]=(t+1)*(t+2)/2%64;var newX=y%5;var newY=(2*x+3*y)%5;x=newX;y=newY}for(var x=0;x<5;x++){for(var y=0;y<5;y++){PI_INDEXES[x+5*y]=y+(2*x+3*y)%5*5}}var LFSR=1;for(var i=0;i<24;i++){var roundConstantMsw=0;var roundConstantLsw=0;for(var j=0;j<7;j++){if(LFSR&1){var bitPosition=(1<>>24)&16711935|(M2i<<24|M2i>>>8)&4278255360;M2i1=(M2i1<<8|M2i1>>>24)&16711935|(M2i1<<24|M2i1>>>8)&4278255360;var lane=state[i];lane.high^=M2i1;lane.low^=M2i}for(var round=0;round<24;round++){for(var x=0;x<5;x++){var tMsw=0,tLsw=0;for(var y=0;y<5;y++){var lane=state[x+5*y];tMsw^=lane.high;tLsw^=lane.low}var Tx=T[x];Tx.high=tMsw;Tx.low=tLsw}for(var x=0;x<5;x++){var Tx4=T[(x+4)%5];var Tx1=T[(x+1)%5];var Tx1Msw=Tx1.high;var Tx1Lsw=Tx1.low;var tMsw=Tx4.high^(Tx1Msw<<1|Tx1Lsw>>>31);var tLsw=Tx4.low^(Tx1Lsw<<1|Tx1Msw>>>31);for(var y=0;y<5;y++){var lane=state[x+5*y];lane.high^=tMsw;lane.low^=tLsw}}for(var laneIndex=1;laneIndex<25;laneIndex++){var tMsw;var tLsw;var lane=state[laneIndex];var laneMsw=lane.high;var laneLsw=lane.low;var rhoOffset=RHO_OFFSETS[laneIndex];if(rhoOffset<32){tMsw=laneMsw<>>32-rhoOffset;tLsw=laneLsw<>>32-rhoOffset}else{tMsw=laneLsw<>>64-rhoOffset;tLsw=laneMsw<>>64-rhoOffset}var TPiLane=T[PI_INDEXES[laneIndex]];TPiLane.high=tMsw;TPiLane.low=tLsw}var T0=T[0];var state0=state[0];T0.high=state0.high;T0.low=state0.low;for(var x=0;x<5;x++){for(var y=0;y<5;y++){var laneIndex=x+5*y;var lane=state[laneIndex];var TLane=T[laneIndex];var Tx1Lane=T[(x+1)%5+5*y];var Tx2Lane=T[(x+2)%5+5*y];lane.high=TLane.high^~Tx1Lane.high&Tx2Lane.high;lane.low=TLane.low^~Tx1Lane.low&Tx2Lane.low}}var lane=state[0];var roundConstant=ROUND_CONSTANTS[round];lane.high^=roundConstant.high;lane.low^=roundConstant.low}},_doFinalize:function(){var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;var blockSizeBits=this.blockSize*32;dataWords[nBitsLeft>>>5]|=1<<24-nBitsLeft%32;dataWords[(Math.ceil((nBitsLeft+1)/blockSizeBits)*blockSizeBits>>>5)-1]|=128;data.sigBytes=dataWords.length*4;this._process();var state=this._state;var outputLengthBytes=this.cfg.outputLength/8;var outputLengthLanes=outputLengthBytes/8;var hashWords=[];for(var i=0;i>>24)&16711935|(laneMsw<<24|laneMsw>>>8)&4278255360;laneLsw=(laneLsw<<8|laneLsw>>>24)&16711935|(laneLsw<<24|laneLsw>>>8)&4278255360;hashWords.push(laneLsw);hashWords.push(laneMsw)}return new WordArray.init(hashWords,outputLengthBytes)},clone:function(){var clone=Hasher.clone.call(this);var state=clone._state=this._state.slice(0);for(var i=0;i<25;i++){state[i]=state[i].clone()}return clone}});C.SHA3=Hasher._createHelper(SHA3);C.HmacSHA3=Hasher._createHmacHelper(SHA3)})(Math);return CryptoJS.SHA3})},{"./core":14,"./x64-core":46}],43:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./x64-core"),require("./sha512"))}else if(typeof define==="function"&&define.amd){define(["./core","./x64-core","./sha512"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_x64=C.x64;var X64Word=C_x64.Word;var X64WordArray=C_x64.WordArray;var C_algo=C.algo;var SHA512=C_algo.SHA512;var SHA384=C_algo.SHA384=SHA512.extend({_doReset:function(){this._hash=new X64WordArray.init([new X64Word.init(3418070365,3238371032),new X64Word.init(1654270250,914150663),new X64Word.init(2438529370,812702999),new X64Word.init(355462360,4144912697),new X64Word.init(1731405415,4290775857),new X64Word.init(2394180231,1750603025),new X64Word.init(3675008525,1694076839),new X64Word.init(1203062813,3204075428)])},_doFinalize:function(){var hash=SHA512._doFinalize.call(this);hash.sigBytes-=16;return hash}});C.SHA384=SHA512._createHelper(SHA384);C.HmacSHA384=SHA512._createHmacHelper(SHA384)})();return CryptoJS.SHA384})},{"./core":14,"./sha512":44,"./x64-core":46}],44:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./x64-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./x64-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var Hasher=C_lib.Hasher;var C_x64=C.x64;var X64Word=C_x64.Word;var X64WordArray=C_x64.WordArray;var C_algo=C.algo;function X64Word_create(){return X64Word.create.apply(X64Word,arguments)}var K=[X64Word_create(1116352408,3609767458),X64Word_create(1899447441,602891725),X64Word_create(3049323471,3964484399),X64Word_create(3921009573,2173295548),X64Word_create(961987163,4081628472),X64Word_create(1508970993,3053834265),X64Word_create(2453635748,2937671579),X64Word_create(2870763221,3664609560),X64Word_create(3624381080,2734883394),X64Word_create(310598401,1164996542),X64Word_create(607225278,1323610764),X64Word_create(1426881987,3590304994),X64Word_create(1925078388,4068182383),X64Word_create(2162078206,991336113),X64Word_create(2614888103,633803317),X64Word_create(3248222580,3479774868),X64Word_create(3835390401,2666613458),X64Word_create(4022224774,944711139),X64Word_create(264347078,2341262773),X64Word_create(604807628,2007800933),X64Word_create(770255983,1495990901),X64Word_create(1249150122,1856431235),X64Word_create(1555081692,3175218132),X64Word_create(1996064986,2198950837),X64Word_create(2554220882,3999719339),X64Word_create(2821834349,766784016),X64Word_create(2952996808,2566594879),X64Word_create(3210313671,3203337956),X64Word_create(3336571891,1034457026),X64Word_create(3584528711,2466948901),X64Word_create(113926993,3758326383),X64Word_create(338241895,168717936),X64Word_create(666307205,1188179964),X64Word_create(773529912,1546045734),X64Word_create(1294757372,1522805485),X64Word_create(1396182291,2643833823),X64Word_create(1695183700,2343527390),X64Word_create(1986661051,1014477480),X64Word_create(2177026350,1206759142),X64Word_create(2456956037,344077627),X64Word_create(2730485921,1290863460),X64Word_create(2820302411,3158454273),X64Word_create(3259730800,3505952657),X64Word_create(3345764771,106217008),X64Word_create(3516065817,3606008344),X64Word_create(3600352804,1432725776),X64Word_create(4094571909,1467031594),X64Word_create(275423344,851169720),X64Word_create(430227734,3100823752),X64Word_create(506948616,1363258195),X64Word_create(659060556,3750685593),X64Word_create(883997877,3785050280),X64Word_create(958139571,3318307427),X64Word_create(1322822218,3812723403),X64Word_create(1537002063,2003034995),X64Word_create(1747873779,3602036899),X64Word_create(1955562222,1575990012),X64Word_create(2024104815,1125592928),X64Word_create(2227730452,2716904306),X64Word_create(2361852424,442776044),X64Word_create(2428436474,593698344),X64Word_create(2756734187,3733110249),X64Word_create(3204031479,2999351573),X64Word_create(3329325298,3815920427),X64Word_create(3391569614,3928383900),X64Word_create(3515267271,566280711),X64Word_create(3940187606,3454069534),X64Word_create(4118630271,4000239992),X64Word_create(116418474,1914138554),X64Word_create(174292421,2731055270),X64Word_create(289380356,3203993006),X64Word_create(460393269,320620315),X64Word_create(685471733,587496836),X64Word_create(852142971,1086792851),X64Word_create(1017036298,365543100),X64Word_create(1126000580,2618297676),X64Word_create(1288033470,3409855158),X64Word_create(1501505948,4234509866),X64Word_create(1607167915,987167468),X64Word_create(1816402316,1246189591)];var W=[];(function(){for(var i=0;i<80;i++){W[i]=X64Word_create()}})();var SHA512=C_algo.SHA512=Hasher.extend({_doReset:function(){this._hash=new X64WordArray.init([new X64Word.init(1779033703,4089235720),new X64Word.init(3144134277,2227873595),new X64Word.init(1013904242,4271175723),new X64Word.init(2773480762,1595750129),new X64Word.init(1359893119,2917565137),new X64Word.init(2600822924,725511199),new X64Word.init(528734635,4215389547),new X64Word.init(1541459225,327033209)])},_doProcessBlock:function(M,offset){var H=this._hash.words;var H0=H[0];var H1=H[1];var H2=H[2];var H3=H[3];var H4=H[4];var H5=H[5];var H6=H[6];var H7=H[7];var H0h=H0.high;var H0l=H0.low;var H1h=H1.high;var H1l=H1.low;var H2h=H2.high;var H2l=H2.low;var H3h=H3.high;var H3l=H3.low;var H4h=H4.high;var H4l=H4.low;var H5h=H5.high;var H5l=H5.low;var H6h=H6.high;var H6l=H6.low;var H7h=H7.high;var H7l=H7.low;var ah=H0h;var al=H0l;var bh=H1h;var bl=H1l;var ch=H2h;var cl=H2l;var dh=H3h;var dl=H3l;var eh=H4h;var el=H4l;var fh=H5h;var fl=H5l;var gh=H6h;var gl=H6l;var hh=H7h;var hl=H7l;for(var i=0;i<80;i++){var Wil;var Wih;var Wi=W[i];if(i<16){Wih=Wi.high=M[offset+i*2]|0;Wil=Wi.low=M[offset+i*2+1]|0}else{var gamma0x=W[i-15];var gamma0xh=gamma0x.high;var gamma0xl=gamma0x.low;var gamma0h=(gamma0xh>>>1|gamma0xl<<31)^(gamma0xh>>>8|gamma0xl<<24)^gamma0xh>>>7;var gamma0l=(gamma0xl>>>1|gamma0xh<<31)^(gamma0xl>>>8|gamma0xh<<24)^(gamma0xl>>>7|gamma0xh<<25);var gamma1x=W[i-2];var gamma1xh=gamma1x.high;var gamma1xl=gamma1x.low;var gamma1h=(gamma1xh>>>19|gamma1xl<<13)^(gamma1xh<<3|gamma1xl>>>29)^gamma1xh>>>6;var gamma1l=(gamma1xl>>>19|gamma1xh<<13)^(gamma1xl<<3|gamma1xh>>>29)^(gamma1xl>>>6|gamma1xh<<26);var Wi7=W[i-7];var Wi7h=Wi7.high;var Wi7l=Wi7.low;var Wi16=W[i-16];var Wi16h=Wi16.high;var Wi16l=Wi16.low;Wil=gamma0l+Wi7l;Wih=gamma0h+Wi7h+(Wil>>>0>>0?1:0);Wil=Wil+gamma1l;Wih=Wih+gamma1h+(Wil>>>0>>0?1:0);Wil=Wil+Wi16l;Wih=Wih+Wi16h+(Wil>>>0>>0?1:0);Wi.high=Wih;Wi.low=Wil}var chh=eh&fh^~eh&gh;var chl=el&fl^~el≷var majh=ah&bh^ah&ch^bh&ch;var majl=al&bl^al&cl^bl&cl;var sigma0h=(ah>>>28|al<<4)^(ah<<30|al>>>2)^(ah<<25|al>>>7);var sigma0l=(al>>>28|ah<<4)^(al<<30|ah>>>2)^(al<<25|ah>>>7);var sigma1h=(eh>>>14|el<<18)^(eh>>>18|el<<14)^(eh<<23|el>>>9);var sigma1l=(el>>>14|eh<<18)^(el>>>18|eh<<14)^(el<<23|eh>>>9);var Ki=K[i];var Kih=Ki.high;var Kil=Ki.low;var t1l=hl+sigma1l;var t1h=hh+sigma1h+(t1l>>>0>>0?1:0);var t1l=t1l+chl;var t1h=t1h+chh+(t1l>>>0>>0?1:0);var t1l=t1l+Kil;var t1h=t1h+Kih+(t1l>>>0>>0?1:0);var t1l=t1l+Wil;var t1h=t1h+Wih+(t1l>>>0>>0?1:0);var t2l=sigma0l+majl;var t2h=sigma0h+majh+(t2l>>>0>>0?1:0);hh=gh;hl=gl;gh=fh;gl=fl;fh=eh;fl=el;el=dl+t1l|0;eh=dh+t1h+(el>>>0
>>0?1:0)|0;dh=ch;dl=cl;ch=bh;cl=bl;bh=ah;bl=al;al=t1l+t2l|0;ah=t1h+t2h+(al>>>0>>0?1:0)|0}H0l=H0.low=H0l+al;H0.high=H0h+ah+(H0l>>>0>>0?1:0);H1l=H1.low=H1l+bl;H1.high=H1h+bh+(H1l>>>0>>0?1:0);H2l=H2.low=H2l+cl;H2.high=H2h+ch+(H2l>>>0>>0?1:0);H3l=H3.low=H3l+dl;H3.high=H3h+dh+(H3l>>>0
>>0?1:0);H4l=H4.low=H4l+el;H4.high=H4h+eh+(H4l>>>0>>0?1:0);H5l=H5.low=H5l+fl;H5.high=H5h+fh+(H5l>>>0>>0?1:0);H6l=H6.low=H6l+gl;H6.high=H6h+gh+(H6l>>>0>>0?1:0);H7l=H7.low=H7l+hl;H7.high=H7h+hh+(H7l>>>0>>0?1:0)},_doFinalize:function(){var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;dataWords[(nBitsLeft+128>>>10<<5)+30]=Math.floor(nBitsTotal/4294967296);dataWords[(nBitsLeft+128>>>10<<5)+31]=nBitsTotal;data.sigBytes=dataWords.length*4;this._process();var hash=this._hash.toX32();return hash},clone:function(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone},blockSize:1024/32});C.SHA512=Hasher._createHelper(SHA512);C.HmacSHA512=Hasher._createHmacHelper(SHA512)})();return CryptoJS.SHA512})},{"./core":14,"./x64-core":46}],45:[function(require,module,exports){(function(root,factory,undef){if(typeof exports==="object"){module.exports=exports=factory(require("./core"),require("./enc-base64"),require("./md5"),require("./evpkdf"),require("./cipher-core"))}else if(typeof define==="function"&&define.amd){define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var BlockCipher=C_lib.BlockCipher;var C_algo=C.algo;var PC1=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4];var PC2=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32];var BIT_SHIFTS=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28];var SBOX_P=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}];var SBOX_MASK=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679];var DES=C_algo.DES=BlockCipher.extend({_doReset:function(){var key=this._key;var keyWords=key.words;var keyBits=[];for(var i=0;i<56;i++){var keyBitPos=PC1[i]-1;keyBits[i]=keyWords[keyBitPos>>>5]>>>31-keyBitPos%32&1}var subKeys=this._subKeys=[];for(var nSubKey=0;nSubKey<16;nSubKey++){var subKey=subKeys[nSubKey]=[];var bitShift=BIT_SHIFTS[nSubKey];for(var i=0;i<24;i++){subKey[i/6|0]|=keyBits[(PC2[i]-1+bitShift)%28]<<31-i%6;subKey[4+(i/6|0)]|=keyBits[28+(PC2[i+24]-1+bitShift)%28]<<31-i%6}subKey[0]=subKey[0]<<1|subKey[0]>>>31;for(var i=1;i<7;i++){subKey[i]=subKey[i]>>>(i-1)*4+3}subKey[7]=subKey[7]<<5|subKey[7]>>>27}var invSubKeys=this._invSubKeys=[];for(var i=0;i<16;i++){invSubKeys[i]=subKeys[15-i]}},encryptBlock:function(M,offset){this._doCryptBlock(M,offset,this._subKeys)},decryptBlock:function(M,offset){this._doCryptBlock(M,offset,this._invSubKeys)},_doCryptBlock:function(M,offset,subKeys){this._lBlock=M[offset];this._rBlock=M[offset+1];exchangeLR.call(this,4,252645135);exchangeLR.call(this,16,65535);exchangeRL.call(this,2,858993459);exchangeRL.call(this,8,16711935);exchangeLR.call(this,1,1431655765);for(var round=0;round<16;round++){var subKey=subKeys[round];var lBlock=this._lBlock;var rBlock=this._rBlock;var f=0;for(var i=0;i<8;i++){f|=SBOX_P[i][((rBlock^subKey[i])&SBOX_MASK[i])>>>0]}this._lBlock=rBlock;this._rBlock=lBlock^f}var t=this._lBlock;this._lBlock=this._rBlock;this._rBlock=t;exchangeLR.call(this,1,1431655765);exchangeRL.call(this,8,16711935);exchangeRL.call(this,2,858993459);exchangeLR.call(this,16,65535);exchangeLR.call(this,4,252645135);M[offset]=this._lBlock;M[offset+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function exchangeLR(offset,mask){var t=(this._lBlock>>>offset^this._rBlock)&mask;this._rBlock^=t;this._lBlock^=t<>>offset^this._lBlock)&mask;this._lBlock^=t;this._rBlock^=t<192.")}var key1=keyWords.slice(0,2);var key2=keyWords.length<4?keyWords.slice(0,2):keyWords.slice(2,4);var key3=keyWords.length<6?keyWords.slice(0,2):keyWords.slice(4,6);this._des1=DES.createEncryptor(WordArray.create(key1));this._des2=DES.createEncryptor(WordArray.create(key2));this._des3=DES.createEncryptor(WordArray.create(key3))},encryptBlock:function(M,offset){this._des1.encryptBlock(M,offset);this._des2.decryptBlock(M,offset);this._des3.encryptBlock(M,offset)},decryptBlock:function(M,offset){this._des3.decryptBlock(M,offset);this._des2.encryptBlock(M,offset);this._des1.decryptBlock(M,offset)},keySize:192/32,ivSize:64/32,blockSize:64/32});C.TripleDES=BlockCipher._createHelper(TripleDES)})();return CryptoJS.TripleDES})},{"./cipher-core":13,"./core":14,"./enc-base64":15,"./evpkdf":18,"./md5":23}],46:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=exports=factory(require("./core"))}else if(typeof define==="function"&&define.amd){define(["./core"],factory)}else{factory(root.CryptoJS)}})(this,function(CryptoJS){(function(undefined){var C=CryptoJS;var C_lib=C.lib;var Base=C_lib.Base;var X32WordArray=C_lib.WordArray;var C_x64=C.x64={};var X64Word=C_x64.Word=Base.extend({init:function(high,low){this.high=high;this.low=low}});var X64WordArray=C_x64.WordArray=Base.extend({init:function(words,sigBytes){words=this.words=words||[];if(sigBytes!=undefined){this.sigBytes=sigBytes}else{this.sigBytes=words.length*8}},toX32:function(){var x64Words=this.words;var x64WordsLength=x64Words.length;var x32Words=[];for(var i=0;i>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],48:[function(require,module,exports){(function(root,factory){if(typeof exports==="object"){module.exports=factory()}else if(typeof define==="function"&&define.amd){define(factory)}else{root.treeify=factory()}})(this,function(){function makePrefix(key,last){var str=last?"└":"├";if(key){str+="─ "}else{str+="──┐"}return str}function filterKeys(obj,hideFunctions){var keys=[];for(var branch in obj){if(!obj.hasOwnProperty(branch)){continue}if(hideFunctions&&typeof obj[branch]==="function"){continue}keys.push(branch)}return keys}function growBranch(key,root,last,lastStates,showValues,hideFunctions,callback){var line="",index=0,lastKey,circular,lastStatesCopy=lastStates.slice(0);if(lastStatesCopy.push([root,last])&&lastStates.length>0){lastStates.forEach(function(lastState,idx){if(idx>0){line+=(lastState[1]?" ":"│")+" "}if(!circular&&lastState[0]===root){circular=true}});line+=makePrefix(key,last)+key;showValues&&(typeof root!=="object"||root instanceof Date)&&(line+=": "+root);circular&&(line+=" (circular ref.)");callback(line)}if(!circular&&typeof root==="object"){var keys=filterKeys(root,hideFunctions);keys.forEach(function(branch){lastKey=++index===keys.length;growBranch(branch,root[branch],lastKey,lastStatesCopy,showValues,hideFunctions,callback)})}}var Treeify={};Treeify.asLines=function(obj,showValues,hideFunctions,lineCallback){var hideFunctionsArg=typeof hideFunctions!=="function"?hideFunctions:false;growBranch(".",obj,false,[],showValues,hideFunctionsArg,lineCallback||hideFunctions)};Treeify.asTree=function(obj,showValues,hideFunctions){var tree="";growBranch(".",obj,false,[],showValues,hideFunctions,function(line){tree+=line+"\n"});return tree};return Treeify})},{}]},{},[6]); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/LICENSE b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/LICENSE new file mode 100644 index 0000000..c328f04 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/LICENSE @@ -0,0 +1,19 @@ +Copyright Fedor Indutny, 2015. + +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. diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/README.md b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/README.md new file mode 100644 index 0000000..cc4226f --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/README.md @@ -0,0 +1,214 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Sponsors + +[![Scout APM](./sponsors/scout-apm.png)](https://scoutapm.com/) +My Open Source work is supported by [Scout APM](https://scoutapm.com/) and +[other sponsors](https://github.com/sponsors/indutny). + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way they work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +* `n` - the argument of the function must be a plain JavaScript + Number. Decimals are not supported. +* `rn` - both argument and return value of the function are plain JavaScript + Numbers. Decimals are not supported. + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.umod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the end of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For + compatibility with browserify and similar tools, use this instead: + `a.toArrayLike(Buffer, endian, length)` +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance +* `BN.max(a, b)` - return `a` if `a` bigger than `b` +* `BN.min(a, b)` - return `a` if `a` less than `b` + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divmod(b)` - quotient and modulus obtained by dividing +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b, value)` - set specified bit to `value` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this trick one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +### Number Size + +Optimized for elliptic curves that work with 256-bit numbers. +There is no limitation on the size of the numbers. + +## LICENSE + +This software is licensed under the MIT License. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/lib/bn.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000..adecc94 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3547 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require('buffer').Buffer; + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [number & 0x3ffffff]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this._strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // '0' - '9' + if (c >= 48 && c <= 57) { + return c - 48; + // 'A' - 'F' + } else if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, 'Invalid character in ' + string); + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this._strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + b = c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + b = c - 17 + 0xa; + + // '0' - '9' + } else { + b = c; + } + assert(c >= 0 && b < mul, 'Invalid character'); + r += b; + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [0]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this._strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + function move (dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; + } + + BN.prototype._move = function _move (dest) { + move(dest, this); + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype._strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + // Check Symbol.for because not everywhere where Symbol defined + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility + if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { + try { + BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; + } + } else { + BN.prototype.inspect = inspect; + } + + function inspect () { + return (this.red ? ''; + } + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16, 2); + }; + + if (Buffer) { + BN.prototype.toBuffer = function toBuffer (endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; + } + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + var allocate = function allocate (ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); + } + return new ArrayType(size); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + this._strip(); + + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + var res = allocate(ArrayType, reqLength); + var postfix = endian === 'le' ? 'LE' : 'BE'; + this['_toArrayLike' + postfix](res, byteLength); + return res; + }; + + BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { + var position = 0; + var carry = 0; + + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; + + res[position++] = word & 0xff; + if (position < res.length) { + res[position++] = (word >> 8) & 0xff; + } + if (position < res.length) { + res[position++] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position < res.length) { + res[position++] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + + if (position < res.length) { + res[position++] = carry; + + while (position < res.length) { + res[position++] = 0; + } + } + }; + + BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { + var position = res.length - 1; + var carry = 0; + + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; + + res[position--] = word & 0xff; + if (position >= 0) { + res[position--] = (word >> 8) & 0xff; + } + if (position >= 0) { + res[position--] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position >= 0) { + res[position--] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + + if (position >= 0) { + res[position--] = carry; + + while (position >= 0) { + res[position--] = 0; + } + } + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] >>> wbit) & 0x01; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this._strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this._strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this._strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this._strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this._strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this._strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out._strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out._strip(); + } + + function jumboMulTo (self, num, out) { + // Temporary disable, see https://github.com/indutny/bn.js/issues/211 + // var fftm = new FFTM(); + // return fftm.mulp(self, num, out); + return bigMulTo(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out._strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return isNegNum ? this.ineg() : this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this._strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this._strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this._strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this._strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this._strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this._strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q._strip(); + } + a._strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modrn = function modrn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return isNegNum ? -acc : acc; + }; + + // WARNING: DEPRECATED + BN.prototype.modn = function modn (num) { + return this.modrn(num); + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + this._strip(); + return isNegNum ? this.ineg() : this; + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this._strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is a BN v4 instance + r.strip(); + } else { + // r is a BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/package.json b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/package.json new file mode 100644 index 0000000..fd038f2 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/bn.js/package.json @@ -0,0 +1,39 @@ +{ + "name": "bn.js", + "version": "5.2.1", + "description": "Big number implementation in pure javascript", + "keywords": [ + "BN", + "Big number", + "BigNum", + "Modulo", + "Montgomery" + ], + "homepage": "https://github.com/indutny/bn.js", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "repository": { + "type": "git", + "url": "git@github.com:indutny/bn.js" + }, + "license": "MIT", + "author": "Fedor Indutny ", + "files": [ + "lib/bn.js" + ], + "main": "lib/bn.js", + "browser": { + "buffer": false + }, + "scripts": { + "lint": "standardx", + "test": "npm run lint && npm run unit", + "unit": "mocha --reporter=spec test/*-test.js" + }, + "devDependencies": { + "eslint-plugin-es5": "^1.5.0", + "mocha": "^8.3.0", + "standardx": "^7.0.0" + } +} diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/LICENSE b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/README.md b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/README.md new file mode 100644 index 0000000..613080b --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/README.md @@ -0,0 +1,47 @@ +# web3-utils + +[![NPM Package][npm-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +This contains useful utility functions for Dapp developers. + +Please read the [documentation][docs] for more. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-utils) or using [Yarn](https://yarnpkg.com/package/web3-utils) + +### Using NPM + +```bash +npm install web3-utils +``` + +### Using Yarn + +```bash +yarn add web3-utils +``` + +## Usage + +```js +const Web3Utils = require('web3-utils'); +console.log(Web3Utils); +{ + sha3: function(){}, + soliditySha3: function(){}, + isAddress: function(){}, + ... +} +``` + +## Types + +All the TypeScript typings are placed in the `types` folder. + +[docs]: http://web3js.readthedocs.io/en/1.0/ +[repo]: https://github.com/ethereum/web3.js +[npm-image]: https://img.shields.io/npm/v/web3-utils.svg +[npm-url]: https://npmjs.org/package/web3-utils diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/index.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/index.js new file mode 100644 index 0000000..f33a432 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/index.js @@ -0,0 +1,408 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . + */ +/** + * @file utils.js + * @author Marek Kotewicz + * @author Fabian Vogelsteller + * @date 2017 + */ +var ethjsUnit = require('ethjs-unit'); +var utils = require('./utils.js'); +var soliditySha3 = require('./soliditySha3.js'); +var randombytes = require('randombytes'); +var BN = require('bn.js'); +/** + * Fires an error in an event emitter and callback and returns the eventemitter + * + * @method _fireError + * @param {Object} error a string, a error, or an object with {message, data} + * @param {Object} emitter + * @param {Function} reject + * @param {Function} callback + * @param {any} optionalData + * @return {Object} the emitter + */ +var _fireError = function (error, emitter, reject, callback, optionalData) { + /*jshint maxcomplexity: 10 */ + // add data if given + if (!!error && typeof error === 'object' && !(error instanceof Error) && error.data) { + if (!!error.data && typeof error.data === 'object' || Array.isArray(error.data)) { + error.data = JSON.stringify(error.data, null, 2); + } + error = error.message + "\n" + error.data; + } + if (typeof error === 'string') { + error = new Error(error); + } + if (typeof callback === 'function') { + callback(error, optionalData); + } + if (typeof reject === 'function') { + // suppress uncatched error if an error listener is present + // OR suppress uncatched error if an callback listener is present + if (emitter && + (typeof emitter.listeners === 'function' && + emitter.listeners('error').length) || typeof callback === 'function') { + emitter.catch(function () { }); + } + // reject later, to be able to return emitter + setTimeout(function () { + reject(error); + }, 1); + } + if (emitter && typeof emitter.emit === 'function') { + // emit later, to be able to return emitter + setTimeout(function () { + emitter.emit('error', error, optionalData); + emitter.removeAllListeners(); + }, 1); + } + return emitter; +}; +/** + * Should be used to create full function/event name from json abi + * + * @method _jsonInterfaceMethodToString + * @param {Object} json + * @return {String} full function/event name + */ +var _jsonInterfaceMethodToString = function (json) { + if (!!json && typeof json === 'object' && json.name && json.name.indexOf('(') !== -1) { + return json.name; + } + return json.name + '(' + _flattenTypes(false, json.inputs).join(',') + ')'; +}; +/** + * Should be used to flatten json abi inputs/outputs into an array of type-representing-strings + * + * @method _flattenTypes + * @param {bool} includeTuple + * @param {Object} puts + * @return {Array} parameters as strings + */ +var _flattenTypes = function (includeTuple, puts) { + // console.log("entered _flattenTypes. inputs/outputs: " + puts) + var types = []; + puts.forEach(function (param) { + if (typeof param.components === 'object') { + if (param.type.substring(0, 5) !== 'tuple') { + throw new Error('components found but type is not tuple; report on GitHub'); + } + var suffix = ''; + var arrayBracket = param.type.indexOf('['); + if (arrayBracket >= 0) { + suffix = param.type.substring(arrayBracket); + } + var result = _flattenTypes(includeTuple, param.components); + // console.log("result should have things: " + result) + if (Array.isArray(result) && includeTuple) { + // console.log("include tuple word, and its an array. joining...: " + result.types) + types.push('tuple(' + result.join(',') + ')' + suffix); + } + else if (!includeTuple) { + // console.log("don't include tuple, but its an array. joining...: " + result) + types.push('(' + result.join(',') + ')' + suffix); + } + else { + // console.log("its a single type within a tuple: " + result.types) + types.push('(' + result + ')'); + } + } + else { + // console.log("its a type and not directly in a tuple: " + param.type) + types.push(param.type); + } + }); + return types; +}; +/** + * Returns a random hex string by the given bytes size + * + * @param {Number} size + * @returns {string} + */ +var randomHex = function (size) { + return '0x' + randombytes(size).toString('hex'); +}; +/** + * Should be called to get ascii from it's hex representation + * + * @method hexToAscii + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ +var hexToAscii = function (hex) { + if (!utils.isHexStrict(hex)) + throw new Error('The parameter must be a valid HEX string.'); + var str = ""; + var i = 0, l = hex.length; + if (hex.substring(0, 2) === '0x') { + i = 2; + } + for (; i < l; i += 2) { + var code = parseInt(hex.slice(i, i + 2), 16); + str += String.fromCharCode(code); + } + return str; +}; +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * + * @method asciiToHex + * @param {String} str + * @returns {String} hex representation of input string + */ +var asciiToHex = function (str) { + if (!str) + return "0x00"; + var hex = ""; + for (var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + } + return "0x" + hex; +}; +/** + * Returns value of unit in Wei + * + * @method getUnitValue + * @param {String} unit the unit to convert to, default ether + * @returns {BN} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ +var getUnitValue = function (unit) { + unit = unit ? unit.toLowerCase() : 'ether'; + if (!ethjsUnit.unitMap[unit]) { + throw new Error('This unit "' + unit + '" doesn\'t exist, please use the one of the following units' + JSON.stringify(ethjsUnit.unitMap, null, 2)); + } + return unit; +}; +/** + * Takes a number of wei and converts it to any other ether unit. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method fromWei + * @param {Number|String} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert to, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ +var fromWei = function (number, unit) { + unit = getUnitValue(unit); + if (!utils.isBN(number) && !(typeof number === 'string')) { + throw new Error('Please pass numbers as strings or BN objects to avoid precision errors.'); + } + return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10); +}; +/** + * Takes a number of a unit and converts it to wei. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method toWei + * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert from, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ +var toWei = function (number, unit) { + unit = getUnitValue(unit); + if (!utils.isBN(number) && !(typeof number === 'string')) { + throw new Error('Please pass numbers as strings or BN objects to avoid precision errors.'); + } + return utils.isBN(number) ? ethjsUnit.toWei(number, unit) : ethjsUnit.toWei(number, unit).toString(10); +}; +/** + * Converts to a checksum address + * + * @method toChecksumAddress + * @param {String} address the given HEX address + * @return {String} + */ +var toChecksumAddress = function (address) { + if (typeof address === 'undefined') + return ''; + if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) + throw new Error('Given address "' + address + '" is not a valid Ethereum address.'); + address = address.toLowerCase().replace(/^0x/i, ''); + var addressHash = utils.sha3(address).replace(/^0x/i, ''); + var checksumAddress = '0x'; + for (var i = 0; i < address.length; i++) { + // If ith character is 8 to f then make it uppercase + if (parseInt(addressHash[i], 16) > 7) { + checksumAddress += address[i].toUpperCase(); + } + else { + checksumAddress += address[i]; + } + } + return checksumAddress; +}; +/** + * Returns -1 if ab; 0 if a == b. + * For more details on this type of function, see + * developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort + * Block tag `safe` and `block number` combination param is not supported + * @method compareBlockNumbers + * + * @param {String|Number|BN} a + * + * @param {String|Number|BN} b + * + * @returns {Number} -1, 0, or 1 + */ +var compareBlockNumbers = function (a, b) { + // Increasing order: (genesis = earliest), safe, (finalized ~ latest), pending + // safe vs block-num cant be compared as block number provided can be on left or right side of safe tag, until safe tag block number is extracted and compared + if (a === b) { + return 0; + } + else if (("genesis" === a || "earliest" === a || 0 === a) && ("genesis" === b || "earliest" === b || 0 === b)) { + return 0; + } + else if ("genesis" === a || "earliest" === a || a === 0) { + // b !== a, thus a < b + return -1; + } + else if ("genesis" === b || "earliest" === b || b === 0) { + // b !== a, thus a > b + return 1; + } + else if (a === "latest" || a === "finalized") { + if (b === "pending") { + return -1; + } + else { + // b !== ("pending" OR "latest"), thus a > b + return 1; + } + } + else if (b === "latest" || b === "finalized") { + if (a === "pending") { + return 1; + } + else { + // b !== ("pending" OR "latest"), thus a > b + return -1; + } + } + else if (a === "pending") { + // b (== OR <) "latest", thus a > b + return 1; + } + else if (b === "pending") { + return -1; + } + else if (a === "safe" || b === "safe") { + // either a or b is "safe" and the other one did not fall into any of the conditions above, so the other one is a number + return undefined; + } + else { + let bnA = new BN(a); + let bnB = new BN(b); + if (bnA.lt(bnB)) { + return -1; + } + else if (bnA.eq(bnB)) { + return 0; + } + else { + return 1; + } + } +}; +module.exports = { + _fireError: _fireError, + _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, + _flattenTypes: _flattenTypes, + // extractDisplayName: extractDisplayName, + // extractTypeName: extractTypeName, + randomHex: randomHex, + BN: utils.BN, + isBN: utils.isBN, + isBigNumber: utils.isBigNumber, + isHex: utils.isHex, + isHexStrict: utils.isHexStrict, + sha3: utils.sha3, + sha3Raw: utils.sha3Raw, + keccak256: utils.sha3, + soliditySha3: soliditySha3.soliditySha3, + soliditySha3Raw: soliditySha3.soliditySha3Raw, + encodePacked: soliditySha3.encodePacked, + isAddress: utils.isAddress, + checkAddressChecksum: utils.checkAddressChecksum, + toChecksumAddress: toChecksumAddress, + toHex: utils.toHex, + toBN: utils.toBN, + bytesToHex: utils.bytesToHex, + hexToBytes: utils.hexToBytes, + hexToNumberString: utils.hexToNumberString, + hexToNumber: utils.hexToNumber, + toDecimal: utils.hexToNumber, + numberToHex: utils.numberToHex, + fromDecimal: utils.numberToHex, + hexToUtf8: utils.hexToUtf8, + hexToString: utils.hexToUtf8, + toUtf8: utils.hexToUtf8, + stripHexPrefix: utils.stripHexPrefix, + utf8ToHex: utils.utf8ToHex, + stringToHex: utils.utf8ToHex, + fromUtf8: utils.utf8ToHex, + hexToAscii: hexToAscii, + toAscii: hexToAscii, + asciiToHex: asciiToHex, + fromAscii: asciiToHex, + unitMap: ethjsUnit.unitMap, + toWei: toWei, + fromWei: fromWei, + padLeft: utils.leftPad, + leftPad: utils.leftPad, + padRight: utils.rightPad, + rightPad: utils.rightPad, + toTwosComplement: utils.toTwosComplement, + isBloom: utils.isBloom, + isUserEthereumAddressInBloom: utils.isUserEthereumAddressInBloom, + isContractAddressInBloom: utils.isContractAddressInBloom, + isTopic: utils.isTopic, + isTopicInBloom: utils.isTopicInBloom, + isInBloom: utils.isInBloom, + compareBlockNumbers: compareBlockNumbers, + toNumber: utils.toNumber +}; diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/soliditySha3.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/soliditySha3.js new file mode 100644 index 0000000..2139720 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/soliditySha3.js @@ -0,0 +1,243 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . + */ +/** + * @file soliditySha3.js + * @author Fabian Vogelsteller + * @date 2017 + */ +var BN = require('bn.js'); +var utils = require('./utils.js'); +var _elementaryName = function (name) { + /*jshint maxcomplexity:false */ + if (name.startsWith('int[')) { + return 'int256' + name.slice(3); + } + else if (name === 'int') { + return 'int256'; + } + else if (name.startsWith('uint[')) { + return 'uint256' + name.slice(4); + } + else if (name === 'uint') { + return 'uint256'; + } + else if (name.startsWith('fixed[')) { + return 'fixed128x128' + name.slice(5); + } + else if (name === 'fixed') { + return 'fixed128x128'; + } + else if (name.startsWith('ufixed[')) { + return 'ufixed128x128' + name.slice(6); + } + else if (name === 'ufixed') { + return 'ufixed128x128'; + } + return name; +}; +// Parse N from type +var _parseTypeN = function (type) { + var typesize = /^\D+(\d+).*$/.exec(type); + return typesize ? parseInt(typesize[1], 10) : null; +}; +// Parse N from type[] +var _parseTypeNArray = function (type) { + var arraySize = /^\D+\d*\[(\d+)\]$/.exec(type); + return arraySize ? parseInt(arraySize[1], 10) : null; +}; +var _parseNumber = function (arg) { + var type = typeof arg; + if (type === 'string') { + if (utils.isHexStrict(arg)) { + return new BN(arg.replace(/0x/i, ''), 16); + } + else { + return new BN(arg, 10); + } + } + else if (type === 'number') { + return new BN(arg); + } + else if (utils.isBigNumber(arg)) { + return new BN(arg.toString(10)); + } + else if (utils.isBN(arg)) { + return arg; + } + else { + throw new Error(arg + ' is not a number'); + } +}; +var _solidityPack = function (type, value, arraySize) { + /*jshint maxcomplexity:false */ + var size, num; + type = _elementaryName(type); + if (type === 'bytes') { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new Error('Invalid bytes characters ' + value.length); + } + return value; + } + else if (type === 'string') { + return utils.utf8ToHex(value); + } + else if (type === 'bool') { + return value ? '01' : '00'; + } + else if (type.startsWith('address')) { + if (arraySize) { + size = 64; + } + else { + size = 40; + } + if (!utils.isAddress(value)) { + throw new Error(value + ' is not a valid address, or the checksum is invalid.'); + } + return utils.leftPad(value.toLowerCase(), size); + } + size = _parseTypeN(type); + if (type.startsWith('bytes')) { + if (!size) { + throw new Error('bytes[] not yet supported in solidity'); + } + // must be 32 byte slices when in an array + if (arraySize) { + size = 32; + } + if (size < 1 || size > 32 || size < value.replace(/^0x/i, '').length / 2) { + throw new Error('Invalid bytes' + size + ' for ' + value); + } + return utils.rightPad(value, size * 2); + } + else if (type.startsWith('uint')) { + if ((size % 8) || (size < 8) || (size > 256)) { + throw new Error('Invalid uint' + size + ' size'); + } + num = _parseNumber(value); + if (num.bitLength() > size) { + throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()); + } + if (num.lt(new BN(0))) { + throw new Error('Supplied uint ' + num.toString() + ' is negative'); + } + return size ? utils.leftPad(num.toString('hex'), size / 8 * 2) : num; + } + else if (type.startsWith('int')) { + if ((size % 8) || (size < 8) || (size > 256)) { + throw new Error('Invalid int' + size + ' size'); + } + num = _parseNumber(value); + if (num.bitLength() > size) { + throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()); + } + if (num.lt(new BN(0))) { + return num.toTwos(size).toString('hex'); + } + else { + return size ? utils.leftPad(num.toString('hex'), size / 8 * 2) : num; + } + } + else { + // FIXME: support all other types + throw new Error('Unsupported or invalid type: ' + type); + } +}; +var _processSolidityEncodePackedArgs = function (arg) { + /*jshint maxcomplexity:false */ + if (Array.isArray(arg)) { + throw new Error('Autodetection of array types is not supported.'); + } + var type, value = ''; + var hexArg, arraySize; + // if type is given + if (!!arg && typeof arg === 'object' && (arg.hasOwnProperty('v') || arg.hasOwnProperty('t') || arg.hasOwnProperty('value') || arg.hasOwnProperty('type'))) { + type = arg.hasOwnProperty('t') ? arg.t : arg.type; + value = arg.hasOwnProperty('v') ? arg.v : arg.value; + // otherwise try to guess the type + } + else { + type = utils.toHex(arg, true); + value = utils.toHex(arg); + if (!type.startsWith('int') && !type.startsWith('uint')) { + type = 'bytes'; + } + } + if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) { + value = new BN(value); + } + // get the array size + if (Array.isArray(value)) { + arraySize = _parseTypeNArray(type); + if (arraySize && value.length !== arraySize) { + throw new Error(type + ' is not matching the given array ' + JSON.stringify(value)); + } + else { + arraySize = value.length; + } + } + if (Array.isArray(value)) { + hexArg = value.map(function (val) { + return _solidityPack(type, val, arraySize).toString('hex').replace('0x', ''); + }); + return hexArg.join(''); + } + else { + hexArg = _solidityPack(type, value, arraySize); + return hexArg.toString('hex').replace('0x', ''); + } +}; +/** + * Hashes solidity values to a sha3 hash using keccak 256 + * + * @method soliditySha3 + * @return {Object} the sha3 + */ +var soliditySha3 = function () { + /*jshint maxcomplexity:false */ + var args = Array.prototype.slice.call(arguments); + var hexArgs = args.map(_processSolidityEncodePackedArgs); + // console.log(args, hexArgs); + // console.log('0x'+ hexArgs.join('')); + return utils.sha3('0x' + hexArgs.join('')); +}; +/** + * Hashes solidity values to a sha3 hash using keccak 256 but does return the hash of value `null` instead of `null` + * + * @method soliditySha3Raw + * @return {Object} the sha3 + */ +var soliditySha3Raw = function () { + return utils.sha3Raw('0x' + Array.prototype.slice.call(arguments).map(_processSolidityEncodePackedArgs).join('')); +}; +/** + * Encode packed args to hex + * + * @method encodePacked + * @return {String} the hex encoded arguments + */ +var encodePacked = function () { + /*jshint maxcomplexity:false */ + var args = Array.prototype.slice.call(arguments); + var hexArgs = args.map(_processSolidityEncodePackedArgs); + return '0x' + hexArgs.join('').toLowerCase(); +}; +module.exports = { + soliditySha3: soliditySha3, + soliditySha3Raw: soliditySha3Raw, + encodePacked: encodePacked +}; diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/utils.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/utils.js new file mode 100644 index 0000000..6384514 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/lib/utils.js @@ -0,0 +1,523 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . + */ +/** + * @file utils.js + * @author Fabian Vogelsteller + * @date 2017 + */ +var BN = require('bn.js'); +var numberToBN = require('number-to-bn'); +var utf8 = require('utf8'); +var ethereumjsUtil = require('@ethereumjs/util'); +var ethereumBloomFilters = require('ethereum-bloom-filters'); +var { keccak256 } = require('ethereum-cryptography/keccak.js'); +/** + * Returns true if object is BN, otherwise false + * + * @method isBN + * @param {Object} object + * @return {Boolean} + */ +var isBN = function (object) { + return BN.isBN(object); +}; +/** + * Returns true if object is BigNumber, otherwise false + * + * @method isBigNumber + * @param {Object} object + * @return {Boolean} + */ +var isBigNumber = function (object) { + return object && object.constructor && object.constructor.name === 'BigNumber'; +}; +/** + * Takes an input and transforms it into an BN + * + * @method toBN + * @param {Number|String|BN} number, string, HEX string or BN + * @return {BN} BN + */ +var toBN = function (number) { + try { + return numberToBN.apply(null, arguments); + } + catch (e) { + throw new Error(e + ' Given value: "' + number + '"'); + } +}; +/** + * Takes and input transforms it into BN and if it is negative value, into two's complement + * + * @method toTwosComplement + * @param {Number|String|BN} number + * @return {String} + */ +var toTwosComplement = function (number) { + return '0x' + toBN(number).toTwos(256).toString(16, 64); +}; +/** + * Checks if the given string is an address + * + * @method isAddress + * @param {String} address the given HEX address + * @return {Boolean} + */ +var isAddress = function (address) { + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { + return false; + // If it's ALL lowercase or ALL upppercase + } + else if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) { + return true; + // Otherwise check each case + } + else { + return checkAddressChecksum(address); + } +}; +/** + * Checks if the given string is a checksummed address + * + * @method checkAddressChecksum + * @param {String} address the given HEX address + * @return {Boolean} + */ +var checkAddressChecksum = function (address) { + // Check each case + address = address.replace(/^0x/i, ''); + var addressHash = sha3(address.toLowerCase()).replace(/^0x/i, ''); + for (var i = 0; i < 40; i++) { + // the nth letter should be uppercase if the nth digit of casemap is 1 + if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { + return false; + } + } + return true; +}; +/** + * Should be called to pad string to expected length + * + * @method leftPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ +var leftPad = function (string, chars, sign) { + var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; + string = string.toString(16).replace(/^0x/i, ''); + var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; + return (hasPrefix ? '0x' : '') + new Array(padding).join(sign ? sign : "0") + string; +}; +/** + * Should be called to pad string to expected length + * + * @method rightPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ +var rightPad = function (string, chars, sign) { + var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; + string = string.toString(16).replace(/^0x/i, ''); + var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; + return (hasPrefix ? '0x' : '') + string + (new Array(padding).join(sign ? sign : "0")); +}; +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * + * @method utf8ToHex + * @param {String} str + * @returns {String} hex representation of input string + */ +var utf8ToHex = function (str) { + str = utf8.encode(str); + var hex = ""; + // remove \u0000 padding from either side + str = str.replace(/^(?:\u0000)*/, ''); + str = str.split("").reverse().join(""); + str = str.replace(/^(?:\u0000)*/, ''); + str = str.split("").reverse().join(""); + for (var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + // if (code !== 0) { + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + // } + } + return "0x" + hex; +}; +/** + * Should be called to get utf8 from it's hex representation + * + * @method hexToUtf8 + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ +var hexToUtf8 = function (hex) { + if (!isHexStrict(hex)) + throw new Error('The parameter "' + hex + '" must be a valid HEX string.'); + var str = ""; + var code = 0; + hex = hex.replace(/^0x/i, ''); + // remove 00 padding from either side + hex = hex.replace(/^(?:00)*/, ''); + hex = hex.split("").reverse().join(""); + hex = hex.replace(/^(?:00)*/, ''); + hex = hex.split("").reverse().join(""); + var l = hex.length; + for (var i = 0; i < l; i += 2) { + code = parseInt(hex.slice(i, i + 2), 16); + // if (code !== 0) { + str += String.fromCharCode(code); + // } + } + return utf8.decode(str); +}; +/** + * Converts value to it's number representation. + * However, if the value is larger than the maximum safe integer, returns the value as a string. + * + * @method hexToNumber + * @param {String|Number|BN} value + * @param {Boolean} bigIntOnOverflow - if true, return the hex value in case of overflow + * @return {Number|String} + */ +var hexToNumber = function (value, bigIntOnOverflow = false) { + if (!value) { + return value; + } + if (typeof value === 'string' && !isHexStrict(value)) { + throw new Error('Given value "' + value + '" is not a valid hex string.'); + } + const n = toBN(value); + if (bigIntOnOverflow && (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER)) { + return BigInt(n); + } + return n.toNumber(); +}; +/** + * Converts value to it's decimal representation in string + * + * @method hexToNumberString + * @param {String|Number|BN} value + * @return {String} + */ +var hexToNumberString = function (value) { + if (!value) + return value; + if (typeof value === 'string' && !isHexStrict(value)) { + throw new Error('Given value "' + value + '" is not a valid hex string.'); + } + return toBN(value).toString(10); +}; +/** + * Converts value to it's hex representation + * + * @method numberToHex + * @param {String|Number|BN} value + * @return {String} + */ +var numberToHex = function (value) { + if ((value === null || value === undefined)) { + return value; + } + if (!isFinite(value) && !isHexStrict(value)) { + throw new Error('Given input "' + value + '" is not a number.'); + } + var number = toBN(value); + var result = number.toString(16); + return number.lt(new BN(0)) ? '-0x' + result.slice(1) : '0x' + result; +}; +/** + * Convert a byte array to a hex string + * + * Note: Implementation from crypto-js + * + * @method bytesToHex + * @param {Array} bytes + * @return {String} the hex string + */ +var bytesToHex = function (bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + /* jshint ignore:start */ + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + /* jshint ignore:end */ + } + return '0x' + hex.join(""); +}; +/** + * Convert a hex string to a byte array + * + * Note: Implementation from crypto-js + * + * @method hexToBytes + * @param {string} hex + * @return {Array} the byte array + */ +var hexToBytes = function (hex) { + hex = hex.toString(16); + if (!isHexStrict(hex)) { + throw new Error('Given value "' + hex + '" is not a valid hex string.'); + } + hex = hex.replace(/^0x/i, ''); + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.slice(c, c + 2), 16)); + return bytes; +}; +/** + * Auto converts any given value into it's hex representation. + * + * And even stringifys objects before. + * + * @method toHex + * @param {String|Number|BN|Object|Buffer} value + * @param {Boolean} returnType + * @return {String} + */ +var toHex = function (value, returnType) { + /*jshint maxcomplexity: false */ + if (isAddress(value)) { + return returnType ? 'address' : '0x' + value.toLowerCase().replace(/^0x/i, ''); + } + if (typeof value === 'boolean') { + return returnType ? 'bool' : value ? '0x01' : '0x00'; + } + if (Buffer.isBuffer(value)) { + return '0x' + value.toString('hex'); + } + if (typeof value === 'object' && !!value && !isBigNumber(value) && !isBN(value)) { + return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); + } + // if its a negative number, pass it through numberToHex + if (typeof value === 'string') { + if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) { + return returnType ? 'int256' : numberToHex(value); + } + else if (value.indexOf('0x') === 0 || value.indexOf('0X') === 0) { + return returnType ? 'bytes' : value; + } + else if (!isFinite(value)) { + return returnType ? 'string' : utf8ToHex(value); + } + } + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); +}; +/** + * Check if string is HEX, requires a 0x in front + * + * @method isHexStrict + * @param {String} hex to be checked + * @returns {Boolean} + */ +var isHexStrict = function (hex) { + return ((typeof hex === 'string' || typeof hex === 'number') && /^(-)?0x[0-9a-f]*$/i.test(hex)); +}; +/** + * Check if string is HEX + * + * @method isHex + * @param {String} hex to be checked + * @returns {Boolean} + */ +var isHex = function (hex) { + return ((typeof hex === 'string' || typeof hex === 'number') && /^(-0x|0x)?[0-9a-f]*$/i.test(hex)); +}; +/** + * Remove 0x prefix from string + * + * @method stripHexPrefix + * @param {String} str to be checked + * @returns {String} + */ +var stripHexPrefix = function (str) { + if (str !== 0 && isHex(str)) + return str.replace(/^(-)?0x/i, '$1'); + return str; +}; +/** + * Returns true if given string is a valid Ethereum block header bloom. + * + * @method isBloom + * @param {String} bloom encoded bloom filter + * @return {Boolean} + */ +var isBloom = function (bloom) { + return ethereumBloomFilters.isBloom(bloom); +}; +/** + * Returns true if the ethereum users address is part of the given bloom + * note: false positives are possible. + * + * @method isUserEthereumAddressInBloom + * @param {String} ethereumAddress encoded bloom filter + * @param {String} bloom ethereum addresss + * @return {Boolean} + */ +var isUserEthereumAddressInBloom = function (bloom, ethereumAddress) { + return ethereumBloomFilters.isUserEthereumAddressInBloom(bloom, ethereumAddress); +}; +/** + * Returns true if the contract address is part of the given bloom + * note: false positives are possible. + * + * @method isUserEthereumAddressInBloom + * @param {String} bloom encoded bloom filter + * @param {String} contractAddress contract addresss + * @return {Boolean} + */ +var isContractAddressInBloom = function (bloom, contractAddress) { + return ethereumBloomFilters.isContractAddressInBloom(bloom, contractAddress); +}; +/** + * Returns true if given string is a valid log topic. + * + * @method isTopic + * @param {String} topic encoded topic + * @return {Boolean} + */ +var isTopic = function (topic) { + return ethereumBloomFilters.isTopic(topic); +}; +/** + * Returns true if the topic is part of the given bloom + * note: false positives are possible. + * + * @method isTopicInBloom + * @param {String} bloom encoded bloom filter + * @param {String} topic encoded topic + * @return {Boolean} + */ +var isTopicInBloom = function (bloom, topic) { + return ethereumBloomFilters.isTopicInBloom(bloom, topic); +}; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @method isInBloom + * @param {String} bloom encoded bloom filter + * @param {String | Uint8Array} topic encoded value + * @return {Boolean} + */ +var isInBloom = function (bloom, topic) { + return ethereumBloomFilters.isInBloom(bloom, topic); +}; +/** + * Hashes values to a sha3 hash using keccak 256 + * + * To hash a HEX string the hex must have 0x in front. + * + * @method sha3 + * @return {String} the sha3 string + */ +var SHA3_NULL_S = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; +var sha3 = function (value) { + if (isBN(value)) { + value = value.toString(); + } + if (isHexStrict(value) && /^0x/i.test((value).toString())) { + value = ethereumjsUtil.toBuffer(value); + } + else if (typeof value === 'string') { + // Assume value is an arbitrary string + value = Buffer.from(value, 'utf-8'); + } + var returnValue = ethereumjsUtil.bufferToHex(keccak256(value)); + if (returnValue === SHA3_NULL_S) { + return null; + } + else { + return returnValue; + } +}; +// expose the under the hood keccak256 +sha3._Hash = keccak256; +/** + * @method sha3Raw + * + * @param value + * + * @returns {string} + */ +var sha3Raw = function (value) { + value = sha3(value); + if (value === null) { + return SHA3_NULL_S; + } + return value; +}; +/** + * Auto converts any given value into it's hex representation, + * then converts hex to number. + * + * @method toNumber + * @param {String|Number|BN} value + * @param {Boolean} bigIntOnOverflow - if true, return the hex value in case of overflow + * @return {Number|String} + */ +var toNumber = function (value, bigIntOnOverflow = false) { + return typeof value === 'number' ? value : hexToNumber(toHex(value), bigIntOnOverflow); +}; +// 1.x currently accepts 0x... strings, bn.js after update doesn't. it would be a breaking change +var BNwrapped = function (value) { + // check negative + if (typeof value == "string" && value.includes("0x")) { + const [negative, hexValue] = value.toLocaleLowerCase().startsWith('-') ? ["-", value.slice(3)] : ["", value.slice(2)]; + return new BN(negative + hexValue, 16); + } + else { + return new BN(value); + } +}; +Object.setPrototypeOf(BNwrapped, BN); +Object.setPrototypeOf(BNwrapped.prototype, BN.prototype); +module.exports = { + BN: BNwrapped, + isBN: isBN, + isBigNumber: isBigNumber, + toBN: toBN, + isAddress: isAddress, + isBloom: isBloom, + isUserEthereumAddressInBloom: isUserEthereumAddressInBloom, + isContractAddressInBloom: isContractAddressInBloom, + isTopic: isTopic, + isTopicInBloom: isTopicInBloom, + isInBloom: isInBloom, + checkAddressChecksum: checkAddressChecksum, + utf8ToHex: utf8ToHex, + hexToUtf8: hexToUtf8, + hexToNumber: hexToNumber, + hexToNumberString: hexToNumberString, + numberToHex: numberToHex, + toHex: toHex, + hexToBytes: hexToBytes, + bytesToHex: bytesToHex, + isHex: isHex, + isHexStrict: isHexStrict, + stripHexPrefix: stripHexPrefix, + leftPad: leftPad, + rightPad: rightPad, + toTwosComplement: toTwosComplement, + sha3: sha3, + sha3Raw: sha3Raw, + toNumber: toNumber +}; diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/package.json b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/package.json new file mode 100644 index 0000000..3e033c1 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/package.json @@ -0,0 +1,31 @@ +{ + "name": "web3-utils", + "version": "1.10.3", + "description": "Collection of utility functions used in web3.js.", + "repository": "https://github.com/ethereum/web3.js/tree/1.x/packages/web3-utils", + "license": "LGPL-3.0", + "engines": { + "node": ">=8.0.0" + }, + "types": "types/index.d.ts", + "scripts": { + "compile": "tsc -b tsconfig.json", + "dtslint": "dtslint --localTs ../../node_modules/typescript/lib types" + }, + "main": "lib/index.js", + "dependencies": { + "@ethereumjs/util": "^8.1.0", + "bn.js": "^5.2.1", + "ethereum-bloom-filters": "^1.0.6", + "ethereum-cryptography": "^2.1.2", + "ethjs-unit": "0.1.6", + "number-to-bn": "1.7.0", + "randombytes": "^2.1.0", + "utf8": "3.0.0" + }, + "devDependencies": { + "dtslint": "^3.4.1", + "typescript": "4.9.5" + }, + "gitHead": "24d310caa06af88cb1fe236b7d3b9d135f053d71" +} diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/index.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/index.js new file mode 100644 index 0000000..c3b2ded --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/index.js @@ -0,0 +1,448 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . + */ +/** + * @file utils.js + * @author Marek Kotewicz + * @author Fabian Vogelsteller + * @date 2017 + */ + +var ethjsUnit = require('ethjs-unit'); +var utils = require('./utils.js'); +var soliditySha3 = require('./soliditySha3.js'); +var randombytes = require('randombytes'); +var BN = require('bn.js'); + + +/** + * Fires an error in an event emitter and callback and returns the eventemitter + * + * @method _fireError + * @param {Object} error a string, a error, or an object with {message, data} + * @param {Object} emitter + * @param {Function} reject + * @param {Function} callback + * @param {any} optionalData + * @return {Object} the emitter + */ +var _fireError = function (error, emitter, reject, callback, optionalData) { + /*jshint maxcomplexity: 10 */ + + // add data if given + if(!!error && typeof error === 'object' && !(error instanceof Error) && error.data) { + if(!!error.data && typeof error.data === 'object' || Array.isArray(error.data)) { + error.data = JSON.stringify(error.data, null, 2); + } + + error = error.message +"\n"+ error.data; + } + + if(typeof error === 'string') { + error = new Error(error); + } + + if (typeof callback === 'function') { + callback(error, optionalData); + } + if (typeof reject === 'function') { + // suppress uncatched error if an error listener is present + // OR suppress uncatched error if an callback listener is present + if ( + emitter && + (typeof emitter.listeners === 'function' && + emitter.listeners('error').length) || typeof callback === 'function' + ) { + emitter.catch(function(){}); + } + // reject later, to be able to return emitter + setTimeout(function () { + reject(error); + }, 1); + } + + if(emitter && typeof emitter.emit === 'function') { + // emit later, to be able to return emitter + setTimeout(function () { + emitter.emit('error', error, optionalData); + emitter.removeAllListeners(); + }, 1); + } + + return emitter; +}; + +/** + * Should be used to create full function/event name from json abi + * + * @method _jsonInterfaceMethodToString + * @param {Object} json + * @return {String} full function/event name + */ +var _jsonInterfaceMethodToString = function (json) { + if (!!json && typeof json === 'object' && json.name && json.name.indexOf('(') !== -1) { + return json.name; + } + + return json.name + '(' + _flattenTypes(false, json.inputs).join(',') + ')'; +}; + + +/** + * Should be used to flatten json abi inputs/outputs into an array of type-representing-strings + * + * @method _flattenTypes + * @param {bool} includeTuple + * @param {Object} puts + * @return {Array} parameters as strings + */ +var _flattenTypes = function(includeTuple, puts) +{ + // console.log("entered _flattenTypes. inputs/outputs: " + puts) + var types = []; + + puts.forEach(function(param) { + if (typeof param.components === 'object') { + if (param.type.substring(0, 5) !== 'tuple') { + throw new Error('components found but type is not tuple; report on GitHub'); + } + var suffix = ''; + var arrayBracket = param.type.indexOf('['); + if (arrayBracket >= 0) { suffix = param.type.substring(arrayBracket); } + var result = _flattenTypes(includeTuple, param.components); + // console.log("result should have things: " + result) + if(Array.isArray(result) && includeTuple) { + // console.log("include tuple word, and its an array. joining...: " + result.types) + types.push('tuple(' + result.join(',') + ')' + suffix); + } + else if(!includeTuple) { + // console.log("don't include tuple, but its an array. joining...: " + result) + types.push('(' + result.join(',') + ')' + suffix); + } + else { + // console.log("its a single type within a tuple: " + result.types) + types.push('(' + result + ')'); + } + } else { + // console.log("its a type and not directly in a tuple: " + param.type) + types.push(param.type); + } + }); + + return types; +}; +  + +/** + * Returns a random hex string by the given bytes size + * + * @param {Number} size + * @returns {string} + */ +var randomHex = function(size) { + return '0x' + randombytes(size).toString('hex'); +}; + +/** + * Should be called to get ascii from it's hex representation + * + * @method hexToAscii + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ +var hexToAscii = function(hex) { + if (!utils.isHexStrict(hex)) + throw new Error('The parameter must be a valid HEX string.'); + + var str = ""; + var i = 0, l = hex.length; + if (hex.substring(0, 2) === '0x') { + i = 2; + } + for (; i < l; i+=2) { + var code = parseInt(hex.slice(i, i + 2), 16); + str += String.fromCharCode(code); + } + + return str; +}; + +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * + * @method asciiToHex + * @param {String} str + * @returns {String} hex representation of input string + */ +var asciiToHex = function(str) { + if(!str) + return "0x00"; + var hex = ""; + for(var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return "0x" + hex; +}; + + + +/** + * Returns value of unit in Wei + * + * @method getUnitValue + * @param {String} unit the unit to convert to, default ether + * @returns {BN} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ +var getUnitValue = function (unit) { + unit = unit ? unit.toLowerCase() : 'ether'; + if (!ethjsUnit.unitMap[unit]) { + throw new Error('This unit "'+ unit +'" doesn\'t exist, please use the one of the following units' + JSON.stringify(ethjsUnit.unitMap, null, 2)); + } + return unit; +}; + +/** + * Takes a number of wei and converts it to any other ether unit. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method fromWei + * @param {Number|String} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert to, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ +var fromWei = function(number, unit) { + unit = getUnitValue(unit); + + if(!utils.isBN(number) && !(typeof number === 'string')) { + throw new Error('Please pass numbers as strings or BN objects to avoid precision errors.'); + } + + return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10); +}; + +/** + * Takes a number of a unit and converts it to wei. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method toWei + * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert from, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ +var toWei = function(number, unit) { + unit = getUnitValue(unit); + + if(!utils.isBN(number) && !(typeof number === 'string')) { + throw new Error('Please pass numbers as strings or BN objects to avoid precision errors.'); + } + + return utils.isBN(number) ? ethjsUnit.toWei(number, unit) : ethjsUnit.toWei(number, unit).toString(10); +}; + + + + +/** + * Converts to a checksum address + * + * @method toChecksumAddress + * @param {String} address the given HEX address + * @return {String} + */ +var toChecksumAddress = function (address) { + if (typeof address === 'undefined') return ''; + + if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) + throw new Error('Given address "'+ address +'" is not a valid Ethereum address.'); + + + + address = address.toLowerCase().replace(/^0x/i,''); + var addressHash = utils.sha3(address).replace(/^0x/i,''); + var checksumAddress = '0x'; + + for (var i = 0; i < address.length; i++ ) { + // If ith character is 8 to f then make it uppercase + if (parseInt(addressHash[i], 16) > 7) { + checksumAddress += address[i].toUpperCase(); + } else { + checksumAddress += address[i]; + } + } + return checksumAddress; +}; + +/** + * Returns -1 if ab; 0 if a == b. + * For more details on this type of function, see + * developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort + * Block tag `safe` and `block number` combination param is not supported + * @method compareBlockNumbers + * + * @param {String|Number|BN} a + * + * @param {String|Number|BN} b + * + * @returns {Number} -1, 0, or 1 + */ +var compareBlockNumbers = function(a, b) { + // Increasing order: (genesis = earliest), safe, (finalized ~ latest), pending + // safe vs block-num cant be compared as block number provided can be on left or right side of safe tag, until safe tag block number is extracted and compared + if (a === b) { + return 0; + } else if (("genesis" === a || "earliest" === a || 0 === a) && ("genesis" === b || "earliest" === b || 0 === b)) { + return 0; + } else if ("genesis" === a || "earliest" === a || a === 0) { + // b !== a, thus a < b + return -1; + } else if ("genesis" === b || "earliest" === b || b === 0) { + // b !== a, thus a > b + return 1; + } else if (a === "latest" || a === "finalized") { + if (b === "pending") { + return -1; + } else { + // b !== ("pending" OR "latest"), thus a > b + return 1; + } + } else if (b === "latest" || b === "finalized") { + if (a === "pending") { + return 1; + } else { + // b !== ("pending" OR "latest"), thus a > b + return -1 + } + } else if (a === "pending") { + // b (== OR <) "latest", thus a > b + return 1; + } else if (b === "pending") { + return -1; + } else if(a === "safe" || b === "safe") { + // either a or b is "safe" and the other one did not fall into any of the conditions above, so the other one is a number + return undefined; + } + else { + let bnA = new BN(a); + let bnB = new BN(b); + if(bnA.lt(bnB)) { + return -1; + } else if(bnA.eq(bnB)) { + return 0; + } else { + return 1; + } + } +}; + +module.exports = { + _fireError: _fireError, + _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, + _flattenTypes: _flattenTypes, + // extractDisplayName: extractDisplayName, + // extractTypeName: extractTypeName, + randomHex: randomHex, + BN: utils.BN, + isBN: utils.isBN, + isBigNumber: utils.isBigNumber, + isHex: utils.isHex, + isHexStrict: utils.isHexStrict, + sha3: utils.sha3, + sha3Raw: utils.sha3Raw, + keccak256: utils.sha3, + soliditySha3: soliditySha3.soliditySha3, + soliditySha3Raw: soliditySha3.soliditySha3Raw, + encodePacked: soliditySha3.encodePacked, + isAddress: utils.isAddress, + checkAddressChecksum: utils.checkAddressChecksum, + toChecksumAddress: toChecksumAddress, + toHex: utils.toHex, + toBN: utils.toBN, + + bytesToHex: utils.bytesToHex, + hexToBytes: utils.hexToBytes, + + hexToNumberString: utils.hexToNumberString, + + hexToNumber: utils.hexToNumber, + toDecimal: utils.hexToNumber, // alias + + numberToHex: utils.numberToHex, + fromDecimal: utils.numberToHex, // alias + + hexToUtf8: utils.hexToUtf8, + hexToString: utils.hexToUtf8, + toUtf8: utils.hexToUtf8, + stripHexPrefix: utils.stripHexPrefix, + + utf8ToHex: utils.utf8ToHex, + stringToHex: utils.utf8ToHex, + fromUtf8: utils.utf8ToHex, + + hexToAscii: hexToAscii, + toAscii: hexToAscii, + asciiToHex: asciiToHex, + fromAscii: asciiToHex, + + unitMap: ethjsUnit.unitMap, + toWei: toWei, + fromWei: fromWei, + + padLeft: utils.leftPad, + leftPad: utils.leftPad, + padRight: utils.rightPad, + rightPad: utils.rightPad, + toTwosComplement: utils.toTwosComplement, + + isBloom: utils.isBloom, + isUserEthereumAddressInBloom: utils.isUserEthereumAddressInBloom, + isContractAddressInBloom: utils.isContractAddressInBloom, + isTopic: utils.isTopic, + isTopicInBloom: utils.isTopicInBloom, + isInBloom: utils.isInBloom, + + compareBlockNumbers: compareBlockNumbers, + + toNumber: utils.toNumber +}; diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/soliditySha3.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/soliditySha3.js new file mode 100644 index 0000000..3366180 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/soliditySha3.js @@ -0,0 +1,274 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . + */ +/** + * @file soliditySha3.js + * @author Fabian Vogelsteller + * @date 2017 + */ + +var BN = require('bn.js'); +var utils = require('./utils.js'); + + +var _elementaryName = function (name) { + /*jshint maxcomplexity:false */ + + if (name.startsWith('int[')) { + return 'int256' + name.slice(3); + } else if (name === 'int') { + return 'int256'; + } else if (name.startsWith('uint[')) { + return 'uint256' + name.slice(4); + } else if (name === 'uint') { + return 'uint256'; + } else if (name.startsWith('fixed[')) { + return 'fixed128x128' + name.slice(5); + } else if (name === 'fixed') { + return 'fixed128x128'; + } else if (name.startsWith('ufixed[')) { + return 'ufixed128x128' + name.slice(6); + } else if (name === 'ufixed') { + return 'ufixed128x128'; + } + return name; +}; + +// Parse N from type +var _parseTypeN = function (type) { + var typesize = /^\D+(\d+).*$/.exec(type); + return typesize ? parseInt(typesize[1], 10) : null; +}; + +// Parse N from type[] +var _parseTypeNArray = function (type) { + var arraySize = /^\D+\d*\[(\d+)\]$/.exec(type); + return arraySize ? parseInt(arraySize[1], 10) : null; +}; + +var _parseNumber = function (arg) { + var type = typeof arg; + if (type === 'string') { + if (utils.isHexStrict(arg)) { + return new BN(arg.replace(/0x/i,''), 16); + } else { + return new BN(arg, 10); + } + } else if (type === 'number') { + return new BN(arg); + } else if (utils.isBigNumber(arg)) { + return new BN(arg.toString(10)); + } else if (utils.isBN(arg)) { + return arg; + } else { + throw new Error(arg +' is not a number'); + } +}; + +var _solidityPack = function (type, value, arraySize) { + /*jshint maxcomplexity:false */ + + var size, num; + type = _elementaryName(type); + + + if (type === 'bytes') { + + if (value.replace(/^0x/i,'').length % 2 !== 0) { + throw new Error('Invalid bytes characters '+ value.length); + } + + return value; + } else if (type === 'string') { + return utils.utf8ToHex(value); + } else if (type === 'bool') { + return value ? '01' : '00'; + } else if (type.startsWith('address')) { + if(arraySize) { + size = 64; + } else { + size = 40; + } + + if(!utils.isAddress(value)) { + throw new Error(value +' is not a valid address, or the checksum is invalid.'); + } + + return utils.leftPad(value.toLowerCase(), size); + } + + size = _parseTypeN(type); + + if (type.startsWith('bytes')) { + + if(!size) { + throw new Error('bytes[] not yet supported in solidity'); + } + + // must be 32 byte slices when in an array + if(arraySize) { + size = 32; + } + + if (size < 1 || size > 32 || size < value.replace(/^0x/i,'').length / 2 ) { + throw new Error('Invalid bytes' + size +' for '+ value); + } + + return utils.rightPad(value, size * 2); + } else if (type.startsWith('uint')) { + + if ((size % 8) || (size < 8) || (size > 256)) { + throw new Error('Invalid uint'+size+' size'); + } + + num = _parseNumber(value); + if (num.bitLength() > size) { + throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()); + } + + if(num.lt(new BN(0))) { + throw new Error('Supplied uint '+ num.toString() +' is negative'); + } + + return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num; + } else if (type.startsWith('int')) { + + if ((size % 8) || (size < 8) || (size > 256)) { + throw new Error('Invalid int'+size+' size'); + } + + num = _parseNumber(value); + if (num.bitLength() > size) { + throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()); + } + + if(num.lt(new BN(0))) { + return num.toTwos(size).toString('hex'); + } else { + return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num; + } + + } else { + // FIXME: support all other types + throw new Error('Unsupported or invalid type: ' + type); + } +}; + + +var _processSolidityEncodePackedArgs = function (arg) { + /*jshint maxcomplexity:false */ + + if(Array.isArray(arg)) { + throw new Error('Autodetection of array types is not supported.'); + } + + var type, value = ''; + var hexArg, arraySize; + + // if type is given + if (!!arg && typeof arg === 'object' && (arg.hasOwnProperty('v') || arg.hasOwnProperty('t') || arg.hasOwnProperty('value') || arg.hasOwnProperty('type'))) { + type = arg.hasOwnProperty('t') ? arg.t : arg.type; + value = arg.hasOwnProperty('v') ? arg.v : arg.value; + + // otherwise try to guess the type + } else { + + type = utils.toHex(arg, true); + value = utils.toHex(arg); + + if (!type.startsWith('int') && !type.startsWith('uint')) { + type = 'bytes'; + } + } + + if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) { + value = new BN(value); + } + + // get the array size + if(Array.isArray(value)) { + arraySize = _parseTypeNArray(type); + if(arraySize && value.length !== arraySize) { + throw new Error(type +' is not matching the given array '+ JSON.stringify(value)); + } else { + arraySize = value.length; + } + } + + + if (Array.isArray(value)) { + hexArg = value.map(function (val) { + return _solidityPack(type, val, arraySize).toString('hex').replace('0x',''); + }); + return hexArg.join(''); + } else { + hexArg = _solidityPack(type, value, arraySize); + return hexArg.toString('hex').replace('0x',''); + } + +}; + +/** + * Hashes solidity values to a sha3 hash using keccak 256 + * + * @method soliditySha3 + * @return {Object} the sha3 + */ +var soliditySha3 = function () { + /*jshint maxcomplexity:false */ + + var args = Array.prototype.slice.call(arguments); + + var hexArgs = args.map(_processSolidityEncodePackedArgs); + + // console.log(args, hexArgs); + // console.log('0x'+ hexArgs.join('')); + + return utils.sha3('0x'+ hexArgs.join('')); +}; + +/** + * Hashes solidity values to a sha3 hash using keccak 256 but does return the hash of value `null` instead of `null` + * + * @method soliditySha3Raw + * @return {Object} the sha3 + */ +var soliditySha3Raw = function () { + return utils.sha3Raw('0x'+ Array.prototype.slice.call(arguments).map(_processSolidityEncodePackedArgs).join('')); +}; + +/** + * Encode packed args to hex + * + * @method encodePacked + * @return {String} the hex encoded arguments + */ +var encodePacked = function () { + /*jshint maxcomplexity:false */ + + var args = Array.prototype.slice.call(arguments); + + var hexArgs = args.map(_processSolidityEncodePackedArgs); + + return '0x'+ hexArgs.join('').toLowerCase(); +}; + + +module.exports = { + soliditySha3: soliditySha3, + soliditySha3Raw: soliditySha3Raw, + encodePacked: encodePacked +}; diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/utils.js b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/utils.js new file mode 100644 index 0000000..e3a9419 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/src/utils.js @@ -0,0 +1,589 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . + */ +/** + * @file utils.js + * @author Fabian Vogelsteller + * @date 2017 + */ + +var BN = require('bn.js'); +var numberToBN = require('number-to-bn'); +var utf8 = require('utf8'); +var ethereumjsUtil = require('@ethereumjs/util'); +var ethereumBloomFilters = require('ethereum-bloom-filters'); +var {keccak256} = require('ethereum-cryptography/keccak.js'); + +/** + * Returns true if object is BN, otherwise false + * + * @method isBN + * @param {Object} object + * @return {Boolean} + */ +var isBN = function (object) { + return BN.isBN(object); +}; + +/** + * Returns true if object is BigNumber, otherwise false + * + * @method isBigNumber + * @param {Object} object + * @return {Boolean} + */ +var isBigNumber = function (object) { + return object && object.constructor && object.constructor.name === 'BigNumber'; +}; + +/** + * Takes an input and transforms it into an BN + * + * @method toBN + * @param {Number|String|BN} number, string, HEX string or BN + * @return {BN} BN + */ +var toBN = function(number){ + try { + return numberToBN.apply(null, arguments); + } catch(e) { + throw new Error(e + ' Given value: "'+ number +'"'); + } +}; + + +/** + * Takes and input transforms it into BN and if it is negative value, into two's complement + * + * @method toTwosComplement + * @param {Number|String|BN} number + * @return {String} + */ +var toTwosComplement = function (number) { + return '0x'+ toBN(number).toTwos(256).toString(16, 64); +}; + +/** + * Checks if the given string is an address + * + * @method isAddress + * @param {String} address the given HEX address + * @return {Boolean} + */ +var isAddress = function (address) { + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { + return false; + // If it's ALL lowercase or ALL upppercase + } else if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) { + return true; + // Otherwise check each case + } else { + return checkAddressChecksum(address); + } +}; + + + +/** + * Checks if the given string is a checksummed address + * + * @method checkAddressChecksum + * @param {String} address the given HEX address + * @return {Boolean} + */ +var checkAddressChecksum = function (address) { + // Check each case + address = address.replace(/^0x/i,''); + var addressHash = sha3(address.toLowerCase()).replace(/^0x/i,''); + + for (var i = 0; i < 40; i++ ) { + // the nth letter should be uppercase if the nth digit of casemap is 1 + if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { + return false; + } + } + return true; +}; + +/** + * Should be called to pad string to expected length + * + * @method leftPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ +var leftPad = function (string, chars, sign) { + var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; + string = string.toString(16).replace(/^0x/i,''); + + var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; + + return (hasPrefix ? '0x' : '') + new Array(padding).join(sign ? sign : "0") + string; +}; + +/** + * Should be called to pad string to expected length + * + * @method rightPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ +var rightPad = function (string, chars, sign) { + var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; + string = string.toString(16).replace(/^0x/i,''); + + var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; + + return (hasPrefix ? '0x' : '') + string + (new Array(padding).join(sign ? sign : "0")); +}; + + +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * + * @method utf8ToHex + * @param {String} str + * @returns {String} hex representation of input string + */ +var utf8ToHex = function(str) { + str = utf8.encode(str); + var hex = ""; + + // remove \u0000 padding from either side + str = str.replace(/^(?:\u0000)*/,''); + str = str.split("").reverse().join(""); + str = str.replace(/^(?:\u0000)*/,''); + str = str.split("").reverse().join(""); + + for(var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + // if (code !== 0) { + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + // } + } + + return "0x" + hex; +}; + +/** + * Should be called to get utf8 from it's hex representation + * + * @method hexToUtf8 + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ +var hexToUtf8 = function(hex) { + if (!isHexStrict(hex)) + throw new Error('The parameter "'+ hex +'" must be a valid HEX string.'); + + var str = ""; + var code = 0; + hex = hex.replace(/^0x/i,''); + + // remove 00 padding from either side + hex = hex.replace(/^(?:00)*/,''); + hex = hex.split("").reverse().join(""); + hex = hex.replace(/^(?:00)*/,''); + hex = hex.split("").reverse().join(""); + + var l = hex.length; + + for (var i=0; i < l; i+=2) { + code = parseInt(hex.slice(i, i + 2), 16); + // if (code !== 0) { + str += String.fromCharCode(code); + // } + } + + return utf8.decode(str); +}; + + +/** + * Converts value to it's number representation. + * However, if the value is larger than the maximum safe integer, returns the value as a string. + * + * @method hexToNumber + * @param {String|Number|BN} value + * @param {Boolean} bigIntOnOverflow - if true, return the hex value in case of overflow + * @return {Number|String} + */ +var hexToNumber = function (value, bigIntOnOverflow = false) { + if (!value) { + return value; + } + + if (typeof value === 'string' && !isHexStrict(value)) { + throw new Error('Given value "'+value+'" is not a valid hex string.'); + } + + const n = toBN(value); + if (bigIntOnOverflow && (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER)) { + return BigInt(n); + } + return n.toNumber(); +}; + +/** + * Converts value to it's decimal representation in string + * + * @method hexToNumberString + * @param {String|Number|BN} value + * @return {String} + */ +var hexToNumberString = function (value) { + if (!value) return value; + + if (typeof value === 'string' && !isHexStrict(value)) { + throw new Error('Given value "'+value+'" is not a valid hex string.'); + } + + return toBN(value).toString(10); +}; + + +/** + * Converts value to it's hex representation + * + * @method numberToHex + * @param {String|Number|BN} value + * @return {String} + */ +var numberToHex = function (value) { + if ((value === null || value === undefined)) { + return value; + } + + if (!isFinite(value) && !isHexStrict(value)) { + throw new Error('Given input "'+value+'" is not a number.'); + } + + var number = toBN(value); + var result = number.toString(16); + + return number.lt(new BN(0)) ? '-0x' + result.slice(1) : '0x' + result; +}; + + +/** + * Convert a byte array to a hex string + * + * Note: Implementation from crypto-js + * + * @method bytesToHex + * @param {Array} bytes + * @return {String} the hex string + */ +var bytesToHex = function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + /* jshint ignore:start */ + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + /* jshint ignore:end */ + } + return '0x'+ hex.join(""); +}; + +/** + * Convert a hex string to a byte array + * + * Note: Implementation from crypto-js + * + * @method hexToBytes + * @param {string} hex + * @return {Array} the byte array + */ +var hexToBytes = function(hex) { + hex = hex.toString(16); + + if (!isHexStrict(hex)) { + throw new Error('Given value "'+ hex +'" is not a valid hex string.'); + } + + hex = hex.replace(/^0x/i,''); + + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.slice(c, c + 2), 16)); + return bytes; +}; + +/** + * Auto converts any given value into it's hex representation. + * + * And even stringifys objects before. + * + * @method toHex + * @param {String|Number|BN|Object|Buffer} value + * @param {Boolean} returnType + * @return {String} + */ +var toHex = function (value, returnType) { + /*jshint maxcomplexity: false */ + + if (isAddress(value)) { + return returnType ? 'address' : '0x'+ value.toLowerCase().replace(/^0x/i,''); + } + + if (typeof value === 'boolean' ) { + return returnType ? 'bool' : value ? '0x01' : '0x00'; + } + + if (Buffer.isBuffer(value)) { + return '0x' + value.toString('hex'); + } + + if (typeof value === 'object' && !!value && !isBigNumber(value) && !isBN(value)) { + return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); + } + + // if its a negative number, pass it through numberToHex + if (typeof value === 'string') { + if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) { + return returnType ? 'int256' : numberToHex(value); + } else if(value.indexOf('0x') === 0 || value.indexOf('0X') === 0) { + return returnType ? 'bytes' : value; + } else if (!isFinite(value)) { + return returnType ? 'string' : utf8ToHex(value); + } + } + + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); +}; + + +/** + * Check if string is HEX, requires a 0x in front + * + * @method isHexStrict + * @param {String} hex to be checked + * @returns {Boolean} + */ +var isHexStrict = function (hex) { + return ((typeof hex === 'string' || typeof hex === 'number') && /^(-)?0x[0-9a-f]*$/i.test(hex)); +}; + +/** + * Check if string is HEX + * + * @method isHex + * @param {String} hex to be checked + * @returns {Boolean} + */ +var isHex = function (hex) { + return ((typeof hex === 'string' || typeof hex === 'number') && /^(-0x|0x)?[0-9a-f]*$/i.test(hex)); +}; + +/** + * Remove 0x prefix from string + * + * @method stripHexPrefix + * @param {String} str to be checked + * @returns {String} + */ +var stripHexPrefix = function (str) { + if (str !== 0 && isHex(str)) + return str.replace(/^(-)?0x/i, '$1') + return str; +}; + +/** + * Returns true if given string is a valid Ethereum block header bloom. + * + * @method isBloom + * @param {String} bloom encoded bloom filter + * @return {Boolean} + */ +var isBloom = function (bloom) { + return ethereumBloomFilters.isBloom(bloom); +}; + +/** + * Returns true if the ethereum users address is part of the given bloom + * note: false positives are possible. + * + * @method isUserEthereumAddressInBloom + * @param {String} ethereumAddress encoded bloom filter + * @param {String} bloom ethereum addresss + * @return {Boolean} + */ +var isUserEthereumAddressInBloom = function (bloom, ethereumAddress) { + return ethereumBloomFilters.isUserEthereumAddressInBloom(bloom, ethereumAddress); +}; + +/** + * Returns true if the contract address is part of the given bloom + * note: false positives are possible. + * + * @method isUserEthereumAddressInBloom + * @param {String} bloom encoded bloom filter + * @param {String} contractAddress contract addresss + * @return {Boolean} + */ +var isContractAddressInBloom = function (bloom, contractAddress) { + return ethereumBloomFilters.isContractAddressInBloom(bloom, contractAddress); +}; + +/** + * Returns true if given string is a valid log topic. + * + * @method isTopic + * @param {String} topic encoded topic + * @return {Boolean} + */ +var isTopic = function (topic) { + return ethereumBloomFilters.isTopic(topic); +}; + +/** + * Returns true if the topic is part of the given bloom + * note: false positives are possible. + * + * @method isTopicInBloom + * @param {String} bloom encoded bloom filter + * @param {String} topic encoded topic + * @return {Boolean} + */ +var isTopicInBloom = function (bloom, topic) { + return ethereumBloomFilters.isTopicInBloom(bloom, topic); +}; + +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @method isInBloom + * @param {String} bloom encoded bloom filter + * @param {String | Uint8Array} topic encoded value + * @return {Boolean} + */ +var isInBloom = function (bloom, topic) { + return ethereumBloomFilters.isInBloom(bloom, topic); +}; + +/** + * Hashes values to a sha3 hash using keccak 256 + * + * To hash a HEX string the hex must have 0x in front. + * + * @method sha3 + * @return {String} the sha3 string + */ +var SHA3_NULL_S = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; + +var sha3 = function (value) { + if (isBN(value)) { + value = value.toString(); + } + + if (isHexStrict(value) && /^0x/i.test((value).toString())) { + value = ethereumjsUtil.toBuffer(value); + } else if (typeof value === 'string') { + // Assume value is an arbitrary string + value = Buffer.from(value, 'utf-8'); + } + + var returnValue = ethereumjsUtil.bufferToHex(keccak256(value)); + + if(returnValue === SHA3_NULL_S) { + return null; + } else { + return returnValue; + } +}; +// expose the under the hood keccak256 +sha3._Hash = keccak256; + +/** + * @method sha3Raw + * + * @param value + * + * @returns {string} + */ +var sha3Raw = function(value) { + value = sha3(value); + + if (value === null) { + return SHA3_NULL_S; + } + + return value; +}; + +/** + * Auto converts any given value into it's hex representation, + * then converts hex to number. + * + * @method toNumber + * @param {String|Number|BN} value + * @param {Boolean} bigIntOnOverflow - if true, return the hex value in case of overflow + * @return {Number|String} + */ +var toNumber = function (value, bigIntOnOverflow = false) { + return typeof value === 'number' ? value : hexToNumber(toHex(value), bigIntOnOverflow); +} + +// 1.x currently accepts 0x... strings, bn.js after update doesn't. it would be a breaking change +var BNwrapped = function (value) { + // check negative + if (typeof value == "string" && value.includes("0x")) { + const [negative, hexValue] = value.toLocaleLowerCase().startsWith('-') ? ["-", value.slice(3)] : ["", value.slice(2)]; + return new BN(negative + hexValue, 16); + } + else { + return new BN(value); + } +}; +Object.setPrototypeOf(BNwrapped, BN); +Object.setPrototypeOf(BNwrapped.prototype, BN.prototype); + +module.exports = { + BN: BNwrapped, + isBN: isBN, + isBigNumber: isBigNumber, + toBN: toBN, + isAddress: isAddress, + isBloom: isBloom, + isUserEthereumAddressInBloom: isUserEthereumAddressInBloom, + isContractAddressInBloom: isContractAddressInBloom, + isTopic: isTopic, + isTopicInBloom: isTopicInBloom, + isInBloom: isInBloom, + checkAddressChecksum: checkAddressChecksum, + utf8ToHex: utf8ToHex, + hexToUtf8: hexToUtf8, + hexToNumber: hexToNumber, + hexToNumberString: hexToNumberString, + numberToHex: numberToHex, + toHex: toHex, + hexToBytes: hexToBytes, + bytesToHex: bytesToHex, + isHex: isHex, + isHexStrict: isHexStrict, + stripHexPrefix: stripHexPrefix, + leftPad: leftPad, + rightPad: rightPad, + toTwosComplement: toTwosComplement, + sha3: sha3, + sha3Raw: sha3Raw, + toNumber: toNumber +}; diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/tsconfig.json b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/tsconfig.json new file mode 100644 index 0000000..f4d2037 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./lib", + "esModuleInterop": true + }, + "include": [ + "./src" + ] + } diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/index.d.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/index.d.ts new file mode 100644 index 0000000..825e803 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/index.d.ts @@ -0,0 +1,243 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file index.d.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); + +export type Unit = + | 'noether' + | 'wei' + | 'kwei' + | 'Kwei' + | 'babbage' + | 'femtoether' + | 'mwei' + | 'Mwei' + | 'lovelace' + | 'picoether' + | 'gwei' + | 'Gwei' + | 'shannon' + | 'nanoether' + | 'nano' + | 'szabo' + | 'microether' + | 'micro' + | 'finney' + | 'milliether' + | 'milli' + | 'ether' + | 'kether' + | 'grand' + | 'mether' + | 'gether' + | 'tether'; + +export type Mixed = + | string + | number + | BN + | { + type: string; + value: string; + } + | { + t: string; + v: string | BN | number; + } + | boolean; + +export type Hex = string | number; + +// utils types +export function isBN(value: string | number): boolean; +export function isBigNumber(value: BN): boolean; +export function toBN(value: number | string): BN; +export function toTwosComplement(value: number | string | BN): string; +export function isAddress(address: string, chainId?: number): boolean; +export function isHex(hex: Hex): boolean; +export function isHexStrict(hex: Hex): boolean; +export function asciiToHex(string: string, length?: number): string; +export function hexToAscii(string: string): string; +export function toAscii(string: string): string; +export function bytesToHex(bytes: number[]): string; +export function numberToHex(value: number | string | BN): string; +export function checkAddressChecksum(address: string): boolean; +export function fromAscii(string: string): string; +export function fromDecimal(value: string | number): string; +export function fromUtf8(string: string): string; +export function fromWei(value: string | BN, unit?: Unit): string; +export function hexToBytes(hex: Hex): number[]; +export function hexToNumber(hex: Hex,bigIntOnOverflow?: boolean): number | string; +export function hexToNumberString(hex: Hex): string; +export function hexToString(hex: Hex): string; +export function hexToUtf8(string: string): string; +export function keccak256(value: string | BN): string; +export function padLeft(value: string | number, characterAmount: number, sign?: string): string; +export function leftPad(string: string | number, characterAmount: number, sign?: string): string; +export function rightPad(string: string | number, characterAmount: number, sign?: string): string; +export function padRight(string: string | number, characterAmount: number, sign?: string): string; +export function sha3(value: string | BN | Buffer): string | null; +export function sha3Raw(value: string | BN | Buffer): string; +export function randomHex(bytesSize: number): string; +export function utf8ToHex(string: string): string; +export function stringToHex(string: string): string; +export function toChecksumAddress(address: string): string; +export function toDecimal(hex: Hex): number; +export function toHex(value: number | string | BN): string; +export function toUtf8(string: string): string; +export function toWei(val: BN, unit?: Unit): BN; +export function toWei(val: string, unit?: Unit): string; +export function isBloom(bloom: string): boolean; +export function isInBloom(bloom: string, value: string | Uint8Array): boolean; +export function isUserEthereumAddressInBloom(bloom: string, ethereumAddress: string): boolean; +export function isContractAddressInBloom(bloom: string, contractAddress: string): boolean; +export function isTopicInBloom(bloom: string, topic: string): boolean; +export function isTopic(topic: string): boolean; +export function jsonInterfaceMethodToString(abiItem: AbiItem): string; +export function soliditySha3(...val: Mixed[]): string | null; +export function soliditySha3Raw(...val: Mixed[]): string; +export function encodePacked(...val: Mixed[]): string | null; +export function getUnitValue(unit: Unit): string; +export function unitMap(): Units; +export function testAddress(bloom: string, address: string): boolean; +export function testTopic(bloom: string, topic: string): boolean; +export function getSignatureParameters(signature: string): {r: string; s: string; v: number}; +export function stripHexPrefix(str: string): string; +export function toNumber(value: number | string | BN, bigIntOnOverflow?: boolean): number | string; + +// interfaces +export interface Utils { + isBN(value: string | number): boolean; + isBigNumber(value: BN): boolean; + toBN(value: number | string): BN; + toTwosComplement(value: number | string | BN): string; + isAddress(address: string, chainId?: number): boolean; + isHex(hex: Hex): boolean; + isHexStrict(hex: Hex): boolean; + asciiToHex(string: string, length?: number): string; + hexToAscii(string: string): string; + toAscii(string: string): string; + bytesToHex(bytes: number[]): string; + numberToHex(value: number | string | BN): string; + checkAddressChecksum(address: string, chainId?: number): boolean; + fromAscii(string: string): string; + fromDecimal(value: string | number): string; + fromUtf8(string: string): string; + fromWei(value: string | BN, unit?: Unit): string; + hexToBytes(hex: Hex): number[]; + hexToNumber(hex: Hex, bigIntOnOverflow?: boolean): number | string; + hexToNumberString(hex: Hex): string; + hexToString(hex: Hex): string; + hexToUtf8(string: string): string; + keccak256(value: string | BN): string; + padLeft(value: string | number, characterAmount: number, sign?: string): string; + leftPad(string: string | number, characterAmount: number, sign?: string): string; + rightPad(string: string | number, characterAmount: number, sign?: string): string; + padRight(string: string | number, characterAmount: number, sign?: string): string; + sha3(value: string | BN): string | null; + randomHex(bytesSize: number): string; + utf8ToHex(string: string): string; + stringToHex(string: string): string; + toChecksumAddress(address: string): string; + toDecimal(hex: Hex): number; + toHex(value: number | string | BN): string; + toUtf8(string: string): string; + toWei(val: BN, unit?: Unit): BN; + toWei(val: string, unit?: Unit): string; + isBloom(bloom: string): boolean; + isInBloom(bloom: string, value: string | Uint8Array): boolean; + isUserEthereumAddressInBloom(bloom: string, ethereumAddress: string): boolean; + isContractAddressInBloom(bloom: string, contractAddress: string): boolean; + isTopicInBloom(bloom: string, topic: string): boolean; + isTopic(topic: string): boolean; + _jsonInterfaceMethodToString(abiItem: AbiItem): string; + soliditySha3(...val: Mixed[]): string | null; + soliditySha3Raw(...val: Mixed[]): string; + encodePacked(...val: Mixed[]): string | null; + getUnitValue(unit: Unit): string; + unitMap(): Units; + testAddress(bloom: string, address: string): boolean; + testTopic(bloom: string, topic: string): boolean; + getSignatureParameters(signature: string): {r: string; s: string; v: number}; + stripHexPrefix(str: string): string; + toNumber(value: number | string | BN, bigIntOnOverflow?: boolean): number | string; +} + +export interface Units { + noether: string; + wei: string; + kwei: string; + Kwei: string; + babbage: string; + femtoether: string; + mwei: string; + Mwei: string; + lovelace: string; + picoether: string; + gwei: string; + Gwei: string; + shannon: string; + nanoether: string; + nano: string; + szabo: string; + microether: string; + micro: string; + finney: string; + milliether: string; + milli: string; + ether: string; + kether: string; + grand: string; + mether: string; + gether: string; + tether: string; +} + +export type AbiType = 'function' | 'constructor' | 'event' | 'fallback' | 'receive'; +export type StateMutabilityType = 'pure' | 'view' | 'nonpayable' | 'payable'; + +export interface AbiItem { + anonymous?: boolean; + constant?: boolean; + inputs?: AbiInput[]; + name?: string; + outputs?: AbiOutput[]; + payable?: boolean; + stateMutability?: StateMutabilityType; + type: AbiType; + gas?: number; +} + +export interface AbiInput { + name: string; + type: string; + indexed?: boolean; + components?: AbiInput[]; + internalType?: string; +} + +export interface AbiOutput { + name: string; + type: string; + components?: AbiOutput[]; + internalType?: string; +} diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/ascii-to-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/ascii-to-hex-test.ts new file mode 100644 index 0000000..0f2f750 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/ascii-to-hex-test.ts @@ -0,0 +1,47 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file ascii-to-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {asciiToHex} from 'web3-utils'; + +// $ExpectType string +asciiToHex('I have 100!'); + +// $ExpectType string +asciiToHex('I have 100!', 32); + +// $ExpectError +asciiToHex(345); +// $ExpectError +asciiToHex(new BN(3)); +// $ExpectError +asciiToHex({}); +// $ExpectError +asciiToHex(true); +// $ExpectError +asciiToHex(['string']); +// $ExpectError +asciiToHex([4]); +// $ExpectError +asciiToHex(null); +// $ExpectError +asciiToHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/bytes-to-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/bytes-to-hex-test.ts new file mode 100644 index 0000000..af7253c --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/bytes-to-hex-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file bytes-to-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {bytesToHex} from 'web3-utils'; + +// $ExpectType string +bytesToHex([72]); + +// $ExpectError +bytesToHex(['string']); +// $ExpectError +bytesToHex(345); +// $ExpectError +bytesToHex(new BN(3)); +// $ExpectError +bytesToHex({}); +// $ExpectError +bytesToHex(true); +// $ExpectError +bytesToHex(['string']); +// $ExpectError +bytesToHex(null); +// $ExpectError +bytesToHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/check-address-checksum-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/check-address-checksum-test.ts new file mode 100644 index 0000000..b5843e5 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/check-address-checksum-test.ts @@ -0,0 +1,60 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file check-address-checksum-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {checkAddressChecksum} from 'web3-utils'; + +// $ExpectType boolean +checkAddressChecksum('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); + +// $ExpectError +checkAddressChecksum('0xFb6916095CA1dF60bb79CE92ce3Ea74C37c5D359', 31); +// $ExpectError +checkAddressChecksum('0xFb6916095CA1dF60bb79CE92ce3Ea74C37c5D359', undefined); +// $ExpectError +checkAddressChecksum([4]); +// $ExpectError +checkAddressChecksum(['string']); +// $ExpectError +checkAddressChecksum(345); +// $ExpectError +checkAddressChecksum(new BN(3)); +// $ExpectError +checkAddressChecksum({}); +// $ExpectError +checkAddressChecksum(true); +// $ExpectError +checkAddressChecksum(null); +// $ExpectError +checkAddressChecksum(undefined); +// $ExpectError +checkAddressChecksum('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', 'string'); +// $ExpectError +checkAddressChecksum('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', [4]); +// $ExpectError +checkAddressChecksum('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', new BN(3)); +// $ExpectError +checkAddressChecksum('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', {}); +// $ExpectError +checkAddressChecksum('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', true); +// $ExpectError +checkAddressChecksum('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', null); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/encode-packed.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/encode-packed.ts new file mode 100644 index 0000000..acfa7e7 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/encode-packed.ts @@ -0,0 +1,52 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file solidity-sha3-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {encodePacked} from 'web3-utils'; + +// $ExpectType string | null +encodePacked('234564535', '0xfff23243', true, -10); +// $ExpectType string | null +encodePacked('Hello!%'); +// $ExpectType string | null +encodePacked('234'); +// $ExpectType string | null +encodePacked(0xea); +// $ExpectType string | null +encodePacked(new BN(3)); +// $ExpectType string | null +encodePacked({type: 'uint256', value: '234'}); +// $ExpectType string | null +encodePacked({t: 'uint', v: new BN('234')}); +// $ExpectType string | null +encodePacked({t: 'string', v: 'Hello!%'}, {t: 'int8', v: -23}, {t: 'address', v: '0x85F43D8a49eeB85d32Cf465507DD71d507100C1d'}); +// $ExpectType string | null +encodePacked('0x407D73d8a49eeb85D32Cf465507dd71d507100c1'); + +// $ExpectError +encodePacked(['hey']); +// $ExpectError +encodePacked([34]); +// $ExpectError +encodePacked(null); +// $ExpectError +encodePacked(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-ascii-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-ascii-test.ts new file mode 100644 index 0000000..504c6ee --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-ascii-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file from-ascii-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {fromAscii} from 'web3-utils'; + +// $ExpectType string +fromAscii('I have 100!'); + +// $ExpectError +fromAscii(345); +// $ExpectError +fromAscii(new BN(3)); +// $ExpectError +fromAscii({}); +// $ExpectError +fromAscii(true); +// $ExpectError +fromAscii(['string']); +// $ExpectError +fromAscii([4]); +// $ExpectError +fromAscii(null); +// $ExpectError +fromAscii(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-decimal-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-decimal-test.ts new file mode 100644 index 0000000..3870aa3 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-decimal-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file from-decimal-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {fromDecimal} from 'web3-utils'; + +// $ExpectType string +fromDecimal('232'); +// $ExpectType string +fromDecimal(232); + +// $ExpectError +fromDecimal(new BN(3)); +// $ExpectError +fromDecimal(['string']); +// $ExpectError +fromDecimal([4]); +// $ExpectError +fromDecimal({}); +// $ExpectError +fromDecimal(true); +// $ExpectError +fromDecimal(null); +// $ExpectError +fromDecimal(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-utf8-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-utf8-test.ts new file mode 100644 index 0000000..8ab06f8 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-utf8-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file from-utf8-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {fromUtf8} from 'web3-utils'; + +// $ExpectType string +fromUtf8('I have 100£'); + +// $ExpectError +fromUtf8(232); +// $ExpectError +fromUtf8(new BN(3)); +// $ExpectError +fromUtf8(['string']); +// $ExpectError +fromUtf8([4]); +// $ExpectError +fromUtf8({}); +// $ExpectError +fromUtf8(true); +// $ExpectError +fromUtf8(null); +// $ExpectError +fromUtf8(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-wei-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-wei-test.ts new file mode 100644 index 0000000..852616f --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/from-wei-test.ts @@ -0,0 +1,52 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file from-wei-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {fromWei} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType string +fromWei(bigNumber); +// $ExpectType string +fromWei('1'); +// $ExpectType string +fromWei(bigNumber, 'ether'); +// $ExpectType string +fromWei('1', 'ether'); + +// $ExpectError +fromWei(232); +// $ExpectError +fromWei(['string']); +// $ExpectError +fromWei([4]); +// $ExpectError +fromWei({}); +// $ExpectError +fromWei(true); +// $ExpectError +fromWei(null); +// $ExpectError +fromWei(undefined); +// $ExpectError +fromWei(new BN(3), 'blah'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/get-signature-params-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/get-signature-params-test.ts new file mode 100644 index 0000000..e1f4422 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/get-signature-params-test.ts @@ -0,0 +1,45 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file get-signature-params-tests.ts + * @author Aalok Singh + * @date 2018 + */ + +import BN = require('bn.js'); +import {getSignatureParameters} from 'web3-utils'; + +// $ExpectType { r: string; s: string; v: number; } +getSignatureParameters( + '0x90dc0e49b5a80eef86fcedcb863dcc727aeae5c11187c001fd3d18780ead2cc7701ba1986099a49164702f3d8b2c8dbbd45a6d1beb37d212d21fb1be4bb762a400' +); +// $ExpectError +getSignatureParameters(345); +// $ExpectError +getSignatureParameters(new BN(3)); +// $ExpectError +getSignatureParameters({}); +// $ExpectError +getSignatureParameters(true); +// $ExpectError +getSignatureParameters(['string']); +// $ExpectError +getSignatureParameters([4]); +// $ExpectError +getSignatureParameters(null); +// $ExpectError +getSignatureParameters(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/get-unit-value-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/get-unit-value-test.ts new file mode 100644 index 0000000..27ffc9a --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/get-unit-value-test.ts @@ -0,0 +1,46 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file get-unit-value-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {getUnitValue} from 'web3-utils'; + +// $ExpectType string +getUnitValue('ether'); + +// $ExpectError +getUnitValue('fake'); +// $ExpectError +getUnitValue(656); +// $ExpectError +getUnitValue(new BN(3)); +// $ExpectError +getUnitValue(['string']); +// $ExpectError +getUnitValue([4]); +// $ExpectError +getUnitValue({}); +// $ExpectError +getUnitValue(true); +// $ExpectError +getUnitValue(null); +// $ExpectError +getUnitValue(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-ascii-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-ascii-test.ts new file mode 100644 index 0000000..991e44c --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-ascii-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file hex-to-ascii-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {hexToAscii} from 'web3-utils'; + +// $ExpectType string +hexToAscii('0x4920686176652031303021'); + +// $ExpectError +hexToAscii(345); +// $ExpectError +hexToAscii(new BN(3)); +// $ExpectError +hexToAscii({}); +// $ExpectError +hexToAscii(true); +// $ExpectError +hexToAscii(['string']); +// $ExpectError +hexToAscii([4]); +// $ExpectError +hexToAscii(null); +// $ExpectError +hexToAscii(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-bytes-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-bytes-test.ts new file mode 100644 index 0000000..9a57e35 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-bytes-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file hex-to-bytes-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {hexToBytes} from 'web3-utils'; + +// $ExpectType number[] +hexToBytes('0x000000ea'); +// $ExpectType number[] +hexToBytes(0x000000ea); + +// $ExpectError +hexToBytes([4]); +// $ExpectError +hexToBytes(['string']); +// $ExpectError +hexToBytes(new BN(3)); +// $ExpectError +hexToBytes({}); +// $ExpectError +hexToBytes(true); +// $ExpectError +hexToBytes(null); +// $ExpectError +hexToBytes(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-number-string-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-number-string-test.ts new file mode 100644 index 0000000..10d80d0 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-number-string-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file hex-to-number-string-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {hexToNumberString} from 'web3-utils'; + +// $ExpectType string +hexToNumberString('0xea'); +// $ExpectType string +hexToNumberString(0xea); + +// $ExpectError +hexToNumberString(new BN(3); +// $ExpectError +hexToNumberString(['string']); +// $ExpectError +hexToNumberString([4]); +// $ExpectError +hexToNumberString({}); +// $ExpectError +hexToNumberString(true); +// $ExpectError +hexToNumberString(null); +// $ExpectError +hexToNumberString(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-number-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-number-test.ts new file mode 100644 index 0000000..be409a3 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-number-test.ts @@ -0,0 +1,48 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file hex-to-number-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {hexToNumber} from 'web3-utils'; + +// $ExpectType string | number +hexToNumber('232'); +// $ExpectType string | number +hexToNumber(232); +// $ExpectType string | number +hexToNumber('0x1fffffffffffff'); // the max safe number 2 ^ 53 +// $ExpectType string | number +hexToNumber('0x20000000000000', true); // larger than the 2 ^ 53 (unsafe) + +// $ExpectError +hexToNumber(new BN(3)); +// $ExpectError +hexToNumber(['string']); +// $ExpectError +hexToNumber([4]); +// $ExpectError +hexToNumber({}); +// $ExpectError +hexToNumber(true); +// $ExpectError +hexToNumber(null); +// $ExpectError +hexToNumber(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-string-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-string-test.ts new file mode 100644 index 0000000..000464e --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-string-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file hex-to-string-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {hexToString} from 'web3-utils'; + +// $ExpectType string +hexToString('0x49206861766520313030e282ac'); +// $ExpectType string +hexToString(0x49206861766520313030e282ac); + +// $ExpectError +hexToString(new BN(3)); +// $ExpectError +hexToString(['string']); +// $ExpectError +hexToString([4]); +// $ExpectError +hexToString({}); +// $ExpectError +hexToString(true); +// $ExpectError +hexToString(null); +// $ExpectError +hexToString(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-utf8-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-utf8-test.ts new file mode 100644 index 0000000..021fe0f --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/hex-to-utf8-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file hex-to-utf8-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {hexToUtf8} from 'web3-utils'; + +// $ExpectType string +hexToUtf8('0x49206861766520313030e282ac'); + +// $ExpectError +hexToUtf8(656); +// $ExpectError +hexToUtf8(new BN(3)); +// $ExpectError +hexToUtf8(['string']); +// $ExpectError +hexToUtf8([4]); +// $ExpectError +hexToUtf8({}); +// $ExpectError +hexToUtf8(true); +// $ExpectError +hexToUtf8(null); +// $ExpectError +hexToUtf8(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-address-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-address-test.ts new file mode 100644 index 0000000..6c2847c --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-address-test.ts @@ -0,0 +1,60 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-address-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {isAddress} from 'web3-utils'; + +// $ExpectType boolean +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectType boolean +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', 30); +// $ExpectType boolean +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', undefined); + +// $ExpectError +isAddress(4); +// $ExpectError +isAddress(new BN(3)); +// $ExpectError +isAddress({}); +// $ExpectError +isAddress(true); +// $ExpectError +isAddress(['string']); +// $ExpectError +isAddress([4]); +// $ExpectError +isAddress(null); +// $ExpectError +isAddress(undefined); +// $ExpectError +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', new BN(3)); +// $ExpectError +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', {}); +// $ExpectError +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', true); +// $ExpectError +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', ['string']); +// $ExpectError +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', [4]); +// $ExpectError +isAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51', null); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-big-number-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-big-number-test.ts new file mode 100644 index 0000000..99968cf --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-big-number-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-big-number-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {isBigNumber} from 'web3-utils'; + +// $ExpectType boolean +isBigNumber(new BN(3)); + +// $ExpectError +isBigNumber(7); +// $ExpectError +isBigNumber('4325'); +// $ExpectError +isBigNumber({}); +// $ExpectError +isBigNumber(true); +// $ExpectError +isBigNumber(['string']); +// $ExpectError +isBigNumber([4]); +// $ExpectError +isBigNumber(null); +// $ExpectError +isBigNumber(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-bloom-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-bloom-test.ts new file mode 100644 index 0000000..2caaddb --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-bloom-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-bloom-tests.ts + * @author Josh Stevens + * @date 2019 + */ + +import BN = require('bn.js'); +import { isBloom } from 'web3-utils'; + +// $ExpectType boolean +isBloom('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'); + +// $ExpectError +isBloom(656); +// $ExpectError +isBloom(new BN(3)); +// $ExpectError +isBloom(['string']); +// $ExpectError +isBloom([4]); +// $ExpectError +isBloom({}); +// $ExpectError +isBloom(true); +// $ExpectError +isBloom(null); +// $ExpectError +isBloom(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-bn-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-bn-test.ts new file mode 100644 index 0000000..1a4c9d1 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-bn-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-bn-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {isBN} from 'web3-utils'; + +// $ExpectType boolean +isBN(7); +// $ExpectType boolean +isBN('4325'); + +// $ExpectError +isBN({}); +// $ExpectError +isBN(true); +// $ExpectError +isBN(new BN(3)); +// $ExpectError +isBN(['string']); +// $ExpectError +isBN([4]); +// $ExpectError +isBN(null); +// $ExpectError +isBN(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-contract-address-in-bloom.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-contract-address-in-bloom.ts new file mode 100644 index 0000000..37c5878 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-contract-address-in-bloom.ts @@ -0,0 +1,26 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-contract-address-in-bloom.ts + * @author Josh Stevens + * @date 2019 + */ + +import { isContractAddressInBloom } from 'web3-utils'; + +// $ExpectType boolean +isContractAddressInBloom('0x08200081a06415012858022200cc48143008908c0000824e5405b41520795989024800380a8d4b198910b422b231086c3a62cc402e2573070306f180446440ad401016c3e30781115844d028c89028008a12240c0a2c184c0425b90d7af0530002f981221aa565809132000818c82805023a132a25150400010530ba0080420a10a137054454021882505080a6b6841082d84151010400ba8100c8802d440d060388084052c1300105a0868410648a40540c0f0460e190400807008914361118000a5202e94445ccc088311050052c8002807205212a090d90ba428030266024a910644b1042011aaae05391cc2094c45226400000380880241282ce4e12518c', '0x494bfa3a4576ba6cfe835b0deb78834f0c3e3994'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-hex-strict-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-hex-strict-test.ts new file mode 100644 index 0000000..70c7c46 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-hex-strict-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-hex-strict-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {isHexStrict} from 'web3-utils'; + +// $ExpectType boolean +isHexStrict('0xc1912'); +// $ExpectType boolean +isHexStrict(345); + +// $ExpectError +isHexStrict(new BN(3)); +// $ExpectError +isHexStrict({}); +// $ExpectError +isHexStrict(true); +// $ExpectError +isHexStrict(['string']); +// $ExpectError +isHexStrict([4]); +// $ExpectError +isHexStrict(null); +// $ExpectError +isHexStrict(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-hex-test.ts new file mode 100644 index 0000000..64ffa68 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-hex-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {isHex} from 'web3-utils'; + +// $ExpectType boolean +isHex('0xc1912'); +// $ExpectType boolean +isHex(345); + +// $ExpectError +isHex(new BN(3)); +// $ExpectError +isHex({}); +// $ExpectError +isHex(true); +// $ExpectError +isHex(['string']); +// $ExpectError +isHex([4]); +// $ExpectError +isHex(null); +// $ExpectError +isHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-in-bloom.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-in-bloom.ts new file mode 100644 index 0000000..e2ef4fa --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-in-bloom.ts @@ -0,0 +1,26 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-in-bloom-tests.ts + * @author Josh Stevens + * @date 2019 + */ + +import { isInBloom } from 'web3-utils'; + +// $ExpectType boolean +isInBloom('0x08200081a06415012858022200cc48143008908c0000824e5405b41520795989024800380a8d4b198910b422b231086c3a62cc402e2573070306f180446440ad401016c3e30781115844d028c89028008a12240c0a2c184c0425b90d7af0530002f981221aa565809132000818c82805023a132a25150400010530ba0080420a10a137054454021882505080a6b6841082d84151010400ba8100c8802d440d060388084052c1300105a0868410648a40540c0f0460e190400807008914361118000a5202e94445ccc088311050052c8002807205212a090d90ba428030266024a910644b1042011aaae05391cc2094c45226400000380880241282ce4e12518c', '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic-in-bloom.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic-in-bloom.ts new file mode 100644 index 0000000..e49126b --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic-in-bloom.ts @@ -0,0 +1,26 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-topic-in-bloom.ts + * @author Josh Stevens + * @date 2019 + */ + +import { isTopicInBloom } from 'web3-utils'; + +// $ExpectType boolean +isTopicInBloom('0x08200081a06415012858022200cc48143008908c0000824e5405b41520795989024800380a8d4b198910b422b231086c3a62cc402e2573070306f180446440ad401016c3e30781115844d028c89028008a12240c0a2c184c0425b90d7af0530002f981221aa565809132000818c82805023a132a25150400010530ba0080420a10a137054454021882505080a6b6841082d84151010400ba8100c8802d440d060388084052c1300105a0868410648a40540c0f0460e190400807008914361118000a5202e94445ccc088311050052c8002807205212a090d90ba428030266024a910644b1042011aaae05391cc2094c45226400000380880241282ce4e12518c', '0x4d61726b65745061792e696f206973206465706c6f79696e6720536d61727420'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic-test.ts new file mode 100644 index 0000000..bb60082 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-topic-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {isTopic} from 'web3-utils'; + +// $ExpectType boolean +isTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'); + +// $ExpectError +isTopic(656); +// $ExpectError +isTopic(new BN(3)); +// $ExpectError +isTopic(['string']); +// $ExpectError +isTopic([4]); +// $ExpectError +isTopic({}); +// $ExpectError +isTopic(true); +// $ExpectError +isTopic(null); +// $ExpectError +isTopic(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic.ts new file mode 100644 index 0000000..468cc65 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-topic.ts @@ -0,0 +1,26 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-user-ethereum-address-in-bloom.ts + * @author Josh Stevens + * @date 2019 + */ + +import { isTopic } from 'web3-utils'; + +// $ExpectType boolean +isTopic('0x000000000000000000000000b3bb037d2f2341a1c2775d51909a3d944597987d'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-user-ethereum-address-in-bloom.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-user-ethereum-address-in-bloom.ts new file mode 100644 index 0000000..2fadb63 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/is-user-ethereum-address-in-bloom.ts @@ -0,0 +1,26 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file is-user-ethereum-address-in-bloom.ts + * @author Josh Stevens + * @date 2019 + */ + +import { isUserEthereumAddressInBloom } from 'web3-utils'; + +// $ExpectType boolean +isUserEthereumAddressInBloom('0x08200081a06415012858022200cc48143008908c0000824e5405b41520795989024800380a8d4b198910b422b231086c3a62cc402e2573070306f180446440ad401016c3e30781115844d028c89028008a12240c0a2c184c0425b90d7af0530002f981221aa565809132000818c82805023a132a25150400010530ba0080420a10a137054454021882505080a6b6841082d84151010400ba8100c8802d440d060388084052c1300105a0868410648a40540c0f0460e190400807008914361118000a5202e94445ccc088311050052c8002807205212a090d90ba428030266024a910644b1042011aaae05391cc2094c45226400000380880241282ce4e12518c', '0x494bfa3a4576ba6cfe835b0deb78834f0c3e3994'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/json-interface-method-to-string-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/json-interface-method-to-string-test.ts new file mode 100644 index 0000000..7db99e0 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/json-interface-method-to-string-test.ts @@ -0,0 +1,121 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file json-interface-method-to-string-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import {jsonInterfaceMethodToString, AbiItem} from 'web3-utils'; + +const abiItem: AbiItem = { + anonymous: false, + constant: true, + inputs: [ + { + name: 'testMe', + type: 'uint256[3]' + }, + { + name: 'inputA', + type: 'tuple', + components: [ + { + name: 'a', + type: 'uint8' + }, + { + name: 'b', + type: 'uint8' + } + ] + }, + { + name: 'inputB', + type: 'tuple[]', + components: [ + { + name: 'a1', + type: 'uint256' + }, + { + name: 'a2', + type: 'uint256' + } + ] + }, + { + name: 'inputC', + type: 'uint8', + indexed: false + } + ], + name: "testName", + outputs: [ + { + name: "test", + type: "uint256" + }, + { + name: 'outputA', + type: 'tuple', + components: [ + { + name: 'a', + type: 'uint8' + }, + { + name: 'b', + type: 'uint8' + } + ] + }, + { + name: 'outputB', + type: 'tuple[]', + components: [ + { + name: 'a1', + type: 'uint256' + }, + { + name: 'a2', + type: 'uint256' + } + ] + } + ], + payable: false, + stateMutability: "pure", + type: "function", + gas: 175875 +}; +// $ExpectType string +jsonInterfaceMethodToString(abiItem); + +// $ExpectError +jsonInterfaceMethodToString(['string']); +// $ExpectError +jsonInterfaceMethodToString(234); +// $ExpectError +jsonInterfaceMethodToString([4]); +// $ExpectError +jsonInterfaceMethodToString(true); +// $ExpectError +jsonInterfaceMethodToString(null); +// $ExpectError +jsonInterfaceMethodToString(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/keccak256-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/keccak256-test.ts new file mode 100644 index 0000000..7f3f571 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/keccak256-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file keccak256-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {keccak256} from 'web3-utils'; + +// $ExpectType string +keccak256('234'); +// $ExpectType string +keccak256(new BN(3)); + +// $ExpectError +keccak256(['string']); +// $ExpectError +keccak256(234); +// $ExpectError +keccak256([4]); +// $ExpectError +keccak256({}); +// $ExpectError +keccak256(true); +// $ExpectError +keccak256(null); +// $ExpectError +keccak256(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/left-pad-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/left-pad-test.ts new file mode 100644 index 0000000..936f198 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/left-pad-test.ts @@ -0,0 +1,73 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file left-pad-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {leftPad} from 'web3-utils'; + +const bigNumber = new BN(3); +// $ExpectType string +leftPad('0x3456ff', 20); +// $ExpectType string +leftPad(0x3456ff, 20); +// $ExpectType string +leftPad('Hello', 20, 'x'); + +// $ExpectError +leftPad(bigNumber, 20); +// $ExpectError +leftPad(['string'], 20); +// $ExpectError +leftPad([4], 20); +// $ExpectError +leftPad({}, 20); +// $ExpectError +leftPad(true, 20); +// $ExpectError +leftPad(null, 20); +// $ExpectError +leftPad(undefined, 20); +// $ExpectError +leftPad('0x3456ff', bigNumber); +// $ExpectError +leftPad('0x3456ff', ['string']); +// $ExpectError +leftPad('0x3456ff', [4]); +// $ExpectError +leftPad('0x3456ff', {}); +// $ExpectError +leftPad('0x3456ff', true); +// $ExpectError +leftPad('0x3456ff', null); +// $ExpectError +leftPad('0x3456ff', undefined); +// $ExpectError +leftPad('Hello', 20, bigNumber); +// $ExpectError +leftPad('Hello', 20, ['string']); +// $ExpectError +leftPad('Hello', 20, [4]); +// $ExpectError +leftPad('Hello', 20, {}); +// $ExpectError +leftPad('Hello', 20, true); +// $ExpectError +leftPad('Hello', 20, null); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/number-to-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/number-to-hex-test.ts new file mode 100644 index 0000000..102e22f --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/number-to-hex-test.ts @@ -0,0 +1,46 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file number-to-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {numberToHex} from 'web3-utils'; + +// $ExpectType string +numberToHex('232'); +// $ExpectType string +numberToHex(232); +// $ExpectType string +numberToHex(new BN(3)); + +// $ExpectError +numberToHex(['72']); +// $ExpectError +numberToHex([4]); +// $ExpectError +numberToHex([ 36 ]); +// $ExpectError +numberToHex({}); +// $ExpectError +numberToHex(true); +// $ExpectError +numberToHex(null); +// $ExpectError +numberToHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/pad-left-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/pad-left-test.ts new file mode 100644 index 0000000..e763df6 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/pad-left-test.ts @@ -0,0 +1,74 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file pad-left-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {padLeft} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType string +padLeft('0x3456ff', 20); +// $ExpectType string +padLeft(0x3456ff, 20); +// $ExpectType string +padLeft('Hello', 20, 'x'); + +// $ExpectError +padLeft(bigNumber, 20); +// $ExpectError +padLeft(['string'], 20); +// $ExpectError +padLeft([4], 20); +// $ExpectError +padLeft({}, 20); +// $ExpectError +padLeft(true, 20); +// $ExpectError +padLeft(null, 20); +// $ExpectError +padLeft(undefined, 20); +// $ExpectError +padLeft('0x3456ff', bigNumber); +// $ExpectError +padLeft('0x3456ff', ['string']); +// $ExpectError +padLeft('0x3456ff', [4]); +// $ExpectError +padLeft('0x3456ff', {}); +// $ExpectError +padLeft('0x3456ff', true); +// $ExpectError +padLeft('0x3456ff', null); +// $ExpectError +padLeft('0x3456ff', undefined); +// $ExpectError +padLeft('Hello', 20, bigNumber); +// $ExpectError +padLeft('Hello', 20, ['string']); +// $ExpectError +padLeft('Hello', 20, [4]); +// $ExpectError +padLeft('Hello', 20, {}); +// $ExpectError +padLeft('Hello', 20, true); +// $ExpectError +padLeft('Hello', 20, null); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/pad-right-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/pad-right-test.ts new file mode 100644 index 0000000..97202a8 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/pad-right-test.ts @@ -0,0 +1,74 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file pad-right-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {padRight} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType string +padRight('0x3456ff', 20); +// $ExpectType string +padRight(0x3456ff, 20); +// $ExpectType string +padRight('Hello', 20, 'x'); + +// $ExpectError +padRight(bigNumber, 20); +// $ExpectError +padRight(['string'], 20); +// $ExpectError +padRight([4], 20); +// $ExpectError +padRight({}, 20); +// $ExpectError +padRight(true, 20); +// $ExpectError +padRight(null, 20); +// $ExpectError +padRight(undefined, 20); +// $ExpectError +padRight('0x3456ff', bigNumber); +// $ExpectError +padRight('0x3456ff', ['string']); +// $ExpectError +padRight('0x3456ff', [4]); +// $ExpectError +padRight('0x3456ff', {}); +// $ExpectError +padRight('0x3456ff', true); +// $ExpectError +padRight('0x3456ff', null); +// $ExpectError +padRight('0x3456ff', undefined); +// $ExpectError +padRight('Hello', 20, bigNumber); +// $ExpectError +padRight('Hello', 20, ['string']); +// $ExpectError +padRight('Hello', 20, [4]); +// $ExpectError +padRight('Hello', 20, {}); +// $ExpectError +padRight('Hello', 20, true); +// $ExpectError +padRight('Hello', 20, null); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/random-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/random-hex-test.ts new file mode 100644 index 0000000..64465af --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/random-hex-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file random-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {randomHex} from 'web3-utils'; + +// $ExpectType string +randomHex(32); + +// $ExpectError +randomHex('234'); +// $ExpectError +randomHex(new BN(3)); +// $ExpectError +randomHex(['string']); +// $ExpectError +randomHex([4]); +// $ExpectError +randomHex({}); +// $ExpectError +randomHex(true); +// $ExpectError +randomHex(null); +// $ExpectError +randomHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/right-pad-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/right-pad-test.ts new file mode 100644 index 0000000..f81ace7 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/right-pad-test.ts @@ -0,0 +1,74 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file right-pad-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {rightPad} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType string +rightPad('0x3456ff', 20); +// $ExpectType string +rightPad(0x3456ff, 20); +// $ExpectType string +rightPad('Hello', 20, 'x'); + +// $ExpectError +rightPad(bigNumber, 20); +// $ExpectError +rightPad(['string'], 20); +// $ExpectError +rightPad([4], 20); +// $ExpectError +rightPad({}, 20); +// $ExpectError +rightPad(true, 20); +// $ExpectError +rightPad(null, 20); +// $ExpectError +rightPad(undefined, 20); +// $ExpectError +rightPad('0x3456ff', bigNumber); +// $ExpectError +rightPad('0x3456ff', ['string']); +// $ExpectError +rightPad('0x3456ff', [4]); +// $ExpectError +rightPad('0x3456ff', {}); +// $ExpectError +rightPad('0x3456ff', true); +// $ExpectError +rightPad('0x3456ff', null); +// $ExpectError +rightPad('0x3456ff', undefined); +// $ExpectError +rightPad('Hello', 20, bigNumber); +// $ExpectError +rightPad('Hello', 20, ['string']); +// $ExpectError +rightPad('Hello', 20, [4]); +// $ExpectError +rightPad('Hello', 20, {}); +// $ExpectError +rightPad('Hello', 20, true); +// $ExpectError +rightPad('Hello', 20, null); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/sha3-raw-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/sha3-raw-test.ts new file mode 100644 index 0000000..9cad463 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/sha3-raw-test.ts @@ -0,0 +1,46 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file sha3Raw-tests.ts + * @author Samuel Furter + * @date 2019 + */ + +import BN = require('bn.js'); +import {sha3Raw} from 'web3-utils'; + +// $ExpectType string +sha3Raw('234'); +// $ExpectType string +sha3Raw(Buffer.from('123')); +// $ExpectType string +sha3Raw(new BN(3)); + +// $ExpectError +sha3Raw(['string']); +// $ExpectError +sha3Raw(234); +// $ExpectError +sha3Raw([4]); +// $ExpectError +sha3Raw({}); +// $ExpectError +sha3Raw(true); +// $ExpectError +sha3Raw(null); +// $ExpectError +sha3Raw(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/sha3-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/sha3-test.ts new file mode 100644 index 0000000..6e2b7ef --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/sha3-test.ts @@ -0,0 +1,46 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file sha3-tests.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {sha3} from 'web3-utils'; + +// $ExpectType string | null +sha3('234'); +// $ExpectType string | null +sha3(Buffer.from('123')); +// $ExpectType string | null +sha3(new BN(3)); + +// $ExpectError +sha3(['string']); +// $ExpectError +sha3(234); +// $ExpectError +sha3([4]); +// $ExpectError +sha3({}); +// $ExpectError +sha3(true); +// $ExpectError +sha3(null); +// $ExpectError +sha3(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/solidity-sha3-raw-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/solidity-sha3-raw-test.ts new file mode 100644 index 0000000..38c568f --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/solidity-sha3-raw-test.ts @@ -0,0 +1,52 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file solidity-sha3-raw-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {soliditySha3Raw} from 'web3-utils'; + +// $ExpectType string +soliditySha3Raw('234564535', '0xfff23243', true, -10); +// $ExpectType string +soliditySha3Raw('Hello!%'); +// $ExpectType string +soliditySha3Raw('234'); +// $ExpectType string +soliditySha3Raw(0xea); +// $ExpectType string +soliditySha3Raw(new BN(3)); +// $ExpectType string +soliditySha3Raw({type: 'uint256', value: '234'}); +// $ExpectType string +soliditySha3Raw({t: 'uint', v: new BN('234')}); +// $ExpectType string +soliditySha3Raw({t: 'string', v: 'Hello!%'}, {t: 'int8', v: -23}, {t: 'address', v: '0x85F43D8a49eeB85d32Cf465507DD71d507100C1d'}); +// $ExpectType string +soliditySha3Raw('0x407D73d8a49eeb85D32Cf465507dd71d507100c1'); + +// $ExpectError +soliditySha3Raw(['hey']); +// $ExpectError +soliditySha3Raw([34]); +// $ExpectError +soliditySha3Raw(null); +// $ExpectError +soliditySha3Raw(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/solidity-sha3-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/solidity-sha3-test.ts new file mode 100644 index 0000000..ea7d034 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/solidity-sha3-test.ts @@ -0,0 +1,52 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file solidity-sha3-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {soliditySha3} from 'web3-utils'; + +// $ExpectType string | null +soliditySha3('234564535', '0xfff23243', true, -10); +// $ExpectType string | null +soliditySha3('Hello!%'); +// $ExpectType string | null +soliditySha3('234'); +// $ExpectType string | null +soliditySha3(0xea); +// $ExpectType string | null +soliditySha3(new BN(3)); +// $ExpectType string | null +soliditySha3({type: 'uint256', value: '234'}); +// $ExpectType string | null +soliditySha3({t: 'uint', v: new BN('234')}); +// $ExpectType string | null +soliditySha3({t: 'string', v: 'Hello!%'}, {t: 'int8', v: -23}, {t: 'address', v: '0x85F43D8a49eeB85d32Cf465507DD71d507100C1d'}); +// $ExpectType string | null +soliditySha3('0x407D73d8a49eeb85D32Cf465507dd71d507100c1'); + +// $ExpectError +soliditySha3(['hey']); +// $ExpectError +soliditySha3([34]); +// $ExpectError +soliditySha3(null); +// $ExpectError +soliditySha3(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/string-to-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/string-to-hex-test.ts new file mode 100644 index 0000000..a8c4370 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/string-to-hex-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file string-to-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {stringToHex} from 'web3-utils'; + +// $ExpectType string +stringToHex('I have 100£'); + +// $ExpectError +stringToHex(232); +// $ExpectError +stringToHex(new BN(3)); +// $ExpectError +stringToHex(['string']); +// $ExpectError +stringToHex([4]); +// $ExpectError +stringToHex({}); +// $ExpectError +stringToHex(true); +// $ExpectError +stringToHex(null); +// $ExpectError +stringToHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/strip-hex-prefix-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/strip-hex-prefix-test.ts new file mode 100644 index 0000000..84a54c5 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/strip-hex-prefix-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file strip-hex-prefix-test.ts + * @author Alejandro Cavallero + * @date 2019 + */ + +import BN = require('bn.js'); +import {stripHexPrefix} from 'web3-utils'; + +// $ExpectType string +stripHexPrefix('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb'); + +// $ExpectError +stripHexPrefix(123); +// $ExpectError +stripHexPrefix(new BN(3)); +// $ExpectError +stripHexPrefix(['string']); +// $ExpectError +stripHexPrefix([4]); +// $ExpectError +stripHexPrefix({}); +// $ExpectError +stripHexPrefix(true); +// $ExpectError +stripHexPrefix(null); +// $ExpectError +stripHexPrefix(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/test-address-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/test-address-test.ts new file mode 100644 index 0000000..8c47a1c --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/test-address-test.ts @@ -0,0 +1,62 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file test-address-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {testAddress} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType boolean +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); + +// $ExpectError +testAddress(656, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress(bigNumber, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress(['string'], '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress([4], '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress({}, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress(true, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress(null, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress(undefined, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', 656); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', bigNumber); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', ['string']); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', [4]); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', {}); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', true); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', null); +// $ExpectError +testAddress('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/test-topic-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/test-topic-test.ts new file mode 100644 index 0000000..5c30608 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/test-topic-test.ts @@ -0,0 +1,62 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file test-topic-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {testTopic} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType boolean +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); + +// $ExpectError +testTopic(656, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic(bigNumber, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic(['string'], '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic([4], '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic({}, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic(true, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic(null, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic(undefined, '0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', 656); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', bigNumber); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', ['string']); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', [4]); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', {}); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', true); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', null); +// $ExpectError +testTopic('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-ascii-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-ascii-test.ts new file mode 100644 index 0000000..9d086a2 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-ascii-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-ascii-tests.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toAscii} from 'web3-utils'; + +// $ExpectType string +toAscii('0x4920686176652031303021'); + +// $ExpectError +toAscii(345); +// $ExpectError +toAscii(new BN(3)); +// $ExpectError +toAscii({}); +// $ExpectError +toAscii(true); +// $ExpectError +toAscii(['string']); +// $ExpectError +toAscii([4]); +// $ExpectError +toAscii(null); +// $ExpectError +toAscii(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-bn-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-bn-test.ts new file mode 100644 index 0000000..0df148d --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-bn-test.ts @@ -0,0 +1,41 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-bn-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import {toBN} from 'web3-utils'; + +// $ExpectType BN +toBN(4); +// $ExpectType BN +toBN('443'); + +// $ExpectError +toBN({}); +// $ExpectError +toBN(true); +// $ExpectError +toBN(['string']); +// $ExpectError +toBN([4]); +// $ExpectError +toBN(null); +// $ExpectError +toBN(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-check-sum-address-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-check-sum-address-test.ts new file mode 100644 index 0000000..6fe37fb --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-check-sum-address-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-check-sum-address-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toChecksumAddress} from 'web3-utils'; + +// $ExpectType string +toChecksumAddress('0x8ee7f17bb3f88b01247c21ab6603880b64ae53e811f5e01138822e558cf1ab51'); + +// $ExpectError +toChecksumAddress([4]); +// $ExpectError +toChecksumAddress(['string']); +// $ExpectError +toChecksumAddress(345); +// $ExpectError +toChecksumAddress(new BN(3)); +// $ExpectError +toChecksumAddress({}); +// $ExpectError +toChecksumAddress(true); +// $ExpectError +toChecksumAddress(null); +// $ExpectError +toChecksumAddress(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-decimal-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-decimal-test.ts new file mode 100644 index 0000000..77793f8 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-decimal-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-decimal-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toDecimal} from 'web3-utils'; + +// $ExpectType number +toDecimal('232'); +// $ExpectType number +toDecimal(232); + +// $ExpectError +toDecimal(new BN(3)); +// $ExpectError +toDecimal(['string']); +// $ExpectError +toDecimal([4]); +// $ExpectError +toDecimal({}); +// $ExpectError +toDecimal(true); +// $ExpectError +toDecimal(null); +// $ExpectError +toDecimal(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-hex-test.ts new file mode 100644 index 0000000..0c2be5b --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-hex-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toHex} from 'web3-utils'; + +// $ExpectType string +toHex('234'); +// $ExpectType string +toHex(234); +// $ExpectType string +toHex(new BN(3)); + +// $ExpectError +toHex(['string']); +// $ExpectError +toHex(true); +// $ExpectError +toHex([4]); +// $ExpectError +toHex({}); +// $ExpectError +toHex(null); +// $ExpectError +toHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-number-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-number-test.ts new file mode 100644 index 0000000..0f04731 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-number-test.ts @@ -0,0 +1,48 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-number-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toNumber} from 'web3-utils'; + +// $ExpectType string | number +toNumber('234'); +// $ExpectType string | number +toNumber(234); +// $ExpectType string | number +toNumber(new BN(3)); +// $ExpectType string | number +toNumber('0x1fffffffffffff'); // the max safe number 2 ^ 53 +// $ExpectType string | number +toNumber('0x20000000000000', true); // larger than the 2 ^ 53 (unsafe) + +// $ExpectError +toNumber(['string']); +// $ExpectError +toNumber(true); +// $ExpectError +toNumber([4]); +// $ExpectError +toNumber({}); +// $ExpectError +toNumber(null); +// $ExpectError +toNumber(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-twos-compement-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-twos-compement-test.ts new file mode 100644 index 0000000..1162976 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-twos-compement-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-twos-compement-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toTwosComplement} from 'web3-utils'; + +// $ExpectType string +toTwosComplement(4); +// $ExpectType string +toTwosComplement('443'); +// $ExpectType string +toTwosComplement(new BN(3)); + +// $ExpectError +toTwosComplement({}); +// $ExpectError +toTwosComplement(true); +// $ExpectError +toTwosComplement(['string']); +// $ExpectError +toTwosComplement([4]); +// $ExpectError +toTwosComplement(null); +// $ExpectError +toTwosComplement(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-utf8-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-utf8-test.ts new file mode 100644 index 0000000..54c1074 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-utf8-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-utf8-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toUtf8} from 'web3-utils'; + +// $ExpectType string +toUtf8('0x49206861766520313030e282ac'); + +// $ExpectError +toUtf8(656); +// $ExpectError +toUtf8(new BN(3)); +// $ExpectError +toUtf8(['string']); +// $ExpectError +toUtf8([4]); +// $ExpectError +toUtf8({}); +// $ExpectError +toUtf8(true); +// $ExpectError +toUtf8(null); +// $ExpectError +toUtf8(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-wei-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-wei-test.ts new file mode 100644 index 0000000..ee725b5 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/to-wei-test.ts @@ -0,0 +1,50 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file to-wei-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {toWei} from 'web3-utils'; + +const bigNumber = new BN(3); + +// $ExpectType string +toWei('1'); +// $ExpectType BN +toWei(bigNumber); +// $ExpectType string +toWei('1', 'finney'); +// $ExpectType BN +toWei(bigNumber, 'finney'); + +// $ExpectError +toWei(['string']); +// $ExpectError +toWei([4]); +// $ExpectError +toWei({}); +// $ExpectError +toWei(true); +// $ExpectError +toWei(null); +// $ExpectError +toWei(undefined); +// $ExpectError +toWei(1, 'blah'); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/unit-map-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/unit-map-test.ts new file mode 100644 index 0000000..ab75ed9 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/unit-map-test.ts @@ -0,0 +1,26 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file unit-map-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import {unitMap} from 'web3-utils'; + +// $ExpectType Units +unitMap(); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/utf8-to-hex-test.ts b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/utf8-to-hex-test.ts new file mode 100644 index 0000000..116551b --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tests/utf8-to-hex-test.ts @@ -0,0 +1,44 @@ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file utf8-to-hex-test.ts + * @author Josh Stevens + * @date 2018 + */ + +import BN = require('bn.js'); +import {utf8ToHex} from 'web3-utils'; + +// $ExpectType string +utf8ToHex('I have 100£'); + +// $ExpectError +utf8ToHex(232); +// $ExpectError +utf8ToHex(new BN(3)); +// $ExpectError +utf8ToHex(['string']); +// $ExpectError +utf8ToHex([4]); +// $ExpectError +utf8ToHex({}); +// $ExpectError +utf8ToHex(true); +// $ExpectError +utf8ToHex(null); +// $ExpectError +utf8ToHex(undefined); diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tsconfig.json b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tsconfig.json new file mode 100644 index 0000000..e0200c8 --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noEmit": true, + "allowSyntheticDefaultImports": false, + "baseUrl": ".", + "paths": { + "web3-utils": ["."] + } + } +} diff --git a/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tslint.json b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tslint.json new file mode 100644 index 0000000..84e929c --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/node_modules/web3-utils/types/tslint.json @@ -0,0 +1,11 @@ +{ + "extends": "dtslint/dtslint.json", + "rules": { + "semicolon": false, + "no-import-default-of-export-equals": false, + "file-name-casing": [true, "kebab-case"], + "whitespace": false, + "no-redundant-jsdoc": false, + "max-line-length": false + } +} diff --git a/test/merkletreejs/node_modules/merkletreejs/package.json b/test/merkletreejs/node_modules/merkletreejs/package.json new file mode 100644 index 0000000..50c6d3a --- /dev/null +++ b/test/merkletreejs/node_modules/merkletreejs/package.json @@ -0,0 +1,96 @@ +{ + "name": "merkletreejs", + "version": "0.3.11", + "description": "Construct Merkle Trees and verify proofs", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist", + "merkletree.js" + ], + "scripts": { + "test": "tape test/*.js", + "clean": "rimraf dist", + "dev": "tsc -w", + "build": "npm run clean && tsc && npm run build:browser", + "build:browser": "browserify -t [ babelify --presets [ @babel/preset-env ] ] dist/index.js | uglifyjs > merkletree.js", + "lint": "standardx --fix src/*.ts test/*.js", + "lint:example": "standardx --fix example/*.js", + "docs": "rimraf docs/ && typedoc --plugin typedoc-plugin-markdown --hideSources --theme markdown --hideGenerator --excludeExternals --excludePrivate --out docs src/", + "prepare": "npm run lint && npm run build && npm run build:browser && npm run docs" + }, + "repository": { + "type": "git", + "url": "https://github.com/miguelmota/merkletreejs" + }, + "keywords": [ + "merkle", + "tree", + "hash", + "algorithm", + "crypto", + "bitcoin", + "ethereum", + "proof" + ], + "author": { + "name": "Miguel Mota", + "email": "hello@miguelmota.com", + "url": "https://miguelmota.com/" + }, + "license": { + "type": "MIT", + "url": "https://github.com/miguelmota/merkletreejs/blob/master/LICENSE" + }, + "bugs": { + "url": "https://github.com/miguelmota/merkletreejs/issues" + }, + "homepage": "https://github.com/miguelmota/merkletreejs", + "devDependencies": { + "@babel/core": "^7.10.2", + "@babel/preset-env": "^7.10.2", + "@types/node": "^11.12.1", + "@typescript-eslint/eslint-plugin": "^3.0.2", + "@typescript-eslint/parser": "^3.0.2", + "babelify": "^10.0.0", + "browserify": "^16.5.1", + "circomlibjs": "^0.1.7", + "crypto": "0.0.3", + "ethereum-cryptography": "^1.0.3", + "ethereumjs-util": "^7.0.9", + "keccak256": "^1.0.6", + "rimraf": "^2.6.3", + "sha1": "^1.1.1", + "standard": "^14.3.4", + "standardx": "^5.0.0", + "tape": "^4.9.2", + "typedoc": "^0.17.7", + "typedoc-plugin-markdown": "^2.3.1", + "typescript": "^3.4.1" + }, + "engines": { + "node": ">= 7.6.0" + }, + "dependencies": { + "bignumber.js": "^9.0.1", + "buffer-reverse": "^1.0.1", + "crypto-js": "^4.2.0", + "treeify": "^1.1.0", + "web3-utils": "^1.3.4" + }, + "eslintConfig": { + "rules": { + "no-unused-vars": "off", + "@typescript-eslint/no-unused-vars": "error" + } + }, + "standardx": { + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint/eslint-plugin" + ], + "globals": [ + "BigInt" + ] + } +} diff --git a/test/merkletreejs/node_modules/micro-ftch/LICENSE b/test/merkletreejs/node_modules/micro-ftch/LICENSE new file mode 100644 index 0000000..81a89da --- /dev/null +++ b/test/merkletreejs/node_modules/micro-ftch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/test/merkletreejs/node_modules/micro-ftch/README.md b/test/merkletreejs/node_modules/micro-ftch/README.md new file mode 100644 index 0000000..6a35cfa --- /dev/null +++ b/test/merkletreejs/node_modules/micro-ftch/README.md @@ -0,0 +1,40 @@ +# micro-ftch + +Wraps nodejs built-in modules and browser fetch into one function + +## Usage + +Can be used in browser and in node.js. + +> npm install micro-ftch + +```js +const fetch = require('micro-ftch'); +fetch('https://google.com').then(...) +``` + +## Options + +The list of options that can be supplied as second argument to fetch(url, opts): + +```typescript +export type FETCH_OPT = { + method?: string; + type?: 'text' | 'json' | 'bytes'; // Response encoding (auto-detect if empty) + redirect: boolean; // Follow redirects + expectStatusCode?: number | false; // Expect this status code + headers: Record; + data?: object; // POST/PUT/DELETE request data + full: boolean; // Return full request {headers, status, body} + keepAlive: boolean; // Enable keep-alive (node only) + cors: boolean; // Allow CORS safe-listed headers (browser-only) + referrer: boolean; // Send referrer (browser-only) + sslAllowSelfSigned: boolean; // Allow self-signed ssl certs (node only) + sslPinnedCertificates?: string[]; // Verify fingerprint of certificate (node only) + _redirectCount: number; +}; +``` + +## License + +MIT License (c) 2020, Paul Miller (https://paulmillr.com) \ No newline at end of file diff --git a/test/merkletreejs/node_modules/micro-ftch/index.d.ts b/test/merkletreejs/node_modules/micro-ftch/index.d.ts new file mode 100644 index 0000000..c96af10 --- /dev/null +++ b/test/merkletreejs/node_modules/micro-ftch/index.d.ts @@ -0,0 +1,24 @@ +export declare type FETCH_OPT = { + method?: string; + type?: 'text' | 'json' | 'bytes'; + redirect: boolean; + expectStatusCode?: number | false; + headers: Record; + data?: object; + full: boolean; + keepAlive: boolean; + cors: boolean; + referrer: boolean; + sslAllowSelfSigned: boolean; + sslPinnedCertificates?: string[]; + _redirectCount: number; +}; +export declare class InvalidCertError extends Error { + readonly fingerprint256: string; + constructor(msg: string, fingerprint256: string); +} +export declare class InvalidStatusCodeError extends Error { + readonly statusCode: number; + constructor(statusCode: number); +} +export default function fetchUrl(url: string, options?: Partial): Promise; diff --git a/test/merkletreejs/node_modules/micro-ftch/index.js b/test/merkletreejs/node_modules/micro-ftch/index.js new file mode 100644 index 0000000..7f00c3d --- /dev/null +++ b/test/merkletreejs/node_modules/micro-ftch/index.js @@ -0,0 +1,217 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidStatusCodeError = exports.InvalidCertError = void 0; +const DEFAULT_OPT = Object.freeze({ + redirect: true, + expectStatusCode: 200, + headers: {}, + full: false, + keepAlive: true, + cors: false, + referrer: false, + sslAllowSelfSigned: false, + _redirectCount: 0, +}); +class InvalidCertError extends Error { + constructor(msg, fingerprint256) { + super(msg); + this.fingerprint256 = fingerprint256; + } +} +exports.InvalidCertError = InvalidCertError; +class InvalidStatusCodeError extends Error { + constructor(statusCode) { + super(`Request Failed. Status Code: ${statusCode}`); + this.statusCode = statusCode; + } +} +exports.InvalidStatusCodeError = InvalidStatusCodeError; +function detectType(b, type) { + if (!type || type === 'text' || type === 'json') { + try { + let text = new TextDecoder('utf8', { fatal: true }).decode(b); + if (type === 'text') + return text; + try { + return JSON.parse(text); + } + catch (err) { + if (type === 'json') + throw err; + return text; + } + } + catch (err) { + if (type === 'text' || type === 'json') + throw err; + } + } + return b; +} +let agents = {}; +function fetchNode(url, _options) { + let options = { ...DEFAULT_OPT, ..._options }; + const http = require('http'); + const https = require('https'); + const zlib = require('zlib'); + const { promisify } = require('util'); + const { resolve: urlResolve } = require('url'); + const isSecure = !!/^https/.test(url); + let opts = { + method: options.method || 'GET', + headers: { 'Accept-Encoding': 'gzip, deflate, br' }, + }; + const compactFP = (s) => s.replace(/:| /g, '').toLowerCase(); + if (options.keepAlive) { + const agentOpt = { + keepAlive: true, + keepAliveMsecs: 30 * 1000, + maxFreeSockets: 1024, + maxCachedSessions: 1024, + }; + const agentKey = [ + isSecure, + isSecure && options.sslPinnedCertificates?.map((i) => compactFP(i)).sort(), + ].join(); + opts.agent = + agents[agentKey] || (agents[agentKey] = new (isSecure ? https : http).Agent(agentOpt)); + } + if (options.type === 'json') + opts.headers['Content-Type'] = 'application/json'; + if (options.data) { + if (!options.method) + opts.method = 'POST'; + opts.body = options.type === 'json' ? JSON.stringify(options.data) : options.data; + } + opts.headers = { ...opts.headers, ...options.headers }; + if (options.sslAllowSelfSigned) + opts.rejectUnauthorized = false; + const handleRes = async (res) => { + const status = res.statusCode; + if (options.redirect && 300 <= status && status < 400 && res.headers['location']) { + if (options._redirectCount == 10) + throw new Error('Request failed. Too much redirects.'); + options._redirectCount += 1; + return await fetchNode(urlResolve(url, res.headers['location']), options); + } + if (options.expectStatusCode && status !== options.expectStatusCode) { + res.resume(); + throw new InvalidStatusCodeError(status); + } + let buf = []; + for await (const chunk of res) + buf.push(chunk); + let bytes = Buffer.concat(buf); + const encoding = res.headers['content-encoding']; + if (encoding === 'br') + bytes = await promisify(zlib.brotliDecompress)(bytes); + if (encoding === 'gzip' || encoding === 'deflate') + bytes = await promisify(zlib.unzip)(bytes); + const body = detectType(bytes, options.type); + if (options.full) + return { headers: res.headers, status, body }; + return body; + }; + return new Promise((resolve, reject) => { + const handleError = async (err) => { + if (err && err.code === 'DEPTH_ZERO_SELF_SIGNED_CERT') { + try { + await fetchNode(url, { ...options, sslAllowSelfSigned: true, sslPinnedCertificates: [] }); + } + catch (e) { + if (e && e.fingerprint256) { + err = new InvalidCertError(`Self-signed SSL certificate: ${e.fingerprint256}`, e.fingerprint256); + } + } + } + reject(err); + }; + const req = (isSecure ? https : http).request(url, opts, (res) => { + res.on('error', handleError); + (async () => { + try { + resolve(await handleRes(res)); + } + catch (error) { + reject(error); + } + })(); + }); + req.on('error', handleError); + const pinned = options.sslPinnedCertificates?.map((i) => compactFP(i)); + const mfetchSecureConnect = (socket) => { + const fp256 = compactFP(socket.getPeerCertificate()?.fingerprint256 || ''); + if (!fp256 && socket.isSessionReused()) + return; + if (pinned.includes(fp256)) + return; + req.emit('error', new InvalidCertError(`Invalid SSL certificate: ${fp256} Expected: ${pinned}`, fp256)); + return req.abort(); + }; + if (options.sslPinnedCertificates) { + req.on('socket', (socket) => { + const hasListeners = socket + .listeners('secureConnect') + .map((i) => (i.name || '').replace('bound ', '')) + .includes('mfetchSecureConnect'); + if (hasListeners) + return; + socket.on('secureConnect', mfetchSecureConnect.bind(null, socket)); + }); + } + if (options.keepAlive) + req.setNoDelay(true); + if (opts.body) + req.write(opts.body); + req.end(); + }); +} +const SAFE_HEADERS = new Set(['Accept', 'Accept-Language', 'Content-Language', 'Content-Type'].map((i) => i.toLowerCase())); +const FORBIDDEN_HEADERS = new Set(['Accept-Charset', 'Accept-Encoding', 'Access-Control-Request-Headers', 'Access-Control-Request-Method', + 'Connection', 'Content-Length', 'Cookie', 'Cookie2', 'Date', 'DNT', 'Expect', 'Host', 'Keep-Alive', 'Origin', 'Referer', 'TE', 'Trailer', + 'Transfer-Encoding', 'Upgrade', 'Via'].map((i) => i.toLowerCase())); +async function fetchBrowser(url, _options) { + let options = { ...DEFAULT_OPT, ..._options }; + const headers = new Headers(); + if (options.type === 'json') + headers.set('Content-Type', 'application/json'); + let parsed = new URL(url); + if (parsed.username) { + const auth = btoa(`${parsed.username}:${parsed.password}`); + headers.set('Authorization', `Basic ${auth}`); + parsed.username = ''; + parsed.password = ''; + } + url = '' + parsed; + for (let k in options.headers) { + const name = k.toLowerCase(); + if (SAFE_HEADERS.has(name) || (options.cors && !FORBIDDEN_HEADERS.has(name))) + headers.set(k, options.headers[k]); + } + let opts = { headers, redirect: options.redirect ? 'follow' : 'manual' }; + if (!options.referrer) + opts.referrerPolicy = 'no-referrer'; + if (options.cors) + opts.mode = 'cors'; + if (options.data) { + if (!options.method) + opts.method = 'POST'; + opts.body = options.type === 'json' ? JSON.stringify(options.data) : options.data; + } + const res = await fetch(url, opts); + if (options.expectStatusCode && res.status !== options.expectStatusCode) + throw new InvalidStatusCodeError(res.status); + const body = detectType(new Uint8Array(await res.arrayBuffer()), options.type); + if (options.full) + return { headers: Object.fromEntries(res.headers.entries()), status: res.status, body }; + return body; +} +const IS_NODE = !!(typeof process == 'object' && + process.versions && + process.versions.node && + process.versions.v8); +function fetchUrl(url, options) { + const fn = IS_NODE ? fetchNode : fetchBrowser; + return fn(url, options); +} +exports.default = fetchUrl; diff --git a/test/merkletreejs/node_modules/micro-ftch/package.json b/test/merkletreejs/node_modules/micro-ftch/package.json new file mode 100644 index 0000000..1a5d02c --- /dev/null +++ b/test/merkletreejs/node_modules/micro-ftch/package.json @@ -0,0 +1,30 @@ +{ + "name": "micro-ftch", + "version": "0.3.1", + "description": "Wraps nodejs built-in modules and browser fetch into one function.", + "main": "index.js", + "files": [ + "index.js", + "index.d.ts" + ], + "scripts": { + "bench": "node test/bench.js", + "build": "tsc -d", + "test": "node test/node.js" + }, + "keywords": [ + "fetch", + "http", + "https", + "node", + "browser", + "ajax", + "request" + ], + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT", + "devDependencies": { + "@types/node": "^16.0", + "typescript": "^4.3.5" + } +} diff --git a/test/merkletreejs/node_modules/node-fetch/LICENSE.md b/test/merkletreejs/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..660ffec --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +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. + diff --git a/test/merkletreejs/node_modules/node-fetch/README.md b/test/merkletreejs/node_modules/node-fetch/README.md new file mode 100644 index 0000000..55f09b7 --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/test/merkletreejs/node_modules/node-fetch/browser.js b/test/merkletreejs/node_modules/node-fetch/browser.js new file mode 100644 index 0000000..ee86265 --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/test/merkletreejs/node_modules/node-fetch/lib/index.es.js b/test/merkletreejs/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000..aae9799 --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/test/merkletreejs/node_modules/node-fetch/lib/index.js b/test/merkletreejs/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000..567ff5d --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/test/merkletreejs/node_modules/node-fetch/lib/index.mjs b/test/merkletreejs/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000..2863dd9 --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/test/merkletreejs/node_modules/node-fetch/package.json b/test/merkletreejs/node_modules/node-fetch/package.json new file mode 100644 index 0000000..e0be176 --- /dev/null +++ b/test/merkletreejs/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/test/merkletreejs/node_modules/number-to-bn/.editorconfig b/test/merkletreejs/node_modules/number-to-bn/.editorconfig new file mode 100644 index 0000000..d4eed84 --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/.editorconfig @@ -0,0 +1,7 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = false +indent_style = space +indent_size = 2 diff --git a/test/merkletreejs/node_modules/number-to-bn/.gitattributes b/test/merkletreejs/node_modules/number-to-bn/.gitattributes new file mode 100644 index 0000000..a29125a --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/.gitattributes @@ -0,0 +1,106 @@ +# From https://github.com/Danimoth/gitattributes/blob/master/Web.gitattributes + +# Handle line endings automatically for files detected as text +# and leave all files detected as binary untouched. +* text=auto + +# +# The above will handle all files NOT found below +# + +# +## These files are text and should be normalized (Convert crlf => lf) +# + +# source code +*.php text +*.css text +*.sass text +*.scss text +*.less text +*.styl text +*.js text eol=lf +*.coffee text +*.json text +*.htm text +*.html text +*.xml text +*.svg text +*.txt text +*.ini text +*.inc text +*.pl text +*.rb text +*.py text +*.scm text +*.sql text +*.sh text +*.bat text + +# templates +*.ejs text +*.hbt text +*.jade text +*.haml text +*.hbs text +*.dot text +*.tmpl text +*.phtml text + +# server config +.htaccess text + +# git config +.gitattributes text +.gitignore text +.gitconfig text + +# code analysis config +.jshintrc text +.jscsrc text +.jshintignore text +.csslintrc text + +# misc config +*.yaml text +*.yml text +.editorconfig text + +# build config +*.npmignore text +*.bowerrc text + +# Heroku +Procfile text +.slugignore text + +# Documentation +*.md text +LICENSE text +AUTHORS text + + +# +## These files are binary and should be left untouched +# + +# (binary is a macro for -text -diff) +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.mov binary +*.mp4 binary +*.mp3 binary +*.flv binary +*.fla binary +*.swf binary +*.gz binary +*.zip binary +*.7z binary +*.ttf binary +*.eot binary +*.woff binary +*.pyc binary +*.pdf binary diff --git a/test/merkletreejs/node_modules/number-to-bn/.npmignore b/test/merkletreejs/node_modules/number-to-bn/.npmignore new file mode 100644 index 0000000..3260b1f --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/.npmignore @@ -0,0 +1,8 @@ +# Don't check auto-generated stuff into git +node_modules +coverage +lib + +# Cruft +.DS_Store +npm-debug.log diff --git a/test/merkletreejs/node_modules/number-to-bn/.travis.yml b/test/merkletreejs/node_modules/number-to-bn/.travis.yml new file mode 100644 index 0000000..baeeccb --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/.travis.yml @@ -0,0 +1,5 @@ +sudo: true +language: node_js +node_js: + - "6" +after_success: npm run coveralls diff --git a/test/merkletreejs/node_modules/number-to-bn/.zuul.yml b/test/merkletreejs/node_modules/number-to-bn/.zuul.yml new file mode 100644 index 0000000..24d3fda --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/.zuul.yml @@ -0,0 +1,14 @@ +ui: mocha-bdd +browsers: + - name: chrome + version: 39..latest + - name: firefox + version: 34..latest + - name: safari + version: 5..latest + - name: microsoftedge + version: latest + - name: ie + version: 8..latest + - name: android + version: 5.0..latest diff --git a/test/merkletreejs/node_modules/number-to-bn/CHANGELOG.md b/test/merkletreejs/node_modules/number-to-bn/CHANGELOG.md new file mode 100644 index 0000000..3e837f3 --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/CHANGELOG.md @@ -0,0 +1,41 @@ +# 1.7.0 -- remove console log + +1. Remove bad console log + +# 1.6.0 -- empty hex to zero + +1. Empty hex 0x -> 0 + +# 1.5.0 -- hex number fix + +1. Fixed hex number convetion, now if hex prefixed, always assumes base 16 + +# 1.4.0 -- fix hex number + +1. Fix hex number shim +2. More test cases added + +# 1.3.0 -- better everythign + +1. Better error messages +2. Added umd builds +3. Far more comprehensive testing coverage +4. Far more support for hex string coverage +5. Far more support for number string coverage +6. Less lines of code, more bang for your buck +7. More config + +# 1.2.0 -- decimal number fix + +1. now throws under decimal number + +# 1.1.0 -- es5 support + +1. es5 support + +# 0.0.1 -- number-to-bn + +1. Basic testing +2. Basic docs +3. License +4. basic exports diff --git a/test/merkletreejs/node_modules/number-to-bn/LICENSE b/test/merkletreejs/node_modules/number-to-bn/LICENSE new file mode 100644 index 0000000..b231a71 --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +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. diff --git a/test/merkletreejs/node_modules/number-to-bn/README.md b/test/merkletreejs/node_modules/number-to-bn/README.md new file mode 100644 index 0000000..d395cee --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/README.md @@ -0,0 +1,116 @@ +## number-to-bn + +
+ + + Dependency Status + + + + + devDependency Status + + + + + Build Status + + + + + NPM version + + + + Test Coverage + + + + + js-airbnb-style + +
+ +
+ +A simple method to convert integer or hex integer numbers to BN.js object instances. Does not supprot decimal numbers. + +## Install + +``` +npm install --save number-to-bn +``` + +## Usage + +```js +const numberToBN = require('number-to-bn'); + +console.log(numberToBN('-1')); + +// result -1 + +console.log(numberToBN(1)); + +// result 1 + +console.log(numberToBN(new BN(100))); + +// result 100 + +console.log(numberToBN(new BigNumber(10000))); + +// result 10000 + +console.log(numberToBN('0x0a')); + +// result 10 + +console.log(numberToBN('-0x0a')); + +// result -10 + +console.log(numberToBN('0.9')); // or {}, [], undefined, 9.9 + +// throws new Error(...) + +console.log(numberToBN(null)); // or {}, [], undefined, 9.9 + +// throws new Error(...) +``` + +## Important documents + +- [Changelog](CHANGELOG.md) +- [License](https://raw.githubusercontent.com/silentcicero/number-to-bn/master/LICENSE) + +## Licence + +This project is licensed under the MIT license, Copyright (c) 2016 Nick Dodson. For more information see LICENSE.md. + +``` +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +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. +``` diff --git a/test/merkletreejs/node_modules/number-to-bn/internals/webpack/webpack.config.js b/test/merkletreejs/node_modules/number-to-bn/internals/webpack/webpack.config.js new file mode 100644 index 0000000..4fdb52b --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/internals/webpack/webpack.config.js @@ -0,0 +1,49 @@ +var webpack = require('webpack'); // eslint-disable-line + +var env = process.env.NODE_ENV; // eslint-disable-line +var filename = 'number-to-bn'; // eslint-disable-line +var library = 'numberToBN'; // eslint-disable-line +var config = { + devtool: 'cheap-module-source-map', + entry: [ + './src/index.js', + ], + output: { + path: 'dist', + filename: filename + '.js', // eslint-disable-line + library: library, // eslint-disable-line + libraryTarget: 'umd', + umdNamedDefine: true, + }, + plugins: [ + new webpack.BannerPlugin({ banner: ' /* eslint-disable */ ', raw: true, entryOnly: true }), + new webpack.BannerPlugin({ banner: ' /* eslint-disable */ ', raw: true }), + new webpack.optimize.OccurrenceOrderPlugin(), + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify(env), + }), + ], +}; + +if (env === 'production') { + config.output.filename = filename + '.min.js'; // eslint-disable-line + config.plugins + .push(new webpack.optimize.UglifyJsPlugin({ + compressor: { + pure_getters: true, + unsafe: true, + unsafe_comps: true, + warnings: false, + screw_ie8: false, + }, + mangle: { + screw_ie8: false, + }, + output: { + screw_ie8: false, + }, + })); + config.plugins.push(new webpack.optimize.DedupePlugin()); +} + +module.exports = config; diff --git a/test/merkletreejs/node_modules/number-to-bn/package.json b/test/merkletreejs/node_modules/number-to-bn/package.json new file mode 100644 index 0000000..3ed060e --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/package.json @@ -0,0 +1,66 @@ +{ + "name": "number-to-bn", + "version": "1.7.0", + "description": "A simple method that will convert numbers, hex, BN or bignumber.js object into a BN.js object.", + "main": "src/index.js", + "scripts": { + "start": "npm test", + "release": "npmpub", + "prepublish": "npm run build", + "prebuild": "npm run build:clean && npm run test", + "build:clean": "npm run test:clean && rimraf ./dist", + "build:umd": "cross-env BABEL_ENV=commonjs NODE_ENV=development webpack --config ./internals/webpack/webpack.config.js --progress", + "build:umd:min": "cross-env BABEL_ENV=commonjs NODE_ENV=production webpack --config ./internals/webpack/webpack.config.js --progress", + "build:stats": "cross-env BABEL_ENV=commonjs NODE_ENV=production webpack --config ./internals/webpack/webpack.config.js --progress --profile --json > dist/stats.json", + "build": "npm run build:umd && npm run build:umd:min", + "test:clean": "rimraf ./coverage", + "test": "mocha ./src/tests/**/*.js -R spec --timeout 2000000", + "test-travis": "node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- src/tests/**/*.js -R spec --timeout 2000000", + "test:browser": "zuul -- ./src/tests/*.js", + "test:browser-local": "zuul --local -- ./src/tests/*.js", + "coveralls": "npm run test-travis && cat ./coverage/lcov.info | coveralls" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/SilentCicero/number-to-bn.git" + }, + "engines": { + "npm": ">=3", + "node": ">=6.5.0" + }, + "keywords": [ + "number", + "to", + "bn", + "convert", + "hex", + "bn.js" + ], + "author": "Nick Dodson ", + "license": "MIT", + "bugs": { + "url": "https://github.com/SilentCicero/number-to-bn/issues" + }, + "homepage": "https://github.com/SilentCicero/number-to-bn#readme", + "dependencies": { + "bn.js": "4.11.6", + "strip-hex-prefix": "1.0.0" + }, + "testling": { + "files": "src/tests/*.js" + }, + "devDependencies": { + "bignumber.js": "3.0.1", + "chai": "3.5.0", + "coveralls": "2.11.9", + "istanbul": "0.4.5", + "mocha": "3.2.0", + "zuul": "3.0.0", + + "cross-env": "1.0.7", + "pre-commit": "1.1.3", + "rimraf": "2.3.4", + "webpack": "2.1.0-beta.15" + }, + "pre-commit": "build" +} diff --git a/test/merkletreejs/node_modules/number-to-bn/src/index.js b/test/merkletreejs/node_modules/number-to-bn/src/index.js new file mode 100644 index 0000000..bd09963 --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/src/index.js @@ -0,0 +1,38 @@ +var BN = require('bn.js'); +var stripHexPrefix = require('strip-hex-prefix'); + +/** + * Returns a BN object, converts a number value to a BN + * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object + * @return {Object} `output` BN object of the number + * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number + */ +module.exports = function numberToBN(arg) { + if (typeof arg === 'string' || typeof arg === 'number') { + var multiplier = new BN(1); // eslint-disable-line + var formattedString = String(arg).toLowerCase().trim(); + var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; + var stringArg = stripHexPrefix(formattedString); // eslint-disable-line + if (stringArg.substr(0, 1) === '-') { + stringArg = stripHexPrefix(stringArg.slice(1)); + multiplier = new BN(-1, 10); + } + stringArg = stringArg === '' ? '0' : stringArg; + + if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) + || stringArg.match(/^[a-fA-F]+$/) + || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) { + return new BN(stringArg, 16).mul(multiplier); + } + + if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) { + return new BN(stringArg, 10).mul(multiplier); + } + } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { + if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { + return new BN(arg.toString(10), 10); + } + } + + throw new Error('[number-to-bn] while converting number ' + JSON.stringify(arg) + ' to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.'); +} diff --git a/test/merkletreejs/node_modules/number-to-bn/src/tests/test.index.js b/test/merkletreejs/node_modules/number-to-bn/src/tests/test.index.js new file mode 100644 index 0000000..4f20f19 --- /dev/null +++ b/test/merkletreejs/node_modules/number-to-bn/src/tests/test.index.js @@ -0,0 +1,226 @@ +const numberToBN = require('../index.js'); +const BigNumber = require('bignumber.js'); +const BN = require('bn.js'); +const assert = require('chai').assert; + +describe("numberToBN", () => { + describe("constructor", () => { + it("should be function export", () => { + assert.equal(typeof numberToBN, 'function'); + }); + }); + + const testCases = [ + { value: 0.1, expected: '0', shouldThrow: true }, + { value: '0.1', expected: '0', shouldThrow: true }, + { value: '-0.1', expected: '0', shouldThrow: true }, + { value: '.', expected: '0', shouldThrow: true }, + { value: [], expected: '0', shouldThrow: true }, + { value: undefined, expected: '0', shouldThrow: true }, + { value: null, expected: '0', shouldThrow: true }, + { value: {}, expected: '0', shouldThrow: true }, + { value: true, expected: '0', shouldThrow: true }, + { value: false, expected: '0', shouldThrow: true }, + { value: 'Z', expected: '0', shouldThrow: true }, + { value: 'z', expected: '0', shouldThrow: true }, + { value: 'zZZ', expected: '0', shouldThrow: true }, + { value: 'a.a', expected: '0', shouldThrow: true }, + { value: 'aA.af', expected: '0', shouldThrow: true }, + { value: '0xaA.af', expected: '0', shouldThrow: true }, + { value: '-0xaA.af', expected: '0', shouldThrow: true }, + { value: '-0xa.0a', expected: '0', shouldThrow: true }, + { value: '-0X0A.0a', expected: '0', shouldThrow: true }, + { value: '0x10', expected: '16', shouldThrow: false }, + { value: '-0x10', expected: '-16', shouldThrow: false }, + { value: '0X10', expected: '16', shouldThrow: false }, + { value: '0x', expected: '0', shouldThrow: false }, + { value: '0x10', expected: '16', shouldThrow: false }, + { value: '-0X10', expected: '-16', shouldThrow: false }, + { value: ' 0X10', expected: '16', shouldThrow: false }, + { value: ' -0X10', expected: '-16', shouldThrow: false }, + { value: "20938490284092380dfsjkZ", expected: '0', shouldThrow: true }, + { value: ":", expected: '0', shouldThrow: true }, + { value: "%", expected: '0', shouldThrow: true }, + { value: new BigNumber('100.001'), expected: '0', shouldThrow: true }, + { value: new BigNumber('-100.001'), expected: '0', shouldThrow: true }, + { value: new BigNumber('1.20'), expected: '0', shouldThrow: true }, + { value: 'Someone', expected: '0', shouldThrow: true }, + { value: '100.002fsdfdss', expected: '0', shouldThrow: true }, + { value: new Array(), expected: '-1', shouldThrow: true }, + { value: '0x9184e72a000', expected: new BN('9184e72a000', 16).toString(10) }, + { value: '0x15df', expected: new BN('15df', 16).toString(10) }, + { value: '0x57840CC2C', expected: new BN('57840CC2C', 16).toString(10) }, + { value: '9184E72a000', expected: new BN('9184e72a000', 16).toString(10) }, + { value: '15Df', expected: new BN('15df', 16).toString(10) }, + { value: '57840cC2C', expected: new BN('57840CC2C', 16).toString(10) }, + { value: '9184e72a000', expected: new BN('9184e72a000', 16).toString(10) }, + { value: '15df', expected: new BN('15df', 16).toString(10) }, + { value: '57840CC2C', expected: new BN('57840CC2C', 16).toString(10) }, + { value: ' -9184e72a000 ', expected: new BN('-9184e72a000', 16).toString(10) }, + { value: ' -15df ', expected: new BN('-15df', 16).toString(10) }, + { value: ' -57840CC2C ', expected: new BN('-57840CC2C', 16).toString(10) }, + { value: '-9184e72a000', expected: new BN('-9184e72a000', 16).toString(10) }, + { value: '-15df', expected: new BN('-15df', 16).toString(10) }, + { value: '-57840CC2C', expected: new BN('-57840CC2C', 16).toString(10) }, + { value: ' 0x9184e72a000', expected: new BN('9184e72a000', 16).toString(10) }, + { value: ' 0x15df', expected: new BN('15df', 16).toString(10) }, + { value: ' 0x57840CC2C', expected: new BN('57840CC2C', 16).toString(10) }, + { value: '-0x9184e72a000', expected: new BN('-9184e72a000', 16).toString(10) }, + { value: '-0x15df', expected: new BN('-15df', 16).toString(10) }, + { value: '-0x57840CC2C', expected: new BN('-57840CC2C', 16).toString(10) }, + { value: '', expected: '0', shouldThrow: false }, + { value: '-', expected: '0', shouldThrow: false }, + { value: 0, expected: '0', shouldThrow: false }, + { value: 1, expected: '1', shouldThrow: false }, + { value: -0, expected: '0', shouldThrow: false }, + { value: ' 0', expected: '0', shouldThrow: false }, + { value: ' 1', expected: '1', shouldThrow: false }, + { value: ' -0', expected: '0', shouldThrow: false }, + { value: ' -1 ', expected: '-1', shouldThrow: false }, + { value: ' 0 ', expected: '0', shouldThrow: false }, + { value: ' 1 ', expected: '1', shouldThrow: false }, + { value: ' -0 ', expected: '0', shouldThrow: false }, + { value: ' -1 ', expected: '-1', shouldThrow: false }, + { value: '0 ', expected: '0', shouldThrow: false }, + { value: '1 ', expected: '1', shouldThrow: false }, + { value: '-0 ', expected: '0', shouldThrow: false }, + { value: '-1 ', expected: '-1', shouldThrow: false }, + { value: '0', expected: '0', shouldThrow: false }, + { value: '1', expected: '1', shouldThrow: false }, + { value: '-0', expected: '0', shouldThrow: false }, + { value: '-1', expected: '-1', shouldThrow: false }, + { value: new BN(0), expected: '0', shouldThrow: false }, + { value: new BN(1), expected: '1', shouldThrow: false }, + { value: new BN(-1), expected: '-1', shouldThrow: false }, + { value: new BN(-0), expected: '0', shouldThrow: false }, + { value: new BigNumber(0), expected: '0', shouldThrow: false }, + { value: new BigNumber(1), expected: '1', shouldThrow: false }, + { value: new BigNumber('-1'), expected: '-1', shouldThrow: false }, + { value: new BigNumber('-0'), expected: '0', shouldThrow: false }, + { value: -92348723897, expected: '-92348723897', shouldThrow: false }, + { value: 24387298347, expected: '24387298347', shouldThrow: false }, + { value: 'a', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0a', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0xa', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0x0a', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: 'A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0xA', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0x0A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: '0X0A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' a', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0a', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0xa', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0x0a', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0xA', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0x0A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0X0A', expected: new BN('a', 16).toString(10), shouldThrow: false }, + { value: ' 0aF', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' 0xaf', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' 0x0AF', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' 0Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' 0xAf', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' 0x0AF', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: ' 0X0Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: 'af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0xaf', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0x0af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: 'Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0xAf', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0x0Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: '0X0Af', expected: new BN('af', 16).toString(10), shouldThrow: false }, + { value: new BigNumber('423879248942387943287923489724387987923'), expected: '423879248942387943287923489724387987923', shouldThrow: false }, + { value: new BN('423879248942387943287923489724387987923'), expected: '423879248942387943287923489724387987923', shouldThrow: false }, + { value: new BigNumber('24897234987'), expected: '24897234987', shouldThrow: false }, + { value: new BN('24897234987'), expected: '24897234987', shouldThrow: false }, + { value: new BigNumber('-423879248942387943287923489724387987923'), expected: '-423879248942387943287923489724387987923', shouldThrow: false }, + { value: new BN('-423879248942387943287923489724387987923'), expected: '-423879248942387943287923489724387987923', shouldThrow: false }, + { value: new BigNumber('-24897234987'), expected: '-24897234987', shouldThrow: false }, + { value: new BN('-24897234987'), expected: '-24897234987', shouldThrow: false }, + + // web3 tests + { value: 1, expected: '1' }, + { value: '1', expected: '1' }, + { value: '0x1', expected: '1'}, + { value: '0x01', expected: '1'}, + { value: 15, expected: '15'}, + { value: '15', expected: '15'}, + { value: '0xf', expected: '15'}, + { value: '0x0f', expected: '15'}, + { value: new BN('f', 16), expected: '15'}, + { value: new BigNumber('f', 16), expected: '15'}, + { value: -1, expected: '-1'}, + { value: '-1', expected: '-1'}, + { value: '-0x1', expected: '-1'}, + { value: '-0x01', expected: '-1'}, + { value: -15, expected: '-15'}, + { value: '-15', expected: '-15'}, + { value: '-0xf', expected: '-15'}, + { value: '-0x0f', expected: '-15'}, + { value: '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: '-0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: '-0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: 0, expected: '0'}, + { value: '0', expected: '0'}, + { value: '0x0', expected: '0'}, + { value: -0, expected: '0'}, + { value: '-0', expected: '0'}, + { value: '-0x0', expected: '0'}, + { value: new BN(0), expected: '0'}, + { value: new BigNumber(0), expected: '0'}, + + { value: new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16), expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: new BN('fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd', 16), expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: new BN('-ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16), expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: new BN('-fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd', 16), expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + + // BigNumber found to improperly handle large hex nums... + // { value: new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16), expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + // { value: new BigNumber('fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd', 16), expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + // { value: new BigNumber('-ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16), expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + // { value: new BigNumber('-fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd', 16), expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + + { value: ' 87234987239872349872489724897248972348972389472498728723897234', expected: '87234987239872349872489724897248972348972389472498728723897234', shouldThrow: false }, + { value: ' 0x87234987239872349872489724897248972348972389472498728723897234', expected: '238767897175128767816754103632273854819223082003987283874830606953481859636', shouldThrow: false }, + { value: ' -0x87234987239872349872489724897248972348972389472498728723897234 ', expected: '-238767897175128767816754103632273854819223082003987283874830606953481859636', shouldThrow: false }, + { value: ' 0xfffffffffFffffffffffffffffffffffffffffffffffffffffffffffffffffff', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: ' 0xfffffffffffffffffffffffffffffffffffffffFfffffffffffffffffffffffD ', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: ' -0xfffffffffffffffffffFffffffffffffffffffffffffffffffffffffffffffff', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: ' -0xfffffffffffffffffffffffffffffffffffffffffffffffffFfffffffffffffd ', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: ' fffffffffFffffffffffffffffffffffffffffffffffffffffffffffffffffff', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: ' fffffffffffffffffffffffffffffffffffffffFfffffffffffffffffffffffD ', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: ' -fffffffffffffffffffFffffffffffffffffffffffffffffffffffffffffffff', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: ' -fffffffffffffffffffffffffffffffffffffffffffffffffFfffffffffffffd ', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + + { value: '87234987239872349872489724897248972348972389472498728723897234', expected: '87234987239872349872489724897248972348972389472498728723897234', shouldThrow: false }, + { value: '0x87234987239872349872489724897248972348972389472498728723897234', expected: '238767897175128767816754103632273854819223082003987283874830606953481859636', shouldThrow: false }, + { value: '-0x87234987239872349872489724897248972348972389472498728723897234', expected: '-238767897175128767816754103632273854819223082003987283874830606953481859636', shouldThrow: false }, + { value: '0xfffffffffFffffffffffffffffffffffffffffffffffffffffffffffffffffff', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: '0xfffffffffffffffffffffffffffffffffffffffFfffffffffffffffffffffffD', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: '-0xfffffffffffffffffffFffffffffffffffffffffffffffffffffffffffffffff', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: '-0xfffffffffffffffffffffffffffffffffffffffffffffffffFfffffffffffffd', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: 'fffffffffFffffffffffffffffffffffffffffffffffffffffffffffffffffff', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: 'fffffffffffffffffffffffffffffffffffffffFfffffffffffffffffffffffD', expected: '115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + { value: '-fffffffffffffffffffFffffffffffffffffffffffffffffffffffffffffffff', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639935'}, + { value: '-fffffffffffffffffffffffffffffffffffffffffffffffffFfffffffffffffd', expected: '-115792089237316195423570985008687907853269984665640564039457584007913129639933'}, + ]; + + testCases.forEach(function (test) { + if (test.shouldThrow === true) { + it('should turn ' + test.value + ' to throw Error.. ', function () { + assert.throws(() => numberToBN(test.value), Error); + }); + } else { + it('should turn ' + test.value + ' to ' + test.expected, function () { + assert.equal(numberToBN(test.value).toString(10), test.expected); + }); + } + }); +}); diff --git a/test/merkletreejs/node_modules/randombytes/.travis.yml b/test/merkletreejs/node_modules/randombytes/.travis.yml new file mode 100644 index 0000000..69fdf71 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +matrix: + include: + - node_js: '7' + env: TEST_SUITE=test + - node_js: '6' + env: TEST_SUITE=test + - node_js: '5' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=phantom +script: "npm run-script $TEST_SUITE" diff --git a/test/merkletreejs/node_modules/randombytes/.zuul.yml b/test/merkletreejs/node_modules/randombytes/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/test/merkletreejs/node_modules/randombytes/LICENSE b/test/merkletreejs/node_modules/randombytes/LICENSE new file mode 100644 index 0000000..fea9d48 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 crypto-browserify + +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. diff --git a/test/merkletreejs/node_modules/randombytes/README.md b/test/merkletreejs/node_modules/randombytes/README.md new file mode 100644 index 0000000..3bacba4 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/README.md @@ -0,0 +1,14 @@ +randombytes +=== + +[![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) + +randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues + +```js +var randomBytes = require('randombytes'); +randomBytes(16);//get 16 random bytes +randomBytes(16, function (err, resp) { + // resp is 16 random bytes +}); +``` diff --git a/test/merkletreejs/node_modules/randombytes/browser.js b/test/merkletreejs/node_modules/randombytes/browser.js new file mode 100644 index 0000000..0fb0b71 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/browser.js @@ -0,0 +1,50 @@ +'use strict' + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = require('safe-buffer').Buffer +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} diff --git a/test/merkletreejs/node_modules/randombytes/index.js b/test/merkletreejs/node_modules/randombytes/index.js new file mode 100644 index 0000000..a2d9e39 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').randomBytes diff --git a/test/merkletreejs/node_modules/randombytes/package.json b/test/merkletreejs/node_modules/randombytes/package.json new file mode 100644 index 0000000..3623652 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/package.json @@ -0,0 +1,36 @@ +{ + "name": "randombytes", + "version": "2.1.0", + "description": "random bytes from browserify stand alone", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec", + "phantom": "zuul --phantom -- test.js", + "local": "zuul --local --no-coverage -- test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:crypto-browserify/randombytes.git" + }, + "keywords": [ + "crypto", + "random" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/randombytes/issues" + }, + "homepage": "https://github.com/crypto-browserify/randombytes", + "browser": "browser.js", + "devDependencies": { + "phantomjs": "^1.9.9", + "standard": "^10.0.2", + "tap-spec": "^2.1.2", + "tape": "^4.6.3", + "zuul": "^3.7.2" + }, + "dependencies": { + "safe-buffer": "^5.1.0" + } +} diff --git a/test/merkletreejs/node_modules/randombytes/test.js b/test/merkletreejs/node_modules/randombytes/test.js new file mode 100644 index 0000000..f266976 --- /dev/null +++ b/test/merkletreejs/node_modules/randombytes/test.js @@ -0,0 +1,81 @@ +var test = require('tape') +var randomBytes = require('./') +var MAX_BYTES = 65536 +var MAX_UINT32 = 4294967295 + +test('sync', function (t) { + t.plan(9) + t.equals(randomBytes(0).length, 0, 'len: ' + 0) + t.equals(randomBytes(3).length, 3, 'len: ' + 3) + t.equals(randomBytes(30).length, 30, 'len: ' + 30) + t.equals(randomBytes(300).length, 300, 'len: ' + 300) + t.equals(randomBytes(17 + MAX_BYTES).length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + t.equals(randomBytes(MAX_BYTES * 100).length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + t.throws(function () { + randomBytes(MAX_UINT32 + 1) + }) + t.throws(function () { + t.equals(randomBytes(-1)) + }) + t.throws(function () { + t.equals(randomBytes('hello')) + }) +}) + +test('async', function (t) { + t.plan(9) + + randomBytes(0, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 0, 'len: ' + 0) + }) + + randomBytes(3, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 3, 'len: ' + 3) + }) + + randomBytes(30, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 30, 'len: ' + 30) + }) + + randomBytes(300, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 300, 'len: ' + 300) + }) + + randomBytes(17 + MAX_BYTES, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + }) + + randomBytes(MAX_BYTES * 100, function (err, resp) { + if (err) throw err + + t.equals(resp.length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + }) + + t.throws(function () { + randomBytes(MAX_UINT32 + 1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes(-1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes('hello', function () { + t.ok(false, 'should not get here') + }) + }) +}) diff --git a/test/merkletreejs/node_modules/safe-buffer/LICENSE b/test/merkletreejs/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/test/merkletreejs/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. diff --git a/test/merkletreejs/node_modules/safe-buffer/README.md b/test/merkletreejs/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/test/merkletreejs/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/test/merkletreejs/node_modules/safe-buffer/index.d.ts b/test/merkletreejs/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/test/merkletreejs/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/safe-buffer/index.js b/test/merkletreejs/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/test/merkletreejs/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/test/merkletreejs/node_modules/safe-buffer/package.json b/test/merkletreejs/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/test/merkletreejs/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/test/merkletreejs/node_modules/set-function-length/.eslintrc b/test/merkletreejs/node_modules/set-function-length/.eslintrc new file mode 100644 index 0000000..7cff507 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/.eslintrc @@ -0,0 +1,27 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic" + ], + }], + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "max-lines-per-function": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/test/merkletreejs/node_modules/set-function-length/.github/FUNDING.yml b/test/merkletreejs/node_modules/set-function-length/.github/FUNDING.yml new file mode 100644 index 0000000..92feb6f --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-function-name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/test/merkletreejs/node_modules/set-function-length/.nycrc b/test/merkletreejs/node_modules/set-function-length/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/set-function-length/CHANGELOG.md b/test/merkletreejs/node_modules/set-function-length/CHANGELOG.md new file mode 100644 index 0000000..9539676 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.1](https://github.com/ljharb/set-function-length/compare/v1.1.0...v1.1.1) - 2023-10-19 + +### Fixed + +- [Fix] move `define-data-property` to runtime deps [`#2`](https://github.com/ljharb/set-function-length/issues/2) + +### Commits + +- [Dev Deps] update `object-inspect`; add missing `call-bind` [`5aecf79`](https://github.com/ljharb/set-function-length/commit/5aecf79e7d6400957a5d9bd9ac20d4528908ca18) + +## [v1.1.0](https://github.com/ljharb/set-function-length/compare/v1.0.1...v1.1.0) - 2023-10-13 + +### Commits + +- [New] add `env` entry point [`475c87a`](https://github.com/ljharb/set-function-length/commit/475c87aa2f59b700aaed589d980624ec596acdcb) +- [Tests] add coverage with `nyc` [`14f0bf8`](https://github.com/ljharb/set-function-length/commit/14f0bf8c145ae60bf14a026420a06bb7be132c36) +- [eslint] fix linting failure [`fb516f9`](https://github.com/ljharb/set-function-length/commit/fb516f93c664057138c53559ef63c8622a093335) +- [Deps] update `define-data-property` [`d727e7c`](https://github.com/ljharb/set-function-length/commit/d727e7c6c9a40d7bf26797694e500ea68741feea) + +## [v1.0.1](https://github.com/ljharb/set-function-length/compare/v1.0.0...v1.0.1) - 2023-10-12 + +### Commits + +- [Refactor] use `get-intrinsic`, since it‘s in the dep graph anyways [`278a954`](https://github.com/ljharb/set-function-length/commit/278a954a06cd849051c569ff7aee56df6798933e) +- [meta] add `exports` [`72acfe5`](https://github.com/ljharb/set-function-length/commit/72acfe5a0310071fb205a72caba5ecbab24336a0) + +## v1.0.0 - 2023-10-12 + +### Commits + +- Initial implementation, tests, readme [`fce14e1`](https://github.com/ljharb/set-function-length/commit/fce14e17586460e4f294405173be72b6ffdf7e5f) +- Initial commit [`ca7ba85`](https://github.com/ljharb/set-function-length/commit/ca7ba857c7c283f9d26e21f14e71cd388f2cb722) +- npm init [`6a7e493`](https://github.com/ljharb/set-function-length/commit/6a7e493927736cebcaf5c1a84e69b8e6b7b744d8) +- Only apps should have lockfiles [`d2bf6c4`](https://github.com/ljharb/set-function-length/commit/d2bf6c43de8a51b02a0aa53e8d62cb50c4a2b0da) diff --git a/test/merkletreejs/node_modules/set-function-length/LICENSE b/test/merkletreejs/node_modules/set-function-length/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and 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. diff --git a/test/merkletreejs/node_modules/set-function-length/README.md b/test/merkletreejs/node_modules/set-function-length/README.md new file mode 100644 index 0000000..15e3ac4 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/README.md @@ -0,0 +1,56 @@ +# set-function-length [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s length. + +Arguments: + - `fn`: the function + - `length`: the new length. Must be an integer between 0 and 2**32. + - `loose`: Optional. If true, and the length fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionLength = require('set-function-length'); +var assert = require('assert'); + +function zero() {} +function one(_) {} +function two(_, __) {} + +assert.equal(zero.length, 0); +assert.equal(one.length, 1); +assert.equal(two.length, 2); + +assert.equal(setFunctionLength(zero, 10), zero); +assert.equal(setFunctionLength(one, 11), one); +assert.equal(setFunctionLength(two, 12), two); + +assert.equal(zero.length, 10); +assert.equal(one.length, 11); +assert.equal(two.length, 12); +``` + +[package-url]: https://npmjs.org/package/set-function-length +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-length.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-length.svg +[deps-url]: https://david-dm.org/ljharb/set-function-length +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-length/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-length#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-length.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-length.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-length.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-length +[codecov-image]: https://codecov.io/gh/ljharb/set-function-length/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-length/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-length +[actions-url]: https://github.com/ljharb/set-function-length/actions diff --git a/test/merkletreejs/node_modules/set-function-length/env.js b/test/merkletreejs/node_modules/set-function-length/env.js new file mode 100644 index 0000000..80c0911 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/env.js @@ -0,0 +1,19 @@ +'use strict'; + +var gOPD = require('gopd'); + +var functionsHaveConfigurableLengths = gOPD && gOPD(function () {}, 'length').configurable; + +var functionsHaveWritableLengths = gOPD && gOPD(function () {}, 'length').writable; + +var boundFnsHaveConfigurableLengths = gOPD && gOPD(function () {}.bind(), 'length').configurable; + +var boundFnsHaveWritableLengths = gOPD && gOPD(function () {}.bind(), 'length').writable; + +module.exports = { + __proto__: null, + boundFnsHaveConfigurableLengths: boundFnsHaveConfigurableLengths, + boundFnsHaveWritableLengths: boundFnsHaveWritableLengths, + functionsHaveConfigurableLengths: functionsHaveConfigurableLengths, + functionsHaveWritableLengths: functionsHaveWritableLengths +}; diff --git a/test/merkletreejs/node_modules/set-function-length/index.js b/test/merkletreejs/node_modules/set-function-length/index.js new file mode 100644 index 0000000..7a31688 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/index.js @@ -0,0 +1,41 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $floor = GetIntrinsic('%Math.floor%'); + +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(fn, 'length', length, true, true); + } else { + define(fn, 'length', length); + } + } + return fn; +}; diff --git a/test/merkletreejs/node_modules/set-function-length/package.json b/test/merkletreejs/node_modules/set-function-length/package.json new file mode 100644 index 0000000..fdc2cb6 --- /dev/null +++ b/test/merkletreejs/node_modules/set-function-length/package.json @@ -0,0 +1,84 @@ +{ + "name": "set-function-length", + "version": "1.1.1", + "description": "Set a function's length property", + "main": "index.js", + "exports": { + ".": "./index.js", + "./env": "./env.js", + "./package.json": "./package.json" + }, + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-function-length.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "set", + "function", + "length", + "function.length" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-length/issues" + }, + "homepage": "https://github.com/ljharb/set-function-length#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.4", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "dependencies": { + "define-data-property": "^1.1.1", + "get-intrinsic": "^1.2.1", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/test/merkletreejs/node_modules/setimmediate/LICENSE.txt b/test/merkletreejs/node_modules/setimmediate/LICENSE.txt new file mode 100644 index 0000000..32b20de --- /dev/null +++ b/test/merkletreejs/node_modules/setimmediate/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola + +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. diff --git a/test/merkletreejs/node_modules/setimmediate/package.json b/test/merkletreejs/node_modules/setimmediate/package.json new file mode 100644 index 0000000..9b211e4 --- /dev/null +++ b/test/merkletreejs/node_modules/setimmediate/package.json @@ -0,0 +1,30 @@ +{ + "name": "setimmediate", + "description": "A shim for the setImmediate efficient script yielding API", + "version": "1.0.5", + "author": "YuzuJS", + "contributors": [ + "Domenic Denicola (https://domenic.me)", + "Donavon West (http://donavon.com)", + "Yaffle" + ], + "license": "MIT", + "repository": "YuzuJS/setImmediate", + "main": "setImmediate.js", + "files": [ + "setImmediate.js" + ], + "scripts": { + "lint": "jshint setImmediate.js", + "test": "mocha test/tests.js", + "test-browser": "opener http://localhost:9008/__zuul && zuul test/tests.js --ui mocha-bdd --local 9008", + "test-browser-only": "opener http://localhost:9007/test/browserOnly/index.html && http-server . -p 9007" + }, + "devDependencies": { + "jshint": "^2.5.0", + "mocha": "~1.18.2", + "http-server": "~0.6.1", + "opener": "^1.3", + "zuul": "^1.6.4" + } +} diff --git a/test/merkletreejs/node_modules/setimmediate/setImmediate.js b/test/merkletreejs/node_modules/setimmediate/setImmediate.js new file mode 100644 index 0000000..3c1b06e --- /dev/null +++ b/test/merkletreejs/node_modules/setimmediate/setImmediate.js @@ -0,0 +1,186 @@ +(function (global, undefined) { + "use strict"; + + if (global.setImmediate) { + return; + } + + var nextHandle = 1; // Spec says greater than zero + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global.document; + var registerImmediate; + + function setImmediate(callback) { + // Callback can either be a function or a string + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + // Copy function arguments + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + // Store and register the task + var task = { callback: callback, args: args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined, args); + break; + } + } + + function runIfPresent(handle) { + // From the spec: "Wait until any invocations of this algorithm started before this one have completed." + // So if we're currently running a task, we'll need to delay this invocation. + if (currentlyRunningATask) { + // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a + // "too much recursion" error. + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function () { runIfPresent(handle); }); + }; + } + + function canUsePostMessage() { + // The test against `importScripts` prevents this implementation from being installed inside a web worker, + // where `global.postMessage` means something completely different and can't be used for this purpose. + if (global.postMessage && !global.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global.onmessage; + global.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global.postMessage("", "*"); + global.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + + function installPostMessageImplementation() { + // Installs an event handler on `global` for the `message` event: see + // * https://developer.mozilla.org/en/DOM/window.postMessage + // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global && + typeof event.data === "string" && + event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + + if (global.addEventListener) { + global.addEventListener("message", onGlobalMessage, false); + } else { + global.attachEvent("onmessage", onGlobalMessage); + } + + registerImmediate = function(handle) { + global.postMessage(messagePrefix + handle, "*"); + }; + } + + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + // Create a + + + + + + +

Eukaryotes

+

+      
+   
+
diff --git a/test/merkletreejs/node_modules/treeify/examples/eukaryotes.js b/test/merkletreejs/node_modules/treeify/examples/eukaryotes.js
new file mode 100755
index 0000000..8477e3e
--- /dev/null
+++ b/test/merkletreejs/node_modules/treeify/examples/eukaryotes.js
@@ -0,0 +1,51 @@
+var treeify = require('../treeify');
+
+// Based on information taken from the Tree of Life web project
+// http://tolweb.org/Eukaryotes/3
+var Eukaryotes = {
+   'Archaeplastida (Plantae)': {
+      'Green plants': 'green algae & land plants',
+      'Rhodophyta': 'red algae',
+      'Glaucophytes': 'microalgae'
+   },
+   'Unikonts': {
+      'Opisthokonts': {
+         'Animals': null,
+         'Choanoflagellates': null,
+         'Filasterea': null,
+         'Ichthyosporea': null,
+         'Fungi': 'mushrooms, sac fungi, yeast, molds, etc',
+         'Nucleariidae': 'filose amoebae'
+      },
+      'Amoebozoa': 'amoebae, slime molds, and parasitic protists',
+   },
+   'Chromalveolates': {
+      '': {
+         'Rhizaria': {
+            'Cercozoa': 'amoeboflagellates',
+            'Foraminifera': 'complex cells with reticulopodia',
+            'Radiolaria': null
+         },
+         'Alveolates': 'dinoflagellates, ciliates and apicomplexan parasites',
+         'Stramenopiles': 'e.g. water molds, diatoms, brown algae'
+      },
+      'Hacrobia': 'Haptophyta, Cryptomonads, etc.'
+   },
+   'Excavates': {
+      'Malawimonads': null,
+      'Discicristates': {
+         'Euglenozoa': 'euglenids, diplonemids and kinetoplastids',
+         'Heterolobosea': 'amoeboflagellates with discoidal mitchondrial cristae',
+         'Jakobida': 'free-living, heterotrophic flagellates'
+      },
+      'Parabasalids': 'trichomonads and hypermastigotes',
+      'Fornicata': 'diplomonads and retortamonads',
+      'Preaxostyla': 'oxymonads and Trimastix'
+   }
+};
+
+console.log('Eukaryotes');
+
+treeify.asLines(Eukaryotes, true, function(line) {
+   console.log(line);
+});
diff --git a/test/merkletreejs/node_modules/treeify/examples/fs_tree.js b/test/merkletreejs/node_modules/treeify/examples/fs_tree.js
new file mode 100755
index 0000000..d1076ab
--- /dev/null
+++ b/test/merkletreejs/node_modules/treeify/examples/fs_tree.js
@@ -0,0 +1,45 @@
+#!/usr/bin/env node
+
+(function(){
+
+   try {
+      var dive = require('dive');
+   } catch (ex) {
+      console.error('this example requires "dive", please run "npm install dive"');
+      process.exit(1);
+   }
+
+   var treeify = require('../treeify'),
+       path = require('path'),
+       fs = require('fs'),
+       rootDir = process.argv.length < 3 ? '.' : process.argv[2],
+       tree = {};
+
+   if ( ! fs.existsSync(rootDir)) {
+      console.error('path "' + rootDir + '" does not exist - unable to proceed!');
+      process.exit(1);
+   }
+
+   console.log(rootDir !== '.' ? path.relative(process.cwd(), rootDir) : '.');
+
+   function scanComplete() {
+      process.stdout.write('\r       \r');
+      console.log(treeify.asTree(tree, true));
+   }
+
+   dive(rootDir, { all: true, directories: true }, function(err, thisPath) {
+      var relativePath = path.relative(rootDir, thisPath),
+          node = tree;
+
+      if (relativePath.indexOf('..') !== 0) {
+         relativePath.split(path.sep).forEach(function(part) {
+            typeof node[part] !== 'object' && (node[part] = {});
+            node = node[part];
+         });
+      }
+
+   }, scanComplete);
+
+   process.stdout.write('wait... ');
+
+})();
diff --git a/test/merkletreejs/node_modules/treeify/package.json b/test/merkletreejs/node_modules/treeify/package.json
new file mode 100644
index 0000000..0de9eea
--- /dev/null
+++ b/test/merkletreejs/node_modules/treeify/package.json
@@ -0,0 +1,28 @@
+{
+  "name": "treeify",
+  "version": "1.1.0",
+  "author": "Luke Plaster ",
+  "description": "converts a JS object into a nice and readable tree structure for the console",
+  "license": "MIT",
+  "scripts": {
+    "test": "./node_modules/vows/bin/vows --spec"
+  },
+  "main": "./treeify",
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/notatestuser/treeify.git"
+  },
+  "keywords": [
+    "object", "tree", "print", "console", "pretty"
+  ],
+  "devDependencies": {
+    "vows": "git://github.com/Filirom1/vows.git#expect"
+  },
+  "licenses": [{
+    "type": "MIT",
+    "url": "http://lp.mit-license.org/"
+  }],
+  "engines": {
+    "node": ">=0.6"
+  }
+}
diff --git a/test/merkletreejs/node_modules/treeify/test/tree-test.js b/test/merkletreejs/node_modules/treeify/test/tree-test.js
new file mode 100644
index 0000000..c5841e9
--- /dev/null
+++ b/test/merkletreejs/node_modules/treeify/test/tree-test.js
@@ -0,0 +1,347 @@
+var treeify = require('../treeify'),
+   vows = require('vows'),
+   assert = require('assert'),
+   events = require('events');
+
+// - helper functions -----------------
+
+function treeifyByLineGuts(args) {
+   var emitter = new events.EventEmitter(),
+       lineNum = 0;
+   args.push(function(line) {
+      emitter.emit('success', line);
+      emitter.emit('line ' + (++lineNum), line);
+   });
+   treeify.asLines.apply(this, args);
+   return emitter;
+}
+
+function treeifyByLine(obj) {
+   return function(showValues) {
+      var arguments = [ obj, showValues ];
+      return treeifyByLineGuts(arguments);
+   };
+}
+
+function treeifyByLineWithHideFunctionsArgument(obj) {
+   return function(showValues, hideFunctions) {
+      var arguments = [ obj, showValues, hideFunctions ];
+      return treeifyByLineGuts(arguments);
+   };
+}
+
+function treeifyEntirely(obj) {
+   return function(showValues, hideFunctions) {
+      return treeify.asTree(obj, showValues, hideFunctions);
+   };
+}
+
+function withValuesShown(showValues) {
+   return function(func){ return func(showValues, false) };
+}
+
+function withValuesShownFunctionsHidden() {
+  return function(func){ return func(true, true) };
+
+}
+
+function is(content, arrayIndex) {
+   return function(lines) {
+      var toCheck = lines;
+      if (arrayIndex !== undefined) {
+         toCheck = lines[arrayIndex];
+      }
+      assert.strictEqual(toCheck, content, 'should be "' + content + '" but was "' + toCheck + '"');
+   };
+}
+
+function checkLines(/* ... */) {
+   var ret = {}, entry;
+   for (var line = 1; line <= arguments.length; line++) {
+      if ( ! arguments[line - 1])
+         continue;
+      entry = {};
+      entry['branches correctly on line '+line] = is(arguments[line - 1]);
+      ret['line '+line] = entry;
+   }
+   return ret;
+}
+
+// - the beautiful test suite ---------
+
+vows.describe('tree-test').addBatch({
+
+   'A tree created from an empty object': {
+      topic: {},
+
+      'when returned as a whole tree': {
+         topic: treeifyEntirely,
+
+         'with values hidden': {
+            topic: withValuesShown(false),
+            'is an empty string': is('')
+         },
+         'with values shown': {
+            topic: withValuesShown(true),
+            'is an empty string': is('')
+         }
+      }
+   },
+
+   'A tree created from a single-level object': {
+      topic: {
+         apples: 'gala',      //  ├─ apples: gala
+         oranges: 'mandarin'  //  └─ oranges: mandarin
+      },
+
+      'when returned line-by-line': {
+         topic: treeifyByLine,
+
+         'with values hidden': {
+            topic: withValuesShown(false),
+
+            'is two lines long': function(err, line) {
+               this.expect(2);
+            },
+            on: checkLines('├─ apples',
+                           '└─ oranges')
+         },
+         'with values shown': {
+            topic: withValuesShown(true),
+
+            'is two lines long': function(err, line) {
+               this.expect(2);
+            },
+            on: checkLines('├─ apples: gala',
+                           '└─ oranges: mandarin')
+         }
+      },
+
+      'when returned as a whole tree': {
+         topic: treeifyEntirely,
+
+         'with values hidden': {
+            topic: withValuesShown(false),
+
+            'is not empty': function(tree) {
+               assert.notEqual(tree, '', 'should not be empty');
+            },
+            'contains 2 line breaks': function(tree) {
+               assert.strictEqual(tree.match(/\n/g).length, 2, 'should contain 2 x \n');
+            },
+            '(split into an array of lines)': {
+               topic: function(tree) { return tree.split(/\n/g) },
+               'has a correct first line':  is('├─ apples', 0),
+               'has a correct second line': is('└─ oranges', 1),
+               'has nothing at the end':    is('', 2)
+            }
+         },
+         'with values shown': {
+            topic: withValuesShown(true),
+
+            'is not empty': function(tree) {
+               assert.notEqual(tree, '', 'should not be empty');
+            },
+            'contains 2 line breaks': function(tree) {
+               assert.strictEqual(tree.match(/\n/g).length, 2, 'should contain 2 x \n');
+            },
+            '(split into an array of lines)': {
+               topic: function(tree) { return tree.split(/\n/g) },
+               'has a correct first line':  is('├─ apples: gala', 0),
+               'has a correct second line': is('└─ oranges: mandarin', 1),
+               'has nothing at the end':    is('', 2)
+            }
+         }
+      }
+   },
+
+   'A tree created from a multi-level object': {
+      topic: {
+         oranges: {                  //  ├─ oranges
+            'mandarin': {            //  │  └─ mandarin
+               clementine: null,     //  │     ├─ clementine
+               tangerine:            //  │     └─ tangerine
+                  'so cheap and juicy!'
+            }
+         },
+         apples: {                   //  └─ apples
+            'gala': null,            //     ├─ gala
+            'pink lady': null        //     └─ pink lady
+         }
+      },
+
+      'when returned line-by-line': {
+         topic: treeifyByLine,
+
+         'with values hidden': {
+            topic: withValuesShown(false),
+
+            'is seven lines long': function(err, line) {
+               this.expect(7);
+            },
+            on: checkLines('├─ oranges',
+                           '│  └─ mandarin',
+                           '│     ├─ clementine',
+                           '│     └─ tangerine',
+                           '└─ apples',
+                           '   ├─ gala',
+                           '   └─ pink lady')
+         },
+         'with values shown': {
+            topic: withValuesShown(true),
+            on: checkLines(null, null, null,
+                           '│     └─ tangerine: so cheap and juicy!')
+         }
+      },
+
+      'when returned as a whole tree': {
+         topic: treeifyEntirely,
+
+         'with values shown': {
+            topic: withValuesShown(true),
+
+            '(split into an array of lines)': {
+               topic: function(tree) { return tree.split(/\n/g) },
+               'has a correct first line': is('├─ oranges', 0),
+               'has a correct third line': is('│     └─ tangerine: so cheap and juicy!', 3),
+               'has nothing at the end':   is('', 7)
+            }
+         }
+      }
+   },
+
+   'A tree created from an object with not so circular references': {
+      topic: function() {
+         var obj = { one: 'one', two: { four: 'four' } };
+         obj['three'] = obj.two;
+         return obj;
+      },
+
+      'when returned line-by-line': {
+         topic: treeifyByLine,
+
+         'with values shown': {
+            topic: withValuesShown(true),
+            on: checkLines('├─ one: one',
+                           '├─ two',
+                           '│  └─ four: four',
+                           '└─ three',
+                           '   └─ four: four')
+         }
+      }
+   },
+
+   'A tree created from an object with circular references': {
+      topic: function() {
+         var obj = { one: 'one', two: 'two' };
+         obj['three'] = obj;
+         return obj;
+      },
+
+      'when returned line-by-line': {
+         topic: treeifyByLine,
+
+         'with values shown': {
+            topic: withValuesShown(true),
+            on: checkLines('├─ one: one',
+                           '├─ two: two',
+                           '└─ three (circular ref.)')
+         }
+      }
+   },
+
+   'A tree created from an object containing various types': {
+      topic: {
+         array: [ 'one', 'two' ],
+         numeric: 42,
+         decimal: 42.24,
+         bool: false,
+         nil: null,
+         undef: undefined,
+         date: new Date(2018,0,1)
+      },
+
+      'when returned line-by-line': {
+         topic: treeifyByLine,
+
+         'with values shown': {
+            topic: withValuesShown(true),
+            on: checkLines('├─ array',
+                           '│  ├─ 0: one',
+                           '│  └─ 1: two',
+                           '├─ numeric: 42',
+                           '├─ decimal: 42.24',
+                           '├─ bool: false',
+                           '├─ nil',
+                           '├─ undef: undefined',
+                           '└─ date: Mon Jan 01 2018 00:00:00 GMT+0000 (UTC)')
+         }
+      }
+   },
+
+   'A tree created from an object with prototyped functions': {
+      topic: function() {
+         var func = function(){
+            this.Friendly = 'stuff';
+         }
+         func.prototype.Nasty = function(){}
+         return new func();
+      },
+
+      'when returned as a whole tree': {
+         topic: treeifyEntirely,
+
+         'with values shown': {
+            topic: withValuesShown(true),
+
+            'and split into an array of lines': {
+               topic: function(tree) { return tree.split(/\n/g) },
+               'is a one liner output (with a following blank line)': function(lines) {
+                  assert.equal(lines.length, 2);
+               },
+               'has a correct first line': is('└─ Friendly: stuff', 0)
+            }
+         }
+      }
+   },
+   'A tree with functions': {
+      topic: {
+        func:function(){},
+        Friendly:"stuff",
+        Another:"stuff"
+      },
+
+      'when returned line-by-line': {
+         topic: treeifyByLineWithHideFunctionsArgument,
+
+         'with values shown, but functions hidden': {
+            topic: withValuesShownFunctionsHidden(),
+
+            'is two lines long': function(err, line) {
+               this.expect(2);
+            },
+            on: checkLines('├─ Friendly: stuff',
+                           '└─ Another: stuff')
+         }
+      },
+
+      'when returned as a whole tree': {
+         topic: treeifyEntirely,
+
+         'with values shown, but functions hidden': {
+            topic: withValuesShownFunctionsHidden(),
+
+            'and split into an array of lines': {
+               topic: function(tree) {
+                 console.error(tree);
+                 return tree.split(/\n/g) },
+               'is a one liner output (with a following blank line)': function(lines) {
+                  assert.equal(lines.length, 3);
+               },
+               'has a correct first line': is('├─ Friendly: stuff', 0)
+            }
+         }
+      }
+   }
+
+}).export(module);
diff --git a/test/merkletreejs/node_modules/treeify/treeify.js b/test/merkletreejs/node_modules/treeify/treeify.js
new file mode 100644
index 0000000..17fb428
--- /dev/null
+++ b/test/merkletreejs/node_modules/treeify/treeify.js
@@ -0,0 +1,113 @@
+//     treeify.js
+//     Luke Plaster 
+//     https://github.com/notatestuser/treeify.js
+
+// do the universal module definition dance
+(function (root, factory) {
+
+  if (typeof exports === 'object') {
+    module.exports = factory();
+  } else if (typeof define === 'function' && define.amd) {
+    define(factory);
+  } else {
+    root.treeify = factory();
+  }
+
+}(this, function() {
+
+  function makePrefix(key, last) {
+    var str = (last ? '└' : '├');
+    if (key) {
+      str += '─ ';
+    } else {
+      str += '──┐';
+    }
+    return str;
+  }
+
+  function filterKeys(obj, hideFunctions) {
+    var keys = [];
+    for (var branch in obj) {
+      // always exclude anything in the object's prototype
+      if (!obj.hasOwnProperty(branch)) {
+        continue;
+      }
+      // ... and hide any keys mapped to functions if we've been told to
+      if (hideFunctions && ((typeof obj[branch])==="function")) {
+        continue;
+      }
+      keys.push(branch);
+    }
+    return keys;
+  }
+
+  function growBranch(key, root, last, lastStates, showValues, hideFunctions, callback) {
+    var line = '', index = 0, lastKey, circular, lastStatesCopy = lastStates.slice(0);
+
+    if (lastStatesCopy.push([ root, last ]) && lastStates.length > 0) {
+      // based on the "was last element" states of whatever we're nested within,
+      // we need to append either blankness or a branch to our line
+      lastStates.forEach(function(lastState, idx) {
+        if (idx > 0) {
+          line += (lastState[1] ? ' ' : '│') + '  ';
+        }
+        if ( ! circular && lastState[0] === root) {
+          circular = true;
+        }
+      });
+
+      // the prefix varies based on whether the key contains something to show and
+      // whether we're dealing with the last element in this collection
+      line += makePrefix(key, last) + key;
+
+      // append values and the circular reference indicator
+      showValues && (typeof root !== 'object' || root instanceof Date) && (line += ': ' + root);
+      circular && (line += ' (circular ref.)');
+
+      callback(line);
+    }
+
+    // can we descend into the next item?
+    if ( ! circular && typeof root === 'object') {
+      var keys = filterKeys(root, hideFunctions);
+      keys.forEach(function(branch){
+        // the last key is always printed with a different prefix, so we'll need to know if we have it
+        lastKey = ++index === keys.length;
+
+        // hold your breath for recursive action
+        growBranch(branch, root[branch], lastKey, lastStatesCopy, showValues, hideFunctions, callback);
+      });
+    }
+  };
+
+  // --------------------
+
+  var Treeify = {};
+
+  // Treeify.asLines
+  // --------------------
+  // Outputs the tree line-by-line, calling the lineCallback when each one is available.
+
+  Treeify.asLines = function(obj, showValues, hideFunctions, lineCallback) {
+    /* hideFunctions and lineCallback are curried, which means we don't break apps using the older form */
+    var hideFunctionsArg = typeof hideFunctions !== 'function' ? hideFunctions : false;
+    growBranch('.', obj, false, [], showValues, hideFunctionsArg, lineCallback || hideFunctions);
+  };
+
+  // Treeify.asTree
+  // --------------------
+  // Outputs the entire tree, returning it as a string with line breaks.
+
+  Treeify.asTree = function(obj, showValues, hideFunctions) {
+    var tree = '';
+    growBranch('.', obj, false, [], showValues, hideFunctions, function(line) {
+      tree += line + '\n';
+    });
+    return tree;
+  };
+
+  // --------------------
+
+  return Treeify;
+
+}));
diff --git a/test/merkletreejs/node_modules/undici-types/README.md b/test/merkletreejs/node_modules/undici-types/README.md
new file mode 100644
index 0000000..20a721c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/README.md
@@ -0,0 +1,6 @@
+# undici-types
+
+This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version.
+
+- [GitHub nodejs/undici](https://github.com/nodejs/undici)
+- [Undici Documentation](https://undici.nodejs.org/#/)
diff --git a/test/merkletreejs/node_modules/undici-types/agent.d.ts b/test/merkletreejs/node_modules/undici-types/agent.d.ts
new file mode 100644
index 0000000..58081ce
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/agent.d.ts
@@ -0,0 +1,31 @@
+import { URL } from 'url'
+import Pool from './pool'
+import Dispatcher from "./dispatcher";
+
+export default Agent
+
+declare class Agent extends Dispatcher{
+  constructor(opts?: Agent.Options)
+  /** `true` after `dispatcher.close()` has been called. */
+  closed: boolean;
+  /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */
+  destroyed: boolean;
+  /** Dispatches a request. */
+  dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
+}
+
+declare namespace Agent {
+  export interface Options extends Pool.Options {
+    /** Default: `(origin, opts) => new Pool(origin, opts)`. */
+    factory?(origin: string | URL, opts: Object): Dispatcher;
+    /** Integer. Default: `0` */
+    maxRedirections?: number;
+
+    interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"]
+  }
+
+  export interface DispatchOptions extends Dispatcher.DispatchOptions {
+    /** Integer. */
+    maxRedirections?: number;
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/api.d.ts b/test/merkletreejs/node_modules/undici-types/api.d.ts
new file mode 100644
index 0000000..400341d
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/api.d.ts
@@ -0,0 +1,43 @@
+import { URL, UrlObject } from 'url'
+import { Duplex } from 'stream'
+import Dispatcher from './dispatcher'
+
+export {
+  request,
+  stream,
+  pipeline,
+  connect,
+  upgrade,
+}
+
+/** Performs an HTTP request. */
+declare function request(
+  url: string | URL | UrlObject,
+  options?: { dispatcher?: Dispatcher } & Omit & Partial>,
+): Promise;
+
+/** A faster version of `request`. */
+declare function stream(
+  url: string | URL | UrlObject,
+  options: { dispatcher?: Dispatcher } & Omit,
+  factory: Dispatcher.StreamFactory
+): Promise;
+
+/** For easy use with `stream.pipeline`. */
+declare function pipeline(
+  url: string | URL | UrlObject,
+  options: { dispatcher?: Dispatcher } & Omit,
+  handler: Dispatcher.PipelineHandler
+): Duplex;
+
+/** Starts two-way communications with the requested resource. */
+declare function connect(
+  url: string | URL | UrlObject,
+  options?: { dispatcher?: Dispatcher } & Omit
+): Promise;
+
+/** Upgrade to a different protocol. */
+declare function upgrade(
+  url: string | URL | UrlObject,
+  options?: { dispatcher?: Dispatcher } & Omit
+): Promise;
diff --git a/test/merkletreejs/node_modules/undici-types/balanced-pool.d.ts b/test/merkletreejs/node_modules/undici-types/balanced-pool.d.ts
new file mode 100644
index 0000000..d1e9375
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/balanced-pool.d.ts
@@ -0,0 +1,18 @@
+import Pool from './pool'
+import Dispatcher from './dispatcher'
+import { URL } from 'url'
+
+export default BalancedPool
+
+declare class BalancedPool extends Dispatcher {
+  constructor(url: string | string[] | URL | URL[], options?: Pool.Options);
+
+  addUpstream(upstream: string | URL): BalancedPool;
+  removeUpstream(upstream: string | URL): BalancedPool;
+  upstreams: Array;
+
+  /** `true` after `pool.close()` has been called. */
+  closed: boolean;
+  /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */
+  destroyed: boolean;
+}
diff --git a/test/merkletreejs/node_modules/undici-types/client.d.ts b/test/merkletreejs/node_modules/undici-types/client.d.ts
new file mode 100644
index 0000000..74948b1
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/client.d.ts
@@ -0,0 +1,97 @@
+import { URL } from 'url'
+import { TlsOptions } from 'tls'
+import Dispatcher from './dispatcher'
+import buildConnector from "./connector";
+
+/**
+ * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
+ */
+export class Client extends Dispatcher {
+  constructor(url: string | URL, options?: Client.Options);
+  /** Property to get and set the pipelining factor. */
+  pipelining: number;
+  /** `true` after `client.close()` has been called. */
+  closed: boolean;
+  /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
+  destroyed: boolean;
+}
+
+export declare namespace Client {
+  export interface OptionsInterceptors {
+    Client: readonly Dispatcher.DispatchInterceptor[];
+  }
+  export interface Options {
+    /** TODO */
+    interceptors?: OptionsInterceptors;
+    /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
+    maxHeaderSize?: number;
+    /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
+    headersTimeout?: number;
+    /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */
+    socketTimeout?: never;
+    /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */
+    requestTimeout?: never;
+    /** TODO */
+    connectTimeout?: number;
+    /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
+    bodyTimeout?: number;
+    /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */
+    idleTimeout?: never;
+    /** @deprecated unsupported keepAlive, use pipelining=0 instead */
+    keepAlive?: never;
+    /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
+    keepAliveTimeout?: number;
+    /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */
+    maxKeepAliveTimeout?: never;
+    /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
+    keepAliveMaxTimeout?: number;
+    /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
+    keepAliveTimeoutThreshold?: number;
+    /** TODO */
+    socketPath?: string;
+    /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
+    pipelining?: number;
+    /** @deprecated use the connect option instead */
+    tls?: never;
+    /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
+    strictContentLength?: boolean;
+    /** TODO */
+    maxCachedSessions?: number;
+    /** TODO */
+    maxRedirections?: number;
+    /** TODO */
+    connect?: buildConnector.BuildOptions | buildConnector.connector;
+    /** TODO */
+    maxRequestsPerClient?: number;
+    /** TODO */
+    localAddress?: string;
+    /** Max response body size in bytes, -1 is disabled */
+    maxResponseSize?: number;
+    /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
+    autoSelectFamily?: boolean;
+    /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
+    autoSelectFamilyAttemptTimeout?: number;
+    /**
+     * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
+     * @default false
+    */
+    allowH2?: boolean;
+    /**
+     * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overriden by a SETTINGS remote frame.
+     * @default 100
+    */
+    maxConcurrentStreams?: number
+  }
+  export interface SocketInfo {
+    localAddress?: string
+    localPort?: number
+    remoteAddress?: string
+    remotePort?: number
+    remoteFamily?: string
+    timeout?: number
+    bytesWritten?: number
+    bytesRead?: number
+  }
+}
+
+export default Client;
diff --git a/test/merkletreejs/node_modules/undici-types/connector.d.ts b/test/merkletreejs/node_modules/undici-types/connector.d.ts
new file mode 100644
index 0000000..bd92433
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/connector.d.ts
@@ -0,0 +1,34 @@
+import { TLSSocket, ConnectionOptions } from 'tls'
+import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net'
+
+export default buildConnector
+declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector
+
+declare namespace buildConnector {
+  export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & {
+    allowH2?: boolean;
+    maxCachedSessions?: number | null;
+    socketPath?: string | null;
+    timeout?: number | null;
+    port?: number;
+    keepAlive?: boolean | null;
+    keepAliveInitialDelay?: number | null;
+  }
+
+  export interface Options {
+    hostname: string
+    host?: string
+    protocol: string
+    port: string
+    servername?: string
+    localAddress?: string | null
+    httpSocket?: Socket
+  }
+
+  export type Callback = (...args: CallbackArgs) => void
+  type CallbackArgs = [null, Socket | TLSSocket] | [Error, null]
+
+  export interface connector {
+    (options: buildConnector.Options, callback: buildConnector.Callback): void
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/content-type.d.ts b/test/merkletreejs/node_modules/undici-types/content-type.d.ts
new file mode 100644
index 0000000..f2a87f1
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/content-type.d.ts
@@ -0,0 +1,21 @@
+/// 
+
+interface MIMEType {
+  type: string
+  subtype: string
+  parameters: Map
+  essence: string
+}
+
+/**
+ * Parse a string to a {@link MIMEType} object. Returns `failure` if the string
+ * couldn't be parsed.
+ * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+ */
+export function parseMIMEType (input: string): 'failure' | MIMEType
+
+/**
+ * Convert a MIMEType object to a string.
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ */
+export function serializeAMimeType (mimeType: MIMEType): string
diff --git a/test/merkletreejs/node_modules/undici-types/cookies.d.ts b/test/merkletreejs/node_modules/undici-types/cookies.d.ts
new file mode 100644
index 0000000..aa38cae
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/cookies.d.ts
@@ -0,0 +1,28 @@
+/// 
+
+import type { Headers } from './fetch'
+
+export interface Cookie {
+  name: string
+  value: string
+  expires?: Date | number
+  maxAge?: number
+  domain?: string
+  path?: string
+  secure?: boolean
+  httpOnly?: boolean
+  sameSite?: 'Strict' | 'Lax' | 'None'
+  unparsed?: string[]
+}
+
+export function deleteCookie (
+  headers: Headers,
+  name: string,
+  attributes?: { name?: string, domain?: string }
+): void
+
+export function getCookies (headers: Headers): Record
+
+export function getSetCookies (headers: Headers): Cookie[]
+
+export function setCookie (headers: Headers, cookie: Cookie): void
diff --git a/test/merkletreejs/node_modules/undici-types/diagnostics-channel.d.ts b/test/merkletreejs/node_modules/undici-types/diagnostics-channel.d.ts
new file mode 100644
index 0000000..85d4482
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/diagnostics-channel.d.ts
@@ -0,0 +1,67 @@
+import { Socket } from "net";
+import { URL } from "url";
+import Connector from "./connector";
+import Dispatcher from "./dispatcher";
+
+declare namespace DiagnosticsChannel {
+  interface Request {
+    origin?: string | URL;
+    completed: boolean;
+    method?: Dispatcher.HttpMethod;
+    path: string;
+    headers: string;
+    addHeader(key: string, value: string): Request;
+  }
+  interface Response {
+    statusCode: number;
+    statusText: string;
+    headers: Array;
+  }
+  type Error = unknown;
+  interface ConnectParams {
+    host: URL["host"];
+    hostname: URL["hostname"];
+    protocol: URL["protocol"];
+    port: URL["port"];
+    servername: string | null;
+  }
+  type Connector = Connector.connector;
+  export interface RequestCreateMessage {
+    request: Request;
+  }
+  export interface RequestBodySentMessage {
+    request: Request;
+  }
+  export interface RequestHeadersMessage {
+    request: Request;
+    response: Response;
+  }
+  export interface RequestTrailersMessage {
+    request: Request;
+    trailers: Array;
+  }
+  export interface RequestErrorMessage {
+    request: Request;
+    error: Error;
+  }
+  export interface ClientSendHeadersMessage {
+    request: Request;
+    headers: string;
+    socket: Socket;
+  }
+  export interface ClientBeforeConnectMessage {
+    connectParams: ConnectParams;
+    connector: Connector;
+  }
+  export interface ClientConnectedMessage {
+    socket: Socket;
+    connectParams: ConnectParams;
+    connector: Connector;
+  }
+  export interface ClientConnectErrorMessage {
+    error: Error;
+    socket: Socket;
+    connectParams: ConnectParams;
+    connector: Connector;
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/dispatcher.d.ts b/test/merkletreejs/node_modules/undici-types/dispatcher.d.ts
new file mode 100644
index 0000000..816db19
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/dispatcher.d.ts
@@ -0,0 +1,241 @@
+import { URL } from 'url'
+import { Duplex, Readable, Writable } from 'stream'
+import { EventEmitter } from 'events'
+import { Blob } from 'buffer'
+import { IncomingHttpHeaders } from './header'
+import BodyReadable from './readable'
+import { FormData } from './formdata'
+import Errors from './errors'
+
+type AbortSignal = unknown;
+
+export default Dispatcher
+
+/** Dispatcher is the core API used to dispatch requests. */
+declare class Dispatcher extends EventEmitter {
+  /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */
+  dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
+  /** Starts two-way communications with the requested resource. */
+  connect(options: Dispatcher.ConnectOptions): Promise;
+  connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void;
+  /** Performs an HTTP request. */
+  request(options: Dispatcher.RequestOptions): Promise;
+  request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void;
+  /** For easy use with `stream.pipeline`. */
+  pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex;
+  /** A faster version of `Dispatcher.request`. */
+  stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise;
+  stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void;
+  /** Upgrade to a different protocol. */
+  upgrade(options: Dispatcher.UpgradeOptions): Promise;
+  upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void;
+  /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */
+  close(): Promise;
+  close(callback: () => void): void;
+  /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */
+  destroy(): Promise;
+  destroy(err: Error | null): Promise;
+  destroy(callback: () => void): void;
+  destroy(err: Error | null, callback: () => void): void;
+
+  on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  on(eventName: 'drain', callback: (origin: URL) => void): this;
+
+
+  once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  once(eventName: 'drain', callback: (origin: URL) => void): this;
+
+
+  off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  off(eventName: 'drain', callback: (origin: URL) => void): this;
+
+
+  addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  addListener(eventName: 'drain', callback: (origin: URL) => void): this;
+
+  removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  removeListener(eventName: 'drain', callback: (origin: URL) => void): this;
+
+  prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  prependListener(eventName: 'drain', callback: (origin: URL) => void): this;
+
+  prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this;
+  prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
+  prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this;
+
+  listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[]
+  listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
+  listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
+  listeners(eventName: 'drain'): ((origin: URL) => void)[];
+
+  rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[]
+  rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
+  rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
+  rawListeners(eventName: 'drain'): ((origin: URL) => void)[];
+
+  emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean;
+  emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean;
+  emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean;
+  emit(eventName: 'drain', origin: URL): boolean;
+}
+
+declare namespace Dispatcher {
+  export interface DispatchOptions {
+    origin?: string | URL;
+    path: string;
+    method: HttpMethod;
+    /** Default: `null` */
+    body?: string | Buffer | Uint8Array | Readable | null | FormData;
+    /** Default: `null` */
+    headers?: IncomingHttpHeaders | string[] | null;
+    /** Query string params to be embedded in the request URL. Default: `null` */
+    query?: Record;
+    /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */
+    idempotent?: boolean;
+    /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */
+    blocking?: boolean;
+    /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */
+    upgrade?: boolean | string | null;
+    /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */
+    headersTimeout?: number | null;
+    /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */
+    bodyTimeout?: number | null;
+    /** Whether the request should stablish a keep-alive or not. Default `false` */
+    reset?: boolean;
+    /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */
+    throwOnError?: boolean;
+    /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/
+    expectContinue?: boolean;
+  }
+  export interface ConnectOptions {
+    path: string;
+    /** Default: `null` */
+    headers?: IncomingHttpHeaders | string[] | null;
+    /** Default: `null` */
+    signal?: AbortSignal | EventEmitter | null;
+    /** This argument parameter is passed through to `ConnectData` */
+    opaque?: unknown;
+    /** Default: 0 */
+    maxRedirections?: number;
+    /** Default: `null` */
+    responseHeader?: 'raw' | null;
+  }
+  export interface RequestOptions extends DispatchOptions {
+    /** Default: `null` */
+    opaque?: unknown;
+    /** Default: `null` */
+    signal?: AbortSignal | EventEmitter | null;
+    /** Default: 0 */
+    maxRedirections?: number;
+    /** Default: `null` */
+    onInfo?: (info: { statusCode: number, headers: Record }) => void;
+    /** Default: `null` */
+    responseHeader?: 'raw' | null;
+    /** Default: `64 KiB` */
+    highWaterMark?: number;
+  }
+  export interface PipelineOptions extends RequestOptions {
+    /** `true` if the `handler` will return an object stream. Default: `false` */
+    objectMode?: boolean;
+  }
+  export interface UpgradeOptions {
+    path: string;
+    /** Default: `'GET'` */
+    method?: string;
+    /** Default: `null` */
+    headers?: IncomingHttpHeaders | string[] | null;
+    /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */
+    protocol?: string;
+    /** Default: `null` */
+    signal?: AbortSignal | EventEmitter | null;
+    /** Default: 0 */
+    maxRedirections?: number;
+    /** Default: `null` */
+    responseHeader?: 'raw' | null;
+  }
+  export interface ConnectData {
+    statusCode: number;
+    headers: IncomingHttpHeaders;
+    socket: Duplex;
+    opaque: unknown;
+  }
+  export interface ResponseData {
+    statusCode: number;
+    headers: IncomingHttpHeaders;
+    body: BodyReadable & BodyMixin;
+    trailers: Record;
+    opaque: unknown;
+    context: object;
+  }
+  export interface PipelineHandlerData {
+    statusCode: number;
+    headers: IncomingHttpHeaders;
+    opaque: unknown;
+    body: BodyReadable;
+    context: object;
+  }
+  export interface StreamData {
+    opaque: unknown;
+    trailers: Record;
+  }
+  export interface UpgradeData {
+    headers: IncomingHttpHeaders;
+    socket: Duplex;
+    opaque: unknown;
+  }
+  export interface StreamFactoryData {
+    statusCode: number;
+    headers: IncomingHttpHeaders;
+    opaque: unknown;
+    context: object;
+  }
+  export type StreamFactory = (data: StreamFactoryData) => Writable;
+  export interface DispatchHandlers {
+    /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */
+    onConnect?(abort: () => void): void;
+    /** Invoked when an error has occurred. */
+    onError?(err: Error): void;
+    /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */
+    onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void;
+    /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */
+    onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void): boolean;
+    /** Invoked when response payload data is received. */
+    onData?(chunk: Buffer): boolean;
+    /** Invoked when response payload and trailers have been received and the request has completed. */
+    onComplete?(trailers: string[] | null): void;
+    /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */
+    onBodySent?(chunkSize: number, totalBytesSent: number): void;
+  }
+  export type PipelineHandler = (data: PipelineHandlerData) => Readable;
+  export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH';
+
+  /**
+   * @link https://fetch.spec.whatwg.org/#body-mixin
+   */
+  interface BodyMixin {
+    readonly body?: never; // throws on node v16.6.0
+    readonly bodyUsed: boolean;
+    arrayBuffer(): Promise;
+    blob(): Promise;
+    formData(): Promise;
+    json(): Promise;
+    text(): Promise;
+  }
+
+  export interface DispatchInterceptor {
+    (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch']
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/errors.d.ts b/test/merkletreejs/node_modules/undici-types/errors.d.ts
new file mode 100644
index 0000000..7923ddd
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/errors.d.ts
@@ -0,0 +1,128 @@
+import { IncomingHttpHeaders } from "./header";
+import Client from './client'
+
+export default Errors
+
+declare namespace Errors {
+  export class UndiciError extends Error {
+    name: string;
+    code: string;
+  }
+
+  /** Connect timeout error. */
+  export class ConnectTimeoutError extends UndiciError {
+    name: 'ConnectTimeoutError';
+    code: 'UND_ERR_CONNECT_TIMEOUT';
+  }
+
+  /** A header exceeds the `headersTimeout` option. */
+  export class HeadersTimeoutError extends UndiciError {
+    name: 'HeadersTimeoutError';
+    code: 'UND_ERR_HEADERS_TIMEOUT';
+  }
+
+  /** Headers overflow error. */
+  export class HeadersOverflowError extends UndiciError {
+    name: 'HeadersOverflowError'
+    code: 'UND_ERR_HEADERS_OVERFLOW'
+  }
+
+  /** A body exceeds the `bodyTimeout` option. */
+  export class BodyTimeoutError extends UndiciError {
+    name: 'BodyTimeoutError';
+    code: 'UND_ERR_BODY_TIMEOUT';
+  }
+
+  export class ResponseStatusCodeError extends UndiciError {
+    constructor (
+      message?: string,
+      statusCode?: number,
+      headers?: IncomingHttpHeaders | string[] | null,
+      body?: null | Record | string
+    );
+    name: 'ResponseStatusCodeError';
+    code: 'UND_ERR_RESPONSE_STATUS_CODE';
+    body: null | Record | string
+    status: number
+    statusCode: number
+    headers: IncomingHttpHeaders | string[] | null;
+  }
+
+  /** Passed an invalid argument. */
+  export class InvalidArgumentError extends UndiciError {
+    name: 'InvalidArgumentError';
+    code: 'UND_ERR_INVALID_ARG';
+  }
+
+  /** Returned an invalid value. */
+  export class InvalidReturnValueError extends UndiciError {
+    name: 'InvalidReturnValueError';
+    code: 'UND_ERR_INVALID_RETURN_VALUE';
+  }
+
+  /** The request has been aborted by the user. */
+  export class RequestAbortedError extends UndiciError {
+    name: 'AbortError';
+    code: 'UND_ERR_ABORTED';
+  }
+
+  /** Expected error with reason. */
+  export class InformationalError extends UndiciError {
+    name: 'InformationalError';
+    code: 'UND_ERR_INFO';
+  }
+
+  /** Request body length does not match content-length header. */
+  export class RequestContentLengthMismatchError extends UndiciError {
+    name: 'RequestContentLengthMismatchError';
+    code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH';
+  }
+
+  /** Response body length does not match content-length header. */
+  export class ResponseContentLengthMismatchError extends UndiciError {
+    name: 'ResponseContentLengthMismatchError';
+    code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH';
+  }
+
+  /** Trying to use a destroyed client. */
+  export class ClientDestroyedError extends UndiciError {
+    name: 'ClientDestroyedError';
+    code: 'UND_ERR_DESTROYED';
+  }
+
+  /** Trying to use a closed client. */
+  export class ClientClosedError extends UndiciError {
+    name: 'ClientClosedError';
+    code: 'UND_ERR_CLOSED';
+  }
+
+  /** There is an error with the socket. */
+  export class SocketError extends UndiciError {
+    name: 'SocketError';
+    code: 'UND_ERR_SOCKET';
+    socket: Client.SocketInfo | null
+  }
+
+  /** Encountered unsupported functionality. */
+  export class NotSupportedError extends UndiciError {
+    name: 'NotSupportedError';
+    code: 'UND_ERR_NOT_SUPPORTED';
+  }
+
+  /** No upstream has been added to the BalancedPool. */
+  export class BalancedPoolMissingUpstreamError extends UndiciError {
+    name: 'MissingUpstreamError';
+    code: 'UND_ERR_BPL_MISSING_UPSTREAM';
+  }
+
+  export class HTTPParserError extends UndiciError {
+    name: 'HTTPParserError';
+    code: string;
+  }
+
+  /** The response exceed the length allowed. */
+  export class ResponseExceededMaxSizeError extends UndiciError {
+    name: 'ResponseExceededMaxSizeError';
+    code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE';
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/fetch.d.ts b/test/merkletreejs/node_modules/undici-types/fetch.d.ts
new file mode 100644
index 0000000..fa4619c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/fetch.d.ts
@@ -0,0 +1,209 @@
+// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license)
+// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license)
+/// 
+
+import { Blob } from 'buffer'
+import { URL, URLSearchParams } from 'url'
+import { ReadableStream } from 'stream/web'
+import { FormData } from './formdata'
+
+import Dispatcher from './dispatcher'
+
+export type RequestInfo = string | URL | Request
+
+export declare function fetch (
+  input: RequestInfo,
+  init?: RequestInit
+): Promise
+
+export type BodyInit =
+  | ArrayBuffer
+  | AsyncIterable
+  | Blob
+  | FormData
+  | Iterable
+  | NodeJS.ArrayBufferView
+  | URLSearchParams
+  | null
+  | string
+
+export interface BodyMixin {
+  readonly body: ReadableStream | null
+  readonly bodyUsed: boolean
+
+  readonly arrayBuffer: () => Promise
+  readonly blob: () => Promise
+  readonly formData: () => Promise
+  readonly json: () => Promise
+  readonly text: () => Promise
+}
+
+export interface SpecIterator {
+  next(...args: [] | [TNext]): IteratorResult;
+}
+
+export interface SpecIterableIterator extends SpecIterator {
+  [Symbol.iterator](): SpecIterableIterator;
+}
+
+export interface SpecIterable {
+  [Symbol.iterator](): SpecIterator;
+}
+
+export type HeadersInit = string[][] | Record> | Headers
+
+export declare class Headers implements SpecIterable<[string, string]> {
+  constructor (init?: HeadersInit)
+  readonly append: (name: string, value: string) => void
+  readonly delete: (name: string) => void
+  readonly get: (name: string) => string | null
+  readonly has: (name: string) => boolean
+  readonly set: (name: string, value: string) => void
+  readonly getSetCookie: () => string[]
+  readonly forEach: (
+    callbackfn: (value: string, key: string, iterable: Headers) => void,
+    thisArg?: unknown
+  ) => void
+
+  readonly keys: () => SpecIterableIterator
+  readonly values: () => SpecIterableIterator
+  readonly entries: () => SpecIterableIterator<[string, string]>
+  readonly [Symbol.iterator]: () => SpecIterator<[string, string]>
+}
+
+export type RequestCache =
+  | 'default'
+  | 'force-cache'
+  | 'no-cache'
+  | 'no-store'
+  | 'only-if-cached'
+  | 'reload'
+
+export type RequestCredentials = 'omit' | 'include' | 'same-origin'
+
+type RequestDestination =
+  | ''
+  | 'audio'
+  | 'audioworklet'
+  | 'document'
+  | 'embed'
+  | 'font'
+  | 'image'
+  | 'manifest'
+  | 'object'
+  | 'paintworklet'
+  | 'report'
+  | 'script'
+  | 'sharedworker'
+  | 'style'
+  | 'track'
+  | 'video'
+  | 'worker'
+  | 'xslt'
+
+export interface RequestInit {
+  method?: string
+  keepalive?: boolean
+  headers?: HeadersInit
+  body?: BodyInit
+  redirect?: RequestRedirect
+  integrity?: string
+  signal?: AbortSignal
+  credentials?: RequestCredentials
+  mode?: RequestMode
+  referrer?: string
+  referrerPolicy?: ReferrerPolicy
+  window?: null
+  dispatcher?: Dispatcher
+  duplex?: RequestDuplex
+}
+
+export type ReferrerPolicy =
+  | ''
+  | 'no-referrer'
+  | 'no-referrer-when-downgrade'
+  | 'origin'
+  | 'origin-when-cross-origin'
+  | 'same-origin'
+  | 'strict-origin'
+  | 'strict-origin-when-cross-origin'
+  | 'unsafe-url';
+
+export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin'
+
+export type RequestRedirect = 'error' | 'follow' | 'manual'
+
+export type RequestDuplex = 'half'
+
+export declare class Request implements BodyMixin {
+  constructor (input: RequestInfo, init?: RequestInit)
+
+  readonly cache: RequestCache
+  readonly credentials: RequestCredentials
+  readonly destination: RequestDestination
+  readonly headers: Headers
+  readonly integrity: string
+  readonly method: string
+  readonly mode: RequestMode
+  readonly redirect: RequestRedirect
+  readonly referrerPolicy: string
+  readonly url: string
+
+  readonly keepalive: boolean
+  readonly signal: AbortSignal
+  readonly duplex: RequestDuplex
+
+  readonly body: ReadableStream | null
+  readonly bodyUsed: boolean
+
+  readonly arrayBuffer: () => Promise
+  readonly blob: () => Promise
+  readonly formData: () => Promise
+  readonly json: () => Promise
+  readonly text: () => Promise
+
+  readonly clone: () => Request
+}
+
+export interface ResponseInit {
+  readonly status?: number
+  readonly statusText?: string
+  readonly headers?: HeadersInit
+}
+
+export type ResponseType =
+  | 'basic'
+  | 'cors'
+  | 'default'
+  | 'error'
+  | 'opaque'
+  | 'opaqueredirect'
+
+export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308
+
+export declare class Response implements BodyMixin {
+  constructor (body?: BodyInit, init?: ResponseInit)
+
+  readonly headers: Headers
+  readonly ok: boolean
+  readonly status: number
+  readonly statusText: string
+  readonly type: ResponseType
+  readonly url: string
+  readonly redirected: boolean
+
+  readonly body: ReadableStream | null
+  readonly bodyUsed: boolean
+
+  readonly arrayBuffer: () => Promise
+  readonly blob: () => Promise
+  readonly formData: () => Promise
+  readonly json: () => Promise
+  readonly text: () => Promise
+
+  readonly clone: () => Response
+
+  static error (): Response
+  static json(data: any, init?: ResponseInit): Response
+  static redirect (url: string | URL, status: ResponseRedirectStatus): Response
+}
diff --git a/test/merkletreejs/node_modules/undici-types/file.d.ts b/test/merkletreejs/node_modules/undici-types/file.d.ts
new file mode 100644
index 0000000..c695b7a
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/file.d.ts
@@ -0,0 +1,39 @@
+// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT)
+/// 
+
+import { Blob } from 'buffer'
+
+export interface BlobPropertyBag {
+  type?: string
+  endings?: 'native' | 'transparent'
+}
+
+export interface FilePropertyBag extends BlobPropertyBag {
+  /**
+   * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
+   */
+  lastModified?: number
+}
+
+export declare class File extends Blob {
+  /**
+   * Creates a new File instance.
+   *
+   * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
+   * @param fileName The name of the file.
+   * @param options An options object containing optional attributes for the file.
+   */
+  constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag)
+
+  /**
+   * Name of the file referenced by the File object.
+   */
+  readonly name: string
+
+  /**
+   * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
+   */
+  readonly lastModified: number
+
+  readonly [Symbol.toStringTag]: string
+}
diff --git a/test/merkletreejs/node_modules/undici-types/filereader.d.ts b/test/merkletreejs/node_modules/undici-types/filereader.d.ts
new file mode 100644
index 0000000..f05d231
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/filereader.d.ts
@@ -0,0 +1,54 @@
+/// 
+
+import { Blob } from 'buffer'
+import { DOMException, Event, EventInit, EventTarget } from './patch'
+
+export declare class FileReader {
+  __proto__: EventTarget & FileReader
+
+  constructor ()
+
+  readAsArrayBuffer (blob: Blob): void
+  readAsBinaryString (blob: Blob): void
+  readAsText (blob: Blob, encoding?: string): void
+  readAsDataURL (blob: Blob): void
+
+  abort (): void
+
+  static readonly EMPTY = 0
+  static readonly LOADING = 1
+  static readonly DONE = 2
+
+  readonly EMPTY = 0
+  readonly LOADING = 1
+  readonly DONE = 2
+
+  readonly readyState: number
+
+  readonly result: string | ArrayBuffer | null
+
+  readonly error: DOMException | null
+
+  onloadstart: null | ((this: FileReader, event: ProgressEvent) => void)
+  onprogress: null | ((this: FileReader, event: ProgressEvent) => void)
+  onload: null | ((this: FileReader, event: ProgressEvent) => void)
+  onabort: null |  ((this: FileReader, event: ProgressEvent) => void)
+  onerror: null | ((this: FileReader, event: ProgressEvent) => void)
+  onloadend: null | ((this: FileReader, event: ProgressEvent) => void)
+}
+
+export interface ProgressEventInit extends EventInit {
+  lengthComputable?: boolean
+  loaded?: number
+  total?: number
+}
+
+export declare class ProgressEvent {
+  __proto__: Event & ProgressEvent
+
+  constructor (type: string, eventInitDict?: ProgressEventInit)
+
+  readonly lengthComputable: boolean
+  readonly loaded: number
+  readonly total: number
+}
diff --git a/test/merkletreejs/node_modules/undici-types/formdata.d.ts b/test/merkletreejs/node_modules/undici-types/formdata.d.ts
new file mode 100644
index 0000000..df29a57
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/formdata.d.ts
@@ -0,0 +1,108 @@
+// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT)
+/// 
+
+import { File } from './file'
+import { SpecIterator, SpecIterableIterator } from './fetch'
+
+/**
+ * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
+ */
+declare type FormDataEntryValue = string | File
+
+/**
+ * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch().
+ */
+export declare class FormData {
+  /**
+   * Appends a new value onto an existing key inside a FormData object,
+   * or adds the key if it does not already exist.
+   *
+   * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
+   *
+   * @param name The name of the field whose data is contained in `value`.
+   * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
+    or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
+   * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
+   */
+  append(name: string, value: unknown, fileName?: string): void
+
+  /**
+   * Set a new value for an existing key inside FormData,
+   * or add the new field if it does not already exist.
+   *
+   * @param name The name of the field whose data is contained in `value`.
+   * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
+    or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
+   * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
+   *
+   */
+  set(name: string, value: unknown, fileName?: string): void
+
+  /**
+   * Returns the first value associated with a given key from within a `FormData` object.
+   * If you expect multiple values and want all of them, use the `getAll()` method instead.
+   *
+   * @param {string} name A name of the value you want to retrieve.
+   *
+   * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
+   */
+  get(name: string): FormDataEntryValue | null
+
+  /**
+   * Returns all the values associated with a given key from within a `FormData` object.
+   *
+   * @param {string} name A name of the value you want to retrieve.
+   *
+   * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
+   */
+  getAll(name: string): FormDataEntryValue[]
+
+  /**
+   * Returns a boolean stating whether a `FormData` object contains a certain key.
+   *
+   * @param name A string representing the name of the key you want to test for.
+   *
+   * @return A boolean value.
+   */
+  has(name: string): boolean
+
+  /**
+   * Deletes a key and its value(s) from a `FormData` object.
+   *
+   * @param name The name of the key you want to delete.
+   */
+  delete(name: string): void
+
+  /**
+   * Executes given callback function for each field of the FormData instance
+   */
+  forEach: (
+    callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void,
+    thisArg?: unknown
+  ) => void
+
+  /**
+   * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
+   * Each key is a `string`.
+   */
+  keys: () => SpecIterableIterator
+
+  /**
+   * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
+   * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
+   */
+  values: () => SpecIterableIterator
+
+  /**
+   * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
+   * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
+   */
+  entries: () => SpecIterableIterator<[string, FormDataEntryValue]>
+
+  /**
+   * An alias for FormData#entries()
+   */
+  [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]>
+
+  readonly [Symbol.toStringTag]: string
+}
diff --git a/test/merkletreejs/node_modules/undici-types/global-dispatcher.d.ts b/test/merkletreejs/node_modules/undici-types/global-dispatcher.d.ts
new file mode 100644
index 0000000..728f95c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/global-dispatcher.d.ts
@@ -0,0 +1,9 @@
+import Dispatcher from "./dispatcher";
+
+export {
+  getGlobalDispatcher,
+  setGlobalDispatcher
+}
+
+declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void;
+declare function getGlobalDispatcher(): Dispatcher;
diff --git a/test/merkletreejs/node_modules/undici-types/global-origin.d.ts b/test/merkletreejs/node_modules/undici-types/global-origin.d.ts
new file mode 100644
index 0000000..322542d
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/global-origin.d.ts
@@ -0,0 +1,7 @@
+export {
+	setGlobalOrigin,
+	getGlobalOrigin
+}
+  
+declare function setGlobalOrigin(origin: string | URL | undefined): void;
+declare function getGlobalOrigin(): URL | undefined;
\ No newline at end of file
diff --git a/test/merkletreejs/node_modules/undici-types/handlers.d.ts b/test/merkletreejs/node_modules/undici-types/handlers.d.ts
new file mode 100644
index 0000000..eb4f5a9
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/handlers.d.ts
@@ -0,0 +1,9 @@
+import Dispatcher from "./dispatcher";
+
+export declare class RedirectHandler implements Dispatcher.DispatchHandlers{
+  constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers)
+}
+
+export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{
+  constructor (handler: Dispatcher.DispatchHandlers)
+}
diff --git a/test/merkletreejs/node_modules/undici-types/header.d.ts b/test/merkletreejs/node_modules/undici-types/header.d.ts
new file mode 100644
index 0000000..bfdb329
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/header.d.ts
@@ -0,0 +1,4 @@
+/**
+ * The header type declaration of `undici`.
+ */
+export type IncomingHttpHeaders = Record;
diff --git a/test/merkletreejs/node_modules/undici-types/index.d.ts b/test/merkletreejs/node_modules/undici-types/index.d.ts
new file mode 100644
index 0000000..4589845
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/index.d.ts
@@ -0,0 +1,63 @@
+import Dispatcher from'./dispatcher'
+import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher'
+import { setGlobalOrigin, getGlobalOrigin } from './global-origin'
+import Pool from'./pool'
+import { RedirectHandler, DecoratorHandler } from './handlers'
+
+import BalancedPool from './balanced-pool'
+import Client from'./client'
+import buildConnector from'./connector'
+import errors from'./errors'
+import Agent from'./agent'
+import MockClient from'./mock-client'
+import MockPool from'./mock-pool'
+import MockAgent from'./mock-agent'
+import mockErrors from'./mock-errors'
+import ProxyAgent from'./proxy-agent'
+import { request, pipeline, stream, connect, upgrade } from './api'
+
+export * from './cookies'
+export * from './fetch'
+export * from './file'
+export * from './filereader'
+export * from './formdata'
+export * from './diagnostics-channel'
+export * from './websocket'
+export * from './content-type'
+export * from './cache'
+export { Interceptable } from './mock-interceptor'
+
+export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler }
+export default Undici
+
+declare namespace Undici {
+  var Dispatcher: typeof import('./dispatcher').default
+  var Pool: typeof import('./pool').default;
+  var RedirectHandler: typeof import ('./handlers').RedirectHandler
+  var DecoratorHandler: typeof import ('./handlers').DecoratorHandler
+  var createRedirectInterceptor: typeof import ('./interceptors').createRedirectInterceptor
+  var BalancedPool: typeof import('./balanced-pool').default;
+  var Client: typeof import('./client').default;
+  var buildConnector: typeof import('./connector').default;
+  var errors: typeof import('./errors').default;
+  var Agent: typeof import('./agent').default;
+  var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher;
+  var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher;
+  var request: typeof import('./api').request;
+  var stream: typeof import('./api').stream;
+  var pipeline: typeof import('./api').pipeline;
+  var connect: typeof import('./api').connect;
+  var upgrade: typeof import('./api').upgrade;
+  var MockClient: typeof import('./mock-client').default;
+  var MockPool: typeof import('./mock-pool').default;
+  var MockAgent: typeof import('./mock-agent').default;
+  var mockErrors: typeof import('./mock-errors').default;
+  var fetch: typeof import('./fetch').fetch;
+  var Headers: typeof import('./fetch').Headers;
+  var Response: typeof import('./fetch').Response;
+  var Request: typeof import('./fetch').Request;
+  var FormData: typeof import('./formdata').FormData;
+  var File: typeof import('./file').File;
+  var FileReader: typeof import('./filereader').FileReader;
+  var caches: typeof import('./cache').caches;
+}
diff --git a/test/merkletreejs/node_modules/undici-types/interceptors.d.ts b/test/merkletreejs/node_modules/undici-types/interceptors.d.ts
new file mode 100644
index 0000000..047ac17
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/interceptors.d.ts
@@ -0,0 +1,5 @@
+import Dispatcher from "./dispatcher";
+
+type RedirectInterceptorOpts = { maxRedirections?: number }
+
+export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor
diff --git a/test/merkletreejs/node_modules/undici-types/mock-agent.d.ts b/test/merkletreejs/node_modules/undici-types/mock-agent.d.ts
new file mode 100644
index 0000000..98cd645
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/mock-agent.d.ts
@@ -0,0 +1,50 @@
+import Agent from './agent'
+import Dispatcher from './dispatcher'
+import { Interceptable, MockInterceptor } from './mock-interceptor'
+import MockDispatch = MockInterceptor.MockDispatch;
+
+export default MockAgent
+
+interface PendingInterceptor extends MockDispatch {
+  origin: string;
+}
+
+/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */
+declare class MockAgent extends Dispatcher {
+  constructor(options?: MockAgent.Options)
+  /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */
+  get(origin: string): TInterceptable;
+  get(origin: RegExp): TInterceptable;
+  get(origin: ((origin: string) => boolean)): TInterceptable;
+  /** Dispatches a mocked request. */
+  dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
+  /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */
+  close(): Promise;
+  /** Disables mocking in MockAgent. */
+  deactivate(): void;
+  /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */
+  activate(): void;
+  /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */
+  enableNetConnect(): void;
+  enableNetConnect(host: string): void;
+  enableNetConnect(host: RegExp): void;
+  enableNetConnect(host: ((host: string) => boolean)): void;
+  /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */
+  disableNetConnect(): void;
+  pendingInterceptors(): PendingInterceptor[];
+  assertNoPendingInterceptors(options?: {
+    pendingInterceptorsFormatter?: PendingInterceptorsFormatter;
+  }): void;
+}
+
+interface PendingInterceptorsFormatter {
+  format(pendingInterceptors: readonly PendingInterceptor[]): string;
+}
+
+declare namespace MockAgent {
+  /** MockAgent options. */
+  export interface Options extends Agent.Options {
+    /** A custom agent to be encapsulated by the MockAgent. */
+    agent?: Agent;
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/mock-client.d.ts b/test/merkletreejs/node_modules/undici-types/mock-client.d.ts
new file mode 100644
index 0000000..51d008c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/mock-client.d.ts
@@ -0,0 +1,25 @@
+import Client from './client'
+import Dispatcher from './dispatcher'
+import MockAgent from './mock-agent'
+import { MockInterceptor, Interceptable } from './mock-interceptor'
+
+export default MockClient
+
+/** MockClient extends the Client API and allows one to mock requests. */
+declare class MockClient extends Client implements Interceptable {
+  constructor(origin: string, options: MockClient.Options);
+  /** Intercepts any matching requests that use the same origin as this mock client. */
+  intercept(options: MockInterceptor.Options): MockInterceptor;
+  /** Dispatches a mocked request. */
+  dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean;
+  /** Closes the mock client and gracefully waits for enqueued requests to complete. */
+  close(): Promise;
+}
+
+declare namespace MockClient {
+  /** MockClient options. */
+  export interface Options extends Client.Options {
+    /** The agent to associate this MockClient with. */
+    agent: MockAgent;
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/mock-errors.d.ts b/test/merkletreejs/node_modules/undici-types/mock-errors.d.ts
new file mode 100644
index 0000000..3d9e727
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/mock-errors.d.ts
@@ -0,0 +1,12 @@
+import Errors from './errors'
+
+export default MockErrors
+
+declare namespace MockErrors {
+  /** The request does not match any registered mock dispatches. */
+  export class MockNotMatchedError extends Errors.UndiciError {
+    constructor(message?: string);
+    name: 'MockNotMatchedError';
+    code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED';
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/mock-interceptor.d.ts b/test/merkletreejs/node_modules/undici-types/mock-interceptor.d.ts
new file mode 100644
index 0000000..6b3961c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/mock-interceptor.d.ts
@@ -0,0 +1,93 @@
+import { IncomingHttpHeaders } from './header'
+import Dispatcher from './dispatcher';
+import { BodyInit, Headers } from './fetch'
+
+export {
+  Interceptable,
+  MockInterceptor,
+  MockScope
+}
+
+/** The scope associated with a mock dispatch. */
+declare class MockScope {
+  constructor(mockDispatch: MockInterceptor.MockDispatch);
+  /** Delay a reply by a set amount of time in ms. */
+  delay(waitInMs: number): MockScope;
+  /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */
+  persist(): MockScope;
+  /** Define a reply for a set amount of matching requests. */
+  times(repeatTimes: number): MockScope;
+}
+
+/** The interceptor for a Mock. */
+declare class MockInterceptor {
+  constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]);
+  /** Mock an undici request with the defined reply. */
+  reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope;
+  reply(
+    statusCode: number,
+    data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler,
+    responseOptions?: MockInterceptor.MockResponseOptions
+  ): MockScope;
+  /** Mock an undici request by throwing the defined reply error. */
+  replyWithError(error: TError): MockScope;
+  /** Set default reply headers on the interceptor for subsequent mocked replies. */
+  defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor;
+  /** Set default reply trailers on the interceptor for subsequent mocked replies. */
+  defaultReplyTrailers(trailers: Record): MockInterceptor;
+  /** Set automatically calculated content-length header on subsequent mocked replies. */
+  replyContentLength(): MockInterceptor;
+}
+
+declare namespace MockInterceptor {
+  /** MockInterceptor options. */
+  export interface Options {
+    /** Path to intercept on. */
+    path: string | RegExp | ((path: string) => boolean);
+    /** Method to intercept on. Defaults to GET. */
+    method?: string | RegExp | ((method: string) => boolean);
+    /** Body to intercept on. */
+    body?: string | RegExp | ((body: string) => boolean);
+    /** Headers to intercept on. */
+    headers?: Record boolean)> | ((headers: Record) => boolean);
+    /** Query params to intercept on */
+    query?: Record;
+  }
+  export interface MockDispatch extends Options {
+    times: number | null;
+    persist: boolean;
+    consumed: boolean;
+    data: MockDispatchData;
+  }
+  export interface MockDispatchData extends MockResponseOptions {
+    error: TError | null;
+    statusCode?: number;
+    data?: TData | string;
+  }
+  export interface MockResponseOptions {
+    headers?: IncomingHttpHeaders;
+    trailers?: Record;
+  }
+
+  export interface MockResponseCallbackOptions {
+    path: string;
+    origin: string;
+    method: string;
+    body?: BodyInit | Dispatcher.DispatchOptions['body'];
+    headers: Headers | Record;
+    maxRedirections: number;
+  }
+
+  export type MockResponseDataHandler = (
+    opts: MockResponseCallbackOptions
+  ) => TData | Buffer | string;
+
+  export type MockReplyOptionsCallback = (
+    opts: MockResponseCallbackOptions
+  ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions }
+}
+
+interface Interceptable extends Dispatcher {
+  /** Intercepts any matching requests that use the same origin as this mock client. */
+  intercept(options: MockInterceptor.Options): MockInterceptor;
+}
diff --git a/test/merkletreejs/node_modules/undici-types/mock-pool.d.ts b/test/merkletreejs/node_modules/undici-types/mock-pool.d.ts
new file mode 100644
index 0000000..39e709a
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/mock-pool.d.ts
@@ -0,0 +1,25 @@
+import Pool from './pool'
+import MockAgent from './mock-agent'
+import { Interceptable, MockInterceptor } from './mock-interceptor'
+import Dispatcher from './dispatcher'
+
+export default MockPool
+
+/** MockPool extends the Pool API and allows one to mock requests. */
+declare class MockPool extends Pool implements Interceptable {
+  constructor(origin: string, options: MockPool.Options);
+  /** Intercepts any matching requests that use the same origin as this mock pool. */
+  intercept(options: MockInterceptor.Options): MockInterceptor;
+  /** Dispatches a mocked request. */
+  dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean;
+  /** Closes the mock pool and gracefully waits for enqueued requests to complete. */
+  close(): Promise;
+}
+
+declare namespace MockPool {
+  /** MockPool options. */
+  export interface Options extends Pool.Options {
+    /** The agent to associate this MockPool with. */
+    agent: MockAgent;
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/package.json b/test/merkletreejs/node_modules/undici-types/package.json
new file mode 100644
index 0000000..be7aa4c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/package.json
@@ -0,0 +1,55 @@
+{
+  "name": "undici-types",
+  "version": "5.26.5",
+  "description": "A stand-alone types package for Undici",
+  "homepage": "https://undici.nodejs.org",
+  "bugs": {
+    "url": "https://github.com/nodejs/undici/issues"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/nodejs/undici.git"
+  },
+  "license": "MIT",
+  "types": "index.d.ts",
+  "files": [
+    "*.d.ts"
+  ],
+  "contributors": [
+    {
+      "name": "Daniele Belardi",
+      "url": "https://github.com/dnlup",
+      "author": true
+    },
+    {
+      "name": "Ethan Arrowood",
+      "url": "https://github.com/ethan-arrowood",
+      "author": true
+    },
+    {
+      "name": "Matteo Collina",
+      "url": "https://github.com/mcollina",
+      "author": true
+    },
+    {
+      "name": "Matthew Aitken",
+      "url": "https://github.com/KhafraDev",
+      "author": true
+    },
+    {
+      "name": "Robert Nagy",
+      "url": "https://github.com/ronag",
+      "author": true
+    },
+    {
+      "name": "Szymon Marczak",
+      "url": "https://github.com/szmarczak",
+      "author": true
+    },
+    {
+      "name": "Tomas Della Vedova",
+      "url": "https://github.com/delvedor",
+      "author": true
+    }
+  ]
+}
\ No newline at end of file
diff --git a/test/merkletreejs/node_modules/undici-types/patch.d.ts b/test/merkletreejs/node_modules/undici-types/patch.d.ts
new file mode 100644
index 0000000..3871acf
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/patch.d.ts
@@ -0,0 +1,71 @@
+/// 
+
+// See https://github.com/nodejs/undici/issues/1740
+
+export type DOMException = typeof globalThis extends { DOMException: infer T }
+ ? T
+ : any
+
+export type EventTarget = typeof globalThis extends { EventTarget: infer T }
+  ? T
+  : {
+    addEventListener(
+      type: string,
+      listener: any,
+      options?: any,
+    ): void
+    dispatchEvent(event: Event): boolean
+    removeEventListener(
+      type: string,
+      listener: any,
+      options?: any | boolean,
+    ): void
+  }
+
+export type Event = typeof globalThis extends { Event: infer T }
+  ? T
+  : {
+    readonly bubbles: boolean
+    cancelBubble: () => void
+    readonly cancelable: boolean
+    readonly composed: boolean
+    composedPath(): [EventTarget?]
+    readonly currentTarget: EventTarget | null
+    readonly defaultPrevented: boolean
+    readonly eventPhase: 0 | 2
+    readonly isTrusted: boolean
+    preventDefault(): void
+    returnValue: boolean
+    readonly srcElement: EventTarget | null
+    stopImmediatePropagation(): void
+    stopPropagation(): void
+    readonly target: EventTarget | null
+    readonly timeStamp: number
+    readonly type: string
+  }
+
+export interface EventInit {
+  bubbles?: boolean
+  cancelable?: boolean
+  composed?: boolean
+}
+
+export interface EventListenerOptions {
+  capture?: boolean
+}
+
+export interface AddEventListenerOptions extends EventListenerOptions {
+  once?: boolean
+  passive?: boolean
+  signal?: AbortSignal
+}
+
+export type EventListenerOrEventListenerObject = EventListener | EventListenerObject
+
+export interface EventListenerObject {
+  handleEvent (object: Event): void
+}
+
+export interface EventListener {
+  (evt: Event): void
+}
diff --git a/test/merkletreejs/node_modules/undici-types/pool-stats.d.ts b/test/merkletreejs/node_modules/undici-types/pool-stats.d.ts
new file mode 100644
index 0000000..8b6d2bf
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/pool-stats.d.ts
@@ -0,0 +1,19 @@
+import Pool from "./pool"
+
+export default PoolStats
+
+declare class PoolStats {
+  constructor(pool: Pool);
+  /** Number of open socket connections in this pool. */
+  connected: number;
+  /** Number of open socket connections in this pool that do not have an active request. */
+  free: number;
+  /** Number of pending requests across all clients in this pool. */
+  pending: number;
+  /** Number of queued requests across all clients in this pool. */
+  queued: number;
+  /** Number of currently active requests across all clients in this pool. */
+  running: number;
+  /** Number of active, pending, or queued requests across all clients in this pool. */
+  size: number;
+}
diff --git a/test/merkletreejs/node_modules/undici-types/pool.d.ts b/test/merkletreejs/node_modules/undici-types/pool.d.ts
new file mode 100644
index 0000000..7747d48
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/pool.d.ts
@@ -0,0 +1,28 @@
+import Client from './client'
+import TPoolStats from './pool-stats'
+import { URL } from 'url'
+import Dispatcher from "./dispatcher";
+
+export default Pool
+
+declare class Pool extends Dispatcher {
+  constructor(url: string | URL, options?: Pool.Options)
+  /** `true` after `pool.close()` has been called. */
+  closed: boolean;
+  /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */
+  destroyed: boolean;
+  /** Aggregate stats for a Pool. */
+  readonly stats: TPoolStats;
+}
+
+declare namespace Pool {
+  export type PoolStats = TPoolStats;
+  export interface Options extends Client.Options {
+    /** Default: `(origin, opts) => new Client(origin, opts)`. */
+    factory?(origin: URL, opts: object): Dispatcher;
+    /** The max number of clients to create. `null` if no limit. Default `null`. */
+    connections?: number | null;
+
+    interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"]
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/proxy-agent.d.ts b/test/merkletreejs/node_modules/undici-types/proxy-agent.d.ts
new file mode 100644
index 0000000..96b2638
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/proxy-agent.d.ts
@@ -0,0 +1,30 @@
+import Agent from './agent'
+import buildConnector from './connector';
+import Client from './client'
+import Dispatcher from './dispatcher'
+import { IncomingHttpHeaders } from './header'
+import Pool from './pool'
+
+export default ProxyAgent
+
+declare class ProxyAgent extends Dispatcher {
+  constructor(options: ProxyAgent.Options | string)
+
+  dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
+  close(): Promise;
+}
+
+declare namespace ProxyAgent {
+  export interface Options extends Agent.Options {
+    uri: string;
+    /**
+     * @deprecated use opts.token
+     */
+    auth?: string;
+    token?: string;
+    headers?: IncomingHttpHeaders;
+    requestTls?: buildConnector.BuildOptions;
+    proxyTls?: buildConnector.BuildOptions;
+    clientFactory?(origin: URL, opts: object): Dispatcher;
+  }
+}
diff --git a/test/merkletreejs/node_modules/undici-types/readable.d.ts b/test/merkletreejs/node_modules/undici-types/readable.d.ts
new file mode 100644
index 0000000..4549a8c
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/readable.d.ts
@@ -0,0 +1,61 @@
+import { Readable } from "stream";
+import { Blob } from 'buffer'
+
+export default BodyReadable
+
+declare class BodyReadable extends Readable {
+  constructor(
+    resume?: (this: Readable, size: number) => void | null,
+    abort?: () => void | null,
+    contentType?: string
+  )
+
+  /** Consumes and returns the body as a string
+   *  https://fetch.spec.whatwg.org/#dom-body-text
+   */
+  text(): Promise
+
+  /** Consumes and returns the body as a JavaScript Object
+   *  https://fetch.spec.whatwg.org/#dom-body-json
+   */
+  json(): Promise
+
+  /** Consumes and returns the body as a Blob
+   *  https://fetch.spec.whatwg.org/#dom-body-blob
+   */
+  blob(): Promise
+
+  /** Consumes and returns the body as an ArrayBuffer
+   *  https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+   */
+  arrayBuffer(): Promise
+
+  /** Not implemented
+   *
+   *  https://fetch.spec.whatwg.org/#dom-body-formdata
+   */
+  formData(): Promise
+
+  /** Returns true if the body is not null and the body has been consumed
+   *
+   *  Otherwise, returns false
+   *
+   * https://fetch.spec.whatwg.org/#dom-body-bodyused
+   */
+  readonly bodyUsed: boolean
+
+  /** Throws on node 16.6.0
+   *
+   *  If body is null, it should return null as the body
+   *
+   *  If body is not null, should return the body as a ReadableStream
+   *
+   *  https://fetch.spec.whatwg.org/#dom-body-body
+   */
+  readonly body: never | undefined
+
+  /** Dumps the response body by reading `limit` number of bytes.
+   * @param opts.limit Number of bytes to read (optional) - Default: 262144
+   */
+  dump(opts?: { limit: number }): Promise
+}
diff --git a/test/merkletreejs/node_modules/undici-types/webidl.d.ts b/test/merkletreejs/node_modules/undici-types/webidl.d.ts
new file mode 100644
index 0000000..40cfe06
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/webidl.d.ts
@@ -0,0 +1,220 @@
+// These types are not exported, and are only used internally
+
+/**
+ * Take in an unknown value and return one that is of type T
+ */
+type Converter = (object: unknown) => T
+
+type SequenceConverter = (object: unknown) => T[]
+
+type RecordConverter = (object: unknown) => Record
+
+interface ConvertToIntOpts {
+  clamp?: boolean
+  enforceRange?: boolean
+}
+
+interface WebidlErrors {
+  exception (opts: { header: string, message: string }): TypeError
+  /**
+   * @description Throw an error when conversion from one type to another has failed
+   */
+  conversionFailed (opts: {
+    prefix: string
+    argument: string
+    types: string[]
+  }): TypeError
+  /**
+   * @description Throw an error when an invalid argument is provided
+   */
+  invalidArgument (opts: {
+    prefix: string
+    value: string
+    type: string
+  }): TypeError
+}
+
+interface WebidlUtil {
+  /**
+   * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
+   */
+  Type (object: unknown):
+    | 'Undefined'
+    | 'Boolean'
+    | 'String'
+    | 'Symbol'
+    | 'Number'
+    | 'BigInt'
+    | 'Null'
+    | 'Object'
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+   */
+  ConvertToInt (
+    V: unknown,
+    bitLength: number,
+    signedness: 'signed' | 'unsigned',
+    opts?: ConvertToIntOpts
+  ): number
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+   */
+  IntegerPart (N: number): number
+}
+
+interface WebidlConverters {
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-DOMString
+   */
+  DOMString (V: unknown, opts?: {
+    legacyNullToEmptyString: boolean
+  }): string
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-ByteString
+   */
+  ByteString (V: unknown): string
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-USVString
+   */
+  USVString (V: unknown): string
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-boolean
+   */
+  boolean (V: unknown): boolean
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-any
+   */
+  any (V: Value): Value
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-long-long
+   */
+  ['long long'] (V: unknown): number
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long
+   */
+  ['unsigned long long'] (V: unknown): number
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-unsigned-long
+   */
+  ['unsigned long'] (V: unknown): number
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-unsigned-short
+   */
+  ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer
+   */
+  ArrayBuffer (V: unknown): ArrayBufferLike
+  ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-buffer-source-types
+   */
+  TypedArray (
+    V: unknown,
+    TypedArray: NodeJS.TypedArray | ArrayBufferLike
+  ): NodeJS.TypedArray | ArrayBufferLike
+  TypedArray (
+    V: unknown,
+    TypedArray: NodeJS.TypedArray | ArrayBufferLike,
+    opts?: { allowShared: false }
+  ): NodeJS.TypedArray | ArrayBuffer
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-buffer-source-types
+   */
+  DataView (V: unknown, opts?: { allowShared: boolean }): DataView
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#BufferSource
+   */
+  BufferSource (
+    V: unknown,
+    opts?: { allowShared: boolean }
+  ): NodeJS.TypedArray | ArrayBufferLike | DataView
+
+  ['sequence']: SequenceConverter
+  
+  ['sequence>']: SequenceConverter
+
+  ['record']: RecordConverter
+
+  [Key: string]: (...args: any[]) => unknown
+}
+
+export interface Webidl {
+  errors: WebidlErrors
+  util: WebidlUtil
+  converters: WebidlConverters
+
+  /**
+   * @description Performs a brand-check on {@param V} to ensure it is a
+   * {@param cls} object.
+   */
+  brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-sequence
+   * @description Convert a value, V, to a WebIDL sequence type.
+   */
+  sequenceConverter (C: Converter): SequenceConverter
+
+  illegalConstructor (): never
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#es-to-record
+   * @description Convert a value, V, to a WebIDL record type.
+   */
+  recordConverter (
+    keyConverter: Converter,
+    valueConverter: Converter
+  ): RecordConverter
+
+  /**
+   * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party
+   * interfaces are allowed.
+   */
+  interfaceConverter (cls: Interface): (
+    V: unknown,
+    opts?: { strict: boolean }
+  ) => asserts V is typeof cls
+
+  // TODO(@KhafraDev): a type could likely be implemented that can infer the return type
+  // from the converters given?
+  /**
+   * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are
+   * allowed, values allowed, optional and required keys. Auto converts the value to
+   * a type given a converter.
+   */
+  dictionaryConverter (converters: {
+    key: string,
+    defaultValue?: unknown,
+    required?: boolean,
+    converter: (...args: unknown[]) => unknown,
+    allowedValues?: unknown[]
+  }[]): (V: unknown) => Record
+
+  /**
+   * @see https://webidl.spec.whatwg.org/#idl-nullable-type
+   * @description allows a type, V, to be null
+   */
+  nullableConverter (
+    converter: Converter
+  ): (V: unknown) => ReturnType | null
+
+  argumentLengthCheck (args: { length: number }, min: number, context: {
+    header: string
+    message?: string
+  }): void
+}
diff --git a/test/merkletreejs/node_modules/undici-types/websocket.d.ts b/test/merkletreejs/node_modules/undici-types/websocket.d.ts
new file mode 100644
index 0000000..15a357d
--- /dev/null
+++ b/test/merkletreejs/node_modules/undici-types/websocket.d.ts
@@ -0,0 +1,131 @@
+/// 
+
+import type { Blob } from 'buffer'
+import type { MessagePort } from 'worker_threads'
+import {
+  EventTarget,
+  Event,
+  EventInit,
+  EventListenerOptions,
+  AddEventListenerOptions,
+  EventListenerOrEventListenerObject
+} from './patch'
+import Dispatcher from './dispatcher'
+import { HeadersInit } from './fetch'
+
+export type BinaryType = 'blob' | 'arraybuffer'
+
+interface WebSocketEventMap {
+  close: CloseEvent
+  error: Event
+  message: MessageEvent
+  open: Event
+}
+
+interface WebSocket extends EventTarget {
+  binaryType: BinaryType
+  
+  readonly bufferedAmount: number
+  readonly extensions: string
+
+  onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null
+  onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null
+  onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null
+  onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null
+
+  readonly protocol: string
+  readonly readyState: number
+  readonly url: string
+
+  close(code?: number, reason?: string): void
+  send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void
+
+  readonly CLOSED: number
+  readonly CLOSING: number
+  readonly CONNECTING: number
+  readonly OPEN: number
+
+  addEventListener(
+    type: K,
+    listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
+    options?: boolean | AddEventListenerOptions
+  ): void
+  addEventListener(
+    type: string,
+    listener: EventListenerOrEventListenerObject,
+    options?: boolean | AddEventListenerOptions
+  ): void
+  removeEventListener(
+    type: K,
+    listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
+    options?: boolean | EventListenerOptions
+  ): void
+  removeEventListener(
+    type: string,
+    listener: EventListenerOrEventListenerObject,
+    options?: boolean | EventListenerOptions
+  ): void
+}
+
+export declare const WebSocket: {
+  prototype: WebSocket
+  new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket
+  readonly CLOSED: number
+  readonly CLOSING: number
+  readonly CONNECTING: number
+  readonly OPEN: number
+}
+
+interface CloseEventInit extends EventInit {
+  code?: number
+  reason?: string
+  wasClean?: boolean
+}
+
+interface CloseEvent extends Event {
+  readonly code: number
+  readonly reason: string
+  readonly wasClean: boolean
+}
+
+export declare const CloseEvent: {
+  prototype: CloseEvent
+  new (type: string, eventInitDict?: CloseEventInit): CloseEvent
+}
+
+interface MessageEventInit extends EventInit {
+  data?: T
+  lastEventId?: string
+  origin?: string
+  ports?: (typeof MessagePort)[]
+  source?: typeof MessagePort | null
+}
+
+interface MessageEvent extends Event {
+  readonly data: T
+  readonly lastEventId: string
+  readonly origin: string
+  readonly ports: ReadonlyArray
+  readonly source: typeof MessagePort | null
+  initMessageEvent(
+    type: string,
+    bubbles?: boolean,
+    cancelable?: boolean,
+    data?: any,
+    origin?: string,
+    lastEventId?: string,
+    source?: typeof MessagePort | null,
+    ports?: (typeof MessagePort)[]
+  ): void;
+}
+
+export declare const MessageEvent: {
+  prototype: MessageEvent
+  new(type: string, eventInitDict?: MessageEventInit): MessageEvent
+}
+
+interface WebSocketInit {
+  protocols?: string | string[],
+  dispatcher?: Dispatcher,
+  headers?: HeadersInit
+}
diff --git a/test/merkletreejs/node_modules/utf8/LICENSE-MIT.txt b/test/merkletreejs/node_modules/utf8/LICENSE-MIT.txt
new file mode 100644
index 0000000..a41e0a7
--- /dev/null
+++ b/test/merkletreejs/node_modules/utf8/LICENSE-MIT.txt
@@ -0,0 +1,20 @@
+Copyright Mathias Bynens 
+
+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.
diff --git a/test/merkletreejs/node_modules/utf8/README.md b/test/merkletreejs/node_modules/utf8/README.md
new file mode 100644
index 0000000..595a51b
--- /dev/null
+++ b/test/merkletreejs/node_modules/utf8/README.md
@@ -0,0 +1,85 @@
+# utf8.js [![Build status](https://travis-ci.org/mathiasbynens/utf8.js.svg?branch=master)](https://travis-ci.org/mathiasbynens/utf8.js) [![Code coverage status](http://img.shields.io/coveralls/mathiasbynens/utf8.js/master.svg)](https://coveralls.io/r/mathiasbynens/utf8.js) [![Dependency status](https://gemnasium.com/mathiasbynens/utf8.js.svg)](https://gemnasium.com/mathiasbynens/utf8.js)
+
+_utf8.js_ is a well-tested UTF-8 encoder/decoder written in JavaScript. Unlike many other JavaScript solutions, it is designed to be a _proper_ UTF-8 encoder/decoder: it can encode/decode any scalar Unicode code point values, as per [the Encoding Standard](https://encoding.spec.whatwg.org/#utf-8). [Here’s an online demo.](https://mothereff.in/utf-8)
+
+Feel free to fork if you see possible improvements!
+
+## Installation
+
+Via [npm](https://www.npmjs.com/):
+
+```bash
+npm install utf8
+```
+
+In a browser:
+
+```html
+
+```
+
+In [Node.js](https://nodejs.org/):
+
+```js
+const utf8 = require('utf8');
+```
+
+## API
+
+### `utf8.encode(string)`
+
+Encodes any given JavaScript string (`string`) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use [WTF-8](https://mths.be/wtf8) instead.)
+
+```js
+// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
+utf8.encode('\xA9');
+// → '\xC2\xA9'
+// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
+utf8.encode('\uD800\uDC01');
+// → '\xF0\x90\x80\x81'
+```
+
+### `utf8.decode(byteString)`
+
+Decodes any given UTF-8-encoded string (`byteString`) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use [WTF-8](https://mths.be/wtf8) instead.)
+
+```js
+utf8.decode('\xC2\xA9');
+// → '\xA9'
+
+utf8.decode('\xF0\x90\x80\x81');
+// → '\uD800\uDC01'
+// → U+10001 LINEAR B SYLLABLE B038 E
+```
+
+### `utf8.version`
+
+A string representing the semantic version number.
+
+## Support
+
+utf8.js has been tested in at least Chrome 27-39, Firefox 3-34, Safari 4-8, Opera 10-28, IE 6-11, Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.11, PhantomJS 1.9.0, and Rhino 1.7RC4.
+
+## Unit tests & code coverage
+
+After cloning this repository, run `npm install` to install the dependencies needed for development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`.
+
+Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`.
+
+To generate the code coverage report, use `grunt cover`.
+
+## FAQ
+
+### Why is the first release named v2.0.0? Haven’t you heard of [semantic versioning](http://semver.org/)?
+
+Long before utf8.js was created, the `utf8` module on npm was registered and used by another (slightly buggy) library. @ryanmcgrath was kind enough to give me access to the `utf8` package on npm when I told him about utf8.js. Since there has already been a v1.0.0 release of the old library, and to avoid breaking backwards compatibility with projects that rely on the `utf8` npm package, I decided the tag the first release of utf8.js as v2.0.0 and take it from there.
+
+## Author
+
+| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
+|---|
+| [Mathias Bynens](https://mathiasbynens.be/) |
+
+## License
+
+utf8.js is available under the [MIT](https://mths.be/mit) license.
diff --git a/test/merkletreejs/node_modules/utf8/package.json b/test/merkletreejs/node_modules/utf8/package.json
new file mode 100644
index 0000000..4f0b446
--- /dev/null
+++ b/test/merkletreejs/node_modules/utf8/package.json
@@ -0,0 +1,42 @@
+{
+	"name": "utf8",
+	"version": "3.0.0",
+	"description": "A well-tested UTF-8 encoder/decoder written in JavaScript.",
+	"homepage": "https://mths.be/utf8js",
+	"main": "utf8.js",
+	"keywords": [
+		"charset",
+		"encoding",
+		"unicode",
+		"utf8"
+	],
+	"license": "MIT",
+	"author": {
+		"name": "Mathias Bynens",
+		"url": "https://mathiasbynens.be/"
+	},
+	"repository": {
+		"type": "git",
+		"url": "https://github.com/mathiasbynens/utf8.js.git"
+	},
+	"bugs": "https://github.com/mathiasbynens/utf8.js/issues",
+	"files": [
+		"LICENSE-MIT.txt",
+		"utf8.js"
+	],
+	"scripts": {
+		"test": "node tests/tests.js",
+		"test-extended": "node tests/tests.js --extended",
+		"test-browser": "open tests/index.html",
+		"ci": "npm run build && npm test",
+		"build": "cd tests; if [ ! -f data.json ]; then python generate-test-data.py; fi",
+		"cover-html": "istanbul cover --report html --verbose --dir coverage tests/tests.js; istanbul report --root coverage --format html",
+		"cover-coveralls": "istanbul cover --verbose --dir coverage tests/tests.js && coveralls < coverage/lcov.info; rm -rf coverage/lcov*"
+	},
+	"devDependencies": {
+		"coveralls": "^2.11.14",
+		"istanbul": "^0.4.5",
+		"qunit-extras": "^1.4.2",
+		"qunitjs": "~1.11.0"
+	}
+}
diff --git a/test/merkletreejs/node_modules/utf8/utf8.js b/test/merkletreejs/node_modules/utf8/utf8.js
new file mode 100644
index 0000000..d301582
--- /dev/null
+++ b/test/merkletreejs/node_modules/utf8/utf8.js
@@ -0,0 +1,202 @@
+/*! https://mths.be/utf8js v3.0.0 by @mathias */
+;(function(root) {
+
+	var stringFromCharCode = String.fromCharCode;
+
+	// Taken from https://mths.be/punycode
+	function ucs2decode(string) {
+		var output = [];
+		var counter = 0;
+		var length = string.length;
+		var value;
+		var extra;
+		while (counter < length) {
+			value = string.charCodeAt(counter++);
+			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+				// high surrogate, and there is a next character
+				extra = string.charCodeAt(counter++);
+				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+				} else {
+					// unmatched surrogate; only append this code unit, in case the next
+					// code unit is the high surrogate of a surrogate pair
+					output.push(value);
+					counter--;
+				}
+			} else {
+				output.push(value);
+			}
+		}
+		return output;
+	}
+
+	// Taken from https://mths.be/punycode
+	function ucs2encode(array) {
+		var length = array.length;
+		var index = -1;
+		var value;
+		var output = '';
+		while (++index < length) {
+			value = array[index];
+			if (value > 0xFFFF) {
+				value -= 0x10000;
+				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+				value = 0xDC00 | value & 0x3FF;
+			}
+			output += stringFromCharCode(value);
+		}
+		return output;
+	}
+
+	function checkScalarValue(codePoint) {
+		if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
+			throw Error(
+				'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
+				' is not a scalar value'
+			);
+		}
+	}
+	/*--------------------------------------------------------------------------*/
+
+	function createByte(codePoint, shift) {
+		return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
+	}
+
+	function encodeCodePoint(codePoint) {
+		if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
+			return stringFromCharCode(codePoint);
+		}
+		var symbol = '';
+		if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
+			symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
+		}
+		else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
+			checkScalarValue(codePoint);
+			symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
+			symbol += createByte(codePoint, 6);
+		}
+		else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
+			symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
+			symbol += createByte(codePoint, 12);
+			symbol += createByte(codePoint, 6);
+		}
+		symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
+		return symbol;
+	}
+
+	function utf8encode(string) {
+		var codePoints = ucs2decode(string);
+		var length = codePoints.length;
+		var index = -1;
+		var codePoint;
+		var byteString = '';
+		while (++index < length) {
+			codePoint = codePoints[index];
+			byteString += encodeCodePoint(codePoint);
+		}
+		return byteString;
+	}
+
+	/*--------------------------------------------------------------------------*/
+
+	function readContinuationByte() {
+		if (byteIndex >= byteCount) {
+			throw Error('Invalid byte index');
+		}
+
+		var continuationByte = byteArray[byteIndex] & 0xFF;
+		byteIndex++;
+
+		if ((continuationByte & 0xC0) == 0x80) {
+			return continuationByte & 0x3F;
+		}
+
+		// If we end up here, it’s not a continuation byte
+		throw Error('Invalid continuation byte');
+	}
+
+	function decodeSymbol() {
+		var byte1;
+		var byte2;
+		var byte3;
+		var byte4;
+		var codePoint;
+
+		if (byteIndex > byteCount) {
+			throw Error('Invalid byte index');
+		}
+
+		if (byteIndex == byteCount) {
+			return false;
+		}
+
+		// Read first byte
+		byte1 = byteArray[byteIndex] & 0xFF;
+		byteIndex++;
+
+		// 1-byte sequence (no continuation bytes)
+		if ((byte1 & 0x80) == 0) {
+			return byte1;
+		}
+
+		// 2-byte sequence
+		if ((byte1 & 0xE0) == 0xC0) {
+			byte2 = readContinuationByte();
+			codePoint = ((byte1 & 0x1F) << 6) | byte2;
+			if (codePoint >= 0x80) {
+				return codePoint;
+			} else {
+				throw Error('Invalid continuation byte');
+			}
+		}
+
+		// 3-byte sequence (may include unpaired surrogates)
+		if ((byte1 & 0xF0) == 0xE0) {
+			byte2 = readContinuationByte();
+			byte3 = readContinuationByte();
+			codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
+			if (codePoint >= 0x0800) {
+				checkScalarValue(codePoint);
+				return codePoint;
+			} else {
+				throw Error('Invalid continuation byte');
+			}
+		}
+
+		// 4-byte sequence
+		if ((byte1 & 0xF8) == 0xF0) {
+			byte2 = readContinuationByte();
+			byte3 = readContinuationByte();
+			byte4 = readContinuationByte();
+			codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
+				(byte3 << 0x06) | byte4;
+			if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
+				return codePoint;
+			}
+		}
+
+		throw Error('Invalid UTF-8 detected');
+	}
+
+	var byteArray;
+	var byteCount;
+	var byteIndex;
+	function utf8decode(byteString) {
+		byteArray = ucs2decode(byteString);
+		byteCount = byteArray.length;
+		byteIndex = 0;
+		var codePoints = [];
+		var tmp;
+		while ((tmp = decodeSymbol()) !== false) {
+			codePoints.push(tmp);
+		}
+		return ucs2encode(codePoints);
+	}
+
+	/*--------------------------------------------------------------------------*/
+
+	root.version = '3.0.0';
+	root.encode = utf8encode;
+	root.decode = utf8decode;
+
+}(typeof exports === 'undefined' ? this.utf8 = {} : exports));
diff --git a/test/merkletreejs/node_modules/util/LICENSE b/test/merkletreejs/node_modules/util/LICENSE
new file mode 100644
index 0000000..e3d4e69
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/LICENSE
@@ -0,0 +1,18 @@
+Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+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.
diff --git a/test/merkletreejs/node_modules/util/README.md b/test/merkletreejs/node_modules/util/README.md
new file mode 100644
index 0000000..faced97
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/README.md
@@ -0,0 +1,48 @@
+# util [![Build Status](https://travis-ci.org/browserify/node-util.png?branch=master)](https://travis-ci.org/browserify/node-util)
+
+> Node.js's [util][util] module for all engines.
+
+This implements the Node.js [`util`][util] module for environments that do not have it, like browsers.
+
+## Install
+
+You usually do not have to install `util` yourself. If your code runs in Node.js, `util` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) (up to version 4 -- [see this documentation](https://webpack.js.org/configuration/resolve/#resolvefallback) for how to include polyfills like `util` in webpack 5+) also include the `util` module.
+
+But if none of those apply, with npm do:
+
+```shell
+npm install util
+```
+
+## Usage
+
+```javascript
+var util = require('util')
+var EventEmitter = require('events')
+
+function MyClass() { EventEmitter.call(this) }
+util.inherits(MyClass, EventEmitter)
+```
+
+## Browser Support
+
+The `util` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`.
+
+To use `util.promisify` and `util.callbackify`, Promises must already be available. If you need to support browsers like IE11 that do not support Promises, use a shim. [es6-promise](https://github.com/stefanpenner/es6-promise) is a popular one but there are many others available on npm.
+
+## API
+
+See the [Node.js util docs][util].  `util` currently supports the Node 8 LTS API. However, some of the methods are outdated. The `inspect` and `format` methods included in this module are a lot more simple and barebones than the ones in Node.js.
+
+## Contributing
+
+PRs are very welcome! The main way to contribute to `util` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js.
+This module intends to provide exactly the same API as Node.js, so features that are not available in the core `util` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js.
+
+If there is a difference in behaviour between Node.js's `util` module and this module, please open an issue!
+
+## License
+
+[MIT](./LICENSE)
+
+[util]: https://nodejs.org/docs/latest-v8.x/api/util.html
diff --git a/test/merkletreejs/node_modules/util/package.json b/test/merkletreejs/node_modules/util/package.json
new file mode 100644
index 0000000..2099ec0
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/package.json
@@ -0,0 +1,50 @@
+{
+  "name": "util",
+  "description": "Node.js's util module for all engines",
+  "version": "0.12.5",
+  "author": {
+    "name": "Joyent",
+    "url": "http://www.joyent.com"
+  },
+  "browser": {
+    "./support/isBuffer.js": "./support/isBufferBrowser.js"
+  },
+  "dependencies": {
+    "inherits": "^2.0.3",
+    "is-arguments": "^1.0.4",
+    "is-generator-function": "^1.0.7",
+    "is-typed-array": "^1.1.3",
+    "which-typed-array": "^1.1.2"
+  },
+  "devDependencies": {
+    "airtap": "~1.0.0",
+    "core-js": "^3.6.5",
+    "is-async-supported": "~1.2.0",
+    "object.assign": "~4.1.0",
+    "object.entries": "^1.1.0",
+    "run-series": "~1.1.4",
+    "safe-buffer": "^5.1.2",
+    "tape": "~4.9.0"
+  },
+  "files": [
+    "util.js",
+    "support"
+  ],
+  "homepage": "https://github.com/browserify/node-util",
+  "keywords": [
+    "util"
+  ],
+  "license": "MIT",
+  "main": "./util.js",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/browserify/node-util"
+  },
+  "scripts": {
+    "test": "node test/node/index.js",
+    "test:browsers": "airtap test/browser/index.js",
+    "test:browsers:with-polyfills": "airtap test/browser/with-polyfills.js",
+    "test:browsers:with-polyfills:local": "npm run test:browsers:with-polyfills -- --local",
+    "test:browsers:local": "npm run test:browsers -- --local"
+  }
+}
diff --git a/test/merkletreejs/node_modules/util/support/isBuffer.js b/test/merkletreejs/node_modules/util/support/isBuffer.js
new file mode 100644
index 0000000..ace9ac0
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/support/isBuffer.js
@@ -0,0 +1,3 @@
+module.exports = function isBuffer(arg) {
+  return arg instanceof Buffer;
+}
diff --git a/test/merkletreejs/node_modules/util/support/isBufferBrowser.js b/test/merkletreejs/node_modules/util/support/isBufferBrowser.js
new file mode 100644
index 0000000..0e1bee1
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/support/isBufferBrowser.js
@@ -0,0 +1,6 @@
+module.exports = function isBuffer(arg) {
+  return arg && typeof arg === 'object'
+    && typeof arg.copy === 'function'
+    && typeof arg.fill === 'function'
+    && typeof arg.readUInt8 === 'function';
+}
\ No newline at end of file
diff --git a/test/merkletreejs/node_modules/util/support/types.js b/test/merkletreejs/node_modules/util/support/types.js
new file mode 100644
index 0000000..12e9db3
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/support/types.js
@@ -0,0 +1,334 @@
+// Currently in sync with Node.js lib/internal/util/types.js
+// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
+
+'use strict';
+
+var isArgumentsObject = require('is-arguments');
+var isGeneratorFunction = require('is-generator-function');
+var whichTypedArray = require('which-typed-array');
+var isTypedArray = require('is-typed-array');
+
+function uncurryThis(f) {
+  return f.call.bind(f);
+}
+
+var BigIntSupported = typeof BigInt !== 'undefined';
+var SymbolSupported = typeof Symbol !== 'undefined';
+
+var ObjectToString = uncurryThis(Object.prototype.toString);
+
+var numberValue = uncurryThis(Number.prototype.valueOf);
+var stringValue = uncurryThis(String.prototype.valueOf);
+var booleanValue = uncurryThis(Boolean.prototype.valueOf);
+
+if (BigIntSupported) {
+  var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
+}
+
+if (SymbolSupported) {
+  var symbolValue = uncurryThis(Symbol.prototype.valueOf);
+}
+
+function checkBoxedPrimitive(value, prototypeValueOf) {
+  if (typeof value !== 'object') {
+    return false;
+  }
+  try {
+    prototypeValueOf(value);
+    return true;
+  } catch(e) {
+    return false;
+  }
+}
+
+exports.isArgumentsObject = isArgumentsObject;
+exports.isGeneratorFunction = isGeneratorFunction;
+exports.isTypedArray = isTypedArray;
+
+// Taken from here and modified for better browser support
+// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
+function isPromise(input) {
+	return (
+		(
+			typeof Promise !== 'undefined' &&
+			input instanceof Promise
+		) ||
+		(
+			input !== null &&
+			typeof input === 'object' &&
+			typeof input.then === 'function' &&
+			typeof input.catch === 'function'
+		)
+	);
+}
+exports.isPromise = isPromise;
+
+function isArrayBufferView(value) {
+  if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
+    return ArrayBuffer.isView(value);
+  }
+
+  return (
+    isTypedArray(value) ||
+    isDataView(value)
+  );
+}
+exports.isArrayBufferView = isArrayBufferView;
+
+
+function isUint8Array(value) {
+  return whichTypedArray(value) === 'Uint8Array';
+}
+exports.isUint8Array = isUint8Array;
+
+function isUint8ClampedArray(value) {
+  return whichTypedArray(value) === 'Uint8ClampedArray';
+}
+exports.isUint8ClampedArray = isUint8ClampedArray;
+
+function isUint16Array(value) {
+  return whichTypedArray(value) === 'Uint16Array';
+}
+exports.isUint16Array = isUint16Array;
+
+function isUint32Array(value) {
+  return whichTypedArray(value) === 'Uint32Array';
+}
+exports.isUint32Array = isUint32Array;
+
+function isInt8Array(value) {
+  return whichTypedArray(value) === 'Int8Array';
+}
+exports.isInt8Array = isInt8Array;
+
+function isInt16Array(value) {
+  return whichTypedArray(value) === 'Int16Array';
+}
+exports.isInt16Array = isInt16Array;
+
+function isInt32Array(value) {
+  return whichTypedArray(value) === 'Int32Array';
+}
+exports.isInt32Array = isInt32Array;
+
+function isFloat32Array(value) {
+  return whichTypedArray(value) === 'Float32Array';
+}
+exports.isFloat32Array = isFloat32Array;
+
+function isFloat64Array(value) {
+  return whichTypedArray(value) === 'Float64Array';
+}
+exports.isFloat64Array = isFloat64Array;
+
+function isBigInt64Array(value) {
+  return whichTypedArray(value) === 'BigInt64Array';
+}
+exports.isBigInt64Array = isBigInt64Array;
+
+function isBigUint64Array(value) {
+  return whichTypedArray(value) === 'BigUint64Array';
+}
+exports.isBigUint64Array = isBigUint64Array;
+
+function isMapToString(value) {
+  return ObjectToString(value) === '[object Map]';
+}
+isMapToString.working = (
+  typeof Map !== 'undefined' &&
+  isMapToString(new Map())
+);
+
+function isMap(value) {
+  if (typeof Map === 'undefined') {
+    return false;
+  }
+
+  return isMapToString.working
+    ? isMapToString(value)
+    : value instanceof Map;
+}
+exports.isMap = isMap;
+
+function isSetToString(value) {
+  return ObjectToString(value) === '[object Set]';
+}
+isSetToString.working = (
+  typeof Set !== 'undefined' &&
+  isSetToString(new Set())
+);
+function isSet(value) {
+  if (typeof Set === 'undefined') {
+    return false;
+  }
+
+  return isSetToString.working
+    ? isSetToString(value)
+    : value instanceof Set;
+}
+exports.isSet = isSet;
+
+function isWeakMapToString(value) {
+  return ObjectToString(value) === '[object WeakMap]';
+}
+isWeakMapToString.working = (
+  typeof WeakMap !== 'undefined' &&
+  isWeakMapToString(new WeakMap())
+);
+function isWeakMap(value) {
+  if (typeof WeakMap === 'undefined') {
+    return false;
+  }
+
+  return isWeakMapToString.working
+    ? isWeakMapToString(value)
+    : value instanceof WeakMap;
+}
+exports.isWeakMap = isWeakMap;
+
+function isWeakSetToString(value) {
+  return ObjectToString(value) === '[object WeakSet]';
+}
+isWeakSetToString.working = (
+  typeof WeakSet !== 'undefined' &&
+  isWeakSetToString(new WeakSet())
+);
+function isWeakSet(value) {
+  return isWeakSetToString(value);
+}
+exports.isWeakSet = isWeakSet;
+
+function isArrayBufferToString(value) {
+  return ObjectToString(value) === '[object ArrayBuffer]';
+}
+isArrayBufferToString.working = (
+  typeof ArrayBuffer !== 'undefined' &&
+  isArrayBufferToString(new ArrayBuffer())
+);
+function isArrayBuffer(value) {
+  if (typeof ArrayBuffer === 'undefined') {
+    return false;
+  }
+
+  return isArrayBufferToString.working
+    ? isArrayBufferToString(value)
+    : value instanceof ArrayBuffer;
+}
+exports.isArrayBuffer = isArrayBuffer;
+
+function isDataViewToString(value) {
+  return ObjectToString(value) === '[object DataView]';
+}
+isDataViewToString.working = (
+  typeof ArrayBuffer !== 'undefined' &&
+  typeof DataView !== 'undefined' &&
+  isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
+);
+function isDataView(value) {
+  if (typeof DataView === 'undefined') {
+    return false;
+  }
+
+  return isDataViewToString.working
+    ? isDataViewToString(value)
+    : value instanceof DataView;
+}
+exports.isDataView = isDataView;
+
+// Store a copy of SharedArrayBuffer in case it's deleted elsewhere
+var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;
+function isSharedArrayBufferToString(value) {
+  return ObjectToString(value) === '[object SharedArrayBuffer]';
+}
+function isSharedArrayBuffer(value) {
+  if (typeof SharedArrayBufferCopy === 'undefined') {
+    return false;
+  }
+
+  if (typeof isSharedArrayBufferToString.working === 'undefined') {
+    isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
+  }
+
+  return isSharedArrayBufferToString.working
+    ? isSharedArrayBufferToString(value)
+    : value instanceof SharedArrayBufferCopy;
+}
+exports.isSharedArrayBuffer = isSharedArrayBuffer;
+
+function isAsyncFunction(value) {
+  return ObjectToString(value) === '[object AsyncFunction]';
+}
+exports.isAsyncFunction = isAsyncFunction;
+
+function isMapIterator(value) {
+  return ObjectToString(value) === '[object Map Iterator]';
+}
+exports.isMapIterator = isMapIterator;
+
+function isSetIterator(value) {
+  return ObjectToString(value) === '[object Set Iterator]';
+}
+exports.isSetIterator = isSetIterator;
+
+function isGeneratorObject(value) {
+  return ObjectToString(value) === '[object Generator]';
+}
+exports.isGeneratorObject = isGeneratorObject;
+
+function isWebAssemblyCompiledModule(value) {
+  return ObjectToString(value) === '[object WebAssembly.Module]';
+}
+exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
+
+function isNumberObject(value) {
+  return checkBoxedPrimitive(value, numberValue);
+}
+exports.isNumberObject = isNumberObject;
+
+function isStringObject(value) {
+  return checkBoxedPrimitive(value, stringValue);
+}
+exports.isStringObject = isStringObject;
+
+function isBooleanObject(value) {
+  return checkBoxedPrimitive(value, booleanValue);
+}
+exports.isBooleanObject = isBooleanObject;
+
+function isBigIntObject(value) {
+  return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
+}
+exports.isBigIntObject = isBigIntObject;
+
+function isSymbolObject(value) {
+  return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
+}
+exports.isSymbolObject = isSymbolObject;
+
+function isBoxedPrimitive(value) {
+  return (
+    isNumberObject(value) ||
+    isStringObject(value) ||
+    isBooleanObject(value) ||
+    isBigIntObject(value) ||
+    isSymbolObject(value)
+  );
+}
+exports.isBoxedPrimitive = isBoxedPrimitive;
+
+function isAnyArrayBuffer(value) {
+  return typeof Uint8Array !== 'undefined' && (
+    isArrayBuffer(value) ||
+    isSharedArrayBuffer(value)
+  );
+}
+exports.isAnyArrayBuffer = isAnyArrayBuffer;
+
+['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {
+  Object.defineProperty(exports, method, {
+    enumerable: false,
+    value: function() {
+      throw new Error(method + ' is not supported in userland');
+    }
+  });
+});
diff --git a/test/merkletreejs/node_modules/util/util.js b/test/merkletreejs/node_modules/util/util.js
new file mode 100644
index 0000000..6db393e
--- /dev/null
+++ b/test/merkletreejs/node_modules/util/util.js
@@ -0,0 +1,715 @@
+// Copyright Joyent, Inc. and other Node 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.
+
+var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
+  function getOwnPropertyDescriptors(obj) {
+    var keys = Object.keys(obj);
+    var descriptors = {};
+    for (var i = 0; i < keys.length; i++) {
+      descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
+    }
+    return descriptors;
+  };
+
+var formatRegExp = /%[sdj%]/g;
+exports.format = function(f) {
+  if (!isString(f)) {
+    var objects = [];
+    for (var i = 0; i < arguments.length; i++) {
+      objects.push(inspect(arguments[i]));
+    }
+    return objects.join(' ');
+  }
+
+  var i = 1;
+  var args = arguments;
+  var len = args.length;
+  var str = String(f).replace(formatRegExp, function(x) {
+    if (x === '%%') return '%';
+    if (i >= len) return x;
+    switch (x) {
+      case '%s': return String(args[i++]);
+      case '%d': return Number(args[i++]);
+      case '%j':
+        try {
+          return JSON.stringify(args[i++]);
+        } catch (_) {
+          return '[Circular]';
+        }
+      default:
+        return x;
+    }
+  });
+  for (var x = args[i]; i < len; x = args[++i]) {
+    if (isNull(x) || !isObject(x)) {
+      str += ' ' + x;
+    } else {
+      str += ' ' + inspect(x);
+    }
+  }
+  return str;
+};
+
+
+// Mark that a method should not be used.
+// Returns a modified function which warns once by default.
+// If --no-deprecation is set, then it is a no-op.
+exports.deprecate = function(fn, msg) {
+  if (typeof process !== 'undefined' && process.noDeprecation === true) {
+    return fn;
+  }
+
+  // Allow for deprecating things in the process of starting up.
+  if (typeof process === 'undefined') {
+    return function() {
+      return exports.deprecate(fn, msg).apply(this, arguments);
+    };
+  }
+
+  var warned = false;
+  function deprecated() {
+    if (!warned) {
+      if (process.throwDeprecation) {
+        throw new Error(msg);
+      } else if (process.traceDeprecation) {
+        console.trace(msg);
+      } else {
+        console.error(msg);
+      }
+      warned = true;
+    }
+    return fn.apply(this, arguments);
+  }
+
+  return deprecated;
+};
+
+
+var debugs = {};
+var debugEnvRegex = /^$/;
+
+if (process.env.NODE_DEBUG) {
+  var debugEnv = process.env.NODE_DEBUG;
+  debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
+    .replace(/\*/g, '.*')
+    .replace(/,/g, '$|^')
+    .toUpperCase();
+  debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
+}
+exports.debuglog = function(set) {
+  set = set.toUpperCase();
+  if (!debugs[set]) {
+    if (debugEnvRegex.test(set)) {
+      var pid = process.pid;
+      debugs[set] = function() {
+        var msg = exports.format.apply(exports, arguments);
+        console.error('%s %d: %s', set, pid, msg);
+      };
+    } else {
+      debugs[set] = function() {};
+    }
+  }
+  return debugs[set];
+};
+
+
+/**
+ * Echos the value of a value. Trys to print the value out
+ * in the best way possible given the different types.
+ *
+ * @param {Object} obj The object to print out.
+ * @param {Object} opts Optional options object that alters the output.
+ */
+/* legacy: obj, showHidden, depth, colors*/
+function inspect(obj, opts) {
+  // default options
+  var ctx = {
+    seen: [],
+    stylize: stylizeNoColor
+  };
+  // legacy...
+  if (arguments.length >= 3) ctx.depth = arguments[2];
+  if (arguments.length >= 4) ctx.colors = arguments[3];
+  if (isBoolean(opts)) {
+    // legacy...
+    ctx.showHidden = opts;
+  } else if (opts) {
+    // got an "options" object
+    exports._extend(ctx, opts);
+  }
+  // set default options
+  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
+  if (isUndefined(ctx.depth)) ctx.depth = 2;
+  if (isUndefined(ctx.colors)) ctx.colors = false;
+  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
+  if (ctx.colors) ctx.stylize = stylizeWithColor;
+  return formatValue(ctx, obj, ctx.depth);
+}
+exports.inspect = inspect;
+
+
+// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
+inspect.colors = {
+  'bold' : [1, 22],
+  'italic' : [3, 23],
+  'underline' : [4, 24],
+  'inverse' : [7, 27],
+  'white' : [37, 39],
+  'grey' : [90, 39],
+  'black' : [30, 39],
+  'blue' : [34, 39],
+  'cyan' : [36, 39],
+  'green' : [32, 39],
+  'magenta' : [35, 39],
+  'red' : [31, 39],
+  'yellow' : [33, 39]
+};
+
+// Don't use 'blue' not visible on cmd.exe
+inspect.styles = {
+  'special': 'cyan',
+  'number': 'yellow',
+  'boolean': 'yellow',
+  'undefined': 'grey',
+  'null': 'bold',
+  'string': 'green',
+  'date': 'magenta',
+  // "name": intentionally not styling
+  'regexp': 'red'
+};
+
+
+function stylizeWithColor(str, styleType) {
+  var style = inspect.styles[styleType];
+
+  if (style) {
+    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
+           '\u001b[' + inspect.colors[style][1] + 'm';
+  } else {
+    return str;
+  }
+}
+
+
+function stylizeNoColor(str, styleType) {
+  return str;
+}
+
+
+function arrayToHash(array) {
+  var hash = {};
+
+  array.forEach(function(val, idx) {
+    hash[val] = true;
+  });
+
+  return hash;
+}
+
+
+function formatValue(ctx, value, recurseTimes) {
+  // Provide a hook for user-specified inspect functions.
+  // Check that value is an object with an inspect function on it
+  if (ctx.customInspect &&
+      value &&
+      isFunction(value.inspect) &&
+      // Filter out the util module, it's inspect function is special
+      value.inspect !== exports.inspect &&
+      // Also filter out any prototype objects using the circular check.
+      !(value.constructor && value.constructor.prototype === value)) {
+    var ret = value.inspect(recurseTimes, ctx);
+    if (!isString(ret)) {
+      ret = formatValue(ctx, ret, recurseTimes);
+    }
+    return ret;
+  }
+
+  // Primitive types cannot have properties
+  var primitive = formatPrimitive(ctx, value);
+  if (primitive) {
+    return primitive;
+  }
+
+  // Look up the keys of the object.
+  var keys = Object.keys(value);
+  var visibleKeys = arrayToHash(keys);
+
+  if (ctx.showHidden) {
+    keys = Object.getOwnPropertyNames(value);
+  }
+
+  // IE doesn't make error fields non-enumerable
+  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
+  if (isError(value)
+      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
+    return formatError(value);
+  }
+
+  // Some type of object without properties can be shortcutted.
+  if (keys.length === 0) {
+    if (isFunction(value)) {
+      var name = value.name ? ': ' + value.name : '';
+      return ctx.stylize('[Function' + name + ']', 'special');
+    }
+    if (isRegExp(value)) {
+      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+    }
+    if (isDate(value)) {
+      return ctx.stylize(Date.prototype.toString.call(value), 'date');
+    }
+    if (isError(value)) {
+      return formatError(value);
+    }
+  }
+
+  var base = '', array = false, braces = ['{', '}'];
+
+  // Make Array say that they are Array
+  if (isArray(value)) {
+    array = true;
+    braces = ['[', ']'];
+  }
+
+  // Make functions say that they are functions
+  if (isFunction(value)) {
+    var n = value.name ? ': ' + value.name : '';
+    base = ' [Function' + n + ']';
+  }
+
+  // Make RegExps say that they are RegExps
+  if (isRegExp(value)) {
+    base = ' ' + RegExp.prototype.toString.call(value);
+  }
+
+  // Make dates with properties first say the date
+  if (isDate(value)) {
+    base = ' ' + Date.prototype.toUTCString.call(value);
+  }
+
+  // Make error with message first say the error
+  if (isError(value)) {
+    base = ' ' + formatError(value);
+  }
+
+  if (keys.length === 0 && (!array || value.length == 0)) {
+    return braces[0] + base + braces[1];
+  }
+
+  if (recurseTimes < 0) {
+    if (isRegExp(value)) {
+      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+    } else {
+      return ctx.stylize('[Object]', 'special');
+    }
+  }
+
+  ctx.seen.push(value);
+
+  var output;
+  if (array) {
+    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
+  } else {
+    output = keys.map(function(key) {
+      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
+    });
+  }
+
+  ctx.seen.pop();
+
+  return reduceToSingleString(output, base, braces);
+}
+
+
+function formatPrimitive(ctx, value) {
+  if (isUndefined(value))
+    return ctx.stylize('undefined', 'undefined');
+  if (isString(value)) {
+    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
+                                             .replace(/'/g, "\\'")
+                                             .replace(/\\"/g, '"') + '\'';
+    return ctx.stylize(simple, 'string');
+  }
+  if (isNumber(value))
+    return ctx.stylize('' + value, 'number');
+  if (isBoolean(value))
+    return ctx.stylize('' + value, 'boolean');
+  // For some reason typeof null is "object", so special case here.
+  if (isNull(value))
+    return ctx.stylize('null', 'null');
+}
+
+
+function formatError(value) {
+  return '[' + Error.prototype.toString.call(value) + ']';
+}
+
+
+function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
+  var output = [];
+  for (var i = 0, l = value.length; i < l; ++i) {
+    if (hasOwnProperty(value, String(i))) {
+      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+          String(i), true));
+    } else {
+      output.push('');
+    }
+  }
+  keys.forEach(function(key) {
+    if (!key.match(/^\d+$/)) {
+      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+          key, true));
+    }
+  });
+  return output;
+}
+
+
+function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
+  var name, str, desc;
+  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
+  if (desc.get) {
+    if (desc.set) {
+      str = ctx.stylize('[Getter/Setter]', 'special');
+    } else {
+      str = ctx.stylize('[Getter]', 'special');
+    }
+  } else {
+    if (desc.set) {
+      str = ctx.stylize('[Setter]', 'special');
+    }
+  }
+  if (!hasOwnProperty(visibleKeys, key)) {
+    name = '[' + key + ']';
+  }
+  if (!str) {
+    if (ctx.seen.indexOf(desc.value) < 0) {
+      if (isNull(recurseTimes)) {
+        str = formatValue(ctx, desc.value, null);
+      } else {
+        str = formatValue(ctx, desc.value, recurseTimes - 1);
+      }
+      if (str.indexOf('\n') > -1) {
+        if (array) {
+          str = str.split('\n').map(function(line) {
+            return '  ' + line;
+          }).join('\n').slice(2);
+        } else {
+          str = '\n' + str.split('\n').map(function(line) {
+            return '   ' + line;
+          }).join('\n');
+        }
+      }
+    } else {
+      str = ctx.stylize('[Circular]', 'special');
+    }
+  }
+  if (isUndefined(name)) {
+    if (array && key.match(/^\d+$/)) {
+      return str;
+    }
+    name = JSON.stringify('' + key);
+    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
+      name = name.slice(1, -1);
+      name = ctx.stylize(name, 'name');
+    } else {
+      name = name.replace(/'/g, "\\'")
+                 .replace(/\\"/g, '"')
+                 .replace(/(^"|"$)/g, "'");
+      name = ctx.stylize(name, 'string');
+    }
+  }
+
+  return name + ': ' + str;
+}
+
+
+function reduceToSingleString(output, base, braces) {
+  var numLinesEst = 0;
+  var length = output.reduce(function(prev, cur) {
+    numLinesEst++;
+    if (cur.indexOf('\n') >= 0) numLinesEst++;
+    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
+  }, 0);
+
+  if (length > 60) {
+    return braces[0] +
+           (base === '' ? '' : base + '\n ') +
+           ' ' +
+           output.join(',\n  ') +
+           ' ' +
+           braces[1];
+  }
+
+  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
+}
+
+
+// NOTE: These type checking functions intentionally don't use `instanceof`
+// because it is fragile and can be easily faked with `Object.create()`.
+exports.types = require('./support/types');
+
+function isArray(ar) {
+  return Array.isArray(ar);
+}
+exports.isArray = isArray;
+
+function isBoolean(arg) {
+  return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
+
+function isNull(arg) {
+  return arg === null;
+}
+exports.isNull = isNull;
+
+function isNullOrUndefined(arg) {
+  return arg == null;
+}
+exports.isNullOrUndefined = isNullOrUndefined;
+
+function isNumber(arg) {
+  return typeof arg === 'number';
+}
+exports.isNumber = isNumber;
+
+function isString(arg) {
+  return typeof arg === 'string';
+}
+exports.isString = isString;
+
+function isSymbol(arg) {
+  return typeof arg === 'symbol';
+}
+exports.isSymbol = isSymbol;
+
+function isUndefined(arg) {
+  return arg === void 0;
+}
+exports.isUndefined = isUndefined;
+
+function isRegExp(re) {
+  return isObject(re) && objectToString(re) === '[object RegExp]';
+}
+exports.isRegExp = isRegExp;
+exports.types.isRegExp = isRegExp;
+
+function isObject(arg) {
+  return typeof arg === 'object' && arg !== null;
+}
+exports.isObject = isObject;
+
+function isDate(d) {
+  return isObject(d) && objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
+exports.types.isDate = isDate;
+
+function isError(e) {
+  return isObject(e) &&
+      (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
+exports.types.isNativeError = isError;
+
+function isFunction(arg) {
+  return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
+
+function isPrimitive(arg) {
+  return arg === null ||
+         typeof arg === 'boolean' ||
+         typeof arg === 'number' ||
+         typeof arg === 'string' ||
+         typeof arg === 'symbol' ||  // ES6 symbol
+         typeof arg === 'undefined';
+}
+exports.isPrimitive = isPrimitive;
+
+exports.isBuffer = require('./support/isBuffer');
+
+function objectToString(o) {
+  return Object.prototype.toString.call(o);
+}
+
+
+function pad(n) {
+  return n < 10 ? '0' + n.toString(10) : n.toString(10);
+}
+
+
+var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
+              'Oct', 'Nov', 'Dec'];
+
+// 26 Feb 16:19:34
+function timestamp() {
+  var d = new Date();
+  var time = [pad(d.getHours()),
+              pad(d.getMinutes()),
+              pad(d.getSeconds())].join(':');
+  return [d.getDate(), months[d.getMonth()], time].join(' ');
+}
+
+
+// log is just a thin wrapper to console.log that prepends a timestamp
+exports.log = function() {
+  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
+};
+
+
+/**
+ * Inherit the prototype methods from one constructor into another.
+ *
+ * The Function.prototype.inherits from lang.js rewritten as a standalone
+ * function (not on Function.prototype). NOTE: If this file is to be loaded
+ * during bootstrapping this function needs to be rewritten using some native
+ * functions as prototype setup using normal JavaScript does not work as
+ * expected during bootstrapping (see mirror.js in r114903).
+ *
+ * @param {function} ctor Constructor function which needs to inherit the
+ *     prototype.
+ * @param {function} superCtor Constructor function to inherit prototype from.
+ */
+exports.inherits = require('inherits');
+
+exports._extend = function(origin, add) {
+  // Don't do anything if add isn't an object
+  if (!add || !isObject(add)) return origin;
+
+  var keys = Object.keys(add);
+  var i = keys.length;
+  while (i--) {
+    origin[keys[i]] = add[keys[i]];
+  }
+  return origin;
+};
+
+function hasOwnProperty(obj, prop) {
+  return Object.prototype.hasOwnProperty.call(obj, prop);
+}
+
+var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
+
+exports.promisify = function promisify(original) {
+  if (typeof original !== 'function')
+    throw new TypeError('The "original" argument must be of type Function');
+
+  if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
+    var fn = original[kCustomPromisifiedSymbol];
+    if (typeof fn !== 'function') {
+      throw new TypeError('The "util.promisify.custom" argument must be of type Function');
+    }
+    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
+      value: fn, enumerable: false, writable: false, configurable: true
+    });
+    return fn;
+  }
+
+  function fn() {
+    var promiseResolve, promiseReject;
+    var promise = new Promise(function (resolve, reject) {
+      promiseResolve = resolve;
+      promiseReject = reject;
+    });
+
+    var args = [];
+    for (var i = 0; i < arguments.length; i++) {
+      args.push(arguments[i]);
+    }
+    args.push(function (err, value) {
+      if (err) {
+        promiseReject(err);
+      } else {
+        promiseResolve(value);
+      }
+    });
+
+    try {
+      original.apply(this, args);
+    } catch (err) {
+      promiseReject(err);
+    }
+
+    return promise;
+  }
+
+  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
+
+  if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
+    value: fn, enumerable: false, writable: false, configurable: true
+  });
+  return Object.defineProperties(
+    fn,
+    getOwnPropertyDescriptors(original)
+  );
+}
+
+exports.promisify.custom = kCustomPromisifiedSymbol
+
+function callbackifyOnRejected(reason, cb) {
+  // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
+  // Because `null` is a special error value in callbacks which means "no error
+  // occurred", we error-wrap so the callback consumer can distinguish between
+  // "the promise rejected with null" or "the promise fulfilled with undefined".
+  if (!reason) {
+    var newReason = new Error('Promise was rejected with a falsy value');
+    newReason.reason = reason;
+    reason = newReason;
+  }
+  return cb(reason);
+}
+
+function callbackify(original) {
+  if (typeof original !== 'function') {
+    throw new TypeError('The "original" argument must be of type Function');
+  }
+
+  // We DO NOT return the promise as it gives the user a false sense that
+  // the promise is actually somehow related to the callback's execution
+  // and that the callback throwing will reject the promise.
+  function callbackified() {
+    var args = [];
+    for (var i = 0; i < arguments.length; i++) {
+      args.push(arguments[i]);
+    }
+
+    var maybeCb = args.pop();
+    if (typeof maybeCb !== 'function') {
+      throw new TypeError('The last argument must be of type Function');
+    }
+    var self = this;
+    var cb = function() {
+      return maybeCb.apply(self, arguments);
+    };
+    // In true node style we process the callback on `nextTick` with all the
+    // implications (stack, `uncaughtException`, `async_hooks`)
+    original.apply(this, args)
+      .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },
+            function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
+  }
+
+  Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
+  Object.defineProperties(callbackified,
+                          getOwnPropertyDescriptors(original));
+  return callbackified;
+}
+exports.callbackify = callbackify;
diff --git a/test/merkletreejs/node_modules/web3-core/LICENSE b/test/merkletreejs/node_modules/web3-core/LICENSE
new file mode 100644
index 0000000..29a99ab
--- /dev/null
+++ b/test/merkletreejs/node_modules/web3-core/LICENSE
@@ -0,0 +1,14 @@
+This file is part of web3.js.
+
+web3.js is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+web3.js is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with web3.js.  If not, see .
diff --git a/test/merkletreejs/node_modules/web3-core/README.md b/test/merkletreejs/node_modules/web3-core/README.md
new file mode 100644
index 0000000..a5a2110
--- /dev/null
+++ b/test/merkletreejs/node_modules/web3-core/README.md
@@ -0,0 +1,59 @@
+

+ web3.js +

+ +# web3.js - Web3 Core + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-core` package contains core functions for [web3.js][repo] packages. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-core) or using [Yarn](https://yarnpkg.com/package/web3-core) + +### Using NPM + +```bash +npm install web3-core +``` + +### Using Yarn + +```bash +yarn add web3-core +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-core +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-core%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-core +[downloads-image]: https://img.shields.io/npm/dm/web3-core?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.d.ts new file mode 100644 index 0000000..8d9e6a2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.d.ts @@ -0,0 +1,99 @@ +import { Filter, Numbers, Topic, BlockInput, BlockOutput, LogsInput, LogsOutput, Mutable, PostInput, PostOutput, Proof, ReceiptInput, ReceiptOutput, SyncInput, SyncOutput, TransactionInput, TransactionOutput } from 'web3-types'; +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given storage key array values to hex strings. + */ +export declare const inputStorageKeysFormatter: (keys: Array) => string[]; +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given proof response from the node. + */ +export declare const outputProofFormatter: (proof: Proof) => Proof; +/** + * @deprecated Use format function from web3-utils package instead + * Should the format output to a big number + */ +export declare const outputBigIntegerFormatter: (number: Numbers) => number | bigint; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or the predefined block number 'latest', 'pending', 'earliest', 'genesis' + */ +export declare const inputBlockNumberFormatter: (blockNumber: Numbers | undefined) => string | undefined; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or does return the defaultBlock property of the current module + */ +export declare const inputDefaultBlockNumberFormatter: (blockNumber: Numbers | undefined, defaultBlock: Numbers) => string | undefined; +/** + * @deprecated Use format function from web3-utils package instead + * @param address + */ +export declare const inputAddressFormatter: (address: string) => string | never; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export declare const txInputOptionsFormatter: (options: TransactionInput) => Mutable; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export declare const inputCallFormatter: (options: TransactionInput, defaultAccount?: string) => Mutable; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export declare const inputTransactionFormatter: (options: TransactionInput, defaultAccount?: string) => Mutable; +/** + * @deprecated Use format function from web3-utils package instead + * Hex encodes the data passed to eth_sign and personal_sign + */ +export declare const inputSignFormatter: (data: string) => string; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction to its proper values + * @function outputTransactionFormatter + */ +export declare const outputTransactionFormatter: (tx: TransactionInput) => TransactionOutput; +/** + * @deprecated Use format function from web3-utils package instead + * @param topic + */ +export declare const inputTopicFormatter: (topic: Topic) => Topic | null; +/** + * @deprecated Use format function from web3-utils package instead + * @param filter + */ +export declare const inputLogFormatter: (filter: Filter) => Filter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a log + * @function outputLogFormatter + */ +export declare const outputLogFormatter: (log: Partial) => LogsOutput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction receipt to its proper values + */ +export declare const outputTransactionReceiptFormatter: (receipt: ReceiptInput) => ReceiptOutput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a block to its proper values + * @function outputBlockFormatter + */ +export declare const outputBlockFormatter: (block: BlockInput) => BlockOutput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a whisper post and converts all values to HEX + */ +export declare const inputPostFormatter: (post: PostOutput) => PostInput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a received post message + * @function outputPostFormatter + */ +export declare const outputPostFormatter: (post: PostInput) => PostOutput; +/** + * @deprecated Use format function from web3-utils package instead + */ +export declare const outputSyncingFormatter: (result: SyncInput) => SyncOutput; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.js new file mode 100644 index 0000000..ac64cec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.js @@ -0,0 +1,430 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.outputSyncingFormatter = exports.outputPostFormatter = exports.inputPostFormatter = exports.outputBlockFormatter = exports.outputTransactionReceiptFormatter = exports.outputLogFormatter = exports.inputLogFormatter = exports.inputTopicFormatter = exports.outputTransactionFormatter = exports.inputSignFormatter = exports.inputTransactionFormatter = exports.inputCallFormatter = exports.txInputOptionsFormatter = exports.inputAddressFormatter = exports.inputDefaultBlockNumberFormatter = exports.inputBlockNumberFormatter = exports.outputBigIntegerFormatter = exports.outputProofFormatter = exports.inputStorageKeysFormatter = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_eth_iban_1 = require("web3-eth-iban"); +const web3_types_1 = require("web3-types"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +/* eslint-disable deprecation/deprecation */ +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given storage key array values to hex strings. + */ +const inputStorageKeysFormatter = (keys) => keys.map(num => (0, web3_utils_1.numberToHex)(num)); +exports.inputStorageKeysFormatter = inputStorageKeysFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given proof response from the node. + */ +const outputProofFormatter = (proof) => ({ + address: (0, web3_utils_1.toChecksumAddress)(proof.address), + nonce: (0, web3_utils_1.hexToNumberString)(proof.nonce), + balance: (0, web3_utils_1.hexToNumberString)(proof.balance), +}); +exports.outputProofFormatter = outputProofFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Should the format output to a big number + */ +const outputBigIntegerFormatter = (number) => (0, web3_utils_1.toNumber)(number); +exports.outputBigIntegerFormatter = outputBigIntegerFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or the predefined block number 'latest', 'pending', 'earliest', 'genesis' + */ +const inputBlockNumberFormatter = (blockNumber) => { + if ((0, web3_validator_1.isNullish)(blockNumber)) { + return undefined; + } + if (typeof blockNumber === 'string' && (0, web3_validator_1.isBlockTag)(blockNumber)) { + return blockNumber; + } + if (blockNumber === 'genesis') { + return '0x0'; + } + if (typeof blockNumber === 'string' && (0, web3_utils_1.isHexStrict)(blockNumber)) { + return blockNumber.toLowerCase(); + } + return (0, web3_utils_1.numberToHex)(blockNumber); +}; +exports.inputBlockNumberFormatter = inputBlockNumberFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or does return the defaultBlock property of the current module + */ +const inputDefaultBlockNumberFormatter = (blockNumber, defaultBlock) => { + if (!blockNumber) { + return (0, exports.inputBlockNumberFormatter)(defaultBlock); + } + return (0, exports.inputBlockNumberFormatter)(blockNumber); +}; +exports.inputDefaultBlockNumberFormatter = inputDefaultBlockNumberFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * @param address + */ +const inputAddressFormatter = (address) => { + if (web3_eth_iban_1.Iban.isValid(address) && web3_eth_iban_1.Iban.isDirect(address)) { + const iban = new web3_eth_iban_1.Iban(address); + return iban.toAddress().toLowerCase(); + } + if ((0, web3_utils_1.isAddress)(address)) { + return `0x${address.toLowerCase().replace('0x', '')}`; + } + throw new web3_errors_1.FormatterError(`Provided address ${address} is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted.`); +}; +exports.inputAddressFormatter = inputAddressFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +const txInputOptionsFormatter = (options) => { + var _a; + const modifiedOptions = Object.assign({}, options); + if (options.to) { + // it might be contract creation + modifiedOptions.to = (0, exports.inputAddressFormatter)(options.to); + } + if (options.data && options.input) { + throw new web3_errors_1.FormatterError('You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); + } + if (!options.input && options.data) { + modifiedOptions.input = options.data; + delete modifiedOptions.data; + } + if (options.input && !options.input.startsWith('0x')) { + modifiedOptions.input = `0x${options.input}`; + } + if (modifiedOptions.input && !(0, web3_utils_1.isHexStrict)(modifiedOptions.input)) { + throw new web3_errors_1.FormatterError('The input field must be HEX encoded data.'); + } + // allow both + if (options.gas || options.gasLimit) { + modifiedOptions.gas = (0, web3_utils_1.toNumber)((_a = options.gas) !== null && _a !== void 0 ? _a : options.gasLimit); + } + if (options.maxPriorityFeePerGas || options.maxFeePerGas) { + delete modifiedOptions.gasPrice; + } + ['gasPrice', 'gas', 'value', 'maxPriorityFeePerGas', 'maxFeePerGas', 'nonce', 'chainId'] + .filter(key => !(0, web3_validator_1.isNullish)(modifiedOptions[key])) + .forEach(key => { + modifiedOptions[key] = (0, web3_utils_1.numberToHex)(modifiedOptions[key]); + }); + return modifiedOptions; +}; +exports.txInputOptionsFormatter = txInputOptionsFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +const inputCallFormatter = (options, defaultAccount) => { + var _a; + const opts = (0, exports.txInputOptionsFormatter)(options); + const from = (_a = opts.from) !== null && _a !== void 0 ? _a : defaultAccount; + if (from) { + opts.from = (0, exports.inputAddressFormatter)(from); + } + return opts; +}; +exports.inputCallFormatter = inputCallFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +const inputTransactionFormatter = (options, defaultAccount) => { + var _a; + const opts = (0, exports.txInputOptionsFormatter)(options); + // check from, only if not number, or object + if (!(typeof opts.from === 'number') && !(!!opts.from && typeof opts.from === 'object')) { + opts.from = (_a = opts.from) !== null && _a !== void 0 ? _a : defaultAccount; + if (!options.from && !(typeof options.from === 'number')) { + throw new web3_errors_1.FormatterError('The send transactions "from" field must be defined!'); + } + opts.from = (0, exports.inputAddressFormatter)(options.from); + } + return opts; +}; +exports.inputTransactionFormatter = inputTransactionFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Hex encodes the data passed to eth_sign and personal_sign + */ +const inputSignFormatter = (data) => ((0, web3_utils_1.isHexStrict)(data) ? data : (0, web3_utils_1.utf8ToHex)(data)); +exports.inputSignFormatter = inputSignFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction to its proper values + * @function outputTransactionFormatter + */ +const outputTransactionFormatter = (tx) => { + const modifiedTx = Object.assign({}, tx); + if (tx.blockNumber) { + modifiedTx.blockNumber = (0, web3_utils_1.hexToNumber)(tx.blockNumber); + } + if (tx.transactionIndex) { + modifiedTx.transactionIndex = (0, web3_utils_1.hexToNumber)(tx.transactionIndex); + } + modifiedTx.nonce = (0, web3_utils_1.hexToNumber)(tx.nonce); + modifiedTx.gas = (0, web3_utils_1.hexToNumber)(tx.gas); + if (tx.gasPrice) { + modifiedTx.gasPrice = (0, exports.outputBigIntegerFormatter)(tx.gasPrice); + } + if (tx.maxFeePerGas) { + modifiedTx.maxFeePerGas = (0, exports.outputBigIntegerFormatter)(tx.maxFeePerGas); + } + if (tx.maxPriorityFeePerGas) { + modifiedTx.maxPriorityFeePerGas = (0, exports.outputBigIntegerFormatter)(tx.maxPriorityFeePerGas); + } + if (tx.type) { + modifiedTx.type = (0, web3_utils_1.hexToNumber)(tx.type); + } + modifiedTx.value = (0, exports.outputBigIntegerFormatter)(tx.value); + if (tx.to && (0, web3_utils_1.isAddress)(tx.to)) { + // tx.to could be `0x0` or `null` while contract creation + modifiedTx.to = (0, web3_utils_1.toChecksumAddress)(tx.to); + } + else { + modifiedTx.to = undefined; // set to `null` if invalid address + } + if (tx.from) { + modifiedTx.from = (0, web3_utils_1.toChecksumAddress)(tx.from); + } + return modifiedTx; +}; +exports.outputTransactionFormatter = outputTransactionFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * @param topic + */ +// To align with specification we use the type "null" here +// eslint-disable-next-line @typescript-eslint/ban-types +const inputTopicFormatter = (topic) => { + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + if ((0, web3_validator_1.isNullish)(topic)) + return null; + const value = String(topic); + return (0, web3_validator_1.isHex)(value) ? value : (0, web3_utils_1.fromUtf8)(value); +}; +exports.inputTopicFormatter = inputTopicFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * @param filter + */ +const inputLogFormatter = (filter) => { + var _a; + const val = (0, web3_validator_1.isNullish)(filter) + ? {} + : (0, web3_utils_1.mergeDeep)({}, filter); + // If options !== undefined, don't blow out existing data + if ((0, web3_validator_1.isNullish)(val.fromBlock)) { + val.fromBlock = web3_types_1.BlockTags.LATEST; + } + val.fromBlock = (0, exports.inputBlockNumberFormatter)(val.fromBlock); + if (!(0, web3_validator_1.isNullish)(val.toBlock)) { + val.toBlock = (0, exports.inputBlockNumberFormatter)(val.toBlock); + } + // make sure topics, get converted to hex + val.topics = (_a = val.topics) !== null && _a !== void 0 ? _a : []; + val.topics = val.topics.map(topic => Array.isArray(topic) + ? topic.map(exports.inputTopicFormatter) + : (0, exports.inputTopicFormatter)(topic)); + if (val.address) { + val.address = Array.isArray(val.address) + ? val.address.map(addr => (0, exports.inputAddressFormatter)(addr)) + : (0, exports.inputAddressFormatter)(val.address); + } + return val; +}; +exports.inputLogFormatter = inputLogFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a log + * @function outputLogFormatter + */ +const outputLogFormatter = (log) => { + const modifiedLog = Object.assign({}, log); + const logIndex = typeof log.logIndex === 'string' + ? log.logIndex + : (0, web3_utils_1.numberToHex)(log.logIndex); + // generate a custom log id + if (typeof log.blockHash === 'string' && typeof log.transactionHash === 'string') { + const shaId = (0, web3_utils_1.sha3Raw)(`${log.blockHash.replace('0x', '')}${log.transactionHash.replace('0x', '')}${logIndex.replace('0x', '')}`); + modifiedLog.id = `log_${shaId.replace('0x', '').slice(0, 8)}`; + } + else if (!log.id) { + modifiedLog.id = undefined; + } + if (log.blockNumber && (0, web3_utils_1.isHexStrict)(log.blockNumber)) { + modifiedLog.blockNumber = (0, web3_utils_1.hexToNumber)(log.blockNumber); + } + if (log.transactionIndex && (0, web3_utils_1.isHexStrict)(log.transactionIndex)) { + modifiedLog.transactionIndex = (0, web3_utils_1.hexToNumber)(log.transactionIndex); + } + if (log.logIndex && (0, web3_utils_1.isHexStrict)(log.logIndex)) { + modifiedLog.logIndex = (0, web3_utils_1.hexToNumber)(log.logIndex); + } + if (log.address) { + modifiedLog.address = (0, web3_utils_1.toChecksumAddress)(log.address); + } + return modifiedLog; +}; +exports.outputLogFormatter = outputLogFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction receipt to its proper values + */ +const outputTransactionReceiptFormatter = (receipt) => { + if (typeof receipt !== 'object') { + throw new web3_errors_1.FormatterError(`Received receipt is invalid: ${String(receipt)}`); + } + const modifiedReceipt = Object.assign({}, receipt); + if (receipt.blockNumber) { + modifiedReceipt.blockNumber = (0, web3_utils_1.hexToNumber)(receipt.blockNumber); + } + if (receipt.transactionIndex) { + modifiedReceipt.transactionIndex = (0, web3_utils_1.hexToNumber)(receipt.transactionIndex); + } + modifiedReceipt.cumulativeGasUsed = (0, web3_utils_1.hexToNumber)(receipt.cumulativeGasUsed); + modifiedReceipt.gasUsed = (0, web3_utils_1.hexToNumber)(receipt.gasUsed); + if (receipt.logs && Array.isArray(receipt.logs)) { + modifiedReceipt.logs = receipt.logs.map(exports.outputLogFormatter); + } + if (receipt.effectiveGasPrice) { + modifiedReceipt.effectiveGasPrice = (0, web3_utils_1.hexToNumber)(receipt.effectiveGasPrice); + } + if (receipt.contractAddress) { + modifiedReceipt.contractAddress = (0, web3_utils_1.toChecksumAddress)(receipt.contractAddress); + } + if (receipt.status) { + modifiedReceipt.status = Boolean(parseInt(receipt.status, 10)); + } + return modifiedReceipt; +}; +exports.outputTransactionReceiptFormatter = outputTransactionReceiptFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a block to its proper values + * @function outputBlockFormatter + */ +const outputBlockFormatter = (block) => { + const modifiedBlock = Object.assign({}, block); + // transform to number + modifiedBlock.gasLimit = (0, web3_utils_1.hexToNumber)(block.gasLimit); + modifiedBlock.gasUsed = (0, web3_utils_1.hexToNumber)(block.gasUsed); + modifiedBlock.size = (0, web3_utils_1.hexToNumber)(block.size); + modifiedBlock.timestamp = (0, web3_utils_1.hexToNumber)(block.timestamp); + if (block.number) { + modifiedBlock.number = (0, web3_utils_1.hexToNumber)(block.number); + } + if (block.difficulty) { + modifiedBlock.difficulty = (0, exports.outputBigIntegerFormatter)(block.difficulty); + } + if (block.totalDifficulty) { + modifiedBlock.totalDifficulty = (0, exports.outputBigIntegerFormatter)(block.totalDifficulty); + } + if (block.transactions && Array.isArray(block.transactions)) { + modifiedBlock.transactions = block.transactions.map(exports.outputTransactionFormatter); + } + if (block.miner) { + modifiedBlock.miner = (0, web3_utils_1.toChecksumAddress)(block.miner); + } + if (block.baseFeePerGas) { + modifiedBlock.baseFeePerGas = (0, exports.outputBigIntegerFormatter)(block.baseFeePerGas); + } + return modifiedBlock; +}; +exports.outputBlockFormatter = outputBlockFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a whisper post and converts all values to HEX + */ +const inputPostFormatter = (post) => { + var _a; + const modifiedPost = Object.assign({}, post); + if (post.ttl) { + modifiedPost.ttl = (0, web3_utils_1.numberToHex)(post.ttl); + } + if (post.workToProve) { + modifiedPost.workToProve = (0, web3_utils_1.numberToHex)(post.workToProve); + } + if (post.priority) { + modifiedPost.priority = (0, web3_utils_1.numberToHex)(post.priority); + } + // fallback + if (post.topics && !Array.isArray(post.topics)) { + modifiedPost.topics = post.topics ? [post.topics] : []; + } + // format the following options + modifiedPost.topics = (_a = modifiedPost.topics) === null || _a === void 0 ? void 0 : _a.map(topic => topic.startsWith('0x') ? topic : (0, web3_utils_1.fromUtf8)(topic)); + return modifiedPost; +}; +exports.inputPostFormatter = inputPostFormatter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a received post message + * @function outputPostFormatter + */ +const outputPostFormatter = (post) => { + var _a; + const modifiedPost = Object.assign({}, post); + if (post.expiry) { + modifiedPost.expiry = (0, web3_utils_1.hexToNumber)(post.expiry); + } + if (post.sent) { + modifiedPost.sent = (0, web3_utils_1.hexToNumber)(post.sent); + } + if (post.ttl) { + modifiedPost.ttl = (0, web3_utils_1.hexToNumber)(post.ttl); + } + if (post.workProved) { + modifiedPost.workProved = (0, web3_utils_1.hexToNumber)(post.workProved); + } + // post.payloadRaw = post.payload; + // post.payload = utils.hexToAscii(post.payload); + // if (utils.isJson(post.payload)) { + // post.payload = JSON.parse(post.payload); + // } + // format the following options + if (!post.topics) { + modifiedPost.topics = []; + } + modifiedPost.topics = (_a = modifiedPost.topics) === null || _a === void 0 ? void 0 : _a.map(web3_utils_1.toUtf8); + return modifiedPost; +}; +exports.outputPostFormatter = outputPostFormatter; +/** + * @deprecated Use format function from web3-utils package instead + */ +const outputSyncingFormatter = (result) => { + const modifiedResult = Object.assign({}, result); + modifiedResult.startingBlock = (0, web3_utils_1.hexToNumber)(result.startingBlock); + modifiedResult.currentBlock = (0, web3_utils_1.hexToNumber)(result.currentBlock); + modifiedResult.highestBlock = (0, web3_utils_1.hexToNumber)(result.highestBlock); + if (result.knownStates) { + modifiedResult.knownStates = (0, web3_utils_1.hexToNumber)(result.knownStates); + } + if (result.pulledStates) { + modifiedResult.pulledStates = (0, web3_utils_1.hexToNumber)(result.pulledStates); + } + return modifiedResult; +}; +exports.outputSyncingFormatter = outputSyncingFormatter; +//# sourceMappingURL=formatters.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.js.map new file mode 100644 index 0000000..89bbee0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/formatters.js.map @@ -0,0 +1 @@ +{"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,cAAc,CAAC,YAAY,GAAG,IAAA,wBAAW,EAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAC/D,cAAc,CAAC,YAAY,GAAG,IAAA,wBAAW,EAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAE/D,IAAI,MAAM,CAAC,WAAW,EAAE;QACvB,cAAc,CAAC,WAAW,GAAG,IAAA,wBAAW,EAAC,MAAM,CAAC,WAAW,CAAC,CAAC;KAC7D;IAED,IAAI,MAAM,CAAC,YAAY,EAAE;QACxB,cAAc,CAAC,YAAY,GAAG,IAAA,wBAAW,EAAC,MAAM,CAAC,YAAY,CAAC,CAAC;KAC/D;IAED,OAAO,cAAc,CAAC;AACvB,CAAC,CAAC;AAhBW,QAAA,sBAAsB,0BAgBjC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.d.ts new file mode 100644 index 0000000..fb0acd2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.d.ts @@ -0,0 +1,12 @@ +export * from './web3_config.js'; +export * from './web3_request_manager.js'; +export * from './web3_subscription_manager.js'; +export * from './web3_subscriptions.js'; +export * from './web3_context.js'; +export * from './web3_batch_request.js'; +export * from './utils.js'; +export * from './types.js'; +export * from './formatters.js'; +export * from './web3_promi_event.js'; +export * from './web3_event_emitter.js'; +export * as formatters from './formatters.js'; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.js new file mode 100644 index 0000000..4a7ebdb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.js @@ -0,0 +1,59 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatters = void 0; +__exportStar(require("./web3_config.js"), exports); +__exportStar(require("./web3_request_manager.js"), exports); +__exportStar(require("./web3_subscription_manager.js"), exports); +__exportStar(require("./web3_subscriptions.js"), exports); +__exportStar(require("./web3_context.js"), exports); +__exportStar(require("./web3_batch_request.js"), exports); +__exportStar(require("./utils.js"), exports); +__exportStar(require("./types.js"), exports); +__exportStar(require("./formatters.js"), exports); +__exportStar(require("./web3_promi_event.js"), exports); +__exportStar(require("./web3_event_emitter.js"), exports); +// For backward usability export as namespace +exports.formatters = __importStar(require("./formatters.js")); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.js.map new file mode 100644 index 0000000..af75623 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,mDAAiC;AACjC,4DAA0C;AAC1C,iEAA+C;AAC/C,0DAAwC;AACxC,oDAAkC;AAClC,0DAAwC;AACxC,6CAA2B;AAC3B,6CAA2B;AAC3B,kDAAgC;AAChC,wDAAsC;AACtC,0DAAwC;AAExC,6CAA6C;AAC7C,8DAA8C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-core/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.d.ts new file mode 100644 index 0000000..a27a5cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.d.ts @@ -0,0 +1,10 @@ +import { HexString, Transaction } from 'web3-types'; +export declare type TransactionTypeParser = (transaction: Transaction) => HexString | undefined; +export interface Method { + name: string; + call: string; +} +export interface ExtensionObject { + property?: string; + methods: Method[]; +} diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.d.ts new file mode 100644 index 0000000..36d8419 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.d.ts @@ -0,0 +1,9 @@ +import { EIP1193Provider, LegacyRequestProvider, LegacySendAsyncProvider, LegacySendProvider, SupportedProviders, Web3BaseProvider, MetaMaskProvider } from 'web3-types'; +export declare const isWeb3Provider: (provider: SupportedProviders) => provider is Web3BaseProvider; +export declare const isMetaMaskProvider: (provider: SupportedProviders) => provider is MetaMaskProvider; +export declare const isLegacyRequestProvider: (provider: SupportedProviders) => provider is LegacyRequestProvider; +export declare const isEIP1193Provider: (provider: SupportedProviders) => provider is EIP1193Provider; +export declare const isLegacySendProvider: (provider: SupportedProviders) => provider is LegacySendProvider; +export declare const isLegacySendAsyncProvider: (provider: SupportedProviders) => provider is LegacySendAsyncProvider; +export declare const isSupportedProvider: (provider: SupportedProviders) => provider is SupportedProviders; +export declare const isSupportSubscriptions: (provider: SupportedProviders) => boolean; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.js new file mode 100644 index 0000000..0e2d8cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.js @@ -0,0 +1,56 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSupportSubscriptions = exports.isSupportedProvider = exports.isLegacySendAsyncProvider = exports.isLegacySendProvider = exports.isEIP1193Provider = exports.isLegacyRequestProvider = exports.isMetaMaskProvider = exports.isWeb3Provider = void 0; +const web3_types_1 = require("web3-types"); +const isWeb3Provider = (provider) => web3_types_1.Web3BaseProvider.isWeb3Provider(provider); +exports.isWeb3Provider = isWeb3Provider; +const isMetaMaskProvider = (provider) => typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'AsyncFunction' && 'isMetaMask' in provider && provider.isMetaMask; +exports.isMetaMaskProvider = isMetaMaskProvider; +const isLegacyRequestProvider = (provider) => typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'Function'; +exports.isLegacyRequestProvider = isLegacyRequestProvider; +const isEIP1193Provider = (provider) => typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'AsyncFunction'; +exports.isEIP1193Provider = isEIP1193Provider; +const isLegacySendProvider = (provider) => typeof provider !== 'string' && 'send' in provider; +exports.isLegacySendProvider = isLegacySendProvider; +const isLegacySendAsyncProvider = (provider) => typeof provider !== 'string' && 'sendAsync' in provider; +exports.isLegacySendAsyncProvider = isLegacySendAsyncProvider; +const isSupportedProvider = (provider) => provider && + ((0, exports.isWeb3Provider)(provider) || + (0, exports.isEIP1193Provider)(provider) || + (0, exports.isLegacyRequestProvider)(provider) || + (0, exports.isLegacySendAsyncProvider)(provider) || + (0, exports.isLegacySendProvider)(provider)); +exports.isSupportedProvider = isSupportedProvider; +const isSupportSubscriptions = (provider) => { + if (provider && 'supportsSubscriptions' in provider) { + return provider.supportsSubscriptions(); + } + if (provider && typeof provider !== 'string' && 'on' in provider) { + return true; + } + return false; +}; +exports.isSupportSubscriptions = isSupportSubscriptions; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.js.map new file mode 100644 index 0000000..ab7002f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CASoB;AAEb,MAAM,cAAc,GAAG,CAC7B,QAAiC,EACG,EAAE,CAAC,6BAAgB,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAFrE,QAAA,cAAc,kBAEuD;AAE3E,MAAM,kBAAkB,GAAG,CACjC,QAAiC,EACG,EAAE,CACtC,OAAO,QAAQ,KAAK,QAAQ;IAC7B,SAAS,IAAI,QAAQ;IACrB,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,KAAK,eAAe,IAAI,YAAY,IAAI,QAAQ,IAAI,QAAQ,CAAC,UAAU,CAAC;AAL5F,QAAA,kBAAkB,sBAK0E;AAGlG,MAAM,uBAAuB,GAAG,CACtC,QAAiC,EACG,EAAE,CACtC,OAAO,QAAQ,KAAK,QAAQ;IAC5B,SAAS,IAAI,QAAQ;IACrB,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,KAAK,UAAU,CAAC;AALrC,QAAA,uBAAuB,2BAKc;AAE3C,MAAM,iBAAiB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_request.d.ts new file mode 100644 index 0000000..a144bef --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.d.ts @@ -0,0 +1,16 @@ +import { JsonRpcBatchResponse, JsonRpcOptionalRequest, JsonRpcRequest } from 'web3-types'; +import { Web3DeferredPromise } from 'web3-utils'; +import { Web3RequestManager } from './web3_request_manager.js'; +export declare const DEFAULT_BATCH_REQUEST_TIMEOUT = 1000; +export declare class Web3BatchRequest { + private readonly _requestManager; + private readonly _requests; + constructor(requestManager: Web3RequestManager); + get requests(): JsonRpcRequest[]; + add(request: JsonRpcOptionalRequest): Web3DeferredPromise; + execute(options?: { + timeout?: number; + }): Promise>; + private _processBatchRequest; + private _abortAllRequests; +} diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.js new file mode 100644 index 0000000..271a7ef --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.js @@ -0,0 +1,106 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3BatchRequest = exports.DEFAULT_BATCH_REQUEST_TIMEOUT = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +exports.DEFAULT_BATCH_REQUEST_TIMEOUT = 1000; +class Web3BatchRequest { + constructor(requestManager) { + this._requestManager = requestManager; + this._requests = new Map(); + } + get requests() { + return [...this._requests.values()].map(r => r.payload); + } + add(request) { + const payload = web3_utils_1.jsonRpc.toPayload(request); + const promise = new web3_utils_1.Web3DeferredPromise(); + this._requests.set(payload.id, { payload, promise }); + return promise; + } + // eslint-disable-next-line class-methods-use-this + execute(options) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (this.requests.length === 0) { + return Promise.resolve([]); + } + const request = new web3_utils_1.Web3DeferredPromise({ + timeout: (_a = options === null || options === void 0 ? void 0 : options.timeout) !== null && _a !== void 0 ? _a : exports.DEFAULT_BATCH_REQUEST_TIMEOUT, + eagerStart: true, + timeoutMessage: 'Batch request timeout', + }); + this._processBatchRequest(request).catch(err => request.reject(err)); + request.catch((err) => { + if (err instanceof web3_errors_1.OperationTimeoutError) { + this._abortAllRequests('Batch request timeout'); + } + request.reject(err); + }); + return request; + }); + } + _processBatchRequest(promise) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const response = yield this._requestManager.sendBatch([...this._requests.values()].map(r => r.payload)); + if (response.length !== this._requests.size) { + this._abortAllRequests('Invalid batch response'); + throw new web3_errors_1.ResponseError(response, `Batch request size mismatch the results size. Requests: ${this._requests.size}, Responses: ${response.length}`); + } + const requestIds = this.requests + .map(r => r.id) + .map(Number) + .sort((a, b) => a - b); + const responseIds = response + .map(r => r.id) + .map(Number) + .sort((a, b) => a - b); + if (JSON.stringify(requestIds) !== JSON.stringify(responseIds)) { + this._abortAllRequests('Invalid batch response'); + throw new web3_errors_1.ResponseError(response, `Batch request mismatch the results. Requests: [${requestIds.join()}], Responses: [${responseIds.join()}]`); + } + for (const res of response) { + if (web3_utils_1.jsonRpc.isResponseWithResult(res)) { + (_a = this._requests.get(res.id)) === null || _a === void 0 ? void 0 : _a.promise.resolve(res.result); + } + else if (web3_utils_1.jsonRpc.isResponseWithError(res)) { + (_b = this._requests.get(res.id)) === null || _b === void 0 ? void 0 : _b.promise.reject(res.error); + } + } + promise.resolve(response); + }); + } + _abortAllRequests(msg) { + for (const { promise } of this._requests.values()) { + promise.reject(new web3_errors_1.OperationAbortError(msg)); + } + } +} +exports.Web3BatchRequest = Web3BatchRequest; +//# sourceMappingURL=web3_batch_request.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.js.map new file mode 100644 index 0000000..6cc28c3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_batch_request.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_batch_request.js","sourceRoot":"","sources":["../../src/web3_batch_request.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAGF,2CAA0D;AAC1D,6CAAwF;AAG3E,QAAA,6BAA6B,GAAG,IAAI,CAAC;AAElD,MAAa,gBAAgB;IAO5B,YAAmB,cAAkC;QACpD,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;QACtC,IAAI,CAAC,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;IAC5B,CAAC;IAED,IAAW,QAAQ;QAClB,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACzD,CAAC;IAEM,GAAG,CAAyB,OAAwC;QAC1E,MAAM,OAAO,GAAG,oBAAO,CAAC,SAAS,CAAC,OAAO,CAAmB,CAAC;QAC7D,MAAM,OAAO,GAAG,IAAI,gCAAmB,EAAgB,CAAC;QAExD,IAAI,CAA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,GAAG,CAAC,GAAG,CAAC,EAAY,CAAC,0CAAE,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;iBAChE;aACD;YAED,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;;KAC1B;IAEO,iBAAiB,CAAC,GAAW;QACpC,KAAK,MAAM,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE;YAClD,OAAO,CAAC,MAAM,CAAC,IAAI,iCAAmB,CAAC,GAAG,CAAC,CAAC,CAAC;SAC7C;IACF,CAAC;CACD;AAvGD,4CAuGC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.d.ts new file mode 100644 index 0000000..f36f523 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.d.ts @@ -0,0 +1,246 @@ +import { Numbers, HexString, BlockNumberOrTag, Common } from 'web3-types'; +import { TransactionTypeParser } from './types.js'; +import { TransactionBuilder } from './web3_context.js'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export interface Web3ConfigOptions { + handleRevert: boolean; + defaultAccount?: HexString; + defaultBlock: BlockNumberOrTag; + transactionSendTimeout: number; + transactionBlockTimeout: number; + transactionConfirmationBlocks: number; + transactionPollingInterval: number; + transactionPollingTimeout: number; + transactionReceiptPollingInterval?: number; + transactionConfirmationPollingInterval?: number; + blockHeaderTimeout: number; + maxListenersWarningThreshold: number; + contractDataInputFill: 'data' | 'input' | 'both'; + defaultNetworkId?: Numbers; + defaultChain: string; + defaultHardfork: string; + defaultCommon?: Common; + defaultTransactionType: Numbers; + defaultMaxPriorityFeePerGas: Numbers; + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; + }; + transactionBuilder?: TransactionBuilder; + transactionTypeParser?: TransactionTypeParser; +} +declare type ConfigEvent = P extends unknown ? { + name: P; + oldValue: T[P]; + newValue: T[P]; +} : never; +export declare enum Web3ConfigEvent { + CONFIG_CHANGE = "CONFIG_CHANGE" +} +export declare abstract class Web3Config extends Web3EventEmitter<{ + [Web3ConfigEvent.CONFIG_CHANGE]: ConfigEvent; +}> implements Web3ConfigOptions { + config: Web3ConfigOptions; + constructor(options?: Partial); + setConfig(options: Partial): void; + /** + * The `handleRevert` options property returns the revert reason string if enabled for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + * Default is `false`. + * + * `Note`: At the moment `handleRevert` is only supported for `sendTransaction` and not for `sendSignedTransaction` + */ + get handleRevert(): boolean; + /** + * Will set the handleRevert + */ + set handleRevert(val: boolean); + /** + * The `contractDataInputFill` options property will allow you to set the hash of the method signature and encoded parameters to the property + * either `data`, `input` or both within your contract. + * This will affect the contracts send, call and estimateGas methods + * Default is `input`. + */ + get contractDataInputFill(): "input" | "data" | "both"; + /** + * Will set the contractDataInputFill + */ + set contractDataInputFill(val: "input" | "data" | "both"); + /** + * This default address is used as the default `from` property, if no `from` property is specified in for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + */ + get defaultAccount(): string | undefined; + /** + * Will set the default account. + */ + set defaultAccount(val: string | undefined); + /** + * The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is `"latest"`. + * - web3.eth.getBalance() + * - web3.eth.getCode() + * - web3.eth.getTransactionCount() + * - web3.eth.getStorageAt() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + */ + get defaultBlock(): BlockNumberOrTag; + /** + * Will set the default block. + * + * - A block number + * - `"earliest"` - String: The genesis block + * - `"latest"` - String: The latest block (current head of the blockchain) + * - `"pending"` - String: The currently mined block (including pending transactions) + * - `"finalized"` - String: (For POS networks) The finalized block is one which has been accepted as canonical by greater than 2/3 of validators + * - `"safe"` - String: (For POS networks) The safe head block is one which under normal network conditions, is expected to be included in the canonical chain. Under normal network conditions the safe head and the actual tip of the chain will be equivalent (with safe head trailing only by a few seconds). Safe heads will be less likely to be reorged than the proof of work network`s latest blocks. + */ + set defaultBlock(val: BlockNumberOrTag); + /** + * The time used to wait for Ethereum Node to return the sent transaction result. + * Note: If the RPC call stuck at the Node and therefor timed-out, the transaction may still be pending or even mined by the Network. We recommend checking the pending transactions in such a case. + * Default is `750` seconds (12.5 minutes). + */ + get transactionSendTimeout(): number; + /** + * Will set the transactionSendTimeout. + */ + set transactionSendTimeout(val: number); + /** + * The `transactionBlockTimeout` is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. + * Default is `50`. + */ + get transactionBlockTimeout(): number; + /** + * Will set the transactionBlockTimeout. + */ + set transactionBlockTimeout(val: number); + /** + * This defines the number of blocks it requires until a transaction is considered confirmed. + * Default is `24`. + */ + get transactionConfirmationBlocks(): number; + /** + * Will set the transactionConfirmationBlocks. + */ + set transactionConfirmationBlocks(val: number); + /** + * Used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `1000` ms. + */ + get transactionPollingInterval(): number; + /** + * Will set the transactionPollingInterval. + */ + set transactionPollingInterval(val: number); + /** + * Used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times out, the transaction may still be pending. + * Default is `750` seconds (12.5 minutes). + */ + get transactionPollingTimeout(): number; + /** + * Will set the transactionPollingTimeout. + */ + set transactionPollingTimeout(val: number); + /** + * The `transactionPollingInterval` is used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `undefined` + */ + get transactionReceiptPollingInterval(): number | undefined; + /** + * Will set the transactionReceiptPollingInterval + */ + set transactionReceiptPollingInterval(val: number | undefined); + get transactionConfirmationPollingInterval(): number | undefined; + set transactionConfirmationPollingInterval(val: number | undefined); + /** + * The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt. + * Default is `10` seconds. + */ + get blockHeaderTimeout(): number; + /** + * Will set the blockHeaderTimeout + */ + set blockHeaderTimeout(val: number); + /** + * The enableExperimentalFeatures is used to enable trying new experimental features that are still not fully implemented or not fully tested or still have some related issues. + * Default is `false` for every feature. + */ + get enableExperimentalFeatures(): { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; + }; + /** + * Will set the enableExperimentalFeatures + */ + set enableExperimentalFeatures(val: { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; + }); + get maxListenersWarningThreshold(): number; + set maxListenersWarningThreshold(val: number); + get defaultNetworkId(): Numbers | undefined; + set defaultNetworkId(val: Numbers | undefined); + get defaultChain(): string; + set defaultChain(val: string); + /** + * Will return the default hardfork. Default is `london` + * The default hardfork property can be one of the following: + * - `chainstart` + * - `homestead` + * - `dao` + * - `tangerineWhistle` + * - `spuriousDragon` + * - `byzantium` + * - `constantinople` + * - `petersburg` + * - `istanbul` + * - `berlin` + * - `london` + * - 'arrowGlacier', + * - 'tangerineWhistle', + * - 'muirGlacier' + * + */ + get defaultHardfork(): string; + /** + * Will set the default hardfork. + * + */ + set defaultHardfork(val: string); + /** + * + * Will get the default common property + * The default common property does contain the following Common object: + * - `customChain` - `Object`: The custom chain properties + * - `name` - `string`: (optional) The name of the chain + * - `networkId` - `number`: Network ID of the custom chain + * - `chainId` - `number`: Chain ID of the custom chain + * - `baseChain` - `string`: (optional) mainnet, goerli, kovan, rinkeby, or ropsten + * - `hardfork` - `string`: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london + * Default is `undefined`. + * + */ + get defaultCommon(): Common | undefined; + /** + * Will set the default common property + * + */ + set defaultCommon(val: Common | undefined); + get defaultTransactionType(): Numbers; + set defaultTransactionType(val: Numbers); + get defaultMaxPriorityFeePerGas(): Numbers; + set defaultMaxPriorityFeePerGas(val: Numbers); + get transactionBuilder(): TransactionBuilder | undefined; + set transactionBuilder(val: TransactionBuilder | undefined); + get transactionTypeParser(): TransactionTypeParser | undefined; + set transactionTypeParser(val: TransactionTypeParser | undefined); + private _triggerConfigChange; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.js new file mode 100644 index 0000000..9e658e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.js @@ -0,0 +1,401 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3Config = exports.Web3ConfigEvent = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_event_emitter_js_1 = require("./web3_event_emitter.js"); +var Web3ConfigEvent; +(function (Web3ConfigEvent) { + Web3ConfigEvent["CONFIG_CHANGE"] = "CONFIG_CHANGE"; +})(Web3ConfigEvent = exports.Web3ConfigEvent || (exports.Web3ConfigEvent = {})); +class Web3Config extends web3_event_emitter_js_1.Web3EventEmitter { + constructor(options) { + super(); + this.config = { + handleRevert: false, + defaultAccount: undefined, + defaultBlock: 'latest', + transactionBlockTimeout: 50, + transactionConfirmationBlocks: 24, + transactionPollingInterval: 1000, + transactionPollingTimeout: 750 * 1000, + transactionReceiptPollingInterval: undefined, + transactionSendTimeout: 750 * 1000, + transactionConfirmationPollingInterval: undefined, + blockHeaderTimeout: 10, + maxListenersWarningThreshold: 100, + contractDataInputFill: 'data', + defaultNetworkId: undefined, + defaultChain: 'mainnet', + defaultHardfork: 'london', + // TODO - Check if there is a default Common + defaultCommon: undefined, + defaultTransactionType: '0x2', + defaultMaxPriorityFeePerGas: (0, web3_utils_1.toHex)(2500000000), + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: false, + useRpcCallSpecification: false, + }, + transactionBuilder: undefined, + transactionTypeParser: undefined, + }; + this.setConfig(options !== null && options !== void 0 ? options : {}); + } + setConfig(options) { + // TODO: Improve and add key check + const keys = Object.keys(options); + for (const key of keys) { + this._triggerConfigChange(key, options[key]); + } + Object.assign(this.config, options); + } + /** + * The `handleRevert` options property returns the revert reason string if enabled for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + * Default is `false`. + * + * `Note`: At the moment `handleRevert` is only supported for `sendTransaction` and not for `sendSignedTransaction` + */ + get handleRevert() { + return this.config.handleRevert; + } + /** + * Will set the handleRevert + */ + set handleRevert(val) { + this._triggerConfigChange('handleRevert', val); + this.config.handleRevert = val; + } + /** + * The `contractDataInputFill` options property will allow you to set the hash of the method signature and encoded parameters to the property + * either `data`, `input` or both within your contract. + * This will affect the contracts send, call and estimateGas methods + * Default is `input`. + */ + get contractDataInputFill() { + return this.config.contractDataInputFill; + } + /** + * Will set the contractDataInputFill + */ + set contractDataInputFill(val) { + this._triggerConfigChange('contractDataInputFill', val); + this.config.contractDataInputFill = val; + } + /** + * This default address is used as the default `from` property, if no `from` property is specified in for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + */ + get defaultAccount() { + return this.config.defaultAccount; + } + /** + * Will set the default account. + */ + set defaultAccount(val) { + this._triggerConfigChange('defaultAccount', val); + this.config.defaultAccount = val; + } + /** + * The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is `"latest"`. + * - web3.eth.getBalance() + * - web3.eth.getCode() + * - web3.eth.getTransactionCount() + * - web3.eth.getStorageAt() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + */ + get defaultBlock() { + return this.config.defaultBlock; + } + /** + * Will set the default block. + * + * - A block number + * - `"earliest"` - String: The genesis block + * - `"latest"` - String: The latest block (current head of the blockchain) + * - `"pending"` - String: The currently mined block (including pending transactions) + * - `"finalized"` - String: (For POS networks) The finalized block is one which has been accepted as canonical by greater than 2/3 of validators + * - `"safe"` - String: (For POS networks) The safe head block is one which under normal network conditions, is expected to be included in the canonical chain. Under normal network conditions the safe head and the actual tip of the chain will be equivalent (with safe head trailing only by a few seconds). Safe heads will be less likely to be reorged than the proof of work network`s latest blocks. + */ + set defaultBlock(val) { + this._triggerConfigChange('defaultBlock', val); + this.config.defaultBlock = val; + } + /** + * The time used to wait for Ethereum Node to return the sent transaction result. + * Note: If the RPC call stuck at the Node and therefor timed-out, the transaction may still be pending or even mined by the Network. We recommend checking the pending transactions in such a case. + * Default is `750` seconds (12.5 minutes). + */ + get transactionSendTimeout() { + return this.config.transactionSendTimeout; + } + /** + * Will set the transactionSendTimeout. + */ + set transactionSendTimeout(val) { + this._triggerConfigChange('transactionSendTimeout', val); + this.config.transactionSendTimeout = val; + } + /** + * The `transactionBlockTimeout` is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. + * Default is `50`. + */ + get transactionBlockTimeout() { + return this.config.transactionBlockTimeout; + } + /** + * Will set the transactionBlockTimeout. + */ + set transactionBlockTimeout(val) { + this._triggerConfigChange('transactionBlockTimeout', val); + this.config.transactionBlockTimeout = val; + } + /** + * This defines the number of blocks it requires until a transaction is considered confirmed. + * Default is `24`. + */ + get transactionConfirmationBlocks() { + return this.config.transactionConfirmationBlocks; + } + /** + * Will set the transactionConfirmationBlocks. + */ + set transactionConfirmationBlocks(val) { + this._triggerConfigChange('transactionConfirmationBlocks', val); + this.config.transactionConfirmationBlocks = val; + } + /** + * Used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `1000` ms. + */ + get transactionPollingInterval() { + return this.config.transactionPollingInterval; + } + /** + * Will set the transactionPollingInterval. + */ + set transactionPollingInterval(val) { + this._triggerConfigChange('transactionPollingInterval', val); + this.config.transactionPollingInterval = val; + this.transactionReceiptPollingInterval = val; + this.transactionConfirmationPollingInterval = val; + } + /** + * Used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times out, the transaction may still be pending. + * Default is `750` seconds (12.5 minutes). + */ + get transactionPollingTimeout() { + return this.config.transactionPollingTimeout; + } + /** + * Will set the transactionPollingTimeout. + */ + set transactionPollingTimeout(val) { + this._triggerConfigChange('transactionPollingTimeout', val); + this.config.transactionPollingTimeout = val; + } + /** + * The `transactionPollingInterval` is used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `undefined` + */ + get transactionReceiptPollingInterval() { + return this.config.transactionReceiptPollingInterval; + } + /** + * Will set the transactionReceiptPollingInterval + */ + set transactionReceiptPollingInterval(val) { + this._triggerConfigChange('transactionReceiptPollingInterval', val); + this.config.transactionReceiptPollingInterval = val; + } + get transactionConfirmationPollingInterval() { + return this.config.transactionConfirmationPollingInterval; + } + set transactionConfirmationPollingInterval(val) { + this._triggerConfigChange('transactionConfirmationPollingInterval', val); + this.config.transactionConfirmationPollingInterval = val; + } + /** + * The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt. + * Default is `10` seconds. + */ + get blockHeaderTimeout() { + return this.config.blockHeaderTimeout; + } + /** + * Will set the blockHeaderTimeout + */ + set blockHeaderTimeout(val) { + this._triggerConfigChange('blockHeaderTimeout', val); + this.config.blockHeaderTimeout = val; + } + /** + * The enableExperimentalFeatures is used to enable trying new experimental features that are still not fully implemented or not fully tested or still have some related issues. + * Default is `false` for every feature. + */ + get enableExperimentalFeatures() { + return this.config.enableExperimentalFeatures; + } + /** + * Will set the enableExperimentalFeatures + */ + set enableExperimentalFeatures(val) { + this._triggerConfigChange('enableExperimentalFeatures', val); + this.config.enableExperimentalFeatures = val; + } + get maxListenersWarningThreshold() { + return this.config.maxListenersWarningThreshold; + } + set maxListenersWarningThreshold(val) { + this._triggerConfigChange('maxListenersWarningThreshold', val); + this.setMaxListenerWarningThreshold(val); + this.config.maxListenersWarningThreshold = val; + } + get defaultNetworkId() { + return this.config.defaultNetworkId; + } + set defaultNetworkId(val) { + this._triggerConfigChange('defaultNetworkId', val); + this.config.defaultNetworkId = val; + } + get defaultChain() { + return this.config.defaultChain; + } + set defaultChain(val) { + if (!(0, web3_utils_1.isNullish)(this.config.defaultCommon) && + !(0, web3_utils_1.isNullish)(this.config.defaultCommon.baseChain) && + val !== this.config.defaultCommon.baseChain) + throw new web3_errors_1.ConfigChainMismatchError(this.config.defaultChain, val); + this._triggerConfigChange('defaultChain', val); + this.config.defaultChain = val; + } + /** + * Will return the default hardfork. Default is `london` + * The default hardfork property can be one of the following: + * - `chainstart` + * - `homestead` + * - `dao` + * - `tangerineWhistle` + * - `spuriousDragon` + * - `byzantium` + * - `constantinople` + * - `petersburg` + * - `istanbul` + * - `berlin` + * - `london` + * - 'arrowGlacier', + * - 'tangerineWhistle', + * - 'muirGlacier' + * + */ + get defaultHardfork() { + return this.config.defaultHardfork; + } + /** + * Will set the default hardfork. + * + */ + set defaultHardfork(val) { + if (!(0, web3_utils_1.isNullish)(this.config.defaultCommon) && + !(0, web3_utils_1.isNullish)(this.config.defaultCommon.hardfork) && + val !== this.config.defaultCommon.hardfork) + throw new web3_errors_1.ConfigHardforkMismatchError(this.config.defaultCommon.hardfork, val); + this._triggerConfigChange('defaultHardfork', val); + this.config.defaultHardfork = val; + } + /** + * + * Will get the default common property + * The default common property does contain the following Common object: + * - `customChain` - `Object`: The custom chain properties + * - `name` - `string`: (optional) The name of the chain + * - `networkId` - `number`: Network ID of the custom chain + * - `chainId` - `number`: Chain ID of the custom chain + * - `baseChain` - `string`: (optional) mainnet, goerli, kovan, rinkeby, or ropsten + * - `hardfork` - `string`: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london + * Default is `undefined`. + * + */ + get defaultCommon() { + return this.config.defaultCommon; + } + /** + * Will set the default common property + * + */ + set defaultCommon(val) { + // validation check if default hardfork is set and matches defaultCommon hardfork + if (!(0, web3_utils_1.isNullish)(this.config.defaultHardfork) && + !(0, web3_utils_1.isNullish)(val) && + !(0, web3_utils_1.isNullish)(val.hardfork) && + this.config.defaultHardfork !== val.hardfork) + throw new web3_errors_1.ConfigHardforkMismatchError(this.config.defaultHardfork, val.hardfork); + if (!(0, web3_utils_1.isNullish)(this.config.defaultChain) && + !(0, web3_utils_1.isNullish)(val) && + !(0, web3_utils_1.isNullish)(val.baseChain) && + this.config.defaultChain !== val.baseChain) + throw new web3_errors_1.ConfigChainMismatchError(this.config.defaultChain, val.baseChain); + this._triggerConfigChange('defaultCommon', val); + this.config.defaultCommon = val; + } + get defaultTransactionType() { + return this.config.defaultTransactionType; + } + set defaultTransactionType(val) { + this._triggerConfigChange('defaultTransactionType', val); + this.config.defaultTransactionType = val; + } + get defaultMaxPriorityFeePerGas() { + return this.config.defaultMaxPriorityFeePerGas; + } + set defaultMaxPriorityFeePerGas(val) { + this._triggerConfigChange('defaultMaxPriorityFeePerGas', val); + this.config.defaultMaxPriorityFeePerGas = val; + } + get transactionBuilder() { + return this.config.transactionBuilder; + } + set transactionBuilder(val) { + this._triggerConfigChange('transactionBuilder', val); + this.config.transactionBuilder = val; + } + get transactionTypeParser() { + return this.config.transactionTypeParser; + } + set transactionTypeParser(val) { + this._triggerConfigChange('transactionTypeParser', val); + this.config.transactionTypeParser = val; + } + _triggerConfigChange(config, newValue) { + this.emit(Web3ConfigEvent.CONFIG_CHANGE, { + name: config, + oldValue: this.config[config], + newValue, + }); + } +} +exports.Web3Config = Web3Config; +//# sourceMappingURL=web3_config.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.js.map new file mode 100644 index 0000000..5839123 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_config.js","sourceRoot":"","sources":["../../src/web3_config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,6CAAoF;AACpF,2CAA8C;AAI9C,mEAA2D;AAqC3D,IAAY,eAEX;AAFD,WAAY,eAAe;IAC1B,kDAA+B,CAAA;AAChC,CAAC,EAFW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QAE1B;AAED,MAAsB,UACrB,SAAQ,wCAAqF;IAgC7F,YAAmB,OAAoC;QACtD,KAAK,EAAE,CAAC;QA9BF,WAAM,GAAsB;YAClC,YAAY,EAAE,KAAK;YACnB,cAAc,EAAE,SAAS;YACzB,YAAY,EAAE,QAAQ;YACtB,uBAAuB,EAAE,EAAE;YAC3B,6BAA6B,EAAE,EAAE;YACjC,0BAA0B,EAAE,IAAI;YAChC,yBAAyB,EAAE,GAAG,GAAG,IAAI;YACrC,iCAAiC,EAAE,SAAS;YAC5C,sBAAsB,EAAE,GAAG,GAAG,IAAI;YAClC,sCAAsC,EAAE,SAAS;YACjD,kBAAkB,EAAE,EAAE;YACtB,4BAA4B,EAAE,GAAG;YACjC,qBAAqB,EAAE,MAAM;YAC7B,gBAAgB,EAAE,SAAS;YAC3B,YAAY,EAAE,SAAS;YACvB,eAAe,EAAE,QAAQ;YACzB,4CAA4C;YAC5C,aAAa,EAAE,SAAS;YACxB,sBAAsB,EAAE,KAAK;YAC7B,2BAA2B,EAAE,IAAA,kBAAK,EAAC,UAAU,CAAC;YAC9C,0BAA0B,EAAE;gBAC3B,uCAAuC,EAAE,KAAK;gBAC9C,uBAAuB,EAAE,KAAK;aAC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,CAAC,oBAAoB,EAAE,GAAG,CAAC,CAAC;QACrD,IAAI,CAAC,MAAM,CAAC,kBAAkB,GAAG,GAAG,CAAC;IACtC,CAAC;IAED,IAAW,qBAAqB;QAC/B,OAAO,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC;IAC1C,CAAC;IAED,IAAW,qBAAqB,CAAC,GAAG;QACnC,IAAI,CAAC,oBAAoB,CAAC,uBAAuB,EAAE,GAAG,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,CAAC,qBAAqB,GAAG,GAAG,CAAC;IACzC,CAAC;IAEO,oBAAoB,CAC3B,MAAS,EACT,QAA8B;QAE9B,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,aAAa,EAAE;YACxC,IAAI,EAAE,MAAM;YACZ,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;YAC7B,QAAQ;SAC0B,CAAC,CAAC;IACtC,CAAC;CACD;AAzbD,gCAybC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.d.ts new file mode 100644 index 0000000..d63bd45 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.d.ts @@ -0,0 +1,210 @@ +import { EthExecutionAPI, HexString, Numbers, SupportedProviders, Transaction, Web3AccountProvider, Web3APISpec, Web3BaseProvider, Web3BaseWallet, Web3BaseWalletAccount } from 'web3-types'; +import { BaseTransaction } from 'web3-eth-accounts'; +import { ExtensionObject } from './types.js'; +import { Web3BatchRequest } from './web3_batch_request.js'; +import { Web3Config, Web3ConfigOptions } from './web3_config.js'; +import { Web3RequestManager } from './web3_request_manager.js'; +import { Web3SubscriptionConstructor } from './web3_subscriptions.js'; +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +export declare type Web3ContextObject; +} = any> = { + config: Web3ConfigOptions; + provider?: SupportedProviders | string; + requestManager: Web3RequestManager; + subscriptionManager?: Web3SubscriptionManager | undefined; + registeredSubscriptions?: RegisteredSubs; + providers: typeof Web3RequestManager.providers; + accountProvider?: Web3AccountProvider; + wallet?: Web3BaseWallet; +}; +export declare type Web3ContextInitOptions; +} = any> = { + config?: Partial; + provider?: SupportedProviders | string; + requestManager?: Web3RequestManager; + subscriptionManager?: Web3SubscriptionManager | undefined; + registeredSubscriptions?: RegisteredSubs; + accountProvider?: Web3AccountProvider; + wallet?: Web3BaseWallet; +}; +export declare type Web3ContextConstructor = new (...args: [...extras: T2, context: Web3ContextObject]) => T; +export declare type Web3ContextFactory = Web3ContextConstructor & { + fromContextObject(this: Web3ContextConstructor, contextObject: Web3ContextObject): T; +}; +export declare class Web3Context; +} = any> extends Web3Config { + static readonly providers: { + HttpProvider: import("web3-types").Web3BaseProviderConstructor; + WebsocketProvider: import("web3-types").Web3BaseProviderConstructor; + }; + static givenProvider?: SupportedProviders; + readonly providers: { + HttpProvider: import("web3-types").Web3BaseProviderConstructor; + WebsocketProvider: import("web3-types").Web3BaseProviderConstructor; + }; + protected _requestManager: Web3RequestManager; + protected _subscriptionManager: Web3SubscriptionManager; + protected _accountProvider?: Web3AccountProvider; + protected _wallet?: Web3BaseWallet; + constructor(providerOrContext?: string | SupportedProviders | Web3ContextInitOptions); + get requestManager(): Web3RequestManager; + /** + * Will return the current subscriptionManager ({@link Web3SubscriptionManager}) + */ + get subscriptionManager(): Web3SubscriptionManager; + get wallet(): Web3BaseWallet | undefined; + get accountProvider(): Web3AccountProvider | undefined; + static fromContextObject(this: Web3ContextConstructor, ...args: [Web3ContextObject, ...T3]): T; + getContextObject(): Web3ContextObject; + /** + * Use to create new object of any type extended by `Web3Context` + * and link it to current context. This can be used to initiate a global context object + * and then use it to create new objects of any type extended by `Web3Context`. + */ + use(ContextRef: Web3ContextConstructor, ...args: [...T2]): T; + /** + * Link current context to another context. + */ + link(parentContext: T): void; + registerPlugin(plugin: Web3PluginBase): void; + /** + * Will return the current provider. + * + * @returns Returns the current provider + * @example + * ```ts + * const web3 = new Web3Context("http://localhost:8545"); + * console.log(web3.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get provider(): Web3BaseProvider | undefined; + /** + * Will set the current provider. + * + * @param provider - The provider to set + * + * Accepted providers are of type {@link SupportedProviders} + * @example + * ```ts + * const web3Context = new web3ContextContext("http://localhost:8545"); + * web3Context.provider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set provider(provider: SupportedProviders | string | undefined); + /** + * Will return the current provider. (The same as `provider`) + * + * @returns Returns the current provider + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * console.log(web3Context.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get currentProvider(): Web3BaseProvider | undefined; + /** + * Will set the current provider. (The same as `provider`) + * + * @param provider - {@link SupportedProviders} The provider to set + * + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * web3Context.currentProvider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set currentProvider(provider: SupportedProviders | string | undefined); + /** + * Will return the givenProvider if available. + * + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise `undefined`. + */ + get givenProvider(): SupportedProviders | undefined; + /** + * Will set the provider. + * + * @param provider - {@link SupportedProviders} The provider to set + * @returns Returns true if the provider was set + */ + setProvider(provider?: SupportedProviders | string): boolean; + /** + * Will return the {@link Web3BatchRequest} constructor. + */ + get BatchRequest(): new () => Web3BatchRequest; + /** + * This method allows extending the web3 modules. + * Note: This method is only for backward compatibility, and It is recommended to use Web3 v4 Plugin feature for extending web3.js functionality if you are developing some thing new. + */ + extend(extendObj: ExtensionObject): this; +} +/** + * Extend this class when creating a plugin that either doesn't require {@link EthExecutionAPI}, + * or interacts with a RPC node that doesn't fully implement {@link EthExecutionAPI}. + * + * To add type support for RPC methods to the {@link Web3RequestManager}, + * define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: + * + * @example + * ```ts + * type CustomRpcApi = { + * custom_rpc_method: () => string; + * custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; + * }; + * + * class CustomPlugin extends Web3PluginBase {...} + * ``` + */ +export declare abstract class Web3PluginBase extends Web3Context { + abstract pluginNamespace: string; + protected registerNewTransactionType>(type: Numbers, txClass: NewTxTypeClass): void; +} +/** +* Extend this class when creating a plugin that makes use of {@link EthExecutionAPI}, +* or depends on other Web3 packages (such as `web3-eth-contract`) that depend on {@link EthExecutionAPI}. +* +* To add type support for RPC methods to the {@link Web3RequestManager} (in addition to {@link EthExecutionAPI}), +* define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: +* +* @example +* ```ts +* type CustomRpcApi = { +* custom_rpc_method: () => string; +* custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; +* }; +* +* class CustomPlugin extends Web3PluginBase {...} +* ``` +*/ +export declare abstract class Web3EthPluginBase extends Web3PluginBase { +} +export declare type TransactionBuilder = (options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; +}) => Promise; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.js new file mode 100644 index 0000000..32bee21 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.js @@ -0,0 +1,317 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3EthPluginBase = exports.Web3PluginBase = exports.Web3Context = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line max-classes-per-file +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_eth_accounts_1 = require("web3-eth-accounts"); +const utils_js_1 = require("./utils.js"); +const web3_batch_request_js_1 = require("./web3_batch_request.js"); +// eslint-disable-next-line import/no-cycle +const web3_config_js_1 = require("./web3_config.js"); +const web3_request_manager_js_1 = require("./web3_request_manager.js"); +const web3_subscription_manager_js_1 = require("./web3_subscription_manager.js"); +class Web3Context extends web3_config_js_1.Web3Config { + constructor(providerOrContext) { + var _a; + super(); + this.providers = web3_request_manager_js_1.Web3RequestManager.providers; + // If "providerOrContext" is provided as "string" or an objects matching "SupportedProviders" interface + if ((0, web3_utils_1.isNullish)(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() !== '') || + (0, utils_js_1.isSupportedProvider)(providerOrContext)) { + this._requestManager = new web3_request_manager_js_1.Web3RequestManager(providerOrContext); + this._subscriptionManager = new web3_subscription_manager_js_1.Web3SubscriptionManager(this._requestManager, {}); + return; + } + const { config, provider, requestManager, subscriptionManager, registeredSubscriptions, accountProvider, wallet, } = providerOrContext; + this.setConfig(config !== null && config !== void 0 ? config : {}); + this._requestManager = + requestManager !== null && requestManager !== void 0 ? requestManager : new web3_request_manager_js_1.Web3RequestManager(provider, (_a = config === null || config === void 0 ? void 0 : config.enableExperimentalFeatures) === null || _a === void 0 ? void 0 : _a.useSubscriptionWhenCheckingBlockTimeout); + if (subscriptionManager) { + this._subscriptionManager = subscriptionManager; + } + else { + this._subscriptionManager = new web3_subscription_manager_js_1.Web3SubscriptionManager(this.requestManager, registeredSubscriptions !== null && registeredSubscriptions !== void 0 ? registeredSubscriptions : {}); + } + if (accountProvider) { + this._accountProvider = accountProvider; + } + if (wallet) { + this._wallet = wallet; + } + } + get requestManager() { + return this._requestManager; + } + /** + * Will return the current subscriptionManager ({@link Web3SubscriptionManager}) + */ + get subscriptionManager() { + return this._subscriptionManager; + } + get wallet() { + return this._wallet; + } + get accountProvider() { + return this._accountProvider; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromContextObject(...args) { + return new this(...args.reverse()); + } + getContextObject() { + var _a; + return { + config: this.config, + provider: this.provider, + requestManager: this.requestManager, + subscriptionManager: this.subscriptionManager, + registeredSubscriptions: (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.registeredSubscriptions, + providers: this.providers, + wallet: this.wallet, + accountProvider: this.accountProvider, + }; + } + /** + * Use to create new object of any type extended by `Web3Context` + * and link it to current context. This can be used to initiate a global context object + * and then use it to create new objects of any type extended by `Web3Context`. + */ + use(ContextRef, ...args) { + const newContextChild = new ContextRef(...[...args, this.getContextObject()]); + this.on(web3_config_js_1.Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + newContextChild.setConfig({ [event.name]: event.newValue }); + }); + return newContextChild; + } + /** + * Link current context to another context. + */ + link(parentContext) { + this.setConfig(parentContext.config); + this._requestManager = parentContext.requestManager; + this.provider = parentContext.provider; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this._subscriptionManager = parentContext.subscriptionManager; + this._wallet = parentContext.wallet; + this._accountProvider = parentContext._accountProvider; + parentContext.on(web3_config_js_1.Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.setConfig({ [event.name]: event.newValue }); + }); + } + // eslint-disable-next-line no-use-before-define + registerPlugin(plugin) { + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + if (this[plugin.pluginNamespace] !== undefined) + throw new web3_errors_1.ExistingPluginNamespaceError(plugin.pluginNamespace); + const _pluginObject = { + [plugin.pluginNamespace]: plugin, + }; + _pluginObject[plugin.pluginNamespace].link(this); + Object.assign(this, _pluginObject); + } + /** + * Will return the current provider. + * + * @returns Returns the current provider + * @example + * ```ts + * const web3 = new Web3Context("http://localhost:8545"); + * console.log(web3.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get provider() { + return this.currentProvider; + } + /** + * Will set the current provider. + * + * @param provider - The provider to set + * + * Accepted providers are of type {@link SupportedProviders} + * @example + * ```ts + * const web3Context = new web3ContextContext("http://localhost:8545"); + * web3Context.provider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set provider(provider) { + this.requestManager.setProvider(provider); + } + /** + * Will return the current provider. (The same as `provider`) + * + * @returns Returns the current provider + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * console.log(web3Context.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get currentProvider() { + return this.requestManager.provider; + } + /** + * Will set the current provider. (The same as `provider`) + * + * @param provider - {@link SupportedProviders} The provider to set + * + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * web3Context.currentProvider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set currentProvider(provider) { + this.requestManager.setProvider(provider); + } + /** + * Will return the givenProvider if available. + * + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise `undefined`. + */ + // eslint-disable-next-line class-methods-use-this + get givenProvider() { + return Web3Context.givenProvider; + } + /** + * Will set the provider. + * + * @param provider - {@link SupportedProviders} The provider to set + * @returns Returns true if the provider was set + */ + setProvider(provider) { + this.provider = provider; + return true; + } + /** + * Will return the {@link Web3BatchRequest} constructor. + */ + get BatchRequest() { + return web3_batch_request_js_1.Web3BatchRequest.bind(undefined, this._requestManager); + } + /** + * This method allows extending the web3 modules. + * Note: This method is only for backward compatibility, and It is recommended to use Web3 v4 Plugin feature for extending web3.js functionality if you are developing some thing new. + */ + extend(extendObj) { + var _a; + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + if (extendObj.property && !this[extendObj.property]) + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + this[extendObj.property] = {}; + (_a = extendObj.methods) === null || _a === void 0 ? void 0 : _a.forEach(element => { + const method = (...givenParams) => __awaiter(this, void 0, void 0, function* () { + return this.requestManager.send({ + method: element.call, + params: givenParams, + }); + }); + if (extendObj.property) + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + this[extendObj.property][element.name] = method; + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + else + this[element.name] = method; + }); + return this; + } +} +exports.Web3Context = Web3Context; +Web3Context.providers = web3_request_manager_js_1.Web3RequestManager.providers; +/** + * Extend this class when creating a plugin that either doesn't require {@link EthExecutionAPI}, + * or interacts with a RPC node that doesn't fully implement {@link EthExecutionAPI}. + * + * To add type support for RPC methods to the {@link Web3RequestManager}, + * define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: + * + * @example + * ```ts + * type CustomRpcApi = { + * custom_rpc_method: () => string; + * custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; + * }; + * + * class CustomPlugin extends Web3PluginBase {...} + * ``` + */ +class Web3PluginBase extends Web3Context { + // eslint-disable-next-line class-methods-use-this + registerNewTransactionType(type, txClass) { + web3_eth_accounts_1.TransactionFactory.registerTransactionType(type, txClass); + } +} +exports.Web3PluginBase = Web3PluginBase; +/** +* Extend this class when creating a plugin that makes use of {@link EthExecutionAPI}, +* or depends on other Web3 packages (such as `web3-eth-contract`) that depend on {@link EthExecutionAPI}. +* +* To add type support for RPC methods to the {@link Web3RequestManager} (in addition to {@link EthExecutionAPI}), +* define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: +* +* @example +* ```ts +* type CustomRpcApi = { +* custom_rpc_method: () => string; +* custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; +* }; +* +* class CustomPlugin extends Web3PluginBase {...} +* ``` +*/ +class Web3EthPluginBase extends Web3PluginBase { +} +exports.Web3EthPluginBase = Web3EthPluginBase; +//# sourceMappingURL=web3_context.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.js.map new file mode 100644 index 0000000..16c847a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_context.js","sourceRoot":"","sources":["../../src/web3_context.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,gDAAgD;AAChD,6CAA2D;AAM3D,2CAAuC;AACvC,yDAAwE;AACxE,yCAAiD;AAGjD,mEAA2D;AAC3D,2CAA2C;AAC3C,qDAAkF;AAClF,uEAA+D;AAE/D,iFAAyE;AAkDzE,MAAa,WAMX,SAAQ,2BAAU;IASnB,YACC,iBAG8C;;QAE9C,KAAK,EAAE,CAAC;QAZO,cAAS,GAAG,4CAAkB,CAAC,SAAS,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AAC,IAAI,CAAC,GAAG,MAAM,CAAC;QAClC,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACb,CAAC;;AAlTF,kCAmTC;AA5SuB,qBAAS,GAAG,4CAAkB,CAAC,SAAS,CAAC;AA8SjE;;;;;;;;;;;;;;;;GAgBG;AACF,MAAsB,cAErB,SAAQ,WAAgB;IAGzB,kDAAkD;IACxC,0BAA0B,CAAyD,IAAa,EAAE,OAAuB;QAChI,sCAAkB,CAAC,uBAAuB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;CACD;AATA,wCASA;AAED;;;;;;;;;;;;;;;;EAgBE;AACF,MAAsB,iBAAqD,SAAQ,cAElF;CAAG;AAFJ,8CAEI"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.d.ts new file mode 100644 index 0000000..b4dddb4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.d.ts @@ -0,0 +1,23 @@ +import { EventEmitter } from 'web3-utils'; +export declare type Web3EventMap = Record; +export declare type Web3EventKey = string & keyof T; +export declare type Web3EventCallback = (params: T) => void | Promise; +export interface Web3Emitter { + on>(eventName: K, fn: Web3EventCallback): void; + once>(eventName: K, fn: Web3EventCallback): void; + off>(eventName: K, fn: Web3EventCallback): void; + emit>(eventName: K, params: T[K]): void; +} +export declare class Web3EventEmitter implements Web3Emitter { + private readonly _emitter; + on>(eventName: K, fn: Web3EventCallback): void; + once>(eventName: K, fn: Web3EventCallback): void; + off>(eventName: K, fn: Web3EventCallback): void; + emit>(eventName: K, params: T[K]): void; + listenerCount>(eventName: K): number; + listeners>(eventName: K): Function[]; + eventNames(): (string | symbol)[]; + removeAllListeners(): EventEmitter; + setMaxListenerWarningThreshold(maxListenersWarningThreshold: number): void; + getMaxListeners(): number; +} diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.js new file mode 100644 index 0000000..c7fb8a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.js @@ -0,0 +1,60 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3EventEmitter = void 0; +const web3_utils_1 = require("web3-utils"); +class Web3EventEmitter { + constructor() { + this._emitter = new web3_utils_1.EventEmitter(); + } + on(eventName, fn) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.on(eventName, fn); + } + once(eventName, fn) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.once(eventName, fn); + } + off(eventName, fn) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.off(eventName, fn); + } + emit(eventName, params) { + this._emitter.emit(eventName, params); + } + listenerCount(eventName) { + return this._emitter.listenerCount(eventName); + } + listeners(eventName) { + return this._emitter.listeners(eventName); + } + eventNames() { + return this._emitter.eventNames(); + } + removeAllListeners() { + return this._emitter.removeAllListeners(); + } + setMaxListenerWarningThreshold(maxListenersWarningThreshold) { + this._emitter.setMaxListeners(maxListenersWarningThreshold); + } + getMaxListeners() { + return this._emitter.getMaxListeners(); + } +} +exports.Web3EventEmitter = Web3EventEmitter; +//# sourceMappingURL=web3_event_emitter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.js.map new file mode 100644 index 0000000..28ffbcf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_event_emitter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_event_emitter.js","sourceRoot":"","sources":["../../src/web3_event_emitter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAA0C;AAY1C,MAAa,gBAAgB;IAA7B;QACkB,aAAQ,GAAG,IAAI,yBAAY,EAAE,CAAC;IA0ChD,CAAC;IAxCO,EAAE,CAA4B,SAAY,EAAE,EAA2B;QAC7E,kEAAkE;QAClE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACjC,CAAC;IAEM,IAAI,CAA4B,SAAY,EAAE,EAA2B;QAC/E,kEAAkE;QAClE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAEM,GAAG,CAA4B,SAAY,EAAE,EAA2B;QAC9E,kEAAkE;QAClE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IAClC,CAAC;IAEM,IAAI,CAA4B,SAAY,EAAE,MAAY;QAChE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;IACvC,CAAC;IAEM,aAAa,CAA4B,SAAY;QAC3D,OAAO,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;IAC/C,CAAC;IAEM,SAAS,CAA4B,SAAY;QACvD,OAAO,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC3C,CAAC;IAEM,UAAU;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC;IAEM,kBAAkB;QACxB,OAAO,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC;IAC3C,CAAC;IACM,8BAA8B,CAAC,4BAAoC;QACzE,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,4BAA4B,CAAC,CAAC;IAC7D,CAAC;IACM,eAAe;QACrB,OAAO,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC;IACxC,CAAC;CACD;AA3CD,4CA2CC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.d.ts new file mode 100644 index 0000000..47e475f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.d.ts @@ -0,0 +1,12 @@ +import { Web3EventCallback, Web3EventEmitter, Web3EventKey, Web3EventMap } from './web3_event_emitter.js'; +export declare type PromiseExecutor = (resolve: (data: T) => void, reject: (reason: unknown) => void) => void; +export declare class Web3PromiEvent extends Web3EventEmitter implements Promise { + private readonly _promise; + constructor(executor: PromiseExecutor); + [Symbol.toStringTag]: 'Promise'; + then(onfulfilled?: ((value: ResolveType) => TResult1 | PromiseLike) | undefined, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | undefined): Promise; + catch(onrejected?: ((reason: unknown) => TResult | PromiseLike) | undefined): Promise; + finally(onfinally?: (() => void) | undefined): Promise; + on>(eventName: K, fn: Web3EventCallback): this; + once>(eventName: K, fn: Web3EventCallback): this; +} diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.js new file mode 100644 index 0000000..0cd4829 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.js @@ -0,0 +1,65 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3PromiEvent = void 0; +const web3_event_emitter_js_1 = require("./web3_event_emitter.js"); +class Web3PromiEvent extends web3_event_emitter_js_1.Web3EventEmitter { + constructor(executor) { + super(); + // public tag to treat object as promise by different libs + // eslint-disable-next-line @typescript-eslint/prefer-as-const + this[_a] = 'Promise'; + this._promise = new Promise(executor); + } + then(onfulfilled, onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.then(onfulfilled, onrejected); + }); + } + catch(onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.catch(onrejected); + }); + } + finally(onfinally) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.finally(onfinally); + }); + } + on(eventName, fn) { + super.on(eventName, fn); + return this; + } + once(eventName, fn) { + super.once(eventName, fn); + return this; + } +} +exports.Web3PromiEvent = Web3PromiEvent; +_a = Symbol.toStringTag; +//# sourceMappingURL=web3_promi_event.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.js.map new file mode 100644 index 0000000..bd1b9c1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_promi_event.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_promi_event.js","sourceRoot":"","sources":["../../src/web3_promi_event.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;AAEF,mEAKiC;AAOjC,MAAa,cACZ,SAAQ,wCAA0B;IAKlC,YAAmB,QAAsC;QACxD,KAAK,EAAE,CAAC;QAIT,0DAA0D;QAC1D,8DAA8D;QACvD,QAAoB,GAAc,SAAS,CAAC;QALlD,IAAI,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAc,QAAQ,CAAC,CAAC;IACpD,CAAC;IAMY,IAAI,CAChB,WAAoF,EACpF,UAAgF;;YAEhF,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACpD,CAAC;KAAA;IAEY,KAAK,CACjB,UAA8E;;YAE9E,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACxC,CAAC;KAAA;IAEY,OAAO,CAAC,SAAoC;;YACxD,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACzC,CAAC;KAAA;IAEM,EAAE,CACR,SAAY,EACZ,EAAkC;QAElC,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QAExB,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,IAAI,CACV,SAAY,EACZ,EAAkC;QAElC,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QAE1B,OAAO,IAAI,CAAC;IACb,CAAC;CACD;AAjDD,wCAiDC;KApCQ,MAAM,CAAC,WAAW"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.d.ts new file mode 100644 index 0000000..a48bc95 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.d.ts @@ -0,0 +1,59 @@ +import { EthExecutionAPI, JsonRpcBatchRequest, JsonRpcBatchResponse, SupportedProviders, Web3APIMethod, Web3APIRequest, Web3APIReturnType, Web3APISpec, Web3BaseProviderConstructor } from 'web3-types'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export declare enum Web3RequestManagerEvent { + PROVIDER_CHANGED = "PROVIDER_CHANGED", + BEFORE_PROVIDER_CHANGE = "BEFORE_PROVIDER_CHANGE" +} +export declare class Web3RequestManager extends Web3EventEmitter<{ + [key in Web3RequestManagerEvent]: SupportedProviders | undefined; +}> { + private _provider?; + private readonly useRpcCallSpecification?; + constructor(provider?: SupportedProviders | string, useRpcCallSpecification?: boolean); + /** + * Will return all available providers + */ + static get providers(): { + HttpProvider: Web3BaseProviderConstructor; + WebsocketProvider: Web3BaseProviderConstructor; + }; + /** + * Will return the current provider. + * + * @returns Returns the current provider + */ + get provider(): SupportedProviders | undefined; + /** + * Will return all available providers + */ + get providers(): { + HttpProvider: Web3BaseProviderConstructor; + WebsocketProvider: Web3BaseProviderConstructor; + }; + /** + * Use to set provider. Provider can be a provider instance or a string. + * + * @param provider - The provider to set + */ + setProvider(provider?: SupportedProviders | string): boolean; + /** + * + * Will execute a request + * + * @param request - {@link Web3APIRequest} The request to send + * + * @returns The response of the request {@link ResponseType}. If there is error + * in the response, will throw an error + */ + send, ResponseType = Web3APIReturnType>(request: Web3APIRequest): Promise; + /** + * Same as send, but, will execute a batch of requests + * + * @param request {@link JsonRpcBatchRequest} The batch request to send + */ + sendBatch(request: JsonRpcBatchRequest): Promise>; + private _sendRequest; + private _processJsonRpcResponse; + private static _isReverted; + private _buildResponse; +} diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.js new file mode 100644 index 0000000..fc67107 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.js @@ -0,0 +1,335 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3RequestManager = exports.Web3RequestManagerEvent = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_providers_http_1 = __importDefault(require("web3-providers-http")); +const web3_providers_ws_1 = __importDefault(require("web3-providers-ws")); +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("./utils.js"); +const web3_event_emitter_js_1 = require("./web3_event_emitter.js"); +var Web3RequestManagerEvent; +(function (Web3RequestManagerEvent) { + Web3RequestManagerEvent["PROVIDER_CHANGED"] = "PROVIDER_CHANGED"; + Web3RequestManagerEvent["BEFORE_PROVIDER_CHANGE"] = "BEFORE_PROVIDER_CHANGE"; +})(Web3RequestManagerEvent = exports.Web3RequestManagerEvent || (exports.Web3RequestManagerEvent = {})); +const availableProviders = { + HttpProvider: web3_providers_http_1.default, + WebsocketProvider: web3_providers_ws_1.default, +}; +class Web3RequestManager extends web3_event_emitter_js_1.Web3EventEmitter { + constructor(provider, useRpcCallSpecification) { + super(); + if (!(0, web3_utils_1.isNullish)(provider)) { + this.setProvider(provider); + } + this.useRpcCallSpecification = useRpcCallSpecification; + } + /** + * Will return all available providers + */ + static get providers() { + return availableProviders; + } + /** + * Will return the current provider. + * + * @returns Returns the current provider + */ + get provider() { + return this._provider; + } + /** + * Will return all available providers + */ + // eslint-disable-next-line class-methods-use-this + get providers() { + return availableProviders; + } + /** + * Use to set provider. Provider can be a provider instance or a string. + * + * @param provider - The provider to set + */ + setProvider(provider) { + let newProvider; + // autodetect provider + if (provider && typeof provider === 'string' && this.providers) { + // HTTP + if (/^http(s)?:\/\//i.test(provider)) { + newProvider = new this.providers.HttpProvider(provider); + // WS + } + else if (/^ws(s)?:\/\//i.test(provider)) { + newProvider = new this.providers.WebsocketProvider(provider); + } + else { + throw new web3_errors_1.ProviderError(`Can't autodetect provider for "${provider}"`); + } + } + else if ((0, web3_utils_1.isNullish)(provider)) { + // In case want to unset the provider + newProvider = undefined; + } + else { + newProvider = provider; + } + this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider); + this._provider = newProvider; + this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider); + return true; + } + /** + * + * Will execute a request + * + * @param request - {@link Web3APIRequest} The request to send + * + * @returns The response of the request {@link ResponseType}. If there is error + * in the response, will throw an error + */ + send(request) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield this._sendRequest(request); + if (web3_utils_1.jsonRpc.isResponseWithResult(response)) { + return response.result; + } + throw new web3_errors_1.ResponseError(response); + }); + } + /** + * Same as send, but, will execute a batch of requests + * + * @param request {@link JsonRpcBatchRequest} The batch request to send + */ + sendBatch(request) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield this._sendRequest(request); + return response; + }); + } + _sendRequest(request) { + return __awaiter(this, void 0, void 0, function* () { + const { provider } = this; + if ((0, web3_utils_1.isNullish)(provider)) { + throw new web3_errors_1.ProviderError('Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.'); + } + const payload = web3_utils_1.jsonRpc.isBatchRequest(request) + ? web3_utils_1.jsonRpc.toBatchPayload(request) + : web3_utils_1.jsonRpc.toPayload(request); + if ((0, utils_js_1.isWeb3Provider)(provider)) { + let response; + try { + response = yield provider.request(payload); + } + catch (error) { + // Check if the provider throw an error instead of reject with error + response = error; + } + return this._processJsonRpcResponse(payload, response, { legacy: false, error: false }); + } + if ((0, utils_js_1.isEIP1193Provider)(provider)) { + return provider + .request(payload) + .then(res => this._processJsonRpcResponse(payload, res, { + legacy: true, + error: false, + })) + .catch(error => this._processJsonRpcResponse(payload, error, { legacy: true, error: true })); + } + // TODO: This could be deprecated and removed. + if ((0, utils_js_1.isLegacyRequestProvider)(provider)) { + return new Promise((resolve, reject) => { + const rejectWithError = (err) => reject(this._processJsonRpcResponse(payload, err, { + legacy: true, + error: true, + })); + const resolveWithResponse = (response) => resolve(this._processJsonRpcResponse(payload, response, { + legacy: true, + error: false, + })); + const result = provider.request(payload, + // a callback that is expected to be called after getting the response: + (err, response) => { + if (err) { + return rejectWithError(err); + } + return resolveWithResponse(response); + }); + // Some providers, that follow a previous drafted version of EIP1193, has a `request` function + // that is not defined as `async`, but it returns a promise. + // Such providers would not be picked with if(isEIP1193Provider(provider)) above + // because the `request` function was not defined with `async` and so the function definition is not `AsyncFunction`. + // Like this provider: https://github.dev/NomicFoundation/hardhat/blob/62bea2600785595ba36f2105564076cf5cdf0fd8/packages/hardhat-core/src/internal/core/providers/backwards-compatibility.ts#L19 + // So check if the returned result is a Promise, and resolve with it accordingly. + // Note: in this case we expect the callback provided above to never be called. + if ((0, web3_utils_1.isPromise)(result)) { + const responsePromise = result; + responsePromise.then(resolveWithResponse).catch(rejectWithError); + } + }); + } + // TODO: This could be deprecated and removed. + if ((0, utils_js_1.isLegacySendProvider)(provider)) { + return new Promise((resolve, reject) => { + provider.send(payload, (err, response) => { + if (err) { + return reject(this._processJsonRpcResponse(payload, err, { + legacy: true, + error: true, + })); + } + if ((0, web3_utils_1.isNullish)(response)) { + throw new web3_errors_1.ResponseError('', 'Got a "nullish" response from provider.'); + } + return resolve(this._processJsonRpcResponse(payload, response, { + legacy: true, + error: false, + })); + }); + }); + } + // TODO: This could be deprecated and removed. + if ((0, utils_js_1.isLegacySendAsyncProvider)(provider)) { + return provider + .sendAsync(payload) + .then(response => this._processJsonRpcResponse(payload, response, { legacy: true, error: false })) + .catch(error => this._processJsonRpcResponse(payload, error, { + legacy: true, + error: true, + })); + } + throw new web3_errors_1.ProviderError('Provider does not have a request or send method to use.'); + }); + } + // eslint-disable-next-line class-methods-use-this + _processJsonRpcResponse(payload, response, { legacy, error }) { + if ((0, web3_utils_1.isNullish)(response)) { + return this._buildResponse(payload, + // Some providers uses "null" as valid empty response + // eslint-disable-next-line no-null/no-null + null, error); + } + // This is the majority of the cases so check these first + // A valid JSON-RPC response with error object + if (web3_utils_1.jsonRpc.isResponseWithError(response)) { + // check if its an rpc error + if (this.useRpcCallSpecification && + (0, web3_utils_1.isResponseRpcError)(response)) { + const rpcErrorResponse = response; + // check if rpc error flag is on and response error code match an EIP-1474 or a standard rpc error code + if (web3_errors_1.rpcErrorsMap.get(rpcErrorResponse.error.code)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const Err = web3_errors_1.rpcErrorsMap.get(rpcErrorResponse.error.code).error; + throw new Err(rpcErrorResponse); + } + else { + throw new web3_errors_1.RpcError(rpcErrorResponse); + } + } + else if (!Web3RequestManager._isReverted(response)) { + throw new web3_errors_1.InvalidResponseError(response, payload); + } + } + // This is the majority of the cases so check these first + // A valid JSON-RPC response with result object + if (web3_utils_1.jsonRpc.isResponseWithResult(response)) { + return response; + } + if (response instanceof Error) { + Web3RequestManager._isReverted(response); + throw response; + } + if (!legacy && web3_utils_1.jsonRpc.isBatchRequest(payload) && web3_utils_1.jsonRpc.isBatchResponse(response)) { + return response; + } + if (legacy && !error && web3_utils_1.jsonRpc.isBatchRequest(payload)) { + return response; + } + if (legacy && error && web3_utils_1.jsonRpc.isBatchRequest(payload)) { + // In case of error batch response we don't want to throw Invalid response + throw response; + } + if (legacy && + !web3_utils_1.jsonRpc.isResponseWithError(response) && + !web3_utils_1.jsonRpc.isResponseWithResult(response)) { + return this._buildResponse(payload, response, error); + } + if (web3_utils_1.jsonRpc.isBatchRequest(payload) && !Array.isArray(response)) { + throw new web3_errors_1.ResponseError(response, 'Got normal response for a batch request.'); + } + if (!web3_utils_1.jsonRpc.isBatchRequest(payload) && Array.isArray(response)) { + throw new web3_errors_1.ResponseError(response, 'Got batch response for a normal request.'); + } + if ((web3_utils_1.jsonRpc.isResponseWithError(response) || web3_utils_1.jsonRpc.isResponseWithResult(response)) && + !web3_utils_1.jsonRpc.isBatchRequest(payload)) { + if (response.id && payload.id !== response.id) { + throw new web3_errors_1.InvalidResponseError(response); + } + } + throw new web3_errors_1.ResponseError(response, 'Invalid response'); + } + static _isReverted(response) { + let error; + if (web3_utils_1.jsonRpc.isResponseWithError(response)) { + error = response.error; + } + else if (response instanceof Error) { + error = response; + } + // This message means that there was an error while executing the code of the smart contract + // However, more processing will happen at a higher level to decode the error data, + // according to the Error ABI, if it was available as of EIP-838. + if (error === null || error === void 0 ? void 0 : error.message.includes('revert')) + throw new web3_errors_1.ContractExecutionError(error); + return false; + } + // Need to use same types as _processJsonRpcResponse so have to declare as instance method + // eslint-disable-next-line class-methods-use-this + _buildResponse(payload, response, error) { + const res = { + jsonrpc: '2.0', + // eslint-disable-next-line no-nested-ternary + id: web3_utils_1.jsonRpc.isBatchRequest(payload) + ? payload[0].id + : 'id' in payload + ? payload.id + : // Have to use the null here explicitly + // eslint-disable-next-line no-null/no-null + null, + }; + if (error) { + return Object.assign(Object.assign({}, res), { error: response }); + } + return Object.assign(Object.assign({}, res), { result: response }); + } +} +exports.Web3RequestManager = Web3RequestManager; +//# sourceMappingURL=web3_request_manager.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.js.map new file mode 100644 index 0000000..f9e408e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_request_manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_request_manager.js","sourceRoot":"","sources":["../../src/web3_request_manager.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;AAEF,6CAOqB;AACrB,8EAA+C;AAC/C,0EAA2C;AAmB3C,2CAA+E;AAC/E,yCAMoB;AACpB,mEAA2D;AAE3D,IAAY,uBAGX;AAHD,WAAY,uBAAuB;IAClC,gEAAqC,CAAA;IACrC,4EAAiD,CAAA;AAClD,CAAC,EAHW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAGlC;AAED,MAAM,kBAAkB,GAGpB;IACH,YAAY,EAAE,6BAA2C;IACzD,iBAAiB,EAAE,2BAAyC;CAC5D,CAAC;AAEF,MAAa,kBAEX,SAAQ,wCAER;IAGD,YACC,QAA2C,EAC3C,uBAAiC;QAEjC,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,IAAA,sBAAS,EAAC,QAAQ,CAAC,EAAE;YACzB,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SAC3B;QACD,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAC;IACxD,CAAC;IAED;;OAEG;IACI,MAAM,KAAK,SAAS;QAC1B,OAAO,kBAAkB,CAAC;IAC3B,CAAC;IAED;;;;OAIG;IACH,IAAW,QAAQ;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,kDAAkD;IAClD,IAAW,SAAS;QACnB,OAAO,kBAAkB,CAAC;IAC3B,CAAC;IAED;;;;OAIG;IACI,WAAW,CAAC,QAA2C;QAC7D,IAAI,WAAgD,CAAC;QAErD,sBAAsB;QACtB,IAAI,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE;YAC/D,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B,CAAC;QAEpC,IAAI,oBAAO,CAAC,mBAAmB,CAAY,QAAQ,CAAC,EAAE;YACrD,KAAK,GAAI,QAAqC,CAAC,KAAK,CAAC;SACrD;aAAM,IAAK,QAAoB,YAAY,KAAK,EAAE;YAClD,KAAK,GAAG,QAAmC,CAAC;SAC5C;QAED,4FAA4F;QAC5F,mFAAmF;QACnF,iEAAiE;QACjE,IAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,MAAM,IAAI,oCAAsB,CAAC,KAAK,CAAC,CAAC;QAE/E,OAAO,KAAK,CAAC;IACd,CAAC;IACD,0FAA0F;IAC1F,kDAAkD;IAC1C,cAAc,CACrB,OAAoC,EACpC,QAAgD,EAChD,KAAc;QAEd,MAAM,GAAG,GAAG;YACX,OAAO,EAAE,KAAK;YACd,6CAA6C;YAC7C,EAAE,EAAE,oBAAO,CAAC,cAAc,CAAC,OAAO,CAAC;gBAClC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;gBACf,CAAC,CAAC,IAAI,IAAI,OAAO;oBACjB,CAAC,CAAC,OAAO,CAAC,EAAE;oBACZ,CAAC,CAAC,uCAAuC;wBACvC,2CAA2C;wBAC3C,IAAI;SACP,CAAC;QAEF,IAAI,KAAK,EAAE;YACV,OAAO,gCACH,GAAG,KACN,KAAK,EAAE,QAAmB,GACK,CAAC;SACjC;QAED,OAAO,gCACH,GAAG,KACN,MAAM,EAAE,QAAmB,GACI,CAAC;IAClC,CAAC;CACD;AA9YD,gDA8YC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.d.ts new file mode 100644 index 0000000..9f85af1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.d.ts @@ -0,0 +1,81 @@ +import { DataFormat, JsonRpcNotification, JsonRpcSubscriptionResult, JsonRpcSubscriptionResultOld, Log, Web3APISpec } from 'web3-types'; +import { Web3RequestManager } from './web3_request_manager.js'; +import { Web3SubscriptionConstructor } from './web3_subscriptions.js'; +declare type ShouldUnsubscribeCondition = ({ id, sub, }: { + id: string; + sub: unknown; +}) => boolean | undefined; +export declare class Web3SubscriptionManager; +} = { + [key: string]: Web3SubscriptionConstructor; +}> { + readonly requestManager: Web3RequestManager; + readonly registeredSubscriptions: RegisteredSubs; + private readonly tolerateUnlinkedSubscription; + private readonly _subscriptions; + /** + * + * @param - requestManager + * @param - registeredSubscriptions + * + * @example + * ```ts + * const requestManager = new Web3RequestManager("ws://localhost:8545"); + * const subscriptionManager = new Web3SubscriptionManager(requestManager, {}); + * ``` + */ + constructor(requestManager: Web3RequestManager, registeredSubscriptions: RegisteredSubs); + /** + * @deprecated This constructor overloading should not be used + */ + constructor(requestManager: Web3RequestManager, registeredSubscriptions: RegisteredSubs, tolerateUnlinkedSubscription: boolean); + private listenToProviderEvents; + protected messageListener(data?: JsonRpcSubscriptionResult | JsonRpcSubscriptionResultOld | JsonRpcNotification): void; + /** + * Will create a new subscription + * + * @param name - The subscription you want to subscribe to + * @param args - Optional additional parameters, depending on the subscription type + * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * + * Will subscribe to a specific topic (note: name) + * @returns The subscription object + */ + subscribe(name: T, args?: ConstructorParameters[0], returnFormat?: DataFormat): Promise>; + /** + * Will returns all subscriptions. + */ + get subscriptions(): Map>; + /** + * + * Adds an instance of {@link Web3Subscription} and subscribes to it + * + * @param sub - A {@link Web3Subscription} object + */ + addSubscription(sub: InstanceType): Promise; + /** + * Will clear a subscription + * + * @param id - The subscription of type {@link Web3Subscription} to remove + */ + removeSubscription(sub: InstanceType): Promise; + /** + * Will unsubscribe all subscriptions that fulfill the condition + * + * @param condition - A function that access and `id` and a `subscription` and return `true` or `false` + * @returns An array of all the un-subscribed subscriptions + */ + unsubscribe(condition?: ShouldUnsubscribeCondition): Promise; + /** + * Clears all subscriptions + */ + clear(): void; + /** + * Check whether the current provider supports subscriptions. + * + * @returns `true` or `false` depending on if the current provider supports subscriptions + */ + supportsSubscriptions(): boolean; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.js new file mode 100644 index 0000000..aa6d5e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.js @@ -0,0 +1,193 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3SubscriptionManager = void 0; +const web3_types_1 = require("web3-types"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("./utils.js"); +const web3_request_manager_js_1 = require("./web3_request_manager.js"); +class Web3SubscriptionManager { + constructor(requestManager, registeredSubscriptions, tolerateUnlinkedSubscription = false) { + this.requestManager = requestManager; + this.registeredSubscriptions = registeredSubscriptions; + this.tolerateUnlinkedSubscription = tolerateUnlinkedSubscription; + this._subscriptions = new Map(); + this.requestManager.on(web3_request_manager_js_1.Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, () => __awaiter(this, void 0, void 0, function* () { + yield this.unsubscribe(); + })); + this.requestManager.on(web3_request_manager_js_1.Web3RequestManagerEvent.PROVIDER_CHANGED, () => { + this.clear(); + this.listenToProviderEvents(); + }); + this.listenToProviderEvents(); + } + listenToProviderEvents() { + const providerAsWebProvider = this.requestManager.provider; + if (!this.requestManager.provider || + (typeof (providerAsWebProvider === null || providerAsWebProvider === void 0 ? void 0 : providerAsWebProvider.supportsSubscriptions) === 'function' && + !(providerAsWebProvider === null || providerAsWebProvider === void 0 ? void 0 : providerAsWebProvider.supportsSubscriptions()))) { + return; + } + if (typeof this.requestManager.provider.on === 'function') { + if (typeof this.requestManager.provider.request === 'function') { + // Listen to provider messages and data + this.requestManager.provider.on('message', + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument + (message) => this.messageListener(message)); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument + providerAsWebProvider.on('data', (data) => this.messageListener(data)); + } + } + } + messageListener(data) { + var _a, _b, _c; + if (!data) { + throw new web3_errors_1.SubscriptionError('Should not call messageListener with no data. Type was'); + } + const subscriptionId = ((_a = data.params) === null || _a === void 0 ? void 0 : _a.subscription) || + ((_b = data.data) === null || _b === void 0 ? void 0 : _b.subscription) || + ((_c = data.id) === null || _c === void 0 ? void 0 : _c.toString(16)); + // Process if the received data is related to a subscription + if (subscriptionId) { + const sub = this._subscriptions.get(subscriptionId); + sub === null || sub === void 0 ? void 0 : sub.processSubscriptionData(data); + } + } + /** + * Will create a new subscription + * + * @param name - The subscription you want to subscribe to + * @param args - Optional additional parameters, depending on the subscription type + * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * + * Will subscribe to a specific topic (note: name) + * @returns The subscription object + */ + subscribe(name, args, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + const Klass = this.registeredSubscriptions[name]; + if (!Klass) { + throw new web3_errors_1.SubscriptionError('Invalid subscription type'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const subscription = new Klass(args !== null && args !== void 0 ? args : undefined, { + subscriptionManager: this, + returnFormat, + }); + yield this.addSubscription(subscription); + return subscription; + }); + } + /** + * Will returns all subscriptions. + */ + get subscriptions() { + return this._subscriptions; + } + /** + * + * Adds an instance of {@link Web3Subscription} and subscribes to it + * + * @param sub - A {@link Web3Subscription} object + */ + addSubscription(sub) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.requestManager.provider) { + throw new web3_errors_1.ProviderError('Provider not available'); + } + if (!this.supportsSubscriptions()) { + throw new web3_errors_1.SubscriptionError('The current provider does not support subscriptions'); + } + if (sub.id && this._subscriptions.has(sub.id)) { + throw new web3_errors_1.SubscriptionError(`Subscription with id "${sub.id}" already exists`); + } + yield sub.sendSubscriptionRequest(); + if ((0, web3_utils_1.isNullish)(sub.id)) { + throw new web3_errors_1.SubscriptionError('Subscription is not subscribed yet.'); + } + this._subscriptions.set(sub.id, sub); + return sub.id; + }); + } + /** + * Will clear a subscription + * + * @param id - The subscription of type {@link Web3Subscription} to remove + */ + removeSubscription(sub) { + return __awaiter(this, void 0, void 0, function* () { + const { id } = sub; + if ((0, web3_utils_1.isNullish)(id)) { + throw new web3_errors_1.SubscriptionError('Subscription is not subscribed yet. Or, had already been unsubscribed but not through the Subscription Manager.'); + } + if (!this._subscriptions.has(id) && !this.tolerateUnlinkedSubscription) { + throw new web3_errors_1.SubscriptionError(`Subscription with id "${id.toString()}" does not exists`); + } + yield sub.sendUnsubscribeRequest(); + this._subscriptions.delete(id); + return id; + }); + } + /** + * Will unsubscribe all subscriptions that fulfill the condition + * + * @param condition - A function that access and `id` and a `subscription` and return `true` or `false` + * @returns An array of all the un-subscribed subscriptions + */ + unsubscribe(condition) { + return __awaiter(this, void 0, void 0, function* () { + const result = []; + for (const [id, sub] of this.subscriptions.entries()) { + if (!condition || (typeof condition === 'function' && condition({ id, sub }))) { + result.push(this.removeSubscription(sub)); + } + } + return Promise.all(result); + }); + } + /** + * Clears all subscriptions + */ + clear() { + this._subscriptions.clear(); + } + /** + * Check whether the current provider supports subscriptions. + * + * @returns `true` or `false` depending on if the current provider supports subscriptions + */ + supportsSubscriptions() { + return (0, web3_utils_1.isNullish)(this.requestManager.provider) + ? false + : (0, utils_js_1.isSupportSubscriptions)(this.requestManager.provider); + } +} +exports.Web3SubscriptionManager = Web3SubscriptionManager; +//# sourceMappingURL=web3_subscription_manager.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.js.map new file mode 100644 index 0000000..aaf7a4a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscription_manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscription_manager.js","sourceRoot":"","sources":["../../src/web3_subscription_manager.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAUoB;AACpB,6CAA+D;AAC/D,2CAAuC;AACvC,yCAAoD;AACpD,uEAAwF;AAYxF,MAAa,uBAAuB;IAkCnC,YACiB,cAAuC,EACvC,uBAAuC,EACtC,+BAAwC,KAAK;QAF9C,mBAAc,GAAd,cAAc,CAAyB;QACvC,4BAAuB,GAAvB,uBAAuB,CAAgB;QACtC,iCAA4B,GAA5B,4BAA4B,CAAiB;QA/B9C,mBAAc,GAG3B,IAAI,GAAG,EAAE,CAAC;QA8Bb,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,iDAAuB,CAAC,sBAAsB,EAAE,GAAS,EAAE;YACjF,MAAM,IAAI,CAAC,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,EAAE;gBACrD,IAAI,CAAC,SAAS,IAAI,CAAC,OAAO,SAAS,KAAK,UAAU,IAAI,SAAS,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE;oBAC9E,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;iBAC1C;aACD;YAED,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;KAAA;IAED;;OAEG;IACI,KAAK;QACX,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED;;;;OAIG;IACI,qBAAqB;QAC3B,OAAO,IAAA,sBAAS,EAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC;YAC7C,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,IAAA,iCAAsB,EAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;IACzD,CAAC;CACD;AA9ND,0DA8NC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.d.ts b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.d.ts new file mode 100644 index 0000000..21dfbeb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.d.ts @@ -0,0 +1,57 @@ +import { BlockOutput, DataFormat, EthExecutionAPI, JsonRpcSubscriptionResult, JsonRpcSubscriptionResultOld, JsonRpcNotification, Log, HexString, Web3APIParams, Web3APISpec } from 'web3-types'; +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +import { Web3EventEmitter, Web3EventMap } from './web3_event_emitter.js'; +import { Web3RequestManager } from './web3_request_manager.js'; +declare type CommonSubscriptionEvents = { + data: unknown; + error: Error; + connected: string; +}; +export declare abstract class Web3Subscription extends Web3EventEmitter { + readonly args: ArgsType; + private readonly _subscriptionManager; + private readonly _lastBlock?; + private readonly _returnFormat; + protected _id?: HexString; + constructor(args: ArgsType, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; + }); + /** + * @deprecated This constructor overloading should not be used + */ + constructor(args: ArgsType, options: { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; + }); + get id(): string | undefined; + get lastBlock(): BlockOutput | undefined; + subscribe(): Promise; + processSubscriptionData(data: JsonRpcSubscriptionResult | JsonRpcSubscriptionResultOld | JsonRpcNotification): void; + sendSubscriptionRequest(): Promise; + protected get returnFormat(): DataFormat; + protected get subscriptionManager(): Web3SubscriptionManager>; + }>; + resubscribe(): Promise; + unsubscribe(): Promise; + sendUnsubscribeRequest(): Promise; + protected formatSubscriptionResult(data: CombinedEventMap['data']): CombinedEventMap["data"]; + _processSubscriptionResult(data: CombinedEventMap['data'] | unknown): void; + _processSubscriptionError(error: Error): void; + protected _buildSubscriptionParams(): Web3APIParams; +} +export declare type Web3SubscriptionConstructor = Web3Subscription> = (new (args: any, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; +} | { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; +}) => SubscriptionType) | (new (args: any, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; +}) => SubscriptionType) | (new (args: any, options: { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; +}) => SubscriptionType); +export {}; diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.js b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.js new file mode 100644 index 0000000..d347063 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.js @@ -0,0 +1,136 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3Subscription = void 0; +// eslint-disable-next-line max-classes-per-file +const web3_types_1 = require("web3-types"); +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +// eslint-disable-next-line import/no-cycle +const web3_subscription_manager_js_1 = require("./web3_subscription_manager.js"); +const web3_event_emitter_js_1 = require("./web3_event_emitter.js"); +class Web3Subscription extends web3_event_emitter_js_1.Web3EventEmitter { + constructor(args, options) { + var _a; + super(); + this.args = args; + const { requestManager } = options; + const { subscriptionManager } = options; + if (requestManager && subscriptionManager) { + throw new web3_errors_1.SubscriptionError('Only requestManager or subscriptionManager should be provided at Subscription constructor'); + } + if (!requestManager && !subscriptionManager) { + throw new web3_errors_1.SubscriptionError('Either requestManager or subscriptionManager should be provided at Subscription constructor'); + } + if (requestManager) { + // eslint-disable-next-line deprecation/deprecation + this._subscriptionManager = new web3_subscription_manager_js_1.Web3SubscriptionManager(requestManager, {}, true); + } + else { + this._subscriptionManager = subscriptionManager; + } + this._returnFormat = (_a = options === null || options === void 0 ? void 0 : options.returnFormat) !== null && _a !== void 0 ? _a : web3_types_1.DEFAULT_RETURN_FORMAT; + } + get id() { + return this._id; + } + get lastBlock() { + return this._lastBlock; + } + subscribe() { + return __awaiter(this, void 0, void 0, function* () { + return this._subscriptionManager.addSubscription(this); + }); + } + processSubscriptionData(data) { + var _a, _b; + if (data === null || data === void 0 ? void 0 : data.data) { + // for EIP-1193 provider + this._processSubscriptionResult((_b = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.result) !== null && _b !== void 0 ? _b : data === null || data === void 0 ? void 0 : data.data); + } + else if (data && + web3_utils_1.jsonRpc.isResponseWithNotification(data)) { + this._processSubscriptionResult(data === null || data === void 0 ? void 0 : data.params.result); + } + } + sendSubscriptionRequest() { + return __awaiter(this, void 0, void 0, function* () { + this._id = yield this._subscriptionManager.requestManager.send({ + method: 'eth_subscribe', + params: this._buildSubscriptionParams(), + }); + this.emit('connected', this._id); + return this._id; + }); + } + get returnFormat() { + return this._returnFormat; + } + get subscriptionManager() { + return this._subscriptionManager; + } + resubscribe() { + return __awaiter(this, void 0, void 0, function* () { + yield this.unsubscribe(); + yield this.subscribe(); + }); + } + unsubscribe() { + return __awaiter(this, void 0, void 0, function* () { + if (!this.id) { + return; + } + yield this._subscriptionManager.removeSubscription(this); + }); + } + sendUnsubscribeRequest() { + return __awaiter(this, void 0, void 0, function* () { + yield this._subscriptionManager.requestManager.send({ + method: 'eth_unsubscribe', + params: [this.id], + }); + this._id = undefined; + }); + } + // eslint-disable-next-line class-methods-use-this + formatSubscriptionResult(data) { + return data; + } + _processSubscriptionResult(data) { + this.emit('data', this.formatSubscriptionResult(data)); + } + _processSubscriptionError(error) { + this.emit('error', error); + } + // eslint-disable-next-line class-methods-use-this + _buildSubscriptionParams() { + // This should be overridden in the subclass + throw new Error('Implement in the child class'); + } +} +exports.Web3Subscription = Web3Subscription; +//# sourceMappingURL=web3_subscriptions.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.js.map b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.js.map new file mode 100644 index 0000000..77073d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/commonjs/web3_subscriptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3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BACnD,MAAM,EAAE,iBAAiB;gBACzB,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAA0C;aAC1D,CAAC,CAAC;YACH,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;QACtB,CAAC;KAAA;IAED,kDAAkD;IACxC,wBAAwB,CAAC,IAA8B;QAChE,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,0BAA0B,CAAC,IAAwC;QACzE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC,CAAC;IACxD,CAAC;IAEM,yBAAyB,CAAC,KAAY;QAC5C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC3B,CAAC;IAED,kDAAkD;IACxC,wBAAwB;QACjC,4CAA4C;QAC5C,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IACjD,CAAC;CACD;AAnJD,4CAmJC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/formatters.js b/test/merkletreejs/node_modules/web3-core/lib/esm/formatters.js new file mode 100644 index 0000000..de8376a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/formatters.js @@ -0,0 +1,408 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { FormatterError } from 'web3-errors'; +import { Iban } from 'web3-eth-iban'; +import { BlockTags, } from 'web3-types'; +import { fromUtf8, hexToNumber, hexToNumberString, isAddress, isHexStrict, mergeDeep, numberToHex, sha3Raw, toChecksumAddress, toNumber, toUtf8, utf8ToHex, } from 'web3-utils'; +import { isBlockTag, isHex, isNullish } from 'web3-validator'; +/* eslint-disable deprecation/deprecation */ +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given storage key array values to hex strings. + */ +export const inputStorageKeysFormatter = (keys) => keys.map(num => numberToHex(num)); +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given proof response from the node. + */ +export const outputProofFormatter = (proof) => ({ + address: toChecksumAddress(proof.address), + nonce: hexToNumberString(proof.nonce), + balance: hexToNumberString(proof.balance), +}); +/** + * @deprecated Use format function from web3-utils package instead + * Should the format output to a big number + */ +export const outputBigIntegerFormatter = (number) => toNumber(number); +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or the predefined block number 'latest', 'pending', 'earliest', 'genesis' + */ +export const inputBlockNumberFormatter = (blockNumber) => { + if (isNullish(blockNumber)) { + return undefined; + } + if (typeof blockNumber === 'string' && isBlockTag(blockNumber)) { + return blockNumber; + } + if (blockNumber === 'genesis') { + return '0x0'; + } + if (typeof blockNumber === 'string' && isHexStrict(blockNumber)) { + return blockNumber.toLowerCase(); + } + return numberToHex(blockNumber); +}; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or does return the defaultBlock property of the current module + */ +export const inputDefaultBlockNumberFormatter = (blockNumber, defaultBlock) => { + if (!blockNumber) { + return inputBlockNumberFormatter(defaultBlock); + } + return inputBlockNumberFormatter(blockNumber); +}; +/** + * @deprecated Use format function from web3-utils package instead + * @param address + */ +export const inputAddressFormatter = (address) => { + if (Iban.isValid(address) && Iban.isDirect(address)) { + const iban = new Iban(address); + return iban.toAddress().toLowerCase(); + } + if (isAddress(address)) { + return `0x${address.toLowerCase().replace('0x', '')}`; + } + throw new FormatterError(`Provided address ${address} is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted.`); +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export const txInputOptionsFormatter = (options) => { + var _a; + const modifiedOptions = Object.assign({}, options); + if (options.to) { + // it might be contract creation + modifiedOptions.to = inputAddressFormatter(options.to); + } + if (options.data && options.input) { + throw new FormatterError('You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); + } + if (!options.input && options.data) { + modifiedOptions.input = options.data; + delete modifiedOptions.data; + } + if (options.input && !options.input.startsWith('0x')) { + modifiedOptions.input = `0x${options.input}`; + } + if (modifiedOptions.input && !isHexStrict(modifiedOptions.input)) { + throw new FormatterError('The input field must be HEX encoded data.'); + } + // allow both + if (options.gas || options.gasLimit) { + modifiedOptions.gas = toNumber((_a = options.gas) !== null && _a !== void 0 ? _a : options.gasLimit); + } + if (options.maxPriorityFeePerGas || options.maxFeePerGas) { + delete modifiedOptions.gasPrice; + } + ['gasPrice', 'gas', 'value', 'maxPriorityFeePerGas', 'maxFeePerGas', 'nonce', 'chainId'] + .filter(key => !isNullish(modifiedOptions[key])) + .forEach(key => { + modifiedOptions[key] = numberToHex(modifiedOptions[key]); + }); + return modifiedOptions; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export const inputCallFormatter = (options, defaultAccount) => { + var _a; + const opts = txInputOptionsFormatter(options); + const from = (_a = opts.from) !== null && _a !== void 0 ? _a : defaultAccount; + if (from) { + opts.from = inputAddressFormatter(from); + } + return opts; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export const inputTransactionFormatter = (options, defaultAccount) => { + var _a; + const opts = txInputOptionsFormatter(options); + // check from, only if not number, or object + if (!(typeof opts.from === 'number') && !(!!opts.from && typeof opts.from === 'object')) { + opts.from = (_a = opts.from) !== null && _a !== void 0 ? _a : defaultAccount; + if (!options.from && !(typeof options.from === 'number')) { + throw new FormatterError('The send transactions "from" field must be defined!'); + } + opts.from = inputAddressFormatter(options.from); + } + return opts; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Hex encodes the data passed to eth_sign and personal_sign + */ +export const inputSignFormatter = (data) => (isHexStrict(data) ? data : utf8ToHex(data)); +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction to its proper values + * @function outputTransactionFormatter + */ +export const outputTransactionFormatter = (tx) => { + const modifiedTx = Object.assign({}, tx); + if (tx.blockNumber) { + modifiedTx.blockNumber = hexToNumber(tx.blockNumber); + } + if (tx.transactionIndex) { + modifiedTx.transactionIndex = hexToNumber(tx.transactionIndex); + } + modifiedTx.nonce = hexToNumber(tx.nonce); + modifiedTx.gas = hexToNumber(tx.gas); + if (tx.gasPrice) { + modifiedTx.gasPrice = outputBigIntegerFormatter(tx.gasPrice); + } + if (tx.maxFeePerGas) { + modifiedTx.maxFeePerGas = outputBigIntegerFormatter(tx.maxFeePerGas); + } + if (tx.maxPriorityFeePerGas) { + modifiedTx.maxPriorityFeePerGas = outputBigIntegerFormatter(tx.maxPriorityFeePerGas); + } + if (tx.type) { + modifiedTx.type = hexToNumber(tx.type); + } + modifiedTx.value = outputBigIntegerFormatter(tx.value); + if (tx.to && isAddress(tx.to)) { + // tx.to could be `0x0` or `null` while contract creation + modifiedTx.to = toChecksumAddress(tx.to); + } + else { + modifiedTx.to = undefined; // set to `null` if invalid address + } + if (tx.from) { + modifiedTx.from = toChecksumAddress(tx.from); + } + return modifiedTx; +}; +/** + * @deprecated Use format function from web3-utils package instead + * @param topic + */ +// To align with specification we use the type "null" here +// eslint-disable-next-line @typescript-eslint/ban-types +export const inputTopicFormatter = (topic) => { + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + if (isNullish(topic)) + return null; + const value = String(topic); + return isHex(value) ? value : fromUtf8(value); +}; +/** + * @deprecated Use format function from web3-utils package instead + * @param filter + */ +export const inputLogFormatter = (filter) => { + var _a; + const val = isNullish(filter) + ? {} + : mergeDeep({}, filter); + // If options !== undefined, don't blow out existing data + if (isNullish(val.fromBlock)) { + val.fromBlock = BlockTags.LATEST; + } + val.fromBlock = inputBlockNumberFormatter(val.fromBlock); + if (!isNullish(val.toBlock)) { + val.toBlock = inputBlockNumberFormatter(val.toBlock); + } + // make sure topics, get converted to hex + val.topics = (_a = val.topics) !== null && _a !== void 0 ? _a : []; + val.topics = val.topics.map(topic => Array.isArray(topic) + ? topic.map(inputTopicFormatter) + : inputTopicFormatter(topic)); + if (val.address) { + val.address = Array.isArray(val.address) + ? val.address.map(addr => inputAddressFormatter(addr)) + : inputAddressFormatter(val.address); + } + return val; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a log + * @function outputLogFormatter + */ +export const outputLogFormatter = (log) => { + const modifiedLog = Object.assign({}, log); + const logIndex = typeof log.logIndex === 'string' + ? log.logIndex + : numberToHex(log.logIndex); + // generate a custom log id + if (typeof log.blockHash === 'string' && typeof log.transactionHash === 'string') { + const shaId = sha3Raw(`${log.blockHash.replace('0x', '')}${log.transactionHash.replace('0x', '')}${logIndex.replace('0x', '')}`); + modifiedLog.id = `log_${shaId.replace('0x', '').slice(0, 8)}`; + } + else if (!log.id) { + modifiedLog.id = undefined; + } + if (log.blockNumber && isHexStrict(log.blockNumber)) { + modifiedLog.blockNumber = hexToNumber(log.blockNumber); + } + if (log.transactionIndex && isHexStrict(log.transactionIndex)) { + modifiedLog.transactionIndex = hexToNumber(log.transactionIndex); + } + if (log.logIndex && isHexStrict(log.logIndex)) { + modifiedLog.logIndex = hexToNumber(log.logIndex); + } + if (log.address) { + modifiedLog.address = toChecksumAddress(log.address); + } + return modifiedLog; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction receipt to its proper values + */ +export const outputTransactionReceiptFormatter = (receipt) => { + if (typeof receipt !== 'object') { + throw new FormatterError(`Received receipt is invalid: ${String(receipt)}`); + } + const modifiedReceipt = Object.assign({}, receipt); + if (receipt.blockNumber) { + modifiedReceipt.blockNumber = hexToNumber(receipt.blockNumber); + } + if (receipt.transactionIndex) { + modifiedReceipt.transactionIndex = hexToNumber(receipt.transactionIndex); + } + modifiedReceipt.cumulativeGasUsed = hexToNumber(receipt.cumulativeGasUsed); + modifiedReceipt.gasUsed = hexToNumber(receipt.gasUsed); + if (receipt.logs && Array.isArray(receipt.logs)) { + modifiedReceipt.logs = receipt.logs.map(outputLogFormatter); + } + if (receipt.effectiveGasPrice) { + modifiedReceipt.effectiveGasPrice = hexToNumber(receipt.effectiveGasPrice); + } + if (receipt.contractAddress) { + modifiedReceipt.contractAddress = toChecksumAddress(receipt.contractAddress); + } + if (receipt.status) { + modifiedReceipt.status = Boolean(parseInt(receipt.status, 10)); + } + return modifiedReceipt; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a block to its proper values + * @function outputBlockFormatter + */ +export const outputBlockFormatter = (block) => { + const modifiedBlock = Object.assign({}, block); + // transform to number + modifiedBlock.gasLimit = hexToNumber(block.gasLimit); + modifiedBlock.gasUsed = hexToNumber(block.gasUsed); + modifiedBlock.size = hexToNumber(block.size); + modifiedBlock.timestamp = hexToNumber(block.timestamp); + if (block.number) { + modifiedBlock.number = hexToNumber(block.number); + } + if (block.difficulty) { + modifiedBlock.difficulty = outputBigIntegerFormatter(block.difficulty); + } + if (block.totalDifficulty) { + modifiedBlock.totalDifficulty = outputBigIntegerFormatter(block.totalDifficulty); + } + if (block.transactions && Array.isArray(block.transactions)) { + modifiedBlock.transactions = block.transactions.map(outputTransactionFormatter); + } + if (block.miner) { + modifiedBlock.miner = toChecksumAddress(block.miner); + } + if (block.baseFeePerGas) { + modifiedBlock.baseFeePerGas = outputBigIntegerFormatter(block.baseFeePerGas); + } + return modifiedBlock; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a whisper post and converts all values to HEX + */ +export const inputPostFormatter = (post) => { + var _a; + const modifiedPost = Object.assign({}, post); + if (post.ttl) { + modifiedPost.ttl = numberToHex(post.ttl); + } + if (post.workToProve) { + modifiedPost.workToProve = numberToHex(post.workToProve); + } + if (post.priority) { + modifiedPost.priority = numberToHex(post.priority); + } + // fallback + if (post.topics && !Array.isArray(post.topics)) { + modifiedPost.topics = post.topics ? [post.topics] : []; + } + // format the following options + modifiedPost.topics = (_a = modifiedPost.topics) === null || _a === void 0 ? void 0 : _a.map(topic => topic.startsWith('0x') ? topic : fromUtf8(topic)); + return modifiedPost; +}; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a received post message + * @function outputPostFormatter + */ +export const outputPostFormatter = (post) => { + var _a; + const modifiedPost = Object.assign({}, post); + if (post.expiry) { + modifiedPost.expiry = hexToNumber(post.expiry); + } + if (post.sent) { + modifiedPost.sent = hexToNumber(post.sent); + } + if (post.ttl) { + modifiedPost.ttl = hexToNumber(post.ttl); + } + if (post.workProved) { + modifiedPost.workProved = hexToNumber(post.workProved); + } + // post.payloadRaw = post.payload; + // post.payload = utils.hexToAscii(post.payload); + // if (utils.isJson(post.payload)) { + // post.payload = JSON.parse(post.payload); + // } + // format the following options + if (!post.topics) { + modifiedPost.topics = []; + } + modifiedPost.topics = (_a = modifiedPost.topics) === null || _a === void 0 ? void 0 : _a.map(toUtf8); + return modifiedPost; +}; +/** + * @deprecated Use format function from web3-utils package instead + */ +export const outputSyncingFormatter = (result) => { + const modifiedResult = Object.assign({}, result); + modifiedResult.startingBlock = hexToNumber(result.startingBlock); + modifiedResult.currentBlock = hexToNumber(result.currentBlock); + modifiedResult.highestBlock = hexToNumber(result.highestBlock); + if (result.knownStates) { + modifiedResult.knownStates = hexToNumber(result.knownStates); + } + if (result.pulledStates) { + modifiedResult.pulledStates = hexToNumber(result.pulledStates); + } + return modifiedResult; +}; +//# sourceMappingURL=formatters.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/formatters.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/formatters.js.map new file mode 100644 index 0000000..9a30490 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/formatters.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatters.js","sourceRoot":"","sources":["../../src/formatters.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,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AAI,CAAC,UAAU,CAAC,CAAC;KACvD;IAED,kCAAkC;IAClC,iDAAiD;IAEjD,oCAAoC;IACpC,+CAA+C;IAC/C,IAAI;IAEJ,+BAA+B;IAC/B,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;QACjB,YAAY,CAAC,MAAM,GAAG,EAAE,CAAC;KACzB;IAED,YAAY,CAAC,MAAM,GAAG,MAAA,YAAY,CAAC,MAAM,0CAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAEvD,OAAO,YAAY,CAAC;AACrB,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,MAAiB,EAAc,EAAE;IACvE,MAAM,cAAc,GAAG,kBAAK,MAAM,CAAoC,CAAC;IAEvE,cAAc,CAAC,aAAa,GAAG,WAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IACjE,cAAc,CAAC,YAAY,GAAG,WAAW,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAC/D,cAAc,CAAC,YAAY,GAAG,WAAW,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAE/D,IAAI,MAAM,CAAC,WAAW,EAAE;QACvB,cAAc,CAAC,WAAW,GAAG,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;KAC7D;IAED,IAAI,MAAM,CAAC,YAAY,EAAE;QACxB,cAAc,CAAC,YAAY,GAAG,WAAW,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;KAC/D;IAED,OAAO,cAAc,CAAC;AACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/index.js b/test/merkletreejs/node_modules/web3-core/lib/esm/index.js new file mode 100644 index 0000000..5a4176e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/index.js @@ -0,0 +1,30 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './web3_config.js'; +export * from './web3_request_manager.js'; +export * from './web3_subscription_manager.js'; +export * from './web3_subscriptions.js'; +export * from './web3_context.js'; +export * from './web3_batch_request.js'; +export * from './utils.js'; +export * from './types.js'; +export * from './formatters.js'; +export * from './web3_promi_event.js'; +export * from './web3_event_emitter.js'; +// For backward usability export as namespace +export * as formatters from './formatters.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/index.js.map new file mode 100644 index 0000000..bb95f9c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AAExC,6CAA6C;AAC7C,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/package.json b/test/merkletreejs/node_modules/web3-core/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/types.js b/test/merkletreejs/node_modules/web3-core/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/utils.js b/test/merkletreejs/node_modules/web3-core/lib/esm/utils.js new file mode 100644 index 0000000..93ea1f6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/utils.js @@ -0,0 +1,45 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3BaseProvider, } from 'web3-types'; +export const isWeb3Provider = (provider) => Web3BaseProvider.isWeb3Provider(provider); +export const isMetaMaskProvider = (provider) => typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'AsyncFunction' && 'isMetaMask' in provider && provider.isMetaMask; +export const isLegacyRequestProvider = (provider) => typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'Function'; +export const isEIP1193Provider = (provider) => typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'AsyncFunction'; +export const isLegacySendProvider = (provider) => typeof provider !== 'string' && 'send' in provider; +export const isLegacySendAsyncProvider = (provider) => typeof provider !== 'string' && 'sendAsync' in provider; +export const isSupportedProvider = (provider) => provider && + (isWeb3Provider(provider) || + isEIP1193Provider(provider) || + isLegacyRequestProvider(provider) || + isLegacySendAsyncProvider(provider) || + isLegacySendProvider(provider)); +export const isSupportSubscriptions = (provider) => { + if (provider && 'supportsSubscriptions' in provider) { + return provider.supportsSubscriptions(); + } + if (provider && typeof provider !== 'string' && 'on' in provider) { + return true; + } + return false; +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/utils.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/utils.js.map new file mode 100644 index 0000000..412c854 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAON,gBAAgB,GAEhB,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,cAAc,GAAG,CAC7B,QAAiC,EACG,EAAE,CAAC,gBAAgB,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAElF,MAAM,CAAC,MAAM,kBAAkB,GAAG,CACjC,QAAiC,EACG,EAAE,CACtC,OAAO,QAAQ,KAAK,QAAQ;IAC7B,SAAS,IAAI,QAAQ;IACr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IAAI,IAAI,QAAQ,EAAE;QACjE,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_batch_request.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_batch_request.js new file mode 100644 index 0000000..7975080 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_batch_request.js @@ -0,0 +1,102 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { jsonRpc, Web3DeferredPromise } from 'web3-utils'; +import { OperationAbortError, OperationTimeoutError, ResponseError } from 'web3-errors'; +export const DEFAULT_BATCH_REQUEST_TIMEOUT = 1000; +export class Web3BatchRequest { + constructor(requestManager) { + this._requestManager = requestManager; + this._requests = new Map(); + } + get requests() { + return [...this._requests.values()].map(r => r.payload); + } + add(request) { + const payload = jsonRpc.toPayload(request); + const promise = new Web3DeferredPromise(); + this._requests.set(payload.id, { payload, promise }); + return promise; + } + // eslint-disable-next-line class-methods-use-this + execute(options) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (this.requests.length === 0) { + return Promise.resolve([]); + } + const request = new Web3DeferredPromise({ + timeout: (_a = options === null || options === void 0 ? void 0 : options.timeout) !== null && _a !== void 0 ? _a : DEFAULT_BATCH_REQUEST_TIMEOUT, + eagerStart: true, + timeoutMessage: 'Batch request timeout', + }); + this._processBatchRequest(request).catch(err => request.reject(err)); + request.catch((err) => { + if (err instanceof OperationTimeoutError) { + this._abortAllRequests('Batch request timeout'); + } + request.reject(err); + }); + return request; + }); + } + _processBatchRequest(promise) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const response = yield this._requestManager.sendBatch([...this._requests.values()].map(r => r.payload)); + if (response.length !== this._requests.size) { + this._abortAllRequests('Invalid batch response'); + throw new ResponseError(response, `Batch request size mismatch the results size. Requests: ${this._requests.size}, Responses: ${response.length}`); + } + const requestIds = this.requests + .map(r => r.id) + .map(Number) + .sort((a, b) => a - b); + const responseIds = response + .map(r => r.id) + .map(Number) + .sort((a, b) => a - b); + if (JSON.stringify(requestIds) !== JSON.stringify(responseIds)) { + this._abortAllRequests('Invalid batch response'); + throw new ResponseError(response, `Batch request mismatch the results. Requests: [${requestIds.join()}], Responses: [${responseIds.join()}]`); + } + for (const res of response) { + if (jsonRpc.isResponseWithResult(res)) { + (_a = this._requests.get(res.id)) === null || _a === void 0 ? void 0 : _a.promise.resolve(res.result); + } + else if (jsonRpc.isResponseWithError(res)) { + (_b = this._requests.get(res.id)) === null || _b === void 0 ? void 0 : _b.promise.reject(res.error); + } + } + promise.resolve(response); + }); + } + _abortAllRequests(msg) { + for (const { promise } of this._requests.values()) { + promise.reject(new OperationAbortError(msg)); + } + } +} +//# sourceMappingURL=web3_batch_request.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_batch_request.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_batch_request.js.map new file mode 100644 index 0000000..b9c6f6b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_batch_request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/esm/web3_config.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_config.js new file mode 100644 index 0000000..efda7ad --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_config.js @@ -0,0 +1,397 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ConfigHardforkMismatchError, ConfigChainMismatchError } from 'web3-errors'; +import { isNullish, toHex } from 'web3-utils'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export var Web3ConfigEvent; +(function (Web3ConfigEvent) { + Web3ConfigEvent["CONFIG_CHANGE"] = "CONFIG_CHANGE"; +})(Web3ConfigEvent || (Web3ConfigEvent = {})); +export class Web3Config extends Web3EventEmitter { + constructor(options) { + super(); + this.config = { + handleRevert: false, + defaultAccount: undefined, + defaultBlock: 'latest', + transactionBlockTimeout: 50, + transactionConfirmationBlocks: 24, + transactionPollingInterval: 1000, + transactionPollingTimeout: 750 * 1000, + transactionReceiptPollingInterval: undefined, + transactionSendTimeout: 750 * 1000, + transactionConfirmationPollingInterval: undefined, + blockHeaderTimeout: 10, + maxListenersWarningThreshold: 100, + contractDataInputFill: 'data', + defaultNetworkId: undefined, + defaultChain: 'mainnet', + defaultHardfork: 'london', + // TODO - Check if there is a default Common + defaultCommon: undefined, + defaultTransactionType: '0x2', + defaultMaxPriorityFeePerGas: toHex(2500000000), + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: false, + useRpcCallSpecification: false, + }, + transactionBuilder: undefined, + transactionTypeParser: undefined, + }; + this.setConfig(options !== null && options !== void 0 ? options : {}); + } + setConfig(options) { + // TODO: Improve and add key check + const keys = Object.keys(options); + for (const key of keys) { + this._triggerConfigChange(key, options[key]); + } + Object.assign(this.config, options); + } + /** + * The `handleRevert` options property returns the revert reason string if enabled for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + * Default is `false`. + * + * `Note`: At the moment `handleRevert` is only supported for `sendTransaction` and not for `sendSignedTransaction` + */ + get handleRevert() { + return this.config.handleRevert; + } + /** + * Will set the handleRevert + */ + set handleRevert(val) { + this._triggerConfigChange('handleRevert', val); + this.config.handleRevert = val; + } + /** + * The `contractDataInputFill` options property will allow you to set the hash of the method signature and encoded parameters to the property + * either `data`, `input` or both within your contract. + * This will affect the contracts send, call and estimateGas methods + * Default is `input`. + */ + get contractDataInputFill() { + return this.config.contractDataInputFill; + } + /** + * Will set the contractDataInputFill + */ + set contractDataInputFill(val) { + this._triggerConfigChange('contractDataInputFill', val); + this.config.contractDataInputFill = val; + } + /** + * This default address is used as the default `from` property, if no `from` property is specified in for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + */ + get defaultAccount() { + return this.config.defaultAccount; + } + /** + * Will set the default account. + */ + set defaultAccount(val) { + this._triggerConfigChange('defaultAccount', val); + this.config.defaultAccount = val; + } + /** + * The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is `"latest"`. + * - web3.eth.getBalance() + * - web3.eth.getCode() + * - web3.eth.getTransactionCount() + * - web3.eth.getStorageAt() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + */ + get defaultBlock() { + return this.config.defaultBlock; + } + /** + * Will set the default block. + * + * - A block number + * - `"earliest"` - String: The genesis block + * - `"latest"` - String: The latest block (current head of the blockchain) + * - `"pending"` - String: The currently mined block (including pending transactions) + * - `"finalized"` - String: (For POS networks) The finalized block is one which has been accepted as canonical by greater than 2/3 of validators + * - `"safe"` - String: (For POS networks) The safe head block is one which under normal network conditions, is expected to be included in the canonical chain. Under normal network conditions the safe head and the actual tip of the chain will be equivalent (with safe head trailing only by a few seconds). Safe heads will be less likely to be reorged than the proof of work network`s latest blocks. + */ + set defaultBlock(val) { + this._triggerConfigChange('defaultBlock', val); + this.config.defaultBlock = val; + } + /** + * The time used to wait for Ethereum Node to return the sent transaction result. + * Note: If the RPC call stuck at the Node and therefor timed-out, the transaction may still be pending or even mined by the Network. We recommend checking the pending transactions in such a case. + * Default is `750` seconds (12.5 minutes). + */ + get transactionSendTimeout() { + return this.config.transactionSendTimeout; + } + /** + * Will set the transactionSendTimeout. + */ + set transactionSendTimeout(val) { + this._triggerConfigChange('transactionSendTimeout', val); + this.config.transactionSendTimeout = val; + } + /** + * The `transactionBlockTimeout` is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. + * Default is `50`. + */ + get transactionBlockTimeout() { + return this.config.transactionBlockTimeout; + } + /** + * Will set the transactionBlockTimeout. + */ + set transactionBlockTimeout(val) { + this._triggerConfigChange('transactionBlockTimeout', val); + this.config.transactionBlockTimeout = val; + } + /** + * This defines the number of blocks it requires until a transaction is considered confirmed. + * Default is `24`. + */ + get transactionConfirmationBlocks() { + return this.config.transactionConfirmationBlocks; + } + /** + * Will set the transactionConfirmationBlocks. + */ + set transactionConfirmationBlocks(val) { + this._triggerConfigChange('transactionConfirmationBlocks', val); + this.config.transactionConfirmationBlocks = val; + } + /** + * Used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `1000` ms. + */ + get transactionPollingInterval() { + return this.config.transactionPollingInterval; + } + /** + * Will set the transactionPollingInterval. + */ + set transactionPollingInterval(val) { + this._triggerConfigChange('transactionPollingInterval', val); + this.config.transactionPollingInterval = val; + this.transactionReceiptPollingInterval = val; + this.transactionConfirmationPollingInterval = val; + } + /** + * Used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times out, the transaction may still be pending. + * Default is `750` seconds (12.5 minutes). + */ + get transactionPollingTimeout() { + return this.config.transactionPollingTimeout; + } + /** + * Will set the transactionPollingTimeout. + */ + set transactionPollingTimeout(val) { + this._triggerConfigChange('transactionPollingTimeout', val); + this.config.transactionPollingTimeout = val; + } + /** + * The `transactionPollingInterval` is used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `undefined` + */ + get transactionReceiptPollingInterval() { + return this.config.transactionReceiptPollingInterval; + } + /** + * Will set the transactionReceiptPollingInterval + */ + set transactionReceiptPollingInterval(val) { + this._triggerConfigChange('transactionReceiptPollingInterval', val); + this.config.transactionReceiptPollingInterval = val; + } + get transactionConfirmationPollingInterval() { + return this.config.transactionConfirmationPollingInterval; + } + set transactionConfirmationPollingInterval(val) { + this._triggerConfigChange('transactionConfirmationPollingInterval', val); + this.config.transactionConfirmationPollingInterval = val; + } + /** + * The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt. + * Default is `10` seconds. + */ + get blockHeaderTimeout() { + return this.config.blockHeaderTimeout; + } + /** + * Will set the blockHeaderTimeout + */ + set blockHeaderTimeout(val) { + this._triggerConfigChange('blockHeaderTimeout', val); + this.config.blockHeaderTimeout = val; + } + /** + * The enableExperimentalFeatures is used to enable trying new experimental features that are still not fully implemented or not fully tested or still have some related issues. + * Default is `false` for every feature. + */ + get enableExperimentalFeatures() { + return this.config.enableExperimentalFeatures; + } + /** + * Will set the enableExperimentalFeatures + */ + set enableExperimentalFeatures(val) { + this._triggerConfigChange('enableExperimentalFeatures', val); + this.config.enableExperimentalFeatures = val; + } + get maxListenersWarningThreshold() { + return this.config.maxListenersWarningThreshold; + } + set maxListenersWarningThreshold(val) { + this._triggerConfigChange('maxListenersWarningThreshold', val); + this.setMaxListenerWarningThreshold(val); + this.config.maxListenersWarningThreshold = val; + } + get defaultNetworkId() { + return this.config.defaultNetworkId; + } + set defaultNetworkId(val) { + this._triggerConfigChange('defaultNetworkId', val); + this.config.defaultNetworkId = val; + } + get defaultChain() { + return this.config.defaultChain; + } + set defaultChain(val) { + if (!isNullish(this.config.defaultCommon) && + !isNullish(this.config.defaultCommon.baseChain) && + val !== this.config.defaultCommon.baseChain) + throw new ConfigChainMismatchError(this.config.defaultChain, val); + this._triggerConfigChange('defaultChain', val); + this.config.defaultChain = val; + } + /** + * Will return the default hardfork. Default is `london` + * The default hardfork property can be one of the following: + * - `chainstart` + * - `homestead` + * - `dao` + * - `tangerineWhistle` + * - `spuriousDragon` + * - `byzantium` + * - `constantinople` + * - `petersburg` + * - `istanbul` + * - `berlin` + * - `london` + * - 'arrowGlacier', + * - 'tangerineWhistle', + * - 'muirGlacier' + * + */ + get defaultHardfork() { + return this.config.defaultHardfork; + } + /** + * Will set the default hardfork. + * + */ + set defaultHardfork(val) { + if (!isNullish(this.config.defaultCommon) && + !isNullish(this.config.defaultCommon.hardfork) && + val !== this.config.defaultCommon.hardfork) + throw new ConfigHardforkMismatchError(this.config.defaultCommon.hardfork, val); + this._triggerConfigChange('defaultHardfork', val); + this.config.defaultHardfork = val; + } + /** + * + * Will get the default common property + * The default common property does contain the following Common object: + * - `customChain` - `Object`: The custom chain properties + * - `name` - `string`: (optional) The name of the chain + * - `networkId` - `number`: Network ID of the custom chain + * - `chainId` - `number`: Chain ID of the custom chain + * - `baseChain` - `string`: (optional) mainnet, goerli, kovan, rinkeby, or ropsten + * - `hardfork` - `string`: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london + * Default is `undefined`. + * + */ + get defaultCommon() { + return this.config.defaultCommon; + } + /** + * Will set the default common property + * + */ + set defaultCommon(val) { + // validation check if default hardfork is set and matches defaultCommon hardfork + if (!isNullish(this.config.defaultHardfork) && + !isNullish(val) && + !isNullish(val.hardfork) && + this.config.defaultHardfork !== val.hardfork) + throw new ConfigHardforkMismatchError(this.config.defaultHardfork, val.hardfork); + if (!isNullish(this.config.defaultChain) && + !isNullish(val) && + !isNullish(val.baseChain) && + this.config.defaultChain !== val.baseChain) + throw new ConfigChainMismatchError(this.config.defaultChain, val.baseChain); + this._triggerConfigChange('defaultCommon', val); + this.config.defaultCommon = val; + } + get defaultTransactionType() { + return this.config.defaultTransactionType; + } + set defaultTransactionType(val) { + this._triggerConfigChange('defaultTransactionType', val); + this.config.defaultTransactionType = val; + } + get defaultMaxPriorityFeePerGas() { + return this.config.defaultMaxPriorityFeePerGas; + } + set defaultMaxPriorityFeePerGas(val) { + this._triggerConfigChange('defaultMaxPriorityFeePerGas', val); + this.config.defaultMaxPriorityFeePerGas = val; + } + get transactionBuilder() { + return this.config.transactionBuilder; + } + set transactionBuilder(val) { + this._triggerConfigChange('transactionBuilder', val); + this.config.transactionBuilder = val; + } + get transactionTypeParser() { + return this.config.transactionTypeParser; + } + set transactionTypeParser(val) { + this._triggerConfigChange('transactionTypeParser', val); + this.config.transactionTypeParser = val; + } + _triggerConfigChange(config, newValue) { + this.emit(Web3ConfigEvent.CONFIG_CHANGE, { + name: config, + oldValue: this.config[config], + newValue, + }); + } +} +//# sourceMappingURL=web3_config.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_config.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_config.js.map new file mode 100644 index 0000000..53b4911 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_config.js","sourceRoot":"","sources":["../../src/web3_config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,2BAA2B,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACpF,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAI9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAqC3D,MAAM,CAAN,IAAY,eAEX;AAFD,WA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AQ,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;YAC7B,QAAQ;SAC0B,CAAC,CAAC;IACtC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_context.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_context.js new file mode 100644 index 0000000..e825f75 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_context.js @@ -0,0 +1,311 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line max-classes-per-file +import { ExistingPluginNamespaceError } from 'web3-errors'; +import { isNullish } from 'web3-utils'; +import { TransactionFactory } from 'web3-eth-accounts'; +import { isSupportedProvider } from './utils.js'; +import { Web3BatchRequest } from './web3_batch_request.js'; +// eslint-disable-next-line import/no-cycle +import { Web3Config, Web3ConfigEvent } from './web3_config.js'; +import { Web3RequestManager } from './web3_request_manager.js'; +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +export class Web3Context extends Web3Config { + constructor(providerOrContext) { + var _a; + super(); + this.providers = Web3RequestManager.providers; + // If "providerOrContext" is provided as "string" or an objects matching "SupportedProviders" interface + if (isNullish(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() !== '') || + isSupportedProvider(providerOrContext)) { + this._requestManager = new Web3RequestManager(providerOrContext); + this._subscriptionManager = new Web3SubscriptionManager(this._requestManager, {}); + return; + } + const { config, provider, requestManager, subscriptionManager, registeredSubscriptions, accountProvider, wallet, } = providerOrContext; + this.setConfig(config !== null && config !== void 0 ? config : {}); + this._requestManager = + requestManager !== null && requestManager !== void 0 ? requestManager : new Web3RequestManager(provider, (_a = config === null || config === void 0 ? void 0 : config.enableExperimentalFeatures) === null || _a === void 0 ? void 0 : _a.useSubscriptionWhenCheckingBlockTimeout); + if (subscriptionManager) { + this._subscriptionManager = subscriptionManager; + } + else { + this._subscriptionManager = new Web3SubscriptionManager(this.requestManager, registeredSubscriptions !== null && registeredSubscriptions !== void 0 ? registeredSubscriptions : {}); + } + if (accountProvider) { + this._accountProvider = accountProvider; + } + if (wallet) { + this._wallet = wallet; + } + } + get requestManager() { + return this._requestManager; + } + /** + * Will return the current subscriptionManager ({@link Web3SubscriptionManager}) + */ + get subscriptionManager() { + return this._subscriptionManager; + } + get wallet() { + return this._wallet; + } + get accountProvider() { + return this._accountProvider; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromContextObject(...args) { + return new this(...args.reverse()); + } + getContextObject() { + var _a; + return { + config: this.config, + provider: this.provider, + requestManager: this.requestManager, + subscriptionManager: this.subscriptionManager, + registeredSubscriptions: (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.registeredSubscriptions, + providers: this.providers, + wallet: this.wallet, + accountProvider: this.accountProvider, + }; + } + /** + * Use to create new object of any type extended by `Web3Context` + * and link it to current context. This can be used to initiate a global context object + * and then use it to create new objects of any type extended by `Web3Context`. + */ + use(ContextRef, ...args) { + const newContextChild = new ContextRef(...[...args, this.getContextObject()]); + this.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + newContextChild.setConfig({ [event.name]: event.newValue }); + }); + return newContextChild; + } + /** + * Link current context to another context. + */ + link(parentContext) { + this.setConfig(parentContext.config); + this._requestManager = parentContext.requestManager; + this.provider = parentContext.provider; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this._subscriptionManager = parentContext.subscriptionManager; + this._wallet = parentContext.wallet; + this._accountProvider = parentContext._accountProvider; + parentContext.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.setConfig({ [event.name]: event.newValue }); + }); + } + // eslint-disable-next-line no-use-before-define + registerPlugin(plugin) { + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + if (this[plugin.pluginNamespace] !== undefined) + throw new ExistingPluginNamespaceError(plugin.pluginNamespace); + const _pluginObject = { + [plugin.pluginNamespace]: plugin, + }; + _pluginObject[plugin.pluginNamespace].link(this); + Object.assign(this, _pluginObject); + } + /** + * Will return the current provider. + * + * @returns Returns the current provider + * @example + * ```ts + * const web3 = new Web3Context("http://localhost:8545"); + * console.log(web3.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get provider() { + return this.currentProvider; + } + /** + * Will set the current provider. + * + * @param provider - The provider to set + * + * Accepted providers are of type {@link SupportedProviders} + * @example + * ```ts + * const web3Context = new web3ContextContext("http://localhost:8545"); + * web3Context.provider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set provider(provider) { + this.requestManager.setProvider(provider); + } + /** + * Will return the current provider. (The same as `provider`) + * + * @returns Returns the current provider + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * console.log(web3Context.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get currentProvider() { + return this.requestManager.provider; + } + /** + * Will set the current provider. (The same as `provider`) + * + * @param provider - {@link SupportedProviders} The provider to set + * + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * web3Context.currentProvider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set currentProvider(provider) { + this.requestManager.setProvider(provider); + } + /** + * Will return the givenProvider if available. + * + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise `undefined`. + */ + // eslint-disable-next-line class-methods-use-this + get givenProvider() { + return Web3Context.givenProvider; + } + /** + * Will set the provider. + * + * @param provider - {@link SupportedProviders} The provider to set + * @returns Returns true if the provider was set + */ + setProvider(provider) { + this.provider = provider; + return true; + } + /** + * Will return the {@link Web3BatchRequest} constructor. + */ + get BatchRequest() { + return Web3BatchRequest.bind(undefined, this._requestManager); + } + /** + * This method allows extending the web3 modules. + * Note: This method is only for backward compatibility, and It is recommended to use Web3 v4 Plugin feature for extending web3.js functionality if you are developing some thing new. + */ + extend(extendObj) { + var _a; + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + if (extendObj.property && !this[extendObj.property]) + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + this[extendObj.property] = {}; + (_a = extendObj.methods) === null || _a === void 0 ? void 0 : _a.forEach(element => { + const method = (...givenParams) => __awaiter(this, void 0, void 0, function* () { + return this.requestManager.send({ + method: element.call, + params: givenParams, + }); + }); + if (extendObj.property) + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + this[extendObj.property][element.name] = method; + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + else + this[element.name] = method; + }); + return this; + } +} +Web3Context.providers = Web3RequestManager.providers; +/** + * Extend this class when creating a plugin that either doesn't require {@link EthExecutionAPI}, + * or interacts with a RPC node that doesn't fully implement {@link EthExecutionAPI}. + * + * To add type support for RPC methods to the {@link Web3RequestManager}, + * define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: + * + * @example + * ```ts + * type CustomRpcApi = { + * custom_rpc_method: () => string; + * custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; + * }; + * + * class CustomPlugin extends Web3PluginBase {...} + * ``` + */ +export class Web3PluginBase extends Web3Context { + // eslint-disable-next-line class-methods-use-this + registerNewTransactionType(type, txClass) { + TransactionFactory.registerTransactionType(type, txClass); + } +} +/** +* Extend this class when creating a plugin that makes use of {@link EthExecutionAPI}, +* or depends on other Web3 packages (such as `web3-eth-contract`) that depend on {@link EthExecutionAPI}. +* +* To add type support for RPC methods to the {@link Web3RequestManager} (in addition to {@link EthExecutionAPI}), +* define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: +* +* @example +* ```ts +* type CustomRpcApi = { +* custom_rpc_method: () => string; +* custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; +* }; +* +* class CustomPlugin extends Web3PluginBase {...} +* ``` +*/ +export class Web3EthPluginBase extends Web3PluginBase { +} +//# sourceMappingURL=web3_context.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_context.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_context.js.map new file mode 100644 index 0000000..6c8e2a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_context.js","sourceRoot":"","sources":["../../src/web3_context.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,gDAAgD;AAChD,OAAO,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAC;AAM3D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAmB,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,E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,MAAM,GAAG,CAAO,GAAG,WAAsB,EAAE,EAAE;gBAClD,OAAA,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;oBACxB,MAAM,EAAE,OAAO,CAAC,IAAI;oBACpB,MAAM,EAAE,WAAW;iBACnB,CAAC,CAAA;cAAA,CAAC;YAEJ,IAAI,SAAS,CAAC,QAAQ;gBACrB,6HAA6H;gBAC7H,sEAAsE;gBACtE,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC;YACjD,6HAA6H;;gBACxH,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC;QAClC,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACb,CAAC;;AA3SsB,qBAAS,GAAG,kBAAkB,CAAC,SAAS,CAAC;AA8SjE;;;;;;;;;;;;;;;;GAgBG;AACF,MAAM,OAAgB,cAErB,SAAQ,WAAgB;IAGzB,kDAAkD;IACxC,0BAA0B,CAAyD,IAAa,EAAE,OAAuB;QAChI,kBAAkB,CAAC,uBAAuB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;CACD;AAED;;;;;;;;;;;;;;;;EAgBE;AACF,MAAM,OAAgB,iBAAqD,SAAQ,cAElF;CAAG"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_event_emitter.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_event_emitter.js new file mode 100644 index 0000000..3e9ea42 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_event_emitter.js @@ -0,0 +1,56 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { EventEmitter } from 'web3-utils'; +export class Web3EventEmitter { + constructor() { + this._emitter = new EventEmitter(); + } + on(eventName, fn) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.on(eventName, fn); + } + once(eventName, fn) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.once(eventName, fn); + } + off(eventName, fn) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.off(eventName, fn); + } + emit(eventName, params) { + this._emitter.emit(eventName, params); + } + listenerCount(eventName) { + return this._emitter.listenerCount(eventName); + } + listeners(eventName) { + return this._emitter.listeners(eventName); + } + eventNames() { + return this._emitter.eventNames(); + } + removeAllListeners() { + return this._emitter.removeAllListeners(); + } + setMaxListenerWarningThreshold(maxListenersWarningThreshold) { + this._emitter.setMaxListeners(maxListenersWarningThreshold); + } + getMaxListeners() { + return this._emitter.getMaxListeners(); + } +} +//# sourceMappingURL=web3_event_emitter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_event_emitter.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_event_emitter.js.map new file mode 100644 index 0000000..d1036c0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_event_emitter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_event_emitter.js","sourceRoot":"","sources":["../../src/web3_event_emitter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAY1C,MAAM,OAAO,gBAAgB;IAA7B;QACkB,aAAQ,GAAG,IAAI,YAAY,EAAE,CAAC;IA0ChD,CAAC;IAxCO,EAAE,CAA4B,SAAY,EAAE,EAA2B;QAC7E,kEAAkE;QAClE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACjC,CAAC;IAEM,IAAI,CAA4B,SAAY,EAAE,EAA2B;QAC/E,kEAAkE;QAClE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAEM,GAAG,CAA4B,SAAY,EAAE,EAA2B;QAC9E,kEAAkE;QAClE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IAClC,CAAC;IAEM,IAAI,CAA4B,SAAY,EAAE,MAAY;QAChE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;IACvC,CAAC;IAEM,aAAa,CAA4B,SAAY;QAC3D,OAAO,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;IAC/C,CAAC;IAEM,SAAS,CAA4B,SAAY;QACvD,OAAO,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC3C,CAAC;IAEM,UAAU;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC;IAEM,kBAAkB;QACxB,OAAO,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC;IAC3C,CAAC;IACM,8BAA8B,CAAC,4BAAoC;QACzE,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,4BAA4B,CAAC,CAAC;IAC7D,CAAC;IACM,eAAe;QACrB,OAAO,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC;IACxC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_promi_event.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_promi_event.js new file mode 100644 index 0000000..1e7229b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_promi_event.js @@ -0,0 +1,61 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +import { Web3EventEmitter, } from './web3_event_emitter.js'; +export class Web3PromiEvent extends Web3EventEmitter { + constructor(executor) { + super(); + // public tag to treat object as promise by different libs + // eslint-disable-next-line @typescript-eslint/prefer-as-const + this[_a] = 'Promise'; + this._promise = new Promise(executor); + } + then(onfulfilled, onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.then(onfulfilled, onrejected); + }); + } + catch(onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.catch(onrejected); + }); + } + finally(onfinally) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.finally(onfinally); + }); + } + on(eventName, fn) { + super.on(eventName, fn); + return this; + } + once(eventName, fn) { + super.once(eventName, fn); + return this; + } +} +_a = Symbol.toStringTag; +//# sourceMappingURL=web3_promi_event.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_promi_event.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_promi_event.js.map new file mode 100644 index 0000000..885dc24 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_promi_event.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_promi_event.js","sourceRoot":"","sources":["../../src/web3_promi_event.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;AAEF,OAAO,EAEN,gBAAgB,GAGhB,MAAM,yBAAyB,CAAC;AAOjC,MAAM,OAAO,cACZ,SAAQ,gBAA0B;IAKlC,YAAmB,QAAsC;QACxD,KAAK,EAAE,CAAC;QAIT,0DAA0D;QAC1D,8DAA8D;QACvD,QAAoB,GAAc,SAAS,CAAC;QALlD,IAAI,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAc,QAAQ,CAAC,CAAC;IACpD,CAAC;IAMY,IAAI,CAChB,WAAoF,EACpF,UAAgF;;YAEhF,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACpD,CAAC;KAAA;IAEY,KAAK,CACjB,UAA8E;;YAE9E,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACxC,CAAC;KAAA;IAEY,OAAO,CAAC,SAAoC;;YACxD,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACzC,CAAC;KAAA;IAEM,EAAE,CACR,SAAY,EACZ,EAAkC;QAElC,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QAExB,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,IAAI,CACV,SAAY,EACZ,EAAkC;QAElC,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QAE1B,OAAO,IAAI,CAAC;IACb,CAAC;CACD;KApCQ,MAAM,CAAC,WAAW"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_request_manager.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_request_manager.js new file mode 100644 index 0000000..4fa55ae --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_request_manager.js @@ -0,0 +1,328 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { ContractExecutionError, InvalidResponseError, ProviderError, ResponseError, rpcErrorsMap, RpcError, } from 'web3-errors'; +import HttpProvider from 'web3-providers-http'; +import WSProvider from 'web3-providers-ws'; +import { isNullish, isPromise, jsonRpc, isResponseRpcError } from 'web3-utils'; +import { isEIP1193Provider, isLegacyRequestProvider, isLegacySendAsyncProvider, isLegacySendProvider, isWeb3Provider, } from './utils.js'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export var Web3RequestManagerEvent; +(function (Web3RequestManagerEvent) { + Web3RequestManagerEvent["PROVIDER_CHANGED"] = "PROVIDER_CHANGED"; + Web3RequestManagerEvent["BEFORE_PROVIDER_CHANGE"] = "BEFORE_PROVIDER_CHANGE"; +})(Web3RequestManagerEvent || (Web3RequestManagerEvent = {})); +const availableProviders = { + HttpProvider: HttpProvider, + WebsocketProvider: WSProvider, +}; +export class Web3RequestManager extends Web3EventEmitter { + constructor(provider, useRpcCallSpecification) { + super(); + if (!isNullish(provider)) { + this.setProvider(provider); + } + this.useRpcCallSpecification = useRpcCallSpecification; + } + /** + * Will return all available providers + */ + static get providers() { + return availableProviders; + } + /** + * Will return the current provider. + * + * @returns Returns the current provider + */ + get provider() { + return this._provider; + } + /** + * Will return all available providers + */ + // eslint-disable-next-line class-methods-use-this + get providers() { + return availableProviders; + } + /** + * Use to set provider. Provider can be a provider instance or a string. + * + * @param provider - The provider to set + */ + setProvider(provider) { + let newProvider; + // autodetect provider + if (provider && typeof provider === 'string' && this.providers) { + // HTTP + if (/^http(s)?:\/\//i.test(provider)) { + newProvider = new this.providers.HttpProvider(provider); + // WS + } + else if (/^ws(s)?:\/\//i.test(provider)) { + newProvider = new this.providers.WebsocketProvider(provider); + } + else { + throw new ProviderError(`Can't autodetect provider for "${provider}"`); + } + } + else if (isNullish(provider)) { + // In case want to unset the provider + newProvider = undefined; + } + else { + newProvider = provider; + } + this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider); + this._provider = newProvider; + this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider); + return true; + } + /** + * + * Will execute a request + * + * @param request - {@link Web3APIRequest} The request to send + * + * @returns The response of the request {@link ResponseType}. If there is error + * in the response, will throw an error + */ + send(request) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield this._sendRequest(request); + if (jsonRpc.isResponseWithResult(response)) { + return response.result; + } + throw new ResponseError(response); + }); + } + /** + * Same as send, but, will execute a batch of requests + * + * @param request {@link JsonRpcBatchRequest} The batch request to send + */ + sendBatch(request) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield this._sendRequest(request); + return response; + }); + } + _sendRequest(request) { + return __awaiter(this, void 0, void 0, function* () { + const { provider } = this; + if (isNullish(provider)) { + throw new ProviderError('Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.'); + } + const payload = jsonRpc.isBatchRequest(request) + ? jsonRpc.toBatchPayload(request) + : jsonRpc.toPayload(request); + if (isWeb3Provider(provider)) { + let response; + try { + response = yield provider.request(payload); + } + catch (error) { + // Check if the provider throw an error instead of reject with error + response = error; + } + return this._processJsonRpcResponse(payload, response, { legacy: false, error: false }); + } + if (isEIP1193Provider(provider)) { + return provider + .request(payload) + .then(res => this._processJsonRpcResponse(payload, res, { + legacy: true, + error: false, + })) + .catch(error => this._processJsonRpcResponse(payload, error, { legacy: true, error: true })); + } + // TODO: This could be deprecated and removed. + if (isLegacyRequestProvider(provider)) { + return new Promise((resolve, reject) => { + const rejectWithError = (err) => reject(this._processJsonRpcResponse(payload, err, { + legacy: true, + error: true, + })); + const resolveWithResponse = (response) => resolve(this._processJsonRpcResponse(payload, response, { + legacy: true, + error: false, + })); + const result = provider.request(payload, + // a callback that is expected to be called after getting the response: + (err, response) => { + if (err) { + return rejectWithError(err); + } + return resolveWithResponse(response); + }); + // Some providers, that follow a previous drafted version of EIP1193, has a `request` function + // that is not defined as `async`, but it returns a promise. + // Such providers would not be picked with if(isEIP1193Provider(provider)) above + // because the `request` function was not defined with `async` and so the function definition is not `AsyncFunction`. + // Like this provider: https://github.dev/NomicFoundation/hardhat/blob/62bea2600785595ba36f2105564076cf5cdf0fd8/packages/hardhat-core/src/internal/core/providers/backwards-compatibility.ts#L19 + // So check if the returned result is a Promise, and resolve with it accordingly. + // Note: in this case we expect the callback provided above to never be called. + if (isPromise(result)) { + const responsePromise = result; + responsePromise.then(resolveWithResponse).catch(rejectWithError); + } + }); + } + // TODO: This could be deprecated and removed. + if (isLegacySendProvider(provider)) { + return new Promise((resolve, reject) => { + provider.send(payload, (err, response) => { + if (err) { + return reject(this._processJsonRpcResponse(payload, err, { + legacy: true, + error: true, + })); + } + if (isNullish(response)) { + throw new ResponseError('', 'Got a "nullish" response from provider.'); + } + return resolve(this._processJsonRpcResponse(payload, response, { + legacy: true, + error: false, + })); + }); + }); + } + // TODO: This could be deprecated and removed. + if (isLegacySendAsyncProvider(provider)) { + return provider + .sendAsync(payload) + .then(response => this._processJsonRpcResponse(payload, response, { legacy: true, error: false })) + .catch(error => this._processJsonRpcResponse(payload, error, { + legacy: true, + error: true, + })); + } + throw new ProviderError('Provider does not have a request or send method to use.'); + }); + } + // eslint-disable-next-line class-methods-use-this + _processJsonRpcResponse(payload, response, { legacy, error }) { + if (isNullish(response)) { + return this._buildResponse(payload, + // Some providers uses "null" as valid empty response + // eslint-disable-next-line no-null/no-null + null, error); + } + // This is the majority of the cases so check these first + // A valid JSON-RPC response with error object + if (jsonRpc.isResponseWithError(response)) { + // check if its an rpc error + if (this.useRpcCallSpecification && + isResponseRpcError(response)) { + const rpcErrorResponse = response; + // check if rpc error flag is on and response error code match an EIP-1474 or a standard rpc error code + if (rpcErrorsMap.get(rpcErrorResponse.error.code)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const Err = rpcErrorsMap.get(rpcErrorResponse.error.code).error; + throw new Err(rpcErrorResponse); + } + else { + throw new RpcError(rpcErrorResponse); + } + } + else if (!Web3RequestManager._isReverted(response)) { + throw new InvalidResponseError(response, payload); + } + } + // This is the majority of the cases so check these first + // A valid JSON-RPC response with result object + if (jsonRpc.isResponseWithResult(response)) { + return response; + } + if (response instanceof Error) { + Web3RequestManager._isReverted(response); + throw response; + } + if (!legacy && jsonRpc.isBatchRequest(payload) && jsonRpc.isBatchResponse(response)) { + return response; + } + if (legacy && !error && jsonRpc.isBatchRequest(payload)) { + return response; + } + if (legacy && error && jsonRpc.isBatchRequest(payload)) { + // In case of error batch response we don't want to throw Invalid response + throw response; + } + if (legacy && + !jsonRpc.isResponseWithError(response) && + !jsonRpc.isResponseWithResult(response)) { + return this._buildResponse(payload, response, error); + } + if (jsonRpc.isBatchRequest(payload) && !Array.isArray(response)) { + throw new ResponseError(response, 'Got normal response for a batch request.'); + } + if (!jsonRpc.isBatchRequest(payload) && Array.isArray(response)) { + throw new ResponseError(response, 'Got batch response for a normal request.'); + } + if ((jsonRpc.isResponseWithError(response) || jsonRpc.isResponseWithResult(response)) && + !jsonRpc.isBatchRequest(payload)) { + if (response.id && payload.id !== response.id) { + throw new InvalidResponseError(response); + } + } + throw new ResponseError(response, 'Invalid response'); + } + static _isReverted(response) { + let error; + if (jsonRpc.isResponseWithError(response)) { + error = response.error; + } + else if (response instanceof Error) { + error = response; + } + // This message means that there was an error while executing the code of the smart contract + // However, more processing will happen at a higher level to decode the error data, + // according to the Error ABI, if it was available as of EIP-838. + if (error === null || error === void 0 ? void 0 : error.message.includes('revert')) + throw new ContractExecutionError(error); + return false; + } + // Need to use same types as _processJsonRpcResponse so have to declare as instance method + // eslint-disable-next-line class-methods-use-this + _buildResponse(payload, response, error) { + const res = { + jsonrpc: '2.0', + // eslint-disable-next-line no-nested-ternary + id: jsonRpc.isBatchRequest(payload) + ? payload[0].id + : 'id' in payload + ? payload.id + : // Have to use the null here explicitly + // eslint-disable-next-line no-null/no-null + null, + }; + if (error) { + return Object.assign(Object.assign({}, res), { error: response }); + } + return Object.assign(Object.assign({}, res), { result: response }); + } +} +//# sourceMappingURL=web3_request_manager.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_request_manager.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_request_manager.js.map new file mode 100644 index 0000000..ce34772 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_request_manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_request_manager.js","sourceRoot":"","sources":["../../src/web3_request_manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EACN,sBAAsB,EACtB,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,YAAY,EACZ,QAAQ,GACR,MAAM,aAAa,CAAC;AACrB,OAAO,YAAY,MAAM,qBAAqB,CAAC;AAC/C,OAAO,UAAU,MAAM,mBAAmB,CAAC;AAmB3C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,EACN,iBAAiB,EACjB,uBAAuB,EACvB,yBAAyB,EACzB,oBAAoB,EACpB,cA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AAK,CAAC,CAAC;QAE/E,OAAO,KAAK,CAAC;IACd,CAAC;IACD,0FAA0F;IAC1F,kDAAkD;IAC1C,cAAc,CACrB,OAAoC,EACpC,QAAgD,EAChD,KAAc;QAEd,MAAM,GAAG,GAAG;YACX,OAAO,EAAE,KAAK;YACd,6CAA6C;YAC7C,EAAE,EAAE,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC;gBAClC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;gBACf,CAAC,CAAC,IAAI,IAAI,OAAO;oBACjB,CAAC,CAAC,OAAO,CAAC,EAAE;oBACZ,CAAC,CAAC,uCAAuC;wBACvC,2CAA2C;wBAC3C,IAAI;SACP,CAAC;QAEF,IAAI,KAAK,EAAE;YACV,OAAO,gCACH,GAAG,KACN,KAAK,EAAE,QAAmB,GACK,CAAC;SACjC;QAED,OAAO,gCACH,GAAG,KACN,MAAM,EAAE,QAAmB,GACI,CAAC;IAClC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscription_manager.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscription_manager.js new file mode 100644 index 0000000..a60639c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscription_manager.js @@ -0,0 +1,189 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { DEFAULT_RETURN_FORMAT, } from 'web3-types'; +import { ProviderError, SubscriptionError } from 'web3-errors'; +import { isNullish } from 'web3-utils'; +import { isSupportSubscriptions } from './utils.js'; +import { Web3RequestManagerEvent } from './web3_request_manager.js'; +export class Web3SubscriptionManager { + constructor(requestManager, registeredSubscriptions, tolerateUnlinkedSubscription = false) { + this.requestManager = requestManager; + this.registeredSubscriptions = registeredSubscriptions; + this.tolerateUnlinkedSubscription = tolerateUnlinkedSubscription; + this._subscriptions = new Map(); + this.requestManager.on(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, () => __awaiter(this, void 0, void 0, function* () { + yield this.unsubscribe(); + })); + this.requestManager.on(Web3RequestManagerEvent.PROVIDER_CHANGED, () => { + this.clear(); + this.listenToProviderEvents(); + }); + this.listenToProviderEvents(); + } + listenToProviderEvents() { + const providerAsWebProvider = this.requestManager.provider; + if (!this.requestManager.provider || + (typeof (providerAsWebProvider === null || providerAsWebProvider === void 0 ? void 0 : providerAsWebProvider.supportsSubscriptions) === 'function' && + !(providerAsWebProvider === null || providerAsWebProvider === void 0 ? void 0 : providerAsWebProvider.supportsSubscriptions()))) { + return; + } + if (typeof this.requestManager.provider.on === 'function') { + if (typeof this.requestManager.provider.request === 'function') { + // Listen to provider messages and data + this.requestManager.provider.on('message', + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument + (message) => this.messageListener(message)); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument + providerAsWebProvider.on('data', (data) => this.messageListener(data)); + } + } + } + messageListener(data) { + var _a, _b, _c; + if (!data) { + throw new SubscriptionError('Should not call messageListener with no data. Type was'); + } + const subscriptionId = ((_a = data.params) === null || _a === void 0 ? void 0 : _a.subscription) || + ((_b = data.data) === null || _b === void 0 ? void 0 : _b.subscription) || + ((_c = data.id) === null || _c === void 0 ? void 0 : _c.toString(16)); + // Process if the received data is related to a subscription + if (subscriptionId) { + const sub = this._subscriptions.get(subscriptionId); + sub === null || sub === void 0 ? void 0 : sub.processSubscriptionData(data); + } + } + /** + * Will create a new subscription + * + * @param name - The subscription you want to subscribe to + * @param args - Optional additional parameters, depending on the subscription type + * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * + * Will subscribe to a specific topic (note: name) + * @returns The subscription object + */ + subscribe(name, args, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + const Klass = this.registeredSubscriptions[name]; + if (!Klass) { + throw new SubscriptionError('Invalid subscription type'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const subscription = new Klass(args !== null && args !== void 0 ? args : undefined, { + subscriptionManager: this, + returnFormat, + }); + yield this.addSubscription(subscription); + return subscription; + }); + } + /** + * Will returns all subscriptions. + */ + get subscriptions() { + return this._subscriptions; + } + /** + * + * Adds an instance of {@link Web3Subscription} and subscribes to it + * + * @param sub - A {@link Web3Subscription} object + */ + addSubscription(sub) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.requestManager.provider) { + throw new ProviderError('Provider not available'); + } + if (!this.supportsSubscriptions()) { + throw new SubscriptionError('The current provider does not support subscriptions'); + } + if (sub.id && this._subscriptions.has(sub.id)) { + throw new SubscriptionError(`Subscription with id "${sub.id}" already exists`); + } + yield sub.sendSubscriptionRequest(); + if (isNullish(sub.id)) { + throw new SubscriptionError('Subscription is not subscribed yet.'); + } + this._subscriptions.set(sub.id, sub); + return sub.id; + }); + } + /** + * Will clear a subscription + * + * @param id - The subscription of type {@link Web3Subscription} to remove + */ + removeSubscription(sub) { + return __awaiter(this, void 0, void 0, function* () { + const { id } = sub; + if (isNullish(id)) { + throw new SubscriptionError('Subscription is not subscribed yet. Or, had already been unsubscribed but not through the Subscription Manager.'); + } + if (!this._subscriptions.has(id) && !this.tolerateUnlinkedSubscription) { + throw new SubscriptionError(`Subscription with id "${id.toString()}" does not exists`); + } + yield sub.sendUnsubscribeRequest(); + this._subscriptions.delete(id); + return id; + }); + } + /** + * Will unsubscribe all subscriptions that fulfill the condition + * + * @param condition - A function that access and `id` and a `subscription` and return `true` or `false` + * @returns An array of all the un-subscribed subscriptions + */ + unsubscribe(condition) { + return __awaiter(this, void 0, void 0, function* () { + const result = []; + for (const [id, sub] of this.subscriptions.entries()) { + if (!condition || (typeof condition === 'function' && condition({ id, sub }))) { + result.push(this.removeSubscription(sub)); + } + } + return Promise.all(result); + }); + } + /** + * Clears all subscriptions + */ + clear() { + this._subscriptions.clear(); + } + /** + * Check whether the current provider supports subscriptions. + * + * @returns `true` or `false` depending on if the current provider supports subscriptions + */ + supportsSubscriptions() { + return isNullish(this.requestManager.provider) + ? false + : isSupportSubscriptions(this.requestManager.provider); + } +} +//# sourceMappingURL=web3_subscription_manager.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscription_manager.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscription_manager.js.map new file mode 100644 index 0000000..23fae24 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscription_manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscription_manager.js","sourceRoot":"","sources":["../../src/web3_subscription_manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAEN,qBAAqB,GAQrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EA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yBAAyB,EAAE,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;aACvF;YAED,MAAM,GAAG,CAAC,sBAAsB,EAAE,CAAC;YACnC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YAC/B,OAAO,EAAE,CAAC;QACX,CAAC;KAAA;IACD;;;;;OAKG;IACU,WAAW,CAAC,SAAsC;;YAC9D,MAAM,MAAM,GAAG,EAAE,CAAC;YAClB,KAAK,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,EAAE;gBACrD,IAAI,CAAC,SAAS,IAAI,CAAC,OAAO,SAAS,KAAK,UAAU,IAAI,SAAS,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE;oBAC9E,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;iBAC1C;aACD;YAED,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;KAAA;IAED;;OAEG;IACI,KAAK;QACX,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED;;;;OAIG;IACI,qBAAqB;QAC3B,OAAO,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC;YAC7C,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,sBAAsB,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;IACzD,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscriptions.js b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscriptions.js new file mode 100644 index 0000000..766b932 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscriptions.js @@ -0,0 +1,132 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +// eslint-disable-next-line max-classes-per-file +import { DEFAULT_RETURN_FORMAT, } from 'web3-types'; +import { jsonRpc } from 'web3-utils'; +import { SubscriptionError } from 'web3-errors'; +// eslint-disable-next-line import/no-cycle +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export class Web3Subscription extends Web3EventEmitter { + constructor(args, options) { + var _a; + super(); + this.args = args; + const { requestManager } = options; + const { subscriptionManager } = options; + if (requestManager && subscriptionManager) { + throw new SubscriptionError('Only requestManager or subscriptionManager should be provided at Subscription constructor'); + } + if (!requestManager && !subscriptionManager) { + throw new SubscriptionError('Either requestManager or subscriptionManager should be provided at Subscription constructor'); + } + if (requestManager) { + // eslint-disable-next-line deprecation/deprecation + this._subscriptionManager = new Web3SubscriptionManager(requestManager, {}, true); + } + else { + this._subscriptionManager = subscriptionManager; + } + this._returnFormat = (_a = options === null || options === void 0 ? void 0 : options.returnFormat) !== null && _a !== void 0 ? _a : DEFAULT_RETURN_FORMAT; + } + get id() { + return this._id; + } + get lastBlock() { + return this._lastBlock; + } + subscribe() { + return __awaiter(this, void 0, void 0, function* () { + return this._subscriptionManager.addSubscription(this); + }); + } + processSubscriptionData(data) { + var _a, _b; + if (data === null || data === void 0 ? void 0 : data.data) { + // for EIP-1193 provider + this._processSubscriptionResult((_b = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.result) !== null && _b !== void 0 ? _b : data === null || data === void 0 ? void 0 : data.data); + } + else if (data && + jsonRpc.isResponseWithNotification(data)) { + this._processSubscriptionResult(data === null || data === void 0 ? void 0 : data.params.result); + } + } + sendSubscriptionRequest() { + return __awaiter(this, void 0, void 0, function* () { + this._id = yield this._subscriptionManager.requestManager.send({ + method: 'eth_subscribe', + params: this._buildSubscriptionParams(), + }); + this.emit('connected', this._id); + return this._id; + }); + } + get returnFormat() { + return this._returnFormat; + } + get subscriptionManager() { + return this._subscriptionManager; + } + resubscribe() { + return __awaiter(this, void 0, void 0, function* () { + yield this.unsubscribe(); + yield this.subscribe(); + }); + } + unsubscribe() { + return __awaiter(this, void 0, void 0, function* () { + if (!this.id) { + return; + } + yield this._subscriptionManager.removeSubscription(this); + }); + } + sendUnsubscribeRequest() { + return __awaiter(this, void 0, void 0, function* () { + yield this._subscriptionManager.requestManager.send({ + method: 'eth_unsubscribe', + params: [this.id], + }); + this._id = undefined; + }); + } + // eslint-disable-next-line class-methods-use-this + formatSubscriptionResult(data) { + return data; + } + _processSubscriptionResult(data) { + this.emit('data', this.formatSubscriptionResult(data)); + } + _processSubscriptionError(error) { + this.emit('error', error); + } + // eslint-disable-next-line class-methods-use-this + _buildSubscriptionParams() { + // This should be overridden in the subclass + throw new Error('Implement in the child class'); + } +} +//# sourceMappingURL=web3_subscriptions.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscriptions.js.map b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscriptions.js.map new file mode 100644 index 0000000..92eaec3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/esm/web3_subscriptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"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AAE;gBACb,OAAO;aACP;YAED,MAAM,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAC1D,CAAC;KAAA;IAEY,sBAAsB;;YAClC,MAAM,IAAI,CAAC,oBAAoB,CAAC,cAAc,CAAC,IAAI,CAAC;gBACnD,MAAM,EAAE,iBAAiB;gBACzB,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAA0C;aAC1D,CAAC,CAAC;YACH,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;QACtB,CAAC;KAAA;IAED,kDAAkD;IACxC,wBAAwB,CAAC,IAA8B;QAChE,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,0BAA0B,CAAC,IAAwC;QACzE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC,CAAC;IACxD,CAAC;IAEM,yBAAyB,CAAC,KAAY;QAC5C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC3B,CAAC;IAED,kDAAkD;IACxC,wBAAwB;QACjC,4CAA4C;QAC5C,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IACjD,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/formatters.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/formatters.d.ts new file mode 100644 index 0000000..f9c6dc6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/formatters.d.ts @@ -0,0 +1,100 @@ +import { Filter, Numbers, Topic, BlockInput, BlockOutput, LogsInput, LogsOutput, Mutable, PostInput, PostOutput, Proof, ReceiptInput, ReceiptOutput, SyncInput, SyncOutput, TransactionInput, TransactionOutput } from 'web3-types'; +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given storage key array values to hex strings. + */ +export declare const inputStorageKeysFormatter: (keys: Array) => string[]; +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given proof response from the node. + */ +export declare const outputProofFormatter: (proof: Proof) => Proof; +/** + * @deprecated Use format function from web3-utils package instead + * Should the format output to a big number + */ +export declare const outputBigIntegerFormatter: (number: Numbers) => number | bigint; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or the predefined block number 'latest', 'pending', 'earliest', 'genesis' + */ +export declare const inputBlockNumberFormatter: (blockNumber: Numbers | undefined) => string | undefined; +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or does return the defaultBlock property of the current module + */ +export declare const inputDefaultBlockNumberFormatter: (blockNumber: Numbers | undefined, defaultBlock: Numbers) => string | undefined; +/** + * @deprecated Use format function from web3-utils package instead + * @param address + */ +export declare const inputAddressFormatter: (address: string) => string | never; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export declare const txInputOptionsFormatter: (options: TransactionInput) => Mutable; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export declare const inputCallFormatter: (options: TransactionInput, defaultAccount?: string) => Mutable; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export declare const inputTransactionFormatter: (options: TransactionInput, defaultAccount?: string) => Mutable; +/** + * @deprecated Use format function from web3-utils package instead + * Hex encodes the data passed to eth_sign and personal_sign + */ +export declare const inputSignFormatter: (data: string) => string; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction to its proper values + * @function outputTransactionFormatter + */ +export declare const outputTransactionFormatter: (tx: TransactionInput) => TransactionOutput; +/** + * @deprecated Use format function from web3-utils package instead + * @param topic + */ +export declare const inputTopicFormatter: (topic: Topic) => Topic | null; +/** + * @deprecated Use format function from web3-utils package instead + * @param filter + */ +export declare const inputLogFormatter: (filter: Filter) => Filter; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a log + * @function outputLogFormatter + */ +export declare const outputLogFormatter: (log: Partial) => LogsOutput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction receipt to its proper values + */ +export declare const outputTransactionReceiptFormatter: (receipt: ReceiptInput) => ReceiptOutput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a block to its proper values + * @function outputBlockFormatter + */ +export declare const outputBlockFormatter: (block: BlockInput) => BlockOutput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a whisper post and converts all values to HEX + */ +export declare const inputPostFormatter: (post: PostOutput) => PostInput; +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a received post message + * @function outputPostFormatter + */ +export declare const outputPostFormatter: (post: PostInput) => PostOutput; +/** + * @deprecated Use format function from web3-utils package instead + */ +export declare const outputSyncingFormatter: (result: SyncInput) => SyncOutput; +//# sourceMappingURL=formatters.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/formatters.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/formatters.d.ts.map new file mode 100644 index 0000000..e4d2297 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/formatters.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"formatters.d.ts","sourceRoot":"","sources":["../../src/formatters.ts"],"names":[],"mappings":"AAmBA,OAAO,EAEN,MAAM,EACN,OAAO,EACP,KAAK,EACL,UAAU,EACV,WAAW,EACX,SAAS,EACT,UAAU,EACV,OAAO,EACP,SAAS,EACT,UAAU,EACV,KAAK,EACL,YAAY,EACZ,aAAa,EACb,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,YAAY,CAAC;AAkBpB;;;GAGG;AACH,eAAO,MAAM,yBAAyB,SAAU,MAAM,MAAM,CAAC,aAAsC,CAAC;AAEpG;;;GAGG;AACH,eAAO,MAAM,oBAAoB,UAAW,KAAK,KAAG,KAIlD,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,yBAAyB,WAAY,OAAO,oBAAqB,CAAC;AAE/E;;;GAGG;AACH,eAAO,MAAM,yBAAyB,gBAAiB,OAAO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ejs/node_modules/web3-core/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/index.d.ts new file mode 100644 index 0000000..c328da7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/index.d.ts @@ -0,0 +1,13 @@ +export * from './web3_config.js'; +export * from './web3_request_manager.js'; +export * from './web3_subscription_manager.js'; +export * from './web3_subscriptions.js'; +export * from './web3_context.js'; +export * from './web3_batch_request.js'; +export * from './utils.js'; +export * from './types.js'; +export * from './formatters.js'; +export * from './web3_promi_event.js'; +export * from './web3_event_emitter.js'; +export * as formatters from './formatters.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/index.d.ts.map new file mode 100644 index 0000000..42fa24e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AAGxC,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/types.d.ts new file mode 100644 index 0000000..b950a9a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/types.d.ts @@ -0,0 +1,11 @@ +import { HexString, Transaction } from 'web3-types'; +export declare type TransactionTypeParser = (transaction: Transaction) => HexString | undefined; +export interface Method { + name: string; + call: string; +} +export interface ExtensionObject { + property?: string; + methods: Method[]; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/types.d.ts.map new file mode 100644 index 0000000..9f7f591 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEpD,oBAAY,qBAAqB,GAAG,CACnC,WAAW,EAAE,WAAW,KACpB,SAAS,GAAG,SAAS,CAAC;AAE3B,MAAM,WAAW,MAAM;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,EAAE,CAAC;CAClB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/utils.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/utils.d.ts new file mode 100644 index 0000000..3f237f4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/utils.d.ts @@ -0,0 +1,10 @@ +import { EIP1193Provider, LegacyRequestProvider, LegacySendAsyncProvider, LegacySendProvider, SupportedProviders, Web3BaseProvider, MetaMaskProvider } from 'web3-types'; +export declare const isWeb3Provider: (provider: SupportedProviders) => provider is Web3BaseProvider; +export declare const isMetaMaskProvider: (provider: SupportedProviders) => provider is MetaMaskProvider; +export declare const isLegacyRequestProvider: (provider: SupportedProviders) => provider is LegacyRequestProvider; +export declare const isEIP1193Provider: (provider: SupportedProviders) => provider is EIP1193Provider; +export declare const isLegacySendProvider: (provider: SupportedProviders) => provider is LegacySendProvider; +export declare const isLegacySendAsyncProvider: (provider: SupportedProviders) => provider is LegacySendAsyncProvider; +export declare const isSupportedProvider: (provider: SupportedProviders) => provider is SupportedProviders; +export declare const isSupportSubscriptions: (provider: SupportedProviders) => boolean; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/utils.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/utils.d.ts.map new file mode 100644 index 0000000..1753636 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,eAAe,EACf,qBAAqB,EACrB,uBAAuB,EACvB,kBAAkB,EAClB,kBAAkB,EAElB,gBAAgB,EAChB,gBAAgB,EAChB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,cAAc,+FAEsD,CAAC;AAElF,eAAO,MAAM,kBAAkB,+FAKyE,CAAC;AAGzG,eAAO,MAAM,uBAAuB,+FAKa,CAAC;AAElD,eAAO,MAAM,iBAAiB,8FAKwB,CAAC;AAEvD,eAAO,MAAM,oBAAoB,4FAEsD,CAAC;AAExF,eAAO,MAAM,yBAAyB,iGAE2D,CAAC;AAElG,eAAO,MAAM,mBAAmB,iGAQC,CAAC;AAClC,eAAO,MAAM,sBAAsB,8DAEhC,OAUF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_batch_request.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_batch_request.d.ts new file mode 100644 index 0000000..d285255 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_batch_request.d.ts @@ -0,0 +1,17 @@ +import { JsonRpcBatchResponse, JsonRpcOptionalRequest, JsonRpcRequest } from 'web3-types'; +import { Web3DeferredPromise } from 'web3-utils'; +import { Web3RequestManager } from './web3_request_manager.js'; +export declare const DEFAULT_BATCH_REQUEST_TIMEOUT = 1000; +export declare class Web3BatchRequest { + private readonly _requestManager; + private readonly _requests; + constructor(requestManager: Web3RequestManager); + get requests(): JsonRpcRequest[]; + add(request: JsonRpcOptionalRequest): Web3DeferredPromise; + execute(options?: { + timeout?: number; + }): Promise>; + private _processBatchRequest; + private _abortAllRequests; +} +//# sourceMappingURL=web3_batch_request.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_batch_request.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_batch_request.d.ts.map new file mode 100644 index 0000000..d1b7055 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_batch_request.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_batch_request.d.ts","sourceRoot":"","sources":["../../src/web3_batch_request.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC1F,OAAO,EAAW,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAqB;IACrD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAGxB;gBAEiB,cAAc,EAAE,kBAAkB;IAKrD,IAAW,QAAQ,gCAElB;IAEM,GAAG,CAAC,YAAY,GAAG,OAAO,EAAE,OAAO,EAAE,sBAAsB,CAAC,OAAO,CAAC;IAU9D,OAAO,CAAC,OAAO,CAAC,EAAE;QAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;KACjB,GAAG,OAAO,CAAC,oBAAoB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAwBrC,oBAAoB;IA8ClC,OAAO,CAAC,iBAAiB;CAKzB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_config.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_config.d.ts new file mode 100644 index 0000000..81cb19b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_config.d.ts @@ -0,0 +1,247 @@ +import { Numbers, HexString, BlockNumberOrTag, Common } from 'web3-types'; +import { TransactionTypeParser } from './types.js'; +import { TransactionBuilder } from './web3_context.js'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export interface Web3ConfigOptions { + handleRevert: boolean; + defaultAccount?: HexString; + defaultBlock: BlockNumberOrTag; + transactionSendTimeout: number; + transactionBlockTimeout: number; + transactionConfirmationBlocks: number; + transactionPollingInterval: number; + transactionPollingTimeout: number; + transactionReceiptPollingInterval?: number; + transactionConfirmationPollingInterval?: number; + blockHeaderTimeout: number; + maxListenersWarningThreshold: number; + contractDataInputFill: 'data' | 'input' | 'both'; + defaultNetworkId?: Numbers; + defaultChain: string; + defaultHardfork: string; + defaultCommon?: Common; + defaultTransactionType: Numbers; + defaultMaxPriorityFeePerGas: Numbers; + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; + }; + transactionBuilder?: TransactionBuilder; + transactionTypeParser?: TransactionTypeParser; +} +declare type ConfigEvent = P extends unknown ? { + name: P; + oldValue: T[P]; + newValue: T[P]; +} : never; +export declare enum Web3ConfigEvent { + CONFIG_CHANGE = "CONFIG_CHANGE" +} +export declare abstract class Web3Config extends Web3EventEmitter<{ + [Web3ConfigEvent.CONFIG_CHANGE]: ConfigEvent; +}> implements Web3ConfigOptions { + config: Web3ConfigOptions; + constructor(options?: Partial); + setConfig(options: Partial): void; + /** + * The `handleRevert` options property returns the revert reason string if enabled for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + * Default is `false`. + * + * `Note`: At the moment `handleRevert` is only supported for `sendTransaction` and not for `sendSignedTransaction` + */ + get handleRevert(): boolean; + /** + * Will set the handleRevert + */ + set handleRevert(val: boolean); + /** + * The `contractDataInputFill` options property will allow you to set the hash of the method signature and encoded parameters to the property + * either `data`, `input` or both within your contract. + * This will affect the contracts send, call and estimateGas methods + * Default is `input`. + */ + get contractDataInputFill(): "input" | "data" | "both"; + /** + * Will set the contractDataInputFill + */ + set contractDataInputFill(val: "input" | "data" | "both"); + /** + * This default address is used as the default `from` property, if no `from` property is specified in for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + */ + get defaultAccount(): string | undefined; + /** + * Will set the default account. + */ + set defaultAccount(val: string | undefined); + /** + * The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is `"latest"`. + * - web3.eth.getBalance() + * - web3.eth.getCode() + * - web3.eth.getTransactionCount() + * - web3.eth.getStorageAt() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + */ + get defaultBlock(): BlockNumberOrTag; + /** + * Will set the default block. + * + * - A block number + * - `"earliest"` - String: The genesis block + * - `"latest"` - String: The latest block (current head of the blockchain) + * - `"pending"` - String: The currently mined block (including pending transactions) + * - `"finalized"` - String: (For POS networks) The finalized block is one which has been accepted as canonical by greater than 2/3 of validators + * - `"safe"` - String: (For POS networks) The safe head block is one which under normal network conditions, is expected to be included in the canonical chain. Under normal network conditions the safe head and the actual tip of the chain will be equivalent (with safe head trailing only by a few seconds). Safe heads will be less likely to be reorged than the proof of work network`s latest blocks. + */ + set defaultBlock(val: BlockNumberOrTag); + /** + * The time used to wait for Ethereum Node to return the sent transaction result. + * Note: If the RPC call stuck at the Node and therefor timed-out, the transaction may still be pending or even mined by the Network. We recommend checking the pending transactions in such a case. + * Default is `750` seconds (12.5 minutes). + */ + get transactionSendTimeout(): number; + /** + * Will set the transactionSendTimeout. + */ + set transactionSendTimeout(val: number); + /** + * The `transactionBlockTimeout` is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. + * Default is `50`. + */ + get transactionBlockTimeout(): number; + /** + * Will set the transactionBlockTimeout. + */ + set transactionBlockTimeout(val: number); + /** + * This defines the number of blocks it requires until a transaction is considered confirmed. + * Default is `24`. + */ + get transactionConfirmationBlocks(): number; + /** + * Will set the transactionConfirmationBlocks. + */ + set transactionConfirmationBlocks(val: number); + /** + * Used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `1000` ms. + */ + get transactionPollingInterval(): number; + /** + * Will set the transactionPollingInterval. + */ + set transactionPollingInterval(val: number); + /** + * Used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times out, the transaction may still be pending. + * Default is `750` seconds (12.5 minutes). + */ + get transactionPollingTimeout(): number; + /** + * Will set the transactionPollingTimeout. + */ + set transactionPollingTimeout(val: number); + /** + * The `transactionPollingInterval` is used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `undefined` + */ + get transactionReceiptPollingInterval(): number | undefined; + /** + * Will set the transactionReceiptPollingInterval + */ + set transactionReceiptPollingInterval(val: number | undefined); + get transactionConfirmationPollingInterval(): number | undefined; + set transactionConfirmationPollingInterval(val: number | undefined); + /** + * The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt. + * Default is `10` seconds. + */ + get blockHeaderTimeout(): number; + /** + * Will set the blockHeaderTimeout + */ + set blockHeaderTimeout(val: number); + /** + * The enableExperimentalFeatures is used to enable trying new experimental features that are still not fully implemented or not fully tested or still have some related issues. + * Default is `false` for every feature. + */ + get enableExperimentalFeatures(): { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; + }; + /** + * Will set the enableExperimentalFeatures + */ + set enableExperimentalFeatures(val: { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; + }); + get maxListenersWarningThreshold(): number; + set maxListenersWarningThreshold(val: number); + get defaultNetworkId(): Numbers | undefined; + set defaultNetworkId(val: Numbers | undefined); + get defaultChain(): string; + set defaultChain(val: string); + /** + * Will return the default hardfork. Default is `london` + * The default hardfork property can be one of the following: + * - `chainstart` + * - `homestead` + * - `dao` + * - `tangerineWhistle` + * - `spuriousDragon` + * - `byzantium` + * - `constantinople` + * - `petersburg` + * - `istanbul` + * - `berlin` + * - `london` + * - 'arrowGlacier', + * - 'tangerineWhistle', + * - 'muirGlacier' + * + */ + get defaultHardfork(): string; + /** + * Will set the default hardfork. + * + */ + set defaultHardfork(val: string); + /** + * + * Will get the default common property + * The default common property does contain the following Common object: + * - `customChain` - `Object`: The custom chain properties + * - `name` - `string`: (optional) The name of the chain + * - `networkId` - `number`: Network ID of the custom chain + * - `chainId` - `number`: Chain ID of the custom chain + * - `baseChain` - `string`: (optional) mainnet, goerli, kovan, rinkeby, or ropsten + * - `hardfork` - `string`: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london + * Default is `undefined`. + * + */ + get defaultCommon(): Common | undefined; + /** + * Will set the default common property + * + */ + set defaultCommon(val: Common | undefined); + get defaultTransactionType(): Numbers; + set defaultTransactionType(val: Numbers); + get defaultMaxPriorityFeePerGas(): Numbers; + set defaultMaxPriorityFeePerGas(val: Numbers); + get transactionBuilder(): TransactionBuilder | undefined; + set transactionBuilder(val: TransactionBuilder | undefined); + get transactionTypeParser(): TransactionTypeParser | undefined; + set transactionTypeParser(val: TransactionTypeParser | undefined); + private _triggerConfigChange; +} +export {}; +//# sourceMappingURL=web3_config.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_config.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_config.d.ts.map new file mode 100644 index 0000000..b647d31 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_config.d.ts","sourceRo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AGhC;IAED,IAAW,qBAAqB,sCAE/B;IAED,IAAW,qBAAqB,CAAC,GAAG,mCAAA,EAGnC;IAED,OAAO,CAAC,oBAAoB;CAU5B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_context.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_context.d.ts new file mode 100644 index 0000000..c6ac4f5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_context.d.ts @@ -0,0 +1,211 @@ +import { EthExecutionAPI, HexString, Numbers, SupportedProviders, Transaction, Web3AccountProvider, Web3APISpec, Web3BaseProvider, Web3BaseWallet, Web3BaseWalletAccount } from 'web3-types'; +import { BaseTransaction } from 'web3-eth-accounts'; +import { ExtensionObject } from './types.js'; +import { Web3BatchRequest } from './web3_batch_request.js'; +import { Web3Config, Web3ConfigOptions } from './web3_config.js'; +import { Web3RequestManager } from './web3_request_manager.js'; +import { Web3SubscriptionConstructor } from './web3_subscriptions.js'; +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +export declare type Web3ContextObject; +} = any> = { + config: Web3ConfigOptions; + provider?: SupportedProviders | string; + requestManager: Web3RequestManager; + subscriptionManager?: Web3SubscriptionManager | undefined; + registeredSubscriptions?: RegisteredSubs; + providers: typeof Web3RequestManager.providers; + accountProvider?: Web3AccountProvider; + wallet?: Web3BaseWallet; +}; +export declare type Web3ContextInitOptions; +} = any> = { + config?: Partial; + provider?: SupportedProviders | string; + requestManager?: Web3RequestManager; + subscriptionManager?: Web3SubscriptionManager | undefined; + registeredSubscriptions?: RegisteredSubs; + accountProvider?: Web3AccountProvider; + wallet?: Web3BaseWallet; +}; +export declare type Web3ContextConstructor = new (...args: [...extras: T2, context: Web3ContextObject]) => T; +export declare type Web3ContextFactory = Web3ContextConstructor & { + fromContextObject(this: Web3ContextConstructor, contextObject: Web3ContextObject): T; +}; +export declare class Web3Context; +} = any> extends Web3Config { + static readonly providers: { + HttpProvider: import("web3-types").Web3BaseProviderConstructor; + WebsocketProvider: import("web3-types").Web3BaseProviderConstructor; + }; + static givenProvider?: SupportedProviders; + readonly providers: { + HttpProvider: import("web3-types").Web3BaseProviderConstructor; + WebsocketProvider: import("web3-types").Web3BaseProviderConstructor; + }; + protected _requestManager: Web3RequestManager; + protected _subscriptionManager: Web3SubscriptionManager; + protected _accountProvider?: Web3AccountProvider; + protected _wallet?: Web3BaseWallet; + constructor(providerOrContext?: string | SupportedProviders | Web3ContextInitOptions); + get requestManager(): Web3RequestManager; + /** + * Will return the current subscriptionManager ({@link Web3SubscriptionManager}) + */ + get subscriptionManager(): Web3SubscriptionManager; + get wallet(): Web3BaseWallet | undefined; + get accountProvider(): Web3AccountProvider | undefined; + static fromContextObject(this: Web3ContextConstructor, ...args: [Web3ContextObject, ...T3]): T; + getContextObject(): Web3ContextObject; + /** + * Use to create new object of any type extended by `Web3Context` + * and link it to current context. This can be used to initiate a global context object + * and then use it to create new objects of any type extended by `Web3Context`. + */ + use(ContextRef: Web3ContextConstructor, ...args: [...T2]): T; + /** + * Link current context to another context. + */ + link(parentContext: T): void; + registerPlugin(plugin: Web3PluginBase): void; + /** + * Will return the current provider. + * + * @returns Returns the current provider + * @example + * ```ts + * const web3 = new Web3Context("http://localhost:8545"); + * console.log(web3.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get provider(): Web3BaseProvider | undefined; + /** + * Will set the current provider. + * + * @param provider - The provider to set + * + * Accepted providers are of type {@link SupportedProviders} + * @example + * ```ts + * const web3Context = new web3ContextContext("http://localhost:8545"); + * web3Context.provider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set provider(provider: SupportedProviders | string | undefined); + /** + * Will return the current provider. (The same as `provider`) + * + * @returns Returns the current provider + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * console.log(web3Context.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + get currentProvider(): Web3BaseProvider | undefined; + /** + * Will set the current provider. (The same as `provider`) + * + * @param provider - {@link SupportedProviders} The provider to set + * + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * web3Context.currentProvider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + set currentProvider(provider: SupportedProviders | string | undefined); + /** + * Will return the givenProvider if available. + * + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise `undefined`. + */ + get givenProvider(): SupportedProviders | undefined; + /** + * Will set the provider. + * + * @param provider - {@link SupportedProviders} The provider to set + * @returns Returns true if the provider was set + */ + setProvider(provider?: SupportedProviders | string): boolean; + /** + * Will return the {@link Web3BatchRequest} constructor. + */ + get BatchRequest(): new () => Web3BatchRequest; + /** + * This method allows extending the web3 modules. + * Note: This method is only for backward compatibility, and It is recommended to use Web3 v4 Plugin feature for extending web3.js functionality if you are developing some thing new. + */ + extend(extendObj: ExtensionObject): this; +} +/** + * Extend this class when creating a plugin that either doesn't require {@link EthExecutionAPI}, + * or interacts with a RPC node that doesn't fully implement {@link EthExecutionAPI}. + * + * To add type support for RPC methods to the {@link Web3RequestManager}, + * define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: + * + * @example + * ```ts + * type CustomRpcApi = { + * custom_rpc_method: () => string; + * custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; + * }; + * + * class CustomPlugin extends Web3PluginBase {...} + * ``` + */ +export declare abstract class Web3PluginBase extends Web3Context { + abstract pluginNamespace: string; + protected registerNewTransactionType>(type: Numbers, txClass: NewTxTypeClass): void; +} +/** +* Extend this class when creating a plugin that makes use of {@link EthExecutionAPI}, +* or depends on other Web3 packages (such as `web3-eth-contract`) that depend on {@link EthExecutionAPI}. +* +* To add type support for RPC methods to the {@link Web3RequestManager} (in addition to {@link EthExecutionAPI}), +* define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: +* +* @example +* ```ts +* type CustomRpcApi = { +* custom_rpc_method: () => string; +* custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; +* }; +* +* class CustomPlugin extends Web3PluginBase {...} +* ``` +*/ +export declare abstract class Web3EthPluginBase extends Web3PluginBase { +} +export declare type TransactionBuilder = (options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; +}) => Promise; +//# sourceMappingURL=web3_context.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_context.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_context.d.ts.map new file mode 100644 index 0000000..af2df96 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_context.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_context.d.ts","sourceRoot":"","sources":["../../src/web3_context.ts"],"names":[],"mappings":"AAkBA,OAAO,EACN,eAAe,EACf,SAAS,EAAE,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,gBAAgB,EAAE,cAAc,EACvH,qBAAqB,EACrB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,eAAe,EAAsB,MAAM,mBAAmB,CAAC;AAGxE,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAmB,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gC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IAED;;;OAGG;IACI,MAAM,CAAC,SAAS,EAAE,eAAe;CAsBxC;AAED;;;;;;;;;;;;;;;;GAgBG;AACF,8BAAsB,cAAc,CACpC,GAAG,SAAS,WAAW,GAAG,WAAW,CACpC,SAAQ,WAAW,CAAC,GAAG,CAAC;IACzB,SAAgB,eAAe,EAAE,MAAM,CAAC;IAGxC,SAAS,CAAC,0BAA0B,CAAC,cAAc,SAAS,OAAO,eAAe,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI;CAG1I;AAED;;;;;;;;;;;;;;;;EAgBE;AACF,8BAAsB,iBAAiB,CAAC,GAAG,SAAS,WAAW,GAAG,OAAO,CAAE,SAAQ,cAAc,CAChG,GAAG,GAAG,eAAe,CACrB;CAAG;AAGJ,oBAAY,kBAAkB,CAAC,GAAG,SAAS,WAAW,GAAG,OAAO,IAAI,CACnE,UAAU,GAAG,WAAW,EACvB,OAAO,EAAE;IACV,WAAW,EAAE,WAAW,CAAC;IACzB,WAAW,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC;IAC9B,UAAU,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;IACpC,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_event_emitter.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_event_emitter.d.ts new file mode 100644 index 0000000..b0c566f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_event_emitter.d.ts @@ -0,0 +1,24 @@ +import { EventEmitter } from 'web3-utils'; +export declare type Web3EventMap = Record; +export declare type Web3EventKey = string & keyof T; +export declare type Web3EventCallback = (params: T) => void | Promise; +export interface Web3Emitter { + on>(eventName: K, fn: Web3EventCallback): void; + once>(eventName: K, fn: Web3EventCallback): void; + off>(eventName: K, fn: Web3EventCallback): void; + emit>(eventName: K, params: T[K]): void; +} +export declare class Web3EventEmitter implements Web3Emitter { + private readonly _emitter; + on>(eventName: K, fn: Web3EventCallback): void; + once>(eventName: K, fn: Web3EventCallback): void; + off>(eventName: K, fn: Web3EventCallback): void; + emit>(eventName: K, params: T[K]): void; + listenerCount>(eventName: K): number; + listeners>(eventName: K): Function[]; + eventNames(): (string | symbol)[]; + removeAllListeners(): EventEmitter; + setMaxListenerWarningThreshold(maxListenersWarningThreshold: number): void; + getMaxListeners(): number; +} +//# sourceMappingURL=web3_event_emitter.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_event_emitter.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_event_emitter.d.ts.map new file mode 100644 index 0000000..6ecda16 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_event_emitter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_event_emitter.d.ts","sourceRoot":"","sources":["../../src/web3_event_emitter.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,oBAAY,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACnD,oBAAY,YAAY,CAAC,CAAC,SAAS,YAAY,IAAI,MAAM,GAAG,MAAM,CAAC,CAAC;AACpE,oBAAY,iBAAiB,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACvE,MAAM,WAAW,WAAW,CAAC,CAAC,SAAS,YAAY;IAClD,EAAE,CAAC,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAC/E,IAAI,CAAC,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC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AIV,kBAAkB;IAGlB,8BAA8B,CAAC,4BAA4B,EAAE,MAAM;IAGnE,eAAe;CAGtB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_promi_event.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_promi_event.d.ts new file mode 100644 index 0000000..23680f5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_promi_event.d.ts @@ -0,0 +1,13 @@ +import { Web3EventCallback, Web3EventEmitter, Web3EventKey, Web3EventMap } from './web3_event_emitter.js'; +export declare type PromiseExecutor = (resolve: (data: T) => void, reject: (reason: unknown) => void) => void; +export declare class Web3PromiEvent extends Web3EventEmitter implements Promise { + private readonly _promise; + constructor(executor: PromiseExecutor); + [Symbol.toStringTag]: 'Promise'; + then(onfulfilled?: ((value: ResolveType) => TResult1 | PromiseLike) | undefined, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | undefined): Promise; + catch(onrejected?: ((reason: unknown) => TResult | PromiseLike) | undefined): Promise; + finally(onfinally?: (() => void) | undefined): Promise; + on>(eventName: K, fn: Web3EventCallback): this; + once>(eventName: K, fn: Web3EventCallback): this; +} +//# sourceMappingURL=web3_promi_event.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_promi_event.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_promi_event.d.ts.map new file mode 100644 index 0000000..4ad722b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_promi_event.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_promi_event.d.ts","sourceRoot":"","sources":["../../src/web3_promi_event.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,MAAM,yBAAyB,CAAC;AAEjC,oBAAY,eAAe,CAAC,CAAC,IAAI,CAChC,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,EAC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AAE,EAAE,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GAChC,IAAI;CAKP"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_request_manager.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_request_manager.d.ts new file mode 100644 index 0000000..6e96424 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_request_manager.d.ts @@ -0,0 +1,60 @@ +import { EthExecutionAPI, JsonRpcBatchRequest, JsonRpcBatchResponse, SupportedProviders, Web3APIMethod, Web3APIRequest, Web3APIReturnType, Web3APISpec, Web3BaseProviderConstructor } from 'web3-types'; +import { Web3EventEmitter } from './web3_event_emitter.js'; +export declare enum Web3RequestManagerEvent { + PROVIDER_CHANGED = "PROVIDER_CHANGED", + BEFORE_PROVIDER_CHANGE = "BEFORE_PROVIDER_CHANGE" +} +export declare class Web3RequestManager extends Web3EventEmitter<{ + [key in Web3RequestManagerEvent]: SupportedProviders | undefined; +}> { + private _provider?; + private readonly useRpcCallSpecification?; + constructor(provider?: SupportedProviders | string, useRpcCallSpecification?: boolean); + /** + * Will return all available providers + */ + static get providers(): { + HttpProvider: Web3BaseProviderConstructor; + WebsocketProvider: Web3BaseProviderConstructor; + }; + /** + * Will return the current provider. + * + * @returns Returns the current provider + */ + get provider(): SupportedProviders | undefined; + /** + * Will return all available providers + */ + get providers(): { + HttpProvider: Web3BaseProviderConstructor; + WebsocketProvider: Web3BaseProviderConstructor; + }; + /** + * Use to set provider. Provider can be a provider instance or a string. + * + * @param provider - The provider to set + */ + setProvider(provider?: SupportedProviders | string): boolean; + /** + * + * Will execute a request + * + * @param request - {@link Web3APIRequest} The request to send + * + * @returns The response of the request {@link ResponseType}. If there is error + * in the response, will throw an error + */ + send, ResponseType = Web3APIReturnType>(request: Web3APIRequest): Promise; + /** + * Same as send, but, will execute a batch of requests + * + * @param request {@link JsonRpcBatchRequest} The batch request to send + */ + sendBatch(request: JsonRpcBatchRequest): Promise>; + private _sendRequest; + private _processJsonRpcResponse; + private static _isReverted; + private _buildResponse; +} +//# sourceMappingURL=web3_request_manager.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_request_manager.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_request_manager.d.ts.map new file mode 100644 index 0000000..6dbd475 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_request_manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_request_manager.d.ts","sourceRoot":"","sources":["../../src/web3_request_manager.ts"],"names":[],"mappings":"AA2BA,OAAO,EACN,eAAe,EACf,mBAAmB,EACnB,oBAAoB,EAMpB,kBAAkB,EAClB,aAAa,EAEb,cAAc,EACd,iBAAiB,EACjB,WAAW,EAEX,2BAA2B,EAC3B,MAAM,YAAY,CAAC;AASpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,oBAAY,uBAAuB;IAClC,gBAAgB,qBAAqB;IACrC,sBAAsB,2BAA2B;CACjD;AAUD,qBAAa,kBAAkB,CAC9B,GAAG,SAAS,WAAW,GAAG,eAAe,CACxC,SAAQ,gBAAgB,CAAC;KACzB,GAAG,IAAI,uBAAuB,GAAG,kBAAkB,CAAC,GAAG,CAAC,GAAG,SAAS;CACrE,CAAC;IACD,OAAO,CAAC,SAAS,CAAC,CAA0B;IAC5C,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAAU;gBAElD,QAAQ,CAAC,EAAE,kBAAkB,CAAC,GAAG,CAAC,GAAG,MAAM,EAC3C,uBAAuB,CAAC,EAAE,OAAO;IAUlC;;OAEG;IACH,WAAkB,SAAS;;;MAE1B;IAED;;;;OAIG;IACH,IAAW,QAAQ,wCAElB;IAED;;OAEG;IAEH,IAAW,SAAS;;;MAEnB;IAED;;;;OAIG;IACI,WAAW,CAAC,QAAQ,CAAC,EAAE,kBAAkB,CAAC,GAAG,CAAC,GAAG,MAAM,GAAG,OAAO;IA4BxE;;;;;;;;OAQG;IACU,IAAI,CAChB,MAAM,SAAS,aAAa,CAAC,GAAG,CAAC,EACjC,YAAY,GAAG,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,EAC5C,OAAO,EAAE,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC;IAS9D;;;;OAIG;IACU,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;YAM9E,YAAY;IAwJ1B,OAAO,CAAC,uBAAuB;IAyF/B,OAAO,CAAC,MAAM,CAAC,WAAW;IAoB1B,OAAO,CAAC,cAAc;CA6BtB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscription_manager.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscription_manager.d.ts new file mode 100644 index 0000000..f0737ea --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscription_manager.d.ts @@ -0,0 +1,82 @@ +import { DataFormat, JsonRpcNotification, JsonRpcSubscriptionResult, JsonRpcSubscriptionResultOld, Log, Web3APISpec } from 'web3-types'; +import { Web3RequestManager } from './web3_request_manager.js'; +import { Web3SubscriptionConstructor } from './web3_subscriptions.js'; +declare type ShouldUnsubscribeCondition = ({ id, sub, }: { + id: string; + sub: unknown; +}) => boolean | undefined; +export declare class Web3SubscriptionManager; +} = { + [key: string]: Web3SubscriptionConstructor; +}> { + readonly requestManager: Web3RequestManager; + readonly registeredSubscriptions: RegisteredSubs; + private readonly tolerateUnlinkedSubscription; + private readonly _subscriptions; + /** + * + * @param - requestManager + * @param - registeredSubscriptions + * + * @example + * ```ts + * const requestManager = new Web3RequestManager("ws://localhost:8545"); + * const subscriptionManager = new Web3SubscriptionManager(requestManager, {}); + * ``` + */ + constructor(requestManager: Web3RequestManager, registeredSubscriptions: RegisteredSubs); + /** + * @deprecated This constructor overloading should not be used + */ + constructor(requestManager: Web3RequestManager, registeredSubscriptions: RegisteredSubs, tolerateUnlinkedSubscription: boolean); + private listenToProviderEvents; + protected messageListener(data?: JsonRpcSubscriptionResult | JsonRpcSubscriptionResultOld | JsonRpcNotification): void; + /** + * Will create a new subscription + * + * @param name - The subscription you want to subscribe to + * @param args - Optional additional parameters, depending on the subscription type + * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * + * Will subscribe to a specific topic (note: name) + * @returns The subscription object + */ + subscribe(name: T, args?: ConstructorParameters[0], returnFormat?: DataFormat): Promise>; + /** + * Will returns all subscriptions. + */ + get subscriptions(): Map>; + /** + * + * Adds an instance of {@link Web3Subscription} and subscribes to it + * + * @param sub - A {@link Web3Subscription} object + */ + addSubscription(sub: InstanceType): Promise; + /** + * Will clear a subscription + * + * @param id - The subscription of type {@link Web3Subscription} to remove + */ + removeSubscription(sub: InstanceType): Promise; + /** + * Will unsubscribe all subscriptions that fulfill the condition + * + * @param condition - A function that access and `id` and a `subscription` and return `true` or `false` + * @returns An array of all the un-subscribed subscriptions + */ + unsubscribe(condition?: ShouldUnsubscribeCondition): Promise; + /** + * Clears all subscriptions + */ + clear(): void; + /** + * Check whether the current provider supports subscriptions. + * + * @returns `true` or `false` depending on if the current provider supports subscriptions + */ + supportsSubscriptions(): boolean; +} +export {}; +//# sourceMappingURL=web3_subscription_manager.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscription_manager.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscription_manager.d.ts.map new file mode 100644 index 0000000..c83d48d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscription_manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscription_manager.d.ts","sourceRoot":"","sources":["../../src/web3_subscription_manager.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,UAAU,EAGV,mBAAmB,EACnB,y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,CAAC,CAAC,CAAC,CAAC,CAAC,EAClD,YAAY,GAAE,UAAkC,GAC9C,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;IAiB3C;;OAEG;IACH,IAAW,aAAa,oEAEvB;IAED;;;;;OAKG;IACU,eAAe,CAAC,GAAG,EAAE,YAAY,CAAC,cAAc,CAAC,MAAM,cAAc,CAAC,CAAC;IAwBpF;;;;OAIG;IACU,kBAAkB,CAAC,GAAG,EAAE,YAAY,CAAC,cAAc,CAAC,MAAM,cAAc,CAAC,CAAC;IAiBvF;;;;;OAKG;IACU,WAAW,CAAC,SAAS,CAAC,EAAE,0BAA0B;IAW/D;;OAEG;IACI,KAAK;IAIZ;;;;OAIG;IACI,qBAAqB,IAAI,OAAO;CAKvC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscriptions.d.ts b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscriptions.d.ts new file mode 100644 index 0000000..9dd0ac3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscriptions.d.ts @@ -0,0 +1,58 @@ +import { BlockOutput, DataFormat, EthExecutionAPI, JsonRpcSubscriptionResult, JsonRpcSubscriptionResultOld, JsonRpcNotification, Log, HexString, Web3APIParams, Web3APISpec } from 'web3-types'; +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +import { Web3EventEmitter, Web3EventMap } from './web3_event_emitter.js'; +import { Web3RequestManager } from './web3_request_manager.js'; +declare type CommonSubscriptionEvents = { + data: unknown; + error: Error; + connected: string; +}; +export declare abstract class Web3Subscription extends Web3EventEmitter { + readonly args: ArgsType; + private readonly _subscriptionManager; + private readonly _lastBlock?; + private readonly _returnFormat; + protected _id?: HexString; + constructor(args: ArgsType, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; + }); + /** + * @deprecated This constructor overloading should not be used + */ + constructor(args: ArgsType, options: { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; + }); + get id(): string | undefined; + get lastBlock(): BlockOutput | undefined; + subscribe(): Promise; + processSubscriptionData(data: JsonRpcSubscriptionResult | JsonRpcSubscriptionResultOld | JsonRpcNotification): void; + sendSubscriptionRequest(): Promise; + protected get returnFormat(): DataFormat; + protected get subscriptionManager(): Web3SubscriptionManager>; + }>; + resubscribe(): Promise; + unsubscribe(): Promise; + sendUnsubscribeRequest(): Promise; + protected formatSubscriptionResult(data: CombinedEventMap['data']): CombinedEventMap["data"]; + _processSubscriptionResult(data: CombinedEventMap['data'] | unknown): void; + _processSubscriptionError(error: Error): void; + protected _buildSubscriptionParams(): Web3APIParams; +} +export declare type Web3SubscriptionConstructor = Web3Subscription> = (new (args: any, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; +} | { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; +}) => SubscriptionType) | (new (args: any, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; +}) => SubscriptionType) | (new (args: any, options: { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; +}) => SubscriptionType); +export {}; +//# sourceMappingURL=web3_subscriptions.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscriptions.d.ts.map b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscriptions.d.ts.map new file mode 100644 index 0000000..26430d3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/lib/types/web3_subscriptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscriptions.d.ts","sourceRoot":"","sources":["../../src/web3_subscriptions.ts"],"names":[],"mappings":"AAkBA,OAAO,EACN,WAAW,EAEX,UAAU,EACV,eAAe,EACf,yBAAyB,EACzB,4BAA4B,EAC5B,mBAAmB,EACnB,GAAG,EACH,SAAS,EACT,aAAa,EACb,WAAW,EACX,MAAM,YAAY,CAAC;AAKpB,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO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BAAmB;;OAEhC;IAEY,WAAW;IAKX,WAAW;IAQX,sBAAsB;IASnC,SAAS,CAAC,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,CAAC,MAAM,CAAC;IAI1D,0BAA0B,CAAC,IAAI,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,OAAO;IAInE,yBAAyB,CAAC,KAAK,EAAE,KAAK;IAK7C,SAAS,CAAC,wBAAwB,IAAI,aAAa,CAAC,GAAG,EAAE,eAAe,CAAC;CAIzE;AAED,oBAAY,2BAA2B,CACtC,GAAG,SAAS,WAAW,EAEvB,gBAAgB,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,IAExF,CAAC,KAGD,IAAI,EAAE,GAAG,EACT,OAAO,EACJ;IAAE,mBAAmB,EAAE,uBAAuB,CAAC,GAAG,CAAC,CAAC;IAAC,YAAY,CAAC,EAAE,UAAU,CAAA;CAAE,GAChF;IAAE,cAAc,EAAE,kBAAkB,CAAC,GAAG,CAAC,CAAC;IAAC,YAAY,CAAC,EAAE,UAAU,CAAA;CAAE,KACpE,gBAAgB,CAAC,GACtB,CAAC,KACD,IAAI,EAAE,GAAG,EACT,OAAO,EAAE;IACR,mBAAmB,EAAE,uBAAuB,CAAC,GAAG,CAAC,CAAC;IAClD,YAAY,CAAC,EAAE,UAAU,CAAC;CAC1B,KACI,gBAAgB,CAAC,GACtB,CAAC,KACD,IAAI,EAAE,GAAG,EACT,OAAO,EAAE;IAAE,cAAc,EAAE,kBAAkB,CAAC,GAAG,CAAC,CAAC;IAAC,YAAY,CAAC,EAAE,UAAU,CAAA;CAAE,KAC1E,gBAAgB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-core/package.json b/test/merkletreejs/node_modules/web3-core/package.json new file mode 100644 index 0000000..acc6df0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/package.json @@ -0,0 +1,74 @@ +{ + "name": "web3-core", + "version": "4.3.2", + "description": "Web3 core tools for sub-packages. This is an internal package.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "dependencies": { + "web3-errors": "^1.1.4", + "web3-eth-accounts": "^4.1.0", + "web3-eth-iban": "^4.0.7", + "web3-providers-http": "^4.1.0", + "web3-providers-ws": "^4.0.7", + "web3-types": "^1.3.1", + "web3-utils": "^4.1.0", + "web3-validator": "^2.0.3" + }, + "optionalDependencies": { + "web3-providers-ipc": "^4.0.7" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@types/jest-when": "^3.5.2", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "jest-when": "^3.5.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "gitHead": "b9b5fe0210da1a4ebf62e2b54f37a9c747bfa136" +} diff --git a/test/merkletreejs/node_modules/web3-core/src/formatters.ts b/test/merkletreejs/node_modules/web3-core/src/formatters.ts new file mode 100644 index 0000000..b6d6af3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/formatters.ts @@ -0,0 +1,551 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { FormatterError } from 'web3-errors'; +import { Iban } from 'web3-eth-iban'; +import { + BlockTags, + Filter, + Numbers, + Topic, + BlockInput, + BlockOutput, + LogsInput, + LogsOutput, + Mutable, + PostInput, + PostOutput, + Proof, + ReceiptInput, + ReceiptOutput, + SyncInput, + SyncOutput, + TransactionInput, + TransactionOutput, +} from 'web3-types'; +import { + fromUtf8, + hexToNumber, + hexToNumberString, + isAddress, + isHexStrict, + mergeDeep, + numberToHex, + sha3Raw, + toChecksumAddress, + toNumber, + toUtf8, + utf8ToHex, +} from 'web3-utils'; +import { isBlockTag, isHex, isNullish } from 'web3-validator'; + +/* eslint-disable deprecation/deprecation */ +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given storage key array values to hex strings. + */ +export const inputStorageKeysFormatter = (keys: Array) => keys.map(num => numberToHex(num)); + +/** + * @deprecated Use format function from web3-utils package instead + * Will format the given proof response from the node. + */ +export const outputProofFormatter = (proof: Proof): Proof => ({ + address: toChecksumAddress(proof.address), + nonce: hexToNumberString(proof.nonce), + balance: hexToNumberString(proof.balance), +}); + +/** + * @deprecated Use format function from web3-utils package instead + * Should the format output to a big number + */ +export const outputBigIntegerFormatter = (number: Numbers) => toNumber(number); + +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or the predefined block number 'latest', 'pending', 'earliest', 'genesis' + */ +export const inputBlockNumberFormatter = (blockNumber: Numbers | undefined) => { + if (isNullish(blockNumber)) { + return undefined; + } + + if (typeof blockNumber === 'string' && isBlockTag(blockNumber)) { + return blockNumber; + } + + if (blockNumber === 'genesis') { + return '0x0'; + } + + if (typeof blockNumber === 'string' && isHexStrict(blockNumber)) { + return blockNumber.toLowerCase(); + } + + return numberToHex(blockNumber); +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Returns the given block number as hex string or does return the defaultBlock property of the current module + */ +export const inputDefaultBlockNumberFormatter = ( + blockNumber: Numbers | undefined, + defaultBlock: Numbers, +) => { + if (!blockNumber) { + return inputBlockNumberFormatter(defaultBlock); + } + + return inputBlockNumberFormatter(blockNumber); +}; + +/** + * @deprecated Use format function from web3-utils package instead + * @param address + */ +export const inputAddressFormatter = (address: string): string | never => { + if (Iban.isValid(address) && Iban.isDirect(address)) { + const iban = new Iban(address); + + return iban.toAddress().toLowerCase(); + } + + if (isAddress(address)) { + return `0x${address.toLowerCase().replace('0x', '')}`; + } + + throw new FormatterError( + `Provided address ${address} is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted.`, + ); +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export const txInputOptionsFormatter = (options: TransactionInput): Mutable => { + const modifiedOptions = { ...options } as unknown as Mutable; + + if (options.to) { + // it might be contract creation + modifiedOptions.to = inputAddressFormatter(options.to); + } + + if (options.data && options.input) { + throw new FormatterError( + 'You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.', + ); + } + + if (!options.input && options.data) { + modifiedOptions.input = options.data; + delete modifiedOptions.data; + } + + if (options.input && !options.input.startsWith('0x')) { + modifiedOptions.input = `0x${options.input}`; + } + + if (modifiedOptions.input && !isHexStrict(modifiedOptions.input)) { + throw new FormatterError('The input field must be HEX encoded data.'); + } + + // allow both + if (options.gas || options.gasLimit) { + modifiedOptions.gas = toNumber(options.gas ?? options.gasLimit); + } + + if (options.maxPriorityFeePerGas || options.maxFeePerGas) { + delete modifiedOptions.gasPrice; + } + + ['gasPrice', 'gas', 'value', 'maxPriorityFeePerGas', 'maxFeePerGas', 'nonce', 'chainId'] + .filter(key => !isNullish(modifiedOptions[key])) + .forEach(key => { + modifiedOptions[key] = numberToHex(modifiedOptions[key] as Numbers); + }); + + return modifiedOptions as TransactionOutput; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export const inputCallFormatter = (options: TransactionInput, defaultAccount?: string) => { + const opts = txInputOptionsFormatter(options); + + const from = opts.from ?? defaultAccount; + + if (from) { + opts.from = inputAddressFormatter(from); + } + + return opts; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a transaction and converts all values to HEX + */ +export const inputTransactionFormatter = (options: TransactionInput, defaultAccount?: string) => { + const opts = txInputOptionsFormatter(options); + + // check from, only if not number, or object + if (!(typeof opts.from === 'number') && !(!!opts.from && typeof opts.from === 'object')) { + opts.from = opts.from ?? defaultAccount; + + if (!options.from && !(typeof options.from === 'number')) { + throw new FormatterError('The send transactions "from" field must be defined!'); + } + + opts.from = inputAddressFormatter(options.from); + } + + return opts; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Hex encodes the data passed to eth_sign and personal_sign + */ +export const inputSignFormatter = (data: string) => (isHexStrict(data) ? data : utf8ToHex(data)); + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction to its proper values + * @function outputTransactionFormatter + */ +export const outputTransactionFormatter = (tx: TransactionInput): TransactionOutput => { + const modifiedTx = { ...tx } as unknown as Mutable; + + if (tx.blockNumber) { + modifiedTx.blockNumber = hexToNumber(tx.blockNumber); + } + + if (tx.transactionIndex) { + modifiedTx.transactionIndex = hexToNumber(tx.transactionIndex); + } + + modifiedTx.nonce = hexToNumber(tx.nonce); + modifiedTx.gas = hexToNumber(tx.gas); + + if (tx.gasPrice) { + modifiedTx.gasPrice = outputBigIntegerFormatter(tx.gasPrice); + } + + if (tx.maxFeePerGas) { + modifiedTx.maxFeePerGas = outputBigIntegerFormatter(tx.maxFeePerGas); + } + + if (tx.maxPriorityFeePerGas) { + modifiedTx.maxPriorityFeePerGas = outputBigIntegerFormatter(tx.maxPriorityFeePerGas); + } + + if (tx.type) { + modifiedTx.type = hexToNumber(tx.type); + } + + modifiedTx.value = outputBigIntegerFormatter(tx.value); + + if (tx.to && isAddress(tx.to)) { + // tx.to could be `0x0` or `null` while contract creation + modifiedTx.to = toChecksumAddress(tx.to); + } else { + modifiedTx.to = undefined; // set to `null` if invalid address + } + + if (tx.from) { + modifiedTx.from = toChecksumAddress(tx.from); + } + + return modifiedTx; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * @param topic + */ +// To align with specification we use the type "null" here +// eslint-disable-next-line @typescript-eslint/ban-types +export const inputTopicFormatter = (topic: Topic): Topic | null => { + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + if (isNullish(topic)) return null; + + const value = String(topic); + + return isHex(value) ? value : fromUtf8(value); +}; + +/** + * @deprecated Use format function from web3-utils package instead + * @param filter + */ +export const inputLogFormatter = (filter: Filter) => { + const val: Mutable = isNullish(filter) + ? {} + : mergeDeep({}, filter as Record); + + // If options !== undefined, don't blow out existing data + if (isNullish(val.fromBlock)) { + val.fromBlock = BlockTags.LATEST; + } + + val.fromBlock = inputBlockNumberFormatter(val.fromBlock); + + if (!isNullish(val.toBlock)) { + val.toBlock = inputBlockNumberFormatter(val.toBlock); + } + + // make sure topics, get converted to hex + val.topics = val.topics ?? []; + val.topics = val.topics.map(topic => + Array.isArray(topic) + ? (topic.map(inputTopicFormatter) as Topic[]) + : inputTopicFormatter(topic as Topic), + ); + + if (val.address) { + val.address = Array.isArray(val.address) + ? val.address.map(addr => inputAddressFormatter(addr)) + : inputAddressFormatter(val.address); + } + + return val as Filter; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a log + * @function outputLogFormatter + */ +export const outputLogFormatter = (log: Partial): LogsOutput => { + const modifiedLog = { ...log } as unknown as Mutable; + + const logIndex = + typeof log.logIndex === 'string' + ? log.logIndex + : numberToHex(log.logIndex as unknown as number); + + // generate a custom log id + if (typeof log.blockHash === 'string' && typeof log.transactionHash === 'string') { + const shaId = sha3Raw( + `${log.blockHash.replace('0x', '')}${log.transactionHash.replace( + '0x', + '', + )}${logIndex.replace('0x', '')}`, + ); + modifiedLog.id = `log_${shaId.replace('0x', '').slice(0, 8)}`; + } else if (!log.id) { + modifiedLog.id = undefined; + } + + if (log.blockNumber && isHexStrict(log.blockNumber)) { + modifiedLog.blockNumber = hexToNumber(log.blockNumber); + } + if (log.transactionIndex && isHexStrict(log.transactionIndex)) { + modifiedLog.transactionIndex = hexToNumber(log.transactionIndex); + } + + if (log.logIndex && isHexStrict(log.logIndex)) { + modifiedLog.logIndex = hexToNumber(log.logIndex); + } + + if (log.address) { + modifiedLog.address = toChecksumAddress(log.address); + } + + return modifiedLog; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a transaction receipt to its proper values + */ +export const outputTransactionReceiptFormatter = (receipt: ReceiptInput): ReceiptOutput => { + if (typeof receipt !== 'object') { + throw new FormatterError(`Received receipt is invalid: ${String(receipt)}`); + } + const modifiedReceipt = { ...receipt } as unknown as Mutable; + + if (receipt.blockNumber) { + modifiedReceipt.blockNumber = hexToNumber(receipt.blockNumber); + } + + if (receipt.transactionIndex) { + modifiedReceipt.transactionIndex = hexToNumber(receipt.transactionIndex); + } + + modifiedReceipt.cumulativeGasUsed = hexToNumber(receipt.cumulativeGasUsed); + modifiedReceipt.gasUsed = hexToNumber(receipt.gasUsed); + + if (receipt.logs && Array.isArray(receipt.logs)) { + modifiedReceipt.logs = receipt.logs.map(outputLogFormatter); + } + + if (receipt.effectiveGasPrice) { + modifiedReceipt.effectiveGasPrice = hexToNumber(receipt.effectiveGasPrice); + } + + if (receipt.contractAddress) { + modifiedReceipt.contractAddress = toChecksumAddress(receipt.contractAddress); + } + + if (receipt.status) { + modifiedReceipt.status = Boolean(parseInt(receipt.status, 10)); + } + + return modifiedReceipt; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a block to its proper values + * @function outputBlockFormatter + */ +export const outputBlockFormatter = (block: BlockInput): BlockOutput => { + const modifiedBlock = { ...block } as unknown as Mutable; + + // transform to number + modifiedBlock.gasLimit = hexToNumber(block.gasLimit); + modifiedBlock.gasUsed = hexToNumber(block.gasUsed); + modifiedBlock.size = hexToNumber(block.size); + modifiedBlock.timestamp = hexToNumber(block.timestamp); + + if (block.number) { + modifiedBlock.number = hexToNumber(block.number); + } + + if (block.difficulty) { + modifiedBlock.difficulty = outputBigIntegerFormatter(block.difficulty); + } + + if (block.totalDifficulty) { + modifiedBlock.totalDifficulty = outputBigIntegerFormatter(block.totalDifficulty); + } + + if (block.transactions && Array.isArray(block.transactions)) { + modifiedBlock.transactions = block.transactions.map(outputTransactionFormatter); + } + + if (block.miner) { + modifiedBlock.miner = toChecksumAddress(block.miner); + } + + if (block.baseFeePerGas) { + modifiedBlock.baseFeePerGas = outputBigIntegerFormatter(block.baseFeePerGas); + } + + return modifiedBlock; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the input of a whisper post and converts all values to HEX + */ +export const inputPostFormatter = (post: PostOutput): PostInput => { + const modifiedPost = { ...post } as unknown as Mutable; + + if (post.ttl) { + modifiedPost.ttl = numberToHex(post.ttl); + } + + if (post.workToProve) { + modifiedPost.workToProve = numberToHex(post.workToProve); + } + + if (post.priority) { + modifiedPost.priority = numberToHex(post.priority); + } + + // fallback + if (post.topics && !Array.isArray(post.topics)) { + modifiedPost.topics = post.topics ? [post.topics] : []; + } + + // format the following options + modifiedPost.topics = modifiedPost.topics?.map(topic => + topic.startsWith('0x') ? topic : fromUtf8(topic), + ); + + return modifiedPost; +}; + +/** + * @deprecated Use format function from web3-utils package instead + * Formats the output of a received post message + * @function outputPostFormatter + */ +export const outputPostFormatter = (post: PostInput): PostOutput => { + const modifiedPost = { ...post } as unknown as Mutable; + + if (post.expiry) { + modifiedPost.expiry = hexToNumber(post.expiry); + } + + if (post.sent) { + modifiedPost.sent = hexToNumber(post.sent); + } + + if (post.ttl) { + modifiedPost.ttl = hexToNumber(post.ttl); + } + + if (post.workProved) { + modifiedPost.workProved = hexToNumber(post.workProved); + } + + // post.payloadRaw = post.payload; + // post.payload = utils.hexToAscii(post.payload); + + // if (utils.isJson(post.payload)) { + // post.payload = JSON.parse(post.payload); + // } + + // format the following options + if (!post.topics) { + modifiedPost.topics = []; + } + + modifiedPost.topics = modifiedPost.topics?.map(toUtf8); + + return modifiedPost; +}; + +/** + * @deprecated Use format function from web3-utils package instead + */ +export const outputSyncingFormatter = (result: SyncInput): SyncOutput => { + const modifiedResult = { ...result } as unknown as Mutable; + + modifiedResult.startingBlock = hexToNumber(result.startingBlock); + modifiedResult.currentBlock = hexToNumber(result.currentBlock); + modifiedResult.highestBlock = hexToNumber(result.highestBlock); + + if (result.knownStates) { + modifiedResult.knownStates = hexToNumber(result.knownStates); + } + + if (result.pulledStates) { + modifiedResult.pulledStates = hexToNumber(result.pulledStates); + } + + return modifiedResult; +}; diff --git a/test/merkletreejs/node_modules/web3-core/src/index.ts b/test/merkletreejs/node_modules/web3-core/src/index.ts new file mode 100644 index 0000000..88eb6c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/index.ts @@ -0,0 +1,31 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './web3_config.js'; +export * from './web3_request_manager.js'; +export * from './web3_subscription_manager.js'; +export * from './web3_subscriptions.js'; +export * from './web3_context.js'; +export * from './web3_batch_request.js'; +export * from './utils.js'; +export * from './types.js'; +export * from './formatters.js'; +export * from './web3_promi_event.js'; +export * from './web3_event_emitter.js'; + +// For backward usability export as namespace +export * as formatters from './formatters.js'; diff --git a/test/merkletreejs/node_modules/web3-core/src/types.ts b/test/merkletreejs/node_modules/web3-core/src/types.ts new file mode 100644 index 0000000..3f4e66d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/types.ts @@ -0,0 +1,32 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { HexString, Transaction } from 'web3-types'; + +export type TransactionTypeParser = ( + transaction: Transaction, +) => HexString | undefined; + +export interface Method { + name: string; + call: string; +} + +export interface ExtensionObject { + property?: string; + methods: Method[]; +} diff --git a/test/merkletreejs/node_modules/web3-core/src/utils.ts b/test/merkletreejs/node_modules/web3-core/src/utils.ts new file mode 100644 index 0000000..34c5162 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/utils.ts @@ -0,0 +1,84 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + EIP1193Provider, + LegacyRequestProvider, + LegacySendAsyncProvider, + LegacySendProvider, + SupportedProviders, + Web3APISpec, + Web3BaseProvider, + MetaMaskProvider, +} from 'web3-types'; + +export const isWeb3Provider = ( + provider: SupportedProviders, +): provider is Web3BaseProvider => Web3BaseProvider.isWeb3Provider(provider); + +export const isMetaMaskProvider = ( + provider: SupportedProviders, +): provider is MetaMaskProvider => + typeof provider !== 'string' && +'request' in provider && +provider.request.constructor.name === 'AsyncFunction' && 'isMetaMask' in provider && provider.isMetaMask; + + +export const isLegacyRequestProvider = ( + provider: SupportedProviders, +): provider is LegacyRequestProvider => + typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'Function'; + +export const isEIP1193Provider = ( + provider: SupportedProviders, +): provider is EIP1193Provider => + typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'AsyncFunction'; + +export const isLegacySendProvider = ( + provider: SupportedProviders, +): provider is LegacySendProvider => typeof provider !== 'string' && 'send' in provider; + +export const isLegacySendAsyncProvider = ( + provider: SupportedProviders, +): provider is LegacySendAsyncProvider => typeof provider !== 'string' && 'sendAsync' in provider; + +export const isSupportedProvider = ( + provider: SupportedProviders, +): provider is SupportedProviders => + provider && + (isWeb3Provider(provider) || + isEIP1193Provider(provider) || + isLegacyRequestProvider(provider) || + isLegacySendAsyncProvider(provider) || + isLegacySendProvider(provider)); +export const isSupportSubscriptions = ( + provider: SupportedProviders, +): boolean => { + if (provider && 'supportsSubscriptions' in provider) { + return provider.supportsSubscriptions(); + } + + if (provider && typeof provider !== 'string' && 'on' in provider) { + return true; + } + + return false; +}; diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_batch_request.ts b/test/merkletreejs/node_modules/web3-core/src/web3_batch_request.ts new file mode 100644 index 0000000..10a3eaf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_batch_request.ts @@ -0,0 +1,128 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { JsonRpcBatchResponse, JsonRpcOptionalRequest, JsonRpcRequest } from 'web3-types'; +import { jsonRpc, Web3DeferredPromise } from 'web3-utils'; +import { OperationAbortError, OperationTimeoutError, ResponseError } from 'web3-errors'; +import { Web3RequestManager } from './web3_request_manager.js'; + +export const DEFAULT_BATCH_REQUEST_TIMEOUT = 1000; + +export class Web3BatchRequest { + private readonly _requestManager: Web3RequestManager; + private readonly _requests: Map< + number, + { payload: JsonRpcRequest; promise: Web3DeferredPromise } + >; + + public constructor(requestManager: Web3RequestManager) { + this._requestManager = requestManager; + this._requests = new Map(); + } + + public get requests() { + return [...this._requests.values()].map(r => r.payload); + } + + public add(request: JsonRpcOptionalRequest) { + const payload = jsonRpc.toPayload(request) as JsonRpcRequest; + const promise = new Web3DeferredPromise(); + + this._requests.set(payload.id as number, { payload, promise }); + + return promise; + } + + // eslint-disable-next-line class-methods-use-this + public async execute(options?: { + timeout?: number; + }): Promise> { + if (this.requests.length === 0) { + return Promise.resolve([]); + } + + const request = new Web3DeferredPromise>({ + timeout: options?.timeout ?? DEFAULT_BATCH_REQUEST_TIMEOUT, + eagerStart: true, + timeoutMessage: 'Batch request timeout', + }); + + this._processBatchRequest(request).catch(err => request.reject(err)); + + request.catch((err: Error) => { + if (err instanceof OperationTimeoutError) { + this._abortAllRequests('Batch request timeout'); + } + + request.reject(err); + }); + + return request; + } + + private async _processBatchRequest( + promise: Web3DeferredPromise>, + ) { + const response = await this._requestManager.sendBatch( + [...this._requests.values()].map(r => r.payload), + ); + + if (response.length !== this._requests.size) { + this._abortAllRequests('Invalid batch response'); + + throw new ResponseError( + response, + `Batch request size mismatch the results size. Requests: ${this._requests.size}, Responses: ${response.length}`, + ); + } + + const requestIds = this.requests + .map(r => r.id) + .map(Number) + .sort((a, b) => a - b); + + const responseIds = response + .map(r => r.id) + .map(Number) + .sort((a, b) => a - b); + + if (JSON.stringify(requestIds) !== JSON.stringify(responseIds)) { + this._abortAllRequests('Invalid batch response'); + + throw new ResponseError( + response, + `Batch request mismatch the results. Requests: [${requestIds.join()}], Responses: [${responseIds.join()}]`, + ); + } + + for (const res of response) { + if (jsonRpc.isResponseWithResult(res)) { + this._requests.get(res.id as number)?.promise.resolve(res.result); + } else if (jsonRpc.isResponseWithError(res)) { + this._requests.get(res.id as number)?.promise.reject(res.error); + } + } + + promise.resolve(response); + } + + private _abortAllRequests(msg: string) { + for (const { promise } of this._requests.values()) { + promise.reject(new OperationAbortError(msg)); + } + } +} diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_config.ts b/test/merkletreejs/node_modules/web3-core/src/web3_config.ts new file mode 100644 index 0000000..11e80a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_config.ts @@ -0,0 +1,506 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Numbers, HexString, BlockNumberOrTag, Common } from 'web3-types'; +import { ConfigHardforkMismatchError, ConfigChainMismatchError } from 'web3-errors'; +import { isNullish, toHex } from 'web3-utils'; +import { TransactionTypeParser } from './types.js'; +// eslint-disable-next-line import/no-cycle +import { TransactionBuilder } from './web3_context.js'; +import { Web3EventEmitter } from './web3_event_emitter.js'; + +// To avoid cycle dependency declare this +export interface Web3ConfigOptions { + handleRevert: boolean; + defaultAccount?: HexString; + defaultBlock: BlockNumberOrTag; + transactionSendTimeout: number; + transactionBlockTimeout: number; + transactionConfirmationBlocks: number; + transactionPollingInterval: number; + transactionPollingTimeout: number; + transactionReceiptPollingInterval?: number; + transactionConfirmationPollingInterval?: number; + blockHeaderTimeout: number; + maxListenersWarningThreshold: number; + contractDataInputFill: 'data' | 'input' | 'both'; + defaultNetworkId?: Numbers; + defaultChain: string; + defaultHardfork: string; + + defaultCommon?: Common; + defaultTransactionType: Numbers; + defaultMaxPriorityFeePerGas: Numbers; + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: boolean; + useRpcCallSpecification: boolean; // EIP-1474 https://eips.ethereum.org/EIPS/eip-1474 + // other experimental features... + }; + transactionBuilder?: TransactionBuilder; + transactionTypeParser?: TransactionTypeParser; +} + +type ConfigEvent = P extends unknown + ? { name: P; oldValue: T[P]; newValue: T[P] } + : never; + +export enum Web3ConfigEvent { + CONFIG_CHANGE = 'CONFIG_CHANGE', +} + +export abstract class Web3Config + extends Web3EventEmitter<{ [Web3ConfigEvent.CONFIG_CHANGE]: ConfigEvent }> + implements Web3ConfigOptions +{ + public config: Web3ConfigOptions = { + handleRevert: false, + defaultAccount: undefined, + defaultBlock: 'latest', + transactionBlockTimeout: 50, + transactionConfirmationBlocks: 24, + transactionPollingInterval: 1000, + transactionPollingTimeout: 750 * 1000, + transactionReceiptPollingInterval: undefined, + transactionSendTimeout: 750 * 1000, + transactionConfirmationPollingInterval: undefined, + blockHeaderTimeout: 10, + maxListenersWarningThreshold: 100, + contractDataInputFill: 'data', + defaultNetworkId: undefined, + defaultChain: 'mainnet', + defaultHardfork: 'london', + // TODO - Check if there is a default Common + defaultCommon: undefined, + defaultTransactionType: '0x2', + defaultMaxPriorityFeePerGas: toHex(2500000000), + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: false, + useRpcCallSpecification: false, + }, + transactionBuilder: undefined, + transactionTypeParser: undefined, + }; + + public constructor(options?: Partial) { + super(); + this.setConfig(options ?? {}); + } + + public setConfig(options: Partial) { + // TODO: Improve and add key check + const keys = Object.keys(options) as (keyof Web3ConfigOptions)[]; + for (const key of keys) { + this._triggerConfigChange(key, options[key]) + } + Object.assign(this.config, options); + } + + /** + * The `handleRevert` options property returns the revert reason string if enabled for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + * Default is `false`. + * + * `Note`: At the moment `handleRevert` is only supported for `sendTransaction` and not for `sendSignedTransaction` + */ + public get handleRevert() { + return this.config.handleRevert; + } + + /** + * Will set the handleRevert + */ + public set handleRevert(val) { + this._triggerConfigChange('handleRevert', val); + this.config.handleRevert = val; + } + + /** + * The `contractDataInputFill` options property will allow you to set the hash of the method signature and encoded parameters to the property + * either `data`, `input` or both within your contract. + * This will affect the contracts send, call and estimateGas methods + * Default is `input`. + */ + public get contractDataInputFill() { + return this.config.contractDataInputFill; + } + + /** + * Will set the contractDataInputFill + */ + public set contractDataInputFill(val) { + this._triggerConfigChange('contractDataInputFill', val); + this.config.contractDataInputFill = val; + } + + /** + * This default address is used as the default `from` property, if no `from` property is specified in for the following methods: + * - web3.eth.sendTransaction() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + * - myContract.methods.myMethod().send() + */ + public get defaultAccount() { + return this.config.defaultAccount; + } + /** + * Will set the default account. + */ + public set defaultAccount(val) { + this._triggerConfigChange('defaultAccount', val); + this.config.defaultAccount = val; + } + + /** + * The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is `"latest"`. + * - web3.eth.getBalance() + * - web3.eth.getCode() + * - web3.eth.getTransactionCount() + * - web3.eth.getStorageAt() + * - web3.eth.call() + * - myContract.methods.myMethod().call() + */ + public get defaultBlock() { + return this.config.defaultBlock; + } + + /** + * Will set the default block. + * + * - A block number + * - `"earliest"` - String: The genesis block + * - `"latest"` - String: The latest block (current head of the blockchain) + * - `"pending"` - String: The currently mined block (including pending transactions) + * - `"finalized"` - String: (For POS networks) The finalized block is one which has been accepted as canonical by greater than 2/3 of validators + * - `"safe"` - String: (For POS networks) The safe head block is one which under normal network conditions, is expected to be included in the canonical chain. Under normal network conditions the safe head and the actual tip of the chain will be equivalent (with safe head trailing only by a few seconds). Safe heads will be less likely to be reorged than the proof of work network`s latest blocks. + */ + public set defaultBlock(val) { + this._triggerConfigChange('defaultBlock', val); + this.config.defaultBlock = val; + } + + /** + * The time used to wait for Ethereum Node to return the sent transaction result. + * Note: If the RPC call stuck at the Node and therefor timed-out, the transaction may still be pending or even mined by the Network. We recommend checking the pending transactions in such a case. + * Default is `750` seconds (12.5 minutes). + */ + public get transactionSendTimeout() { + return this.config.transactionSendTimeout; + } + + /** + * Will set the transactionSendTimeout. + */ + public set transactionSendTimeout(val) { + this._triggerConfigChange('transactionSendTimeout', val); + this.config.transactionSendTimeout = val; + } + + /** + * The `transactionBlockTimeout` is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. + * Default is `50`. + */ + public get transactionBlockTimeout() { + return this.config.transactionBlockTimeout; + } + + /** + * Will set the transactionBlockTimeout. + */ + public set transactionBlockTimeout(val) { + this._triggerConfigChange('transactionBlockTimeout', val); + this.config.transactionBlockTimeout = val; + } + + /** + * This defines the number of blocks it requires until a transaction is considered confirmed. + * Default is `24`. + */ + public get transactionConfirmationBlocks() { + return this.config.transactionConfirmationBlocks; + } + + /** + * Will set the transactionConfirmationBlocks. + */ + public set transactionConfirmationBlocks(val) { + this._triggerConfigChange('transactionConfirmationBlocks', val); + this.config.transactionConfirmationBlocks = val; + } + + /** + * Used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `1000` ms. + */ + public get transactionPollingInterval() { + return this.config.transactionPollingInterval; + } + + /** + * Will set the transactionPollingInterval. + */ + public set transactionPollingInterval(val) { + this._triggerConfigChange('transactionPollingInterval', val); + this.config.transactionPollingInterval = val; + + this.transactionReceiptPollingInterval = val; + this.transactionConfirmationPollingInterval = val; + } + /** + * Used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. Note: If this method times out, the transaction may still be pending. + * Default is `750` seconds (12.5 minutes). + */ + public get transactionPollingTimeout() { + return this.config.transactionPollingTimeout; + } + + /** + * Will set the transactionPollingTimeout. + */ + public set transactionPollingTimeout(val) { + this._triggerConfigChange('transactionPollingTimeout', val); + + this.config.transactionPollingTimeout = val; + } + + /** + * The `transactionPollingInterval` is used over HTTP connections. This option defines the number of seconds between Web3 calls for a receipt which confirms that a transaction was mined by the network. + * Default is `undefined` + */ + public get transactionReceiptPollingInterval() { + return this.config.transactionReceiptPollingInterval; + } + + /** + * Will set the transactionReceiptPollingInterval + */ + public set transactionReceiptPollingInterval(val) { + this._triggerConfigChange('transactionReceiptPollingInterval', val); + this.config.transactionReceiptPollingInterval = val; + } + + public get transactionConfirmationPollingInterval() { + return this.config.transactionConfirmationPollingInterval; + } + + public set transactionConfirmationPollingInterval(val) { + this._triggerConfigChange('transactionConfirmationPollingInterval', val); + this.config.transactionConfirmationPollingInterval = val; + } + + /** + * The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt. + * Default is `10` seconds. + */ + public get blockHeaderTimeout() { + return this.config.blockHeaderTimeout; + } + + /** + * Will set the blockHeaderTimeout + */ + public set blockHeaderTimeout(val) { + this._triggerConfigChange('blockHeaderTimeout', val); + + this.config.blockHeaderTimeout = val; + } + + /** + * The enableExperimentalFeatures is used to enable trying new experimental features that are still not fully implemented or not fully tested or still have some related issues. + * Default is `false` for every feature. + */ + public get enableExperimentalFeatures() { + return this.config.enableExperimentalFeatures; + } + + /** + * Will set the enableExperimentalFeatures + */ + public set enableExperimentalFeatures(val) { + this._triggerConfigChange('enableExperimentalFeatures', val); + + this.config.enableExperimentalFeatures = val; + } + + public get maxListenersWarningThreshold() { + return this.config.maxListenersWarningThreshold; + } + + public set maxListenersWarningThreshold(val) { + this._triggerConfigChange('maxListenersWarningThreshold', val); + this.setMaxListenerWarningThreshold(val); + this.config.maxListenersWarningThreshold = val; + } + + public get defaultNetworkId() { + return this.config.defaultNetworkId; + } + + public set defaultNetworkId(val) { + this._triggerConfigChange('defaultNetworkId', val); + + this.config.defaultNetworkId = val; + } + + public get defaultChain() { + return this.config.defaultChain; + } + + public set defaultChain(val) { + if ( + !isNullish(this.config.defaultCommon) && + !isNullish(this.config.defaultCommon.baseChain) && + val !== this.config.defaultCommon.baseChain + ) + throw new ConfigChainMismatchError(this.config.defaultChain, val); + + this._triggerConfigChange('defaultChain', val); + + this.config.defaultChain = val; + } + + /** + * Will return the default hardfork. Default is `london` + * The default hardfork property can be one of the following: + * - `chainstart` + * - `homestead` + * - `dao` + * - `tangerineWhistle` + * - `spuriousDragon` + * - `byzantium` + * - `constantinople` + * - `petersburg` + * - `istanbul` + * - `berlin` + * - `london` + * - 'arrowGlacier', + * - 'tangerineWhistle', + * - 'muirGlacier' + * + */ + public get defaultHardfork() { + return this.config.defaultHardfork; + } + + /** + * Will set the default hardfork. + * + */ + public set defaultHardfork(val) { + if ( + !isNullish(this.config.defaultCommon) && + !isNullish(this.config.defaultCommon.hardfork) && + val !== this.config.defaultCommon.hardfork + ) + throw new ConfigHardforkMismatchError(this.config.defaultCommon.hardfork, val); + this._triggerConfigChange('defaultHardfork', val); + + this.config.defaultHardfork = val; + } + + /** + * + * Will get the default common property + * The default common property does contain the following Common object: + * - `customChain` - `Object`: The custom chain properties + * - `name` - `string`: (optional) The name of the chain + * - `networkId` - `number`: Network ID of the custom chain + * - `chainId` - `number`: Chain ID of the custom chain + * - `baseChain` - `string`: (optional) mainnet, goerli, kovan, rinkeby, or ropsten + * - `hardfork` - `string`: (optional) chainstart, homestead, dao, tangerineWhistle, spuriousDragon, byzantium, constantinople, petersburg, istanbul, berlin, or london + * Default is `undefined`. + * + */ + public get defaultCommon() { + return this.config.defaultCommon; + } + + /** + * Will set the default common property + * + */ + public set defaultCommon(val: Common | undefined) { + // validation check if default hardfork is set and matches defaultCommon hardfork + if ( + !isNullish(this.config.defaultHardfork) && + !isNullish(val) && + !isNullish(val.hardfork) && + this.config.defaultHardfork !== val.hardfork + ) + throw new ConfigHardforkMismatchError(this.config.defaultHardfork, val.hardfork); + if ( + !isNullish(this.config.defaultChain) && + !isNullish(val) && + !isNullish(val.baseChain) && + this.config.defaultChain !== val.baseChain + ) + throw new ConfigChainMismatchError(this.config.defaultChain, val.baseChain); + this._triggerConfigChange('defaultCommon', val); + + this.config.defaultCommon = val; + } + + public get defaultTransactionType() { + return this.config.defaultTransactionType; + } + + public set defaultTransactionType(val) { + this._triggerConfigChange('defaultTransactionType', val); + + this.config.defaultTransactionType = val; + } + + public get defaultMaxPriorityFeePerGas() { + return this.config.defaultMaxPriorityFeePerGas; + } + + public set defaultMaxPriorityFeePerGas(val) { + this._triggerConfigChange('defaultMaxPriorityFeePerGas', val); + this.config.defaultMaxPriorityFeePerGas = val; + } + + public get transactionBuilder() { + return this.config.transactionBuilder; + } + + public set transactionBuilder(val) { + this._triggerConfigChange('transactionBuilder', val); + this.config.transactionBuilder = val; + } + + public get transactionTypeParser() { + return this.config.transactionTypeParser; + } + + public set transactionTypeParser(val) { + this._triggerConfigChange('transactionTypeParser', val); + this.config.transactionTypeParser = val; + } + + private _triggerConfigChange( + config: K, + newValue: Web3ConfigOptions[K], + ) { + this.emit(Web3ConfigEvent.CONFIG_CHANGE, { + name: config, + oldValue: this.config[config], + newValue, + } as ConfigEvent); + } +} diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_context.ts b/test/merkletreejs/node_modules/web3-core/src/web3_context.ts new file mode 100644 index 0000000..f4c72f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_context.ts @@ -0,0 +1,450 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line max-classes-per-file +import { ExistingPluginNamespaceError } from 'web3-errors'; +import { + EthExecutionAPI, + HexString, Numbers, SupportedProviders, Transaction, Web3AccountProvider, Web3APISpec, Web3BaseProvider, Web3BaseWallet, + Web3BaseWalletAccount +} from 'web3-types'; +import { isNullish } from 'web3-utils'; +import { BaseTransaction, TransactionFactory } from 'web3-eth-accounts'; +import { isSupportedProvider } from './utils.js'; +// eslint-disable-next-line import/no-cycle +import { ExtensionObject } from './types.js'; +import { Web3BatchRequest } from './web3_batch_request.js'; +// eslint-disable-next-line import/no-cycle +import { Web3Config, Web3ConfigEvent, Web3ConfigOptions } from './web3_config.js'; +import { Web3RequestManager } from './web3_request_manager.js'; +import { Web3SubscriptionConstructor } from './web3_subscriptions.js'; +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; + +// To avoid circular dependencies, we need to export type from here. +export type Web3ContextObject< + API extends Web3APISpec = unknown, + RegisteredSubs extends { + [key: string]: Web3SubscriptionConstructor; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } = any, +> = { + config: Web3ConfigOptions; + provider?: SupportedProviders | string; + requestManager: Web3RequestManager; + subscriptionManager?: Web3SubscriptionManager | undefined; + registeredSubscriptions?: RegisteredSubs; + providers: typeof Web3RequestManager.providers; + accountProvider?: Web3AccountProvider; + wallet?: Web3BaseWallet; +}; + +export type Web3ContextInitOptions< + API extends Web3APISpec = unknown, + RegisteredSubs extends { + [key: string]: Web3SubscriptionConstructor; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } = any, +> = { + config?: Partial; + provider?: SupportedProviders | string; + requestManager?: Web3RequestManager; + subscriptionManager?: Web3SubscriptionManager | undefined; + registeredSubscriptions?: RegisteredSubs; + accountProvider?: Web3AccountProvider; + wallet?: Web3BaseWallet; +}; + +// eslint-disable-next-line no-use-before-define +export type Web3ContextConstructor = new ( + ...args: [...extras: T2, context: Web3ContextObject] +) => T; + +// To avoid circular dependencies, we need to export type from here. +export type Web3ContextFactory< + // eslint-disable-next-line no-use-before-define + T extends Web3Context, + T2 extends unknown[], +> = Web3ContextConstructor & { + fromContextObject(this: Web3ContextConstructor, contextObject: Web3ContextObject): T; +}; + +export class Web3Context< + API extends Web3APISpec = unknown, + RegisteredSubs extends { + [key: string]: Web3SubscriptionConstructor; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } = any, +> extends Web3Config { + public static readonly providers = Web3RequestManager.providers; + public static givenProvider?: SupportedProviders; + public readonly providers = Web3RequestManager.providers; + protected _requestManager: Web3RequestManager; + protected _subscriptionManager: Web3SubscriptionManager; + protected _accountProvider?: Web3AccountProvider; + protected _wallet?: Web3BaseWallet; + + public constructor( + providerOrContext?: + | string + | SupportedProviders + | Web3ContextInitOptions, + ) { + super(); + + // If "providerOrContext" is provided as "string" or an objects matching "SupportedProviders" interface + if ( + isNullish(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() !== '') || + isSupportedProvider(providerOrContext as SupportedProviders) + ) { + this._requestManager = new Web3RequestManager( + providerOrContext as undefined | string | SupportedProviders, + ); + this._subscriptionManager = new Web3SubscriptionManager( + this._requestManager, + {} as RegisteredSubs, + ); + + return; + } + + const { + config, + provider, + requestManager, + subscriptionManager, + registeredSubscriptions, + accountProvider, + wallet, + } = providerOrContext as Web3ContextInitOptions; + + this.setConfig(config ?? {}); + + this._requestManager = + requestManager ?? + new Web3RequestManager( + provider, + config?.enableExperimentalFeatures?.useSubscriptionWhenCheckingBlockTimeout, + ); + + if (subscriptionManager) { + this._subscriptionManager = subscriptionManager; + } else { + this._subscriptionManager = new Web3SubscriptionManager( + this.requestManager, + registeredSubscriptions ?? ({} as RegisteredSubs), + ); + } + + if (accountProvider) { + this._accountProvider = accountProvider; + } + + if (wallet) { + this._wallet = wallet; + } + } + + public get requestManager() { + return this._requestManager; + } + + /** + * Will return the current subscriptionManager ({@link Web3SubscriptionManager}) + */ + public get subscriptionManager() { + return this._subscriptionManager; + } + + public get wallet() { + return this._wallet; + } + + public get accountProvider() { + return this._accountProvider; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public static fromContextObject( + this: Web3ContextConstructor, + ...args: [Web3ContextObject, ...T3] + ) { + return new this(...(args.reverse() as [...T3, Web3ContextObject])); + } + + public getContextObject(): Web3ContextObject { + return { + config: this.config, + provider: this.provider, + requestManager: this.requestManager, + subscriptionManager: this.subscriptionManager, + registeredSubscriptions: this.subscriptionManager?.registeredSubscriptions, + providers: this.providers, + wallet: this.wallet, + accountProvider: this.accountProvider, + }; + } + + /** + * Use to create new object of any type extended by `Web3Context` + * and link it to current context. This can be used to initiate a global context object + * and then use it to create new objects of any type extended by `Web3Context`. + */ + public use( + ContextRef: Web3ContextConstructor, + ...args: [...T2] + ) { + const newContextChild: T = new ContextRef( + ...([...args, this.getContextObject()] as unknown as [...T2, Web3ContextObject]), + ); + + this.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + newContextChild.setConfig({ [event.name]: event.newValue }); + }); + + return newContextChild; + } + + /** + * Link current context to another context. + */ + public link(parentContext: T) { + this.setConfig(parentContext.config); + this._requestManager = parentContext.requestManager; + this.provider = parentContext.provider; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this._subscriptionManager = parentContext.subscriptionManager; + this._wallet = parentContext.wallet; + this._accountProvider = parentContext._accountProvider; + + parentContext.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.setConfig({ [event.name]: event.newValue }); + }); + } + + // eslint-disable-next-line no-use-before-define + public registerPlugin(plugin: Web3PluginBase) { + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + if (this[plugin.pluginNamespace] !== undefined) + throw new ExistingPluginNamespaceError(plugin.pluginNamespace); + + const _pluginObject = { + [plugin.pluginNamespace]: plugin, + }; + _pluginObject[plugin.pluginNamespace].link(this); + Object.assign(this, _pluginObject); + } + + /** + * Will return the current provider. + * + * @returns Returns the current provider + * @example + * ```ts + * const web3 = new Web3Context("http://localhost:8545"); + * console.log(web3.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + + public get provider(): Web3BaseProvider | undefined { + return this.currentProvider; + } + + /** + * Will set the current provider. + * + * @param provider - The provider to set + * + * Accepted providers are of type {@link SupportedProviders} + * @example + * ```ts + * const web3Context = new web3ContextContext("http://localhost:8545"); + * web3Context.provider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + + public set provider(provider: SupportedProviders | string | undefined) { + this.requestManager.setProvider(provider); + } + + /** + * Will return the current provider. (The same as `provider`) + * + * @returns Returns the current provider + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * console.log(web3Context.provider); + * > HttpProvider { + * clientUrl: 'http://localhost:8545', + * httpProviderOptions: undefined + * } + * ``` + */ + public get currentProvider(): Web3BaseProvider | undefined { + return this.requestManager.provider as Web3BaseProvider; + } + + /** + * Will set the current provider. (The same as `provider`) + * + * @param provider - {@link SupportedProviders} The provider to set + * + * @example + * ```ts + * const web3Context = new Web3Context("http://localhost:8545"); + * web3Context.currentProvider = "ws://localhost:8545"; + * console.log(web3Context.provider); + * > WebSocketProvider { + * _eventEmitter: EventEmitter { + * _events: [Object: null prototype] {}, + * _eventsCount: 0, + * ... + * } + * ``` + */ + public set currentProvider(provider: SupportedProviders | string | undefined) { + this.requestManager.setProvider(provider); + } + + /** + * Will return the givenProvider if available. + * + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise `undefined`. + */ + // eslint-disable-next-line class-methods-use-this + public get givenProvider() { + return Web3Context.givenProvider; + } + /** + * Will set the provider. + * + * @param provider - {@link SupportedProviders} The provider to set + * @returns Returns true if the provider was set + */ + public setProvider(provider?: SupportedProviders | string): boolean { + this.provider = provider; + return true; + } + /** + * Will return the {@link Web3BatchRequest} constructor. + */ + public get BatchRequest(): new () => Web3BatchRequest { + return Web3BatchRequest.bind( + undefined, + this._requestManager as unknown as Web3RequestManager, + ); + } + + /** + * This method allows extending the web3 modules. + * Note: This method is only for backward compatibility, and It is recommended to use Web3 v4 Plugin feature for extending web3.js functionality if you are developing some thing new. + */ + public extend(extendObj: ExtensionObject) { + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + if (extendObj.property && !this[extendObj.property]) + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + this[extendObj.property] = {}; + + extendObj.methods?.forEach(element => { + const method = async (...givenParams: unknown[]) => + this.requestManager.send({ + method: element.call, + params: givenParams, + }); + + if (extendObj.property) + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + this[extendObj.property][element.name] = method; + // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' + else this[element.name] = method; + }); + return this; + } +} + +/** + * Extend this class when creating a plugin that either doesn't require {@link EthExecutionAPI}, + * or interacts with a RPC node that doesn't fully implement {@link EthExecutionAPI}. + * + * To add type support for RPC methods to the {@link Web3RequestManager}, + * define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: + * + * @example + * ```ts + * type CustomRpcApi = { + * custom_rpc_method: () => string; + * custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; + * }; + * + * class CustomPlugin extends Web3PluginBase {...} + * ``` + */ + export abstract class Web3PluginBase< + API extends Web3APISpec = Web3APISpec, +> extends Web3Context { + public abstract pluginNamespace: string; + + // eslint-disable-next-line class-methods-use-this + protected registerNewTransactionType>(type: Numbers, txClass: NewTxTypeClass): void { + TransactionFactory.registerTransactionType(type, txClass); + } +} + +/** +* Extend this class when creating a plugin that makes use of {@link EthExecutionAPI}, +* or depends on other Web3 packages (such as `web3-eth-contract`) that depend on {@link EthExecutionAPI}. +* +* To add type support for RPC methods to the {@link Web3RequestManager} (in addition to {@link EthExecutionAPI}), +* define a {@link Web3APISpec} and pass it as a generic to Web3PluginBase like so: +* +* @example +* ```ts +* type CustomRpcApi = { +* custom_rpc_method: () => string; +* custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) => string; +* }; +* +* class CustomPlugin extends Web3PluginBase {...} +* ``` +*/ +export abstract class Web3EthPluginBase extends Web3PluginBase< + API & EthExecutionAPI +> {} + +// To avoid cycle dependency declare this type in this file +export type TransactionBuilder = < + ReturnType = Transaction, +>(options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; +}) => Promise; diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_event_emitter.ts b/test/merkletreejs/node_modules/web3-core/src/web3_event_emitter.ts new file mode 100644 index 0000000..36180c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_event_emitter.ts @@ -0,0 +1,73 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { EventEmitter } from 'web3-utils'; + +export type Web3EventMap = Record; +export type Web3EventKey = string & keyof T; +export type Web3EventCallback = (params: T) => void | Promise; +export interface Web3Emitter { + on>(eventName: K, fn: Web3EventCallback): void; + once>(eventName: K, fn: Web3EventCallback): void; + off>(eventName: K, fn: Web3EventCallback): void; + emit>(eventName: K, params: T[K]): void; +} + +export class Web3EventEmitter implements Web3Emitter { + private readonly _emitter = new EventEmitter(); + + public on>(eventName: K, fn: Web3EventCallback) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.on(eventName, fn); + } + + public once>(eventName: K, fn: Web3EventCallback) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.once(eventName, fn); + } + + public off>(eventName: K, fn: Web3EventCallback) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this._emitter.off(eventName, fn); + } + + public emit>(eventName: K, params: T[K]) { + this._emitter.emit(eventName, params); + } + + public listenerCount>(eventName: K) { + return this._emitter.listenerCount(eventName); + } + + public listeners>(eventName: K) { + return this._emitter.listeners(eventName); + } + + public eventNames() { + return this._emitter.eventNames(); + } + + public removeAllListeners() { + return this._emitter.removeAllListeners(); + } + public setMaxListenerWarningThreshold(maxListenersWarningThreshold: number) { + this._emitter.setMaxListeners(maxListenersWarningThreshold); + } + public getMaxListeners() { + return this._emitter.getMaxListeners(); + } +} diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_promi_event.ts b/test/merkletreejs/node_modules/web3-core/src/web3_promi_event.ts new file mode 100644 index 0000000..c907d1f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_promi_event.ts @@ -0,0 +1,79 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + Web3EventCallback, + Web3EventEmitter, + Web3EventKey, + Web3EventMap, +} from './web3_event_emitter.js'; + +export type PromiseExecutor = ( + resolve: (data: T) => void, + reject: (reason: unknown) => void, +) => void; + +export class Web3PromiEvent + extends Web3EventEmitter + implements Promise +{ + private readonly _promise: Promise; + + public constructor(executor: PromiseExecutor) { + super(); + this._promise = new Promise(executor); + } + + // public tag to treat object as promise by different libs + // eslint-disable-next-line @typescript-eslint/prefer-as-const + public [Symbol.toStringTag]: 'Promise' = 'Promise'; + + public async then( + onfulfilled?: ((value: ResolveType) => TResult1 | PromiseLike) | undefined, + onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | undefined, + ): Promise { + return this._promise.then(onfulfilled, onrejected); + } + + public async catch( + onrejected?: ((reason: unknown) => TResult | PromiseLike) | undefined, + ): Promise { + return this._promise.catch(onrejected); + } + + public async finally(onfinally?: (() => void) | undefined): Promise { + return this._promise.finally(onfinally); + } + + public on>( + eventName: K, + fn: Web3EventCallback, + ): this { + super.on(eventName, fn); + + return this; + } + + public once>( + eventName: K, + fn: Web3EventCallback, + ): this { + super.once(eventName, fn); + + return this; + } +} diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_request_manager.ts b/test/merkletreejs/node_modules/web3-core/src/web3_request_manager.ts new file mode 100644 index 0000000..df12bc5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_request_manager.ts @@ -0,0 +1,467 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + ContractExecutionError, + InvalidResponseError, + ProviderError, + ResponseError, + rpcErrorsMap, + RpcError, +} from 'web3-errors'; +import HttpProvider from 'web3-providers-http'; +import WSProvider from 'web3-providers-ws'; +import { + EthExecutionAPI, + JsonRpcBatchRequest, + JsonRpcBatchResponse, + JsonRpcPayload, + JsonRpcResponse, + JsonRpcError, + JsonRpcResponseWithResult, + JsonRpcResponseWithError, + SupportedProviders, + Web3APIMethod, + Web3APIPayload, + Web3APIRequest, + Web3APIReturnType, + Web3APISpec, + Web3BaseProvider, + Web3BaseProviderConstructor, +} from 'web3-types'; +import { isNullish, isPromise, jsonRpc, isResponseRpcError } from 'web3-utils'; +import { + isEIP1193Provider, + isLegacyRequestProvider, + isLegacySendAsyncProvider, + isLegacySendProvider, + isWeb3Provider, +} from './utils.js'; +import { Web3EventEmitter } from './web3_event_emitter.js'; + +export enum Web3RequestManagerEvent { + PROVIDER_CHANGED = 'PROVIDER_CHANGED', + BEFORE_PROVIDER_CHANGE = 'BEFORE_PROVIDER_CHANGE', +} + +const availableProviders: { + HttpProvider: Web3BaseProviderConstructor; + WebsocketProvider: Web3BaseProviderConstructor; +} = { + HttpProvider: HttpProvider as Web3BaseProviderConstructor, + WebsocketProvider: WSProvider as Web3BaseProviderConstructor, +}; + +export class Web3RequestManager< + API extends Web3APISpec = EthExecutionAPI, +> extends Web3EventEmitter<{ + [key in Web3RequestManagerEvent]: SupportedProviders | undefined; +}> { + private _provider?: SupportedProviders; + private readonly useRpcCallSpecification?: boolean; + public constructor( + provider?: SupportedProviders | string, + useRpcCallSpecification?: boolean, + ) { + super(); + + if (!isNullish(provider)) { + this.setProvider(provider); + } + this.useRpcCallSpecification = useRpcCallSpecification; + } + + /** + * Will return all available providers + */ + public static get providers() { + return availableProviders; + } + + /** + * Will return the current provider. + * + * @returns Returns the current provider + */ + public get provider() { + return this._provider; + } + + /** + * Will return all available providers + */ + // eslint-disable-next-line class-methods-use-this + public get providers() { + return availableProviders; + } + + /** + * Use to set provider. Provider can be a provider instance or a string. + * + * @param provider - The provider to set + */ + public setProvider(provider?: SupportedProviders | string): boolean { + let newProvider: SupportedProviders | undefined; + + // autodetect provider + if (provider && typeof provider === 'string' && this.providers) { + // HTTP + if (/^http(s)?:\/\//i.test(provider)) { + newProvider = new this.providers.HttpProvider(provider); + + // WS + } else if (/^ws(s)?:\/\//i.test(provider)) { + newProvider = new this.providers.WebsocketProvider(provider); + } else { + throw new ProviderError(`Can't autodetect provider for "${provider}"`); + } + } else if (isNullish(provider)) { + // In case want to unset the provider + newProvider = undefined; + } else { + newProvider = provider as SupportedProviders; + } + + this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider); + this._provider = newProvider; + this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider); + return true; + } + + /** + * + * Will execute a request + * + * @param request - {@link Web3APIRequest} The request to send + * + * @returns The response of the request {@link ResponseType}. If there is error + * in the response, will throw an error + */ + public async send< + Method extends Web3APIMethod, + ResponseType = Web3APIReturnType, + >(request: Web3APIRequest): Promise { + const response = await this._sendRequest(request); + if (jsonRpc.isResponseWithResult(response)) { + return response.result; + } + + throw new ResponseError(response); + } + + /** + * Same as send, but, will execute a batch of requests + * + * @param request {@link JsonRpcBatchRequest} The batch request to send + */ + public async sendBatch(request: JsonRpcBatchRequest): Promise> { + const response = await this._sendRequest(request); + + return response as JsonRpcBatchResponse; + } + + private async _sendRequest< + Method extends Web3APIMethod, + ResponseType = Web3APIReturnType, + >( + request: Web3APIRequest | JsonRpcBatchRequest, + ): Promise> { + const { provider } = this; + + if (isNullish(provider)) { + throw new ProviderError( + 'Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.', + ); + } + + const payload = jsonRpc.isBatchRequest(request) + ? jsonRpc.toBatchPayload(request) + : jsonRpc.toPayload(request); + + if (isWeb3Provider(provider)) { + let response; + + try { + response = await provider.request( + payload as Web3APIPayload, + ); + } catch (error) { + // Check if the provider throw an error instead of reject with error + response = error as JsonRpcResponse; + } + return this._processJsonRpcResponse(payload, response, { legacy: false, error: false }); + } + + if (isEIP1193Provider(provider)) { + return (provider as Web3BaseProvider) + .request(payload as Web3APIPayload) + .then( + res => + this._processJsonRpcResponse(payload, res, { + legacy: true, + error: false, + }) as JsonRpcResponseWithResult, + ) + .catch(error => + this._processJsonRpcResponse( + payload, + error as JsonRpcResponse, + { legacy: true, error: true }, + ), + ); + } + + // TODO: This could be deprecated and removed. + if (isLegacyRequestProvider(provider)) { + return new Promise>((resolve, reject) => { + const rejectWithError = (err: unknown) => + reject( + this._processJsonRpcResponse( + payload, + err as JsonRpcResponse, + { + legacy: true, + error: true, + }, + ), + ); + const resolveWithResponse = (response: JsonRpcResponse) => + resolve( + this._processJsonRpcResponse(payload, response, { + legacy: true, + error: false, + }), + ); + const result = provider.request( + payload, + // a callback that is expected to be called after getting the response: + (err, response) => { + if (err) { + return rejectWithError(err); + } + + return resolveWithResponse(response); + }, + ); + // Some providers, that follow a previous drafted version of EIP1193, has a `request` function + // that is not defined as `async`, but it returns a promise. + // Such providers would not be picked with if(isEIP1193Provider(provider)) above + // because the `request` function was not defined with `async` and so the function definition is not `AsyncFunction`. + // Like this provider: https://github.dev/NomicFoundation/hardhat/blob/62bea2600785595ba36f2105564076cf5cdf0fd8/packages/hardhat-core/src/internal/core/providers/backwards-compatibility.ts#L19 + // So check if the returned result is a Promise, and resolve with it accordingly. + // Note: in this case we expect the callback provided above to never be called. + if (isPromise(result)) { + const responsePromise = result as unknown as Promise< + JsonRpcResponse + >; + responsePromise.then(resolveWithResponse).catch(rejectWithError); + } + }); + } + + // TODO: This could be deprecated and removed. + if (isLegacySendProvider(provider)) { + return new Promise>((resolve, reject): void => { + provider.send(payload, (err, response) => { + if (err) { + return reject( + this._processJsonRpcResponse( + payload, + err as unknown as JsonRpcResponse, + { + legacy: true, + error: true, + }, + ), + ); + } + + if (isNullish(response)) { + throw new ResponseError( + '' as never, + 'Got a "nullish" response from provider.', + ); + } + + return resolve( + this._processJsonRpcResponse(payload, response, { + legacy: true, + error: false, + }), + ); + }); + }); + } + + // TODO: This could be deprecated and removed. + if (isLegacySendAsyncProvider(provider)) { + return provider + .sendAsync(payload) + .then(response => + this._processJsonRpcResponse(payload, response, { legacy: true, error: false }), + ) + .catch(error => + this._processJsonRpcResponse(payload, error as JsonRpcResponse, { + legacy: true, + error: true, + }), + ); + } + + throw new ProviderError('Provider does not have a request or send method to use.'); + } + + // eslint-disable-next-line class-methods-use-this + private _processJsonRpcResponse( + payload: JsonRpcPayload, + response: JsonRpcResponse, + { legacy, error }: { legacy: boolean; error: boolean }, + ): JsonRpcResponse | never { + if (isNullish(response)) { + return this._buildResponse( + payload, + // Some providers uses "null" as valid empty response + // eslint-disable-next-line no-null/no-null + null as unknown as JsonRpcResponse, + error, + ); + } + + // This is the majority of the cases so check these first + // A valid JSON-RPC response with error object + if (jsonRpc.isResponseWithError(response)) { + // check if its an rpc error + if ( + this.useRpcCallSpecification && + isResponseRpcError(response as JsonRpcResponseWithError) + ) { + const rpcErrorResponse = response as JsonRpcResponseWithError; + // check if rpc error flag is on and response error code match an EIP-1474 or a standard rpc error code + if (rpcErrorsMap.get(rpcErrorResponse.error.code)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const Err = rpcErrorsMap.get(rpcErrorResponse.error.code)!.error; + throw new Err(rpcErrorResponse); + } else { + throw new RpcError(rpcErrorResponse); + } + } else if (!Web3RequestManager._isReverted(response)) { + throw new InvalidResponseError(response, payload); + } + } + + // This is the majority of the cases so check these first + // A valid JSON-RPC response with result object + if (jsonRpc.isResponseWithResult(response)) { + return response; + } + + if ((response as unknown) instanceof Error) { + Web3RequestManager._isReverted(response); + throw response; + } + + if (!legacy && jsonRpc.isBatchRequest(payload) && jsonRpc.isBatchResponse(response)) { + return response as JsonRpcBatchResponse; + } + + if (legacy && !error && jsonRpc.isBatchRequest(payload)) { + return response as JsonRpcBatchResponse; + } + + if (legacy && error && jsonRpc.isBatchRequest(payload)) { + // In case of error batch response we don't want to throw Invalid response + throw response; + } + + if ( + legacy && + !jsonRpc.isResponseWithError(response) && + !jsonRpc.isResponseWithResult(response) + ) { + return this._buildResponse(payload, response, error); + } + + if (jsonRpc.isBatchRequest(payload) && !Array.isArray(response)) { + throw new ResponseError(response, 'Got normal response for a batch request.'); + } + + if (!jsonRpc.isBatchRequest(payload) && Array.isArray(response)) { + throw new ResponseError(response, 'Got batch response for a normal request.'); + } + + if ( + (jsonRpc.isResponseWithError(response) || jsonRpc.isResponseWithResult(response)) && + !jsonRpc.isBatchRequest(payload) + ) { + if (response.id && payload.id !== response.id) { + throw new InvalidResponseError(response); + } + } + + throw new ResponseError(response, 'Invalid response'); + } + + private static _isReverted( + response: JsonRpcResponse, + ): boolean { + let error: JsonRpcError | undefined; + + if (jsonRpc.isResponseWithError(response)) { + error = (response as JsonRpcResponseWithError).error; + } else if ((response as unknown) instanceof Error) { + error = response as unknown as JsonRpcError; + } + + // This message means that there was an error while executing the code of the smart contract + // However, more processing will happen at a higher level to decode the error data, + // according to the Error ABI, if it was available as of EIP-838. + if (error?.message.includes('revert')) throw new ContractExecutionError(error); + + return false; + } + // Need to use same types as _processJsonRpcResponse so have to declare as instance method + // eslint-disable-next-line class-methods-use-this + private _buildResponse( + payload: JsonRpcPayload, + response: JsonRpcResponse, + error: boolean, + ): JsonRpcResponse { + const res = { + jsonrpc: '2.0', + // eslint-disable-next-line no-nested-ternary + id: jsonRpc.isBatchRequest(payload) + ? payload[0].id + : 'id' in payload + ? payload.id + : // Have to use the null here explicitly + // eslint-disable-next-line no-null/no-null + null, + }; + + if (error) { + return { + ...res, + error: response as unknown, + } as JsonRpcResponse; + } + + return { + ...res, + result: response as unknown, + } as JsonRpcResponse; + } +} diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_subscription_manager.ts b/test/merkletreejs/node_modules/web3-core/src/web3_subscription_manager.ts new file mode 100644 index 0000000..8e76498 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_subscription_manager.ts @@ -0,0 +1,266 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + DataFormat, + DEFAULT_RETURN_FORMAT, + EIP1193Provider, + JsonRpcNotification, + JsonRpcSubscriptionResult, + JsonRpcSubscriptionResultOld, + Log, + Web3APISpec, + Web3BaseProvider, +} from 'web3-types'; +import { ProviderError, SubscriptionError } from 'web3-errors'; +import { isNullish } from 'web3-utils'; +import { isSupportSubscriptions } from './utils.js'; +import { Web3RequestManager, Web3RequestManagerEvent } from './web3_request_manager.js'; +// eslint-disable-next-line import/no-cycle +import { Web3SubscriptionConstructor } from './web3_subscriptions.js'; + +type ShouldUnsubscribeCondition = ({ + id, + sub, +}: { + id: string; + sub: unknown; +}) => boolean | undefined; + +export class Web3SubscriptionManager< + API extends Web3APISpec = Web3APISpec, + RegisteredSubs extends { [key: string]: Web3SubscriptionConstructor } = { + [key: string]: Web3SubscriptionConstructor; + }, +> { + private readonly _subscriptions: Map< + string, + InstanceType + > = new Map(); + + /** + * + * @param - requestManager + * @param - registeredSubscriptions + * + * @example + * ```ts + * const requestManager = new Web3RequestManager("ws://localhost:8545"); + * const subscriptionManager = new Web3SubscriptionManager(requestManager, {}); + * ``` + */ + public constructor( + requestManager: Web3RequestManager, + registeredSubscriptions: RegisteredSubs, + ); + /** + * @deprecated This constructor overloading should not be used + */ + public constructor( + requestManager: Web3RequestManager, + registeredSubscriptions: RegisteredSubs, + tolerateUnlinkedSubscription: boolean, + ); + public constructor( + public readonly requestManager: Web3RequestManager, + public readonly registeredSubscriptions: RegisteredSubs, + private readonly tolerateUnlinkedSubscription: boolean = false, + ) { + this.requestManager.on(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, async () => { + await this.unsubscribe(); + }); + + this.requestManager.on(Web3RequestManagerEvent.PROVIDER_CHANGED, () => { + this.clear(); + this.listenToProviderEvents(); + }); + + this.listenToProviderEvents(); + } + + private listenToProviderEvents() { + const providerAsWebProvider = this.requestManager.provider as Web3BaseProvider; + if ( + !this.requestManager.provider || + (typeof providerAsWebProvider?.supportsSubscriptions === 'function' && + !providerAsWebProvider?.supportsSubscriptions()) + ) { + return; + } + + if (typeof (this.requestManager.provider as EIP1193Provider).on === 'function') { + if ( + typeof (this.requestManager.provider as EIP1193Provider).request === 'function' + ) { + // Listen to provider messages and data + (this.requestManager.provider as EIP1193Provider).on( + 'message', + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument + (message: any) => this.messageListener(message), + ); + } else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument + providerAsWebProvider.on('data', (data: any) => this.messageListener(data)); + } + } + } + + protected messageListener( + data?: + | JsonRpcSubscriptionResult + | JsonRpcSubscriptionResultOld + | JsonRpcNotification, + ) { + if (!data) { + throw new SubscriptionError('Should not call messageListener with no data. Type was'); + } + const subscriptionId = + (data as JsonRpcNotification).params?.subscription || + (data as JsonRpcSubscriptionResultOld).data?.subscription || + (data as JsonRpcSubscriptionResult).id?.toString(16); + + // Process if the received data is related to a subscription + if (subscriptionId) { + const sub = this._subscriptions.get(subscriptionId); + sub?.processSubscriptionData(data); + } + } + /** + * Will create a new subscription + * + * @param name - The subscription you want to subscribe to + * @param args - Optional additional parameters, depending on the subscription type + * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * + * Will subscribe to a specific topic (note: name) + * @returns The subscription object + */ + public async subscribe( + name: T, + args?: ConstructorParameters[0], + returnFormat: DataFormat = DEFAULT_RETURN_FORMAT, + ): Promise> { + const Klass: RegisteredSubs[T] = this.registeredSubscriptions[name]; + if (!Klass) { + throw new SubscriptionError('Invalid subscription type'); + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const subscription = new Klass(args ?? undefined, { + subscriptionManager: this as Web3SubscriptionManager, + returnFormat, + } as any) as InstanceType; + + await this.addSubscription(subscription); + + return subscription; + } + + /** + * Will returns all subscriptions. + */ + public get subscriptions() { + return this._subscriptions; + } + + /** + * + * Adds an instance of {@link Web3Subscription} and subscribes to it + * + * @param sub - A {@link Web3Subscription} object + */ + public async addSubscription(sub: InstanceType) { + if (!this.requestManager.provider) { + throw new ProviderError('Provider not available'); + } + + if (!this.supportsSubscriptions()) { + throw new SubscriptionError('The current provider does not support subscriptions'); + } + + if (sub.id && this._subscriptions.has(sub.id)) { + throw new SubscriptionError(`Subscription with id "${sub.id}" already exists`); + } + + await sub.sendSubscriptionRequest(); + + if (isNullish(sub.id)) { + throw new SubscriptionError('Subscription is not subscribed yet.'); + } + + this._subscriptions.set(sub.id, sub); + + return sub.id; + } + + /** + * Will clear a subscription + * + * @param id - The subscription of type {@link Web3Subscription} to remove + */ + public async removeSubscription(sub: InstanceType) { + const { id } = sub; + + if (isNullish(id)) { + throw new SubscriptionError( + 'Subscription is not subscribed yet. Or, had already been unsubscribed but not through the Subscription Manager.', + ); + } + + if (!this._subscriptions.has(id) && !this.tolerateUnlinkedSubscription) { + throw new SubscriptionError(`Subscription with id "${id.toString()}" does not exists`); + } + + await sub.sendUnsubscribeRequest(); + this._subscriptions.delete(id); + return id; + } + /** + * Will unsubscribe all subscriptions that fulfill the condition + * + * @param condition - A function that access and `id` and a `subscription` and return `true` or `false` + * @returns An array of all the un-subscribed subscriptions + */ + public async unsubscribe(condition?: ShouldUnsubscribeCondition) { + const result = []; + for (const [id, sub] of this.subscriptions.entries()) { + if (!condition || (typeof condition === 'function' && condition({ id, sub }))) { + result.push(this.removeSubscription(sub)); + } + } + + return Promise.all(result); + } + + /** + * Clears all subscriptions + */ + public clear() { + this._subscriptions.clear(); + } + + /** + * Check whether the current provider supports subscriptions. + * + * @returns `true` or `false` depending on if the current provider supports subscriptions + */ + public supportsSubscriptions(): boolean { + return isNullish(this.requestManager.provider) + ? false + : isSupportSubscriptions(this.requestManager.provider); + } +} diff --git a/test/merkletreejs/node_modules/web3-core/src/web3_subscriptions.ts b/test/merkletreejs/node_modules/web3-core/src/web3_subscriptions.ts new file mode 100644 index 0000000..3cf4cee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-core/src/web3_subscriptions.ts @@ -0,0 +1,218 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// eslint-disable-next-line max-classes-per-file +import { + BlockOutput, + DEFAULT_RETURN_FORMAT, + DataFormat, + EthExecutionAPI, + JsonRpcSubscriptionResult, + JsonRpcSubscriptionResultOld, + JsonRpcNotification, + Log, + HexString, + Web3APIParams, + Web3APISpec, +} from 'web3-types'; +import { jsonRpc } from 'web3-utils'; +import { SubscriptionError } from 'web3-errors'; + +// eslint-disable-next-line import/no-cycle +import { Web3SubscriptionManager } from './web3_subscription_manager.js'; +import { Web3EventEmitter, Web3EventMap } from './web3_event_emitter.js'; +import { Web3RequestManager } from './web3_request_manager.js'; + +type CommonSubscriptionEvents = { + data: unknown; // Fires on each incoming block header. + error: Error; // Fires when an error in the subscription occurs. + connected: string; // Fires once after the subscription successfully connected. Returns the subscription id. +}; + +export abstract class Web3Subscription< + EventMap extends Web3EventMap, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ArgsType = any, + API extends Web3APISpec = EthExecutionAPI, + // The following generic type is just to define the type `CombinedEventMap` and use it inside the class + // it combines the user passed `EventMap` with the `CommonSubscriptionEvents` + // However, this type definition could be refactored depending on the closure of + // [Permit type alias declarations inside a class](https://github.com/microsoft/TypeScript/issues/7061) + CombinedEventMap extends CommonSubscriptionEvents = EventMap & CommonSubscriptionEvents, +> extends Web3EventEmitter { + private readonly _subscriptionManager: Web3SubscriptionManager; + private readonly _lastBlock?: BlockOutput; + private readonly _returnFormat: DataFormat; + protected _id?: HexString; + + public constructor( + args: ArgsType, + options: { subscriptionManager: Web3SubscriptionManager; returnFormat?: DataFormat }, + ); + /** + * @deprecated This constructor overloading should not be used + */ + public constructor( + args: ArgsType, + options: { requestManager: Web3RequestManager; returnFormat?: DataFormat }, + ); + public constructor( + public readonly args: ArgsType, + options: ( + | { subscriptionManager: Web3SubscriptionManager } + | { requestManager: Web3RequestManager } + ) & { + returnFormat?: DataFormat; + }, + ) { + super(); + const { requestManager } = options as { requestManager: Web3RequestManager }; + const { subscriptionManager } = options as { subscriptionManager: Web3SubscriptionManager }; + if (requestManager && subscriptionManager) { + throw new SubscriptionError( + 'Only requestManager or subscriptionManager should be provided at Subscription constructor', + ); + } + if (!requestManager && !subscriptionManager) { + throw new SubscriptionError( + 'Either requestManager or subscriptionManager should be provided at Subscription constructor', + ); + } + if (requestManager) { + // eslint-disable-next-line deprecation/deprecation + this._subscriptionManager = new Web3SubscriptionManager(requestManager, {}, true); + } else { + this._subscriptionManager = subscriptionManager; + } + + this._returnFormat = options?.returnFormat ?? (DEFAULT_RETURN_FORMAT as DataFormat); + } + + public get id() { + return this._id; + } + + public get lastBlock() { + return this._lastBlock; + } + + public async subscribe(): Promise { + return this._subscriptionManager.addSubscription(this); + } + + public processSubscriptionData( + data: + | JsonRpcSubscriptionResult + | JsonRpcSubscriptionResultOld + | JsonRpcNotification, + ) { + if (data?.data) { + // for EIP-1193 provider + this._processSubscriptionResult(data?.data?.result ?? data?.data); + } else if ( + data && + jsonRpc.isResponseWithNotification( + data as unknown as JsonRpcSubscriptionResult | JsonRpcNotification, + ) + ) { + this._processSubscriptionResult(data?.params.result); + } + } + + public async sendSubscriptionRequest(): Promise { + this._id = await this._subscriptionManager.requestManager.send({ + method: 'eth_subscribe', + params: this._buildSubscriptionParams(), + }); + + this.emit('connected', this._id); + return this._id; + } + + protected get returnFormat() { + return this._returnFormat; + } + + protected get subscriptionManager() { + return this._subscriptionManager; + } + + public async resubscribe() { + await this.unsubscribe(); + await this.subscribe(); + } + + public async unsubscribe() { + if (!this.id) { + return; + } + + await this._subscriptionManager.removeSubscription(this); + } + + public async sendUnsubscribeRequest() { + await this._subscriptionManager.requestManager.send({ + method: 'eth_unsubscribe', + params: [this.id] as Web3APIParams, + }); + this._id = undefined; + } + + // eslint-disable-next-line class-methods-use-this + protected formatSubscriptionResult(data: CombinedEventMap['data']) { + return data; + } + + public _processSubscriptionResult(data: CombinedEventMap['data'] | unknown) { + this.emit('data', this.formatSubscriptionResult(data)); + } + + public _processSubscriptionError(error: Error) { + this.emit('error', error); + } + + // eslint-disable-next-line class-methods-use-this + protected _buildSubscriptionParams(): Web3APIParams { + // This should be overridden in the subclass + throw new Error('Implement in the child class'); + } +} + +export type Web3SubscriptionConstructor< + API extends Web3APISpec, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + SubscriptionType extends Web3Subscription = Web3Subscription, +> = + | (new ( + // We accept any type of arguments here and don't deal with this type internally + // eslint-disable-next-line @typescript-eslint/no-explicit-any + args: any, + options: + | { subscriptionManager: Web3SubscriptionManager; returnFormat?: DataFormat } + | { requestManager: Web3RequestManager; returnFormat?: DataFormat }, + ) => SubscriptionType) + | (new ( + args: any, + options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; + }, + ) => SubscriptionType) + | (new ( + args: any, + options: { requestManager: Web3RequestManager; returnFormat?: DataFormat }, + ) => SubscriptionType); diff --git a/test/merkletreejs/node_modules/web3-errors/LICENSE b/test/merkletreejs/node_modules/web3-errors/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-errors/README.md b/test/merkletreejs/node_modules/web3-errors/README.md new file mode 100644 index 0000000..9a68b9a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Web3-Errors + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-errors` This package has web3 error classes. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-errors) or using [Yarn](https://yarnpkg.com/package/web3-errors) + +### Using NPM + +```bash +npm install web3-errors +``` + +### Using Yarn + +```bash +yarn add web3-errors +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-errors +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-errors%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-errors +[downloads-image]: https://img.shields.io/npm/dm/web3-errors?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.d.ts new file mode 100644 index 0000000..698896c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.d.ts @@ -0,0 +1,127 @@ +export declare const ERR_RESPONSE = 100; +export declare const ERR_INVALID_RESPONSE = 101; +export declare const ERR_PARAM = 200; +export declare const ERR_FORMATTERS = 201; +export declare const ERR_METHOD_NOT_IMPLEMENTED = 202; +export declare const ERR_OPERATION_TIMEOUT = 203; +export declare const ERR_OPERATION_ABORT = 204; +export declare const ERR_ABI_ENCODING = 205; +export declare const ERR_EXISTING_PLUGIN_NAMESPACE = 206; +export declare const ERR_INVALID_METHOD_PARAMS = 207; +export declare const ERR_CONTRACT = 300; +export declare const ERR_CONTRACT_RESOLVER_MISSING = 301; +export declare const ERR_CONTRACT_ABI_MISSING = 302; +export declare const ERR_CONTRACT_REQUIRED_CALLBACK = 303; +export declare const ERR_CONTRACT_EVENT_NOT_EXISTS = 304; +export declare const ERR_CONTRACT_RESERVED_EVENT = 305; +export declare const ERR_CONTRACT_MISSING_DEPLOY_DATA = 306; +export declare const ERR_CONTRACT_MISSING_ADDRESS = 307; +export declare const ERR_CONTRACT_MISSING_FROM_ADDRESS = 308; +export declare const ERR_CONTRACT_INSTANTIATION = 309; +export declare const ERR_CONTRACT_EXECUTION_REVERTED = 310; +export declare const ERR_CONTRACT_TX_DATA_AND_INPUT = 311; +export declare const ERR_TX = 400; +export declare const ERR_TX_REVERT_INSTRUCTION = 401; +export declare const ERR_TX_REVERT_TRANSACTION = 402; +export declare const ERR_TX_NO_CONTRACT_ADDRESS = 403; +export declare const ERR_TX_CONTRACT_NOT_STORED = 404; +export declare const ERR_TX_REVERT_WITHOUT_REASON = 405; +export declare const ERR_TX_OUT_OF_GAS = 406; +export declare const ERR_RAW_TX_UNDEFINED = 407; +export declare const ERR_TX_INVALID_SENDER = 408; +export declare const ERR_TX_INVALID_CALL = 409; +export declare const ERR_TX_MISSING_CUSTOM_CHAIN = 410; +export declare const ERR_TX_MISSING_CUSTOM_CHAIN_ID = 411; +export declare const ERR_TX_CHAIN_ID_MISMATCH = 412; +export declare const ERR_TX_INVALID_CHAIN_INFO = 413; +export declare const ERR_TX_MISSING_CHAIN_INFO = 414; +export declare const ERR_TX_MISSING_GAS = 415; +export declare const ERR_TX_INVALID_LEGACY_GAS = 416; +export declare const ERR_TX_INVALID_FEE_MARKET_GAS = 417; +export declare const ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = 418; +export declare const ERR_TX_INVALID_LEGACY_FEE_MARKET = 419; +export declare const ERR_TX_INVALID_OBJECT = 420; +export declare const ERR_TX_INVALID_NONCE_OR_CHAIN_ID = 421; +export declare const ERR_TX_UNABLE_TO_POPULATE_NONCE = 422; +export declare const ERR_TX_UNSUPPORTED_EIP_1559 = 423; +export declare const ERR_TX_UNSUPPORTED_TYPE = 424; +export declare const ERR_TX_DATA_AND_INPUT = 425; +export declare const ERR_TX_POLLING_TIMEOUT = 426; +export declare const ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = 427; +export declare const ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = 428; +export declare const ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = 429; +export declare const ERR_TX_NOT_FOUND = 430; +export declare const ERR_TX_SEND_TIMEOUT = 431; +export declare const ERR_TX_BLOCK_TIMEOUT = 432; +export declare const ERR_TX_SIGNING = 433; +export declare const ERR_TX_GAS_MISMATCH = 434; +export declare const ERR_TX_CHAIN_MISMATCH = 435; +export declare const ERR_TX_HARDFORK_MISMATCH = 436; +export declare const ERR_TX_INVALID_RECEIVER = 437; +export declare const ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = 438; +export declare const ERR_TX_INVALID_PROPERTIES_FOR_TYPE = 439; +export declare const ERR_TX_MISSING_GAS_INNER_ERROR = 440; +export declare const ERR_TX_GAS_MISMATCH_INNER_ERROR = 441; +export declare const ERR_CONN = 500; +export declare const ERR_CONN_INVALID = 501; +export declare const ERR_CONN_TIMEOUT = 502; +export declare const ERR_CONN_NOT_OPEN = 503; +export declare const ERR_CONN_CLOSE = 504; +export declare const ERR_CONN_MAX_ATTEMPTS = 505; +export declare const ERR_CONN_PENDING_REQUESTS = 506; +export declare const ERR_REQ_ALREADY_SENT = 507; +export declare const ERR_PROVIDER = 600; +export declare const ERR_INVALID_PROVIDER = 601; +export declare const ERR_INVALID_CLIENT = 602; +export declare const ERR_SUBSCRIPTION = 603; +export declare const ERR_WS_PROVIDER = 604; +export declare const ERR_PRIVATE_KEY_LENGTH = 701; +export declare const ERR_INVALID_PRIVATE_KEY = 702; +export declare const ERR_UNSUPPORTED_KDF = 703; +export declare const ERR_KEY_DERIVATION_FAIL = 704; +export declare const ERR_KEY_VERSION_UNSUPPORTED = 705; +export declare const ERR_INVALID_PASSWORD = 706; +export declare const ERR_IV_LENGTH = 707; +export declare const ERR_INVALID_KEYSTORE = 708; +export declare const ERR_PBKDF2_ITERATIONS = 709; +export declare const ERR_SIGNATURE_FAILED = 801; +export declare const ERR_INVALID_SIGNATURE = 802; +export declare const GENESIS_BLOCK_NUMBER = "0x0"; +export declare const JSONRPC_ERR_REJECTED_REQUEST = 4001; +export declare const JSONRPC_ERR_UNAUTHORIZED = 4100; +export declare const JSONRPC_ERR_UNSUPPORTED_METHOD = 4200; +export declare const JSONRPC_ERR_DISCONNECTED = 4900; +export declare const JSONRPC_ERR_CHAIN_DISCONNECTED = 4901; +export declare const ERR_ENS_CHECK_INTERFACE_SUPPORT = 901; +export declare const ERR_ENS_UNSUPPORTED_NETWORK = 902; +export declare const ERR_ENS_NETWORK_NOT_SYNCED = 903; +export declare const ERR_INVALID_STRING = 1001; +export declare const ERR_INVALID_BYTES = 1002; +export declare const ERR_INVALID_NUMBER = 1003; +export declare const ERR_INVALID_UNIT = 1004; +export declare const ERR_INVALID_ADDRESS = 1005; +export declare const ERR_INVALID_HEX = 1006; +export declare const ERR_INVALID_TYPE = 1007; +export declare const ERR_INVALID_BOOLEAN = 1008; +export declare const ERR_INVALID_UNSIGNED_INTEGER = 1009; +export declare const ERR_INVALID_SIZE = 1010; +export declare const ERR_INVALID_LARGE_VALUE = 1011; +export declare const ERR_INVALID_BLOCK = 1012; +export declare const ERR_INVALID_TYPE_ABI = 1013; +export declare const ERR_INVALID_NIBBLE_WIDTH = 1014; +export declare const ERR_VALIDATION = 1100; +export declare const ERR_CORE_HARDFORK_MISMATCH = 1101; +export declare const ERR_CORE_CHAIN_MISMATCH = 1102; +export declare const ERR_SCHEMA_FORMAT = 1200; +export declare const ERR_RPC_INVALID_JSON = -32700; +export declare const ERR_RPC_INVALID_REQUEST = -32600; +export declare const ERR_RPC_INVALID_METHOD = -32601; +export declare const ERR_RPC_INVALID_PARAMS = -32602; +export declare const ERR_RPC_INTERNAL_ERROR = -32603; +export declare const ERR_RPC_INVALID_INPUT = -32000; +export declare const ERR_RPC_MISSING_RESOURCE = -32001; +export declare const ERR_RPC_UNAVAILABLE_RESOURCE = -32002; +export declare const ERR_RPC_TRANSACTION_REJECTED = -32003; +export declare const ERR_RPC_UNSUPPORTED_METHOD = -32004; +export declare const ERR_RPC_LIMIT_EXCEEDED = -32005; +export declare const ERR_RPC_NOT_SUPPORTED = -32006; diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.js new file mode 100644 index 0000000..c4acf87 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.js @@ -0,0 +1,166 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = exports.ERR_TX_POLLING_TIMEOUT = exports.ERR_TX_DATA_AND_INPUT = exports.ERR_TX_UNSUPPORTED_TYPE = exports.ERR_TX_UNSUPPORTED_EIP_1559 = exports.ERR_TX_UNABLE_TO_POPULATE_NONCE = exports.ERR_TX_INVALID_NONCE_OR_CHAIN_ID = exports.ERR_TX_INVALID_OBJECT = exports.ERR_TX_INVALID_LEGACY_FEE_MARKET = exports.ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = exports.ERR_TX_INVALID_FEE_MARKET_GAS = exports.ERR_TX_INVALID_LEGACY_GAS = exports.ERR_TX_MISSING_GAS = exports.ERR_TX_MISSING_CHAIN_INFO = exports.ERR_TX_INVALID_CHAIN_INFO = exports.ERR_TX_CHAIN_ID_MISMATCH = exports.ERR_TX_MISSING_CUSTOM_CHAIN_ID = exports.ERR_TX_MISSING_CUSTOM_CHAIN = exports.ERR_TX_INVALID_CALL = exports.ERR_TX_INVALID_SENDER = exports.ERR_RAW_TX_UNDEFINED = exports.ERR_TX_OUT_OF_GAS = exports.ERR_TX_REVERT_WITHOUT_REASON = exports.ERR_TX_CONTRACT_NOT_STORED = exports.ERR_TX_NO_CONTRACT_ADDRESS = exports.ERR_TX_REVERT_TRANSACTION = exports.ERR_TX_REVERT_INSTRUCTION = exports.ERR_TX = exports.ERR_CONTRACT_TX_DATA_AND_INPUT = exports.ERR_CONTRACT_EXECUTION_REVERTED = exports.ERR_CONTRACT_INSTANTIATION = exports.ERR_CONTRACT_MISSING_FROM_ADDRESS = exports.ERR_CONTRACT_MISSING_ADDRESS = exports.ERR_CONTRACT_MISSING_DEPLOY_DATA = exports.ERR_CONTRACT_RESERVED_EVENT = exports.ERR_CONTRACT_EVENT_NOT_EXISTS = exports.ERR_CONTRACT_REQUIRED_CALLBACK = exports.ERR_CONTRACT_ABI_MISSING = exports.ERR_CONTRACT_RESOLVER_MISSING = exports.ERR_CONTRACT = exports.ERR_INVALID_METHOD_PARAMS = exports.ERR_EXISTING_PLUGIN_NAMESPACE = exports.ERR_ABI_ENCODING = exports.ERR_OPERATION_ABORT = exports.ERR_OPERATION_TIMEOUT = exports.ERR_METHOD_NOT_IMPLEMENTED = exports.ERR_FORMATTERS = exports.ERR_PARAM = exports.ERR_INVALID_RESPONSE = exports.ERR_RESPONSE = void 0; +exports.ERR_INVALID_NUMBER = exports.ERR_INVALID_BYTES = exports.ERR_INVALID_STRING = exports.ERR_ENS_NETWORK_NOT_SYNCED = exports.ERR_ENS_UNSUPPORTED_NETWORK = exports.ERR_ENS_CHECK_INTERFACE_SUPPORT = exports.JSONRPC_ERR_CHAIN_DISCONNECTED = exports.JSONRPC_ERR_DISCONNECTED = exports.JSONRPC_ERR_UNSUPPORTED_METHOD = exports.JSONRPC_ERR_UNAUTHORIZED = exports.JSONRPC_ERR_REJECTED_REQUEST = exports.GENESIS_BLOCK_NUMBER = exports.ERR_INVALID_SIGNATURE = exports.ERR_SIGNATURE_FAILED = exports.ERR_PBKDF2_ITERATIONS = exports.ERR_INVALID_KEYSTORE = exports.ERR_IV_LENGTH = exports.ERR_INVALID_PASSWORD = exports.ERR_KEY_VERSION_UNSUPPORTED = exports.ERR_KEY_DERIVATION_FAIL = exports.ERR_UNSUPPORTED_KDF = exports.ERR_INVALID_PRIVATE_KEY = exports.ERR_PRIVATE_KEY_LENGTH = exports.ERR_WS_PROVIDER = exports.ERR_SUBSCRIPTION = exports.ERR_INVALID_CLIENT = exports.ERR_INVALID_PROVIDER = exports.ERR_PROVIDER = exports.ERR_REQ_ALREADY_SENT = exports.ERR_CONN_PENDING_REQUESTS = exports.ERR_CONN_MAX_ATTEMPTS = exports.ERR_CONN_CLOSE = exports.ERR_CONN_NOT_OPEN = exports.ERR_CONN_TIMEOUT = exports.ERR_CONN_INVALID = exports.ERR_CONN = exports.ERR_TX_GAS_MISMATCH_INNER_ERROR = exports.ERR_TX_MISSING_GAS_INNER_ERROR = exports.ERR_TX_INVALID_PROPERTIES_FOR_TYPE = exports.ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = exports.ERR_TX_INVALID_RECEIVER = exports.ERR_TX_HARDFORK_MISMATCH = exports.ERR_TX_CHAIN_MISMATCH = exports.ERR_TX_GAS_MISMATCH = exports.ERR_TX_SIGNING = exports.ERR_TX_BLOCK_TIMEOUT = exports.ERR_TX_SEND_TIMEOUT = exports.ERR_TX_NOT_FOUND = exports.ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = exports.ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = void 0; +exports.ERR_RPC_NOT_SUPPORTED = exports.ERR_RPC_LIMIT_EXCEEDED = exports.ERR_RPC_UNSUPPORTED_METHOD = exports.ERR_RPC_TRANSACTION_REJECTED = exports.ERR_RPC_UNAVAILABLE_RESOURCE = exports.ERR_RPC_MISSING_RESOURCE = exports.ERR_RPC_INVALID_INPUT = exports.ERR_RPC_INTERNAL_ERROR = exports.ERR_RPC_INVALID_PARAMS = exports.ERR_RPC_INVALID_METHOD = exports.ERR_RPC_INVALID_REQUEST = exports.ERR_RPC_INVALID_JSON = exports.ERR_SCHEMA_FORMAT = exports.ERR_CORE_CHAIN_MISMATCH = exports.ERR_CORE_HARDFORK_MISMATCH = exports.ERR_VALIDATION = exports.ERR_INVALID_NIBBLE_WIDTH = exports.ERR_INVALID_TYPE_ABI = exports.ERR_INVALID_BLOCK = exports.ERR_INVALID_LARGE_VALUE = exports.ERR_INVALID_SIZE = exports.ERR_INVALID_UNSIGNED_INTEGER = exports.ERR_INVALID_BOOLEAN = exports.ERR_INVALID_TYPE = exports.ERR_INVALID_HEX = exports.ERR_INVALID_ADDRESS = exports.ERR_INVALID_UNIT = void 0; +// Response error +exports.ERR_RESPONSE = 100; +exports.ERR_INVALID_RESPONSE = 101; +// Generic errors +exports.ERR_PARAM = 200; +exports.ERR_FORMATTERS = 201; +exports.ERR_METHOD_NOT_IMPLEMENTED = 202; +exports.ERR_OPERATION_TIMEOUT = 203; +exports.ERR_OPERATION_ABORT = 204; +exports.ERR_ABI_ENCODING = 205; +exports.ERR_EXISTING_PLUGIN_NAMESPACE = 206; +exports.ERR_INVALID_METHOD_PARAMS = 207; +// Contract error codes +exports.ERR_CONTRACT = 300; +exports.ERR_CONTRACT_RESOLVER_MISSING = 301; +exports.ERR_CONTRACT_ABI_MISSING = 302; +exports.ERR_CONTRACT_REQUIRED_CALLBACK = 303; +exports.ERR_CONTRACT_EVENT_NOT_EXISTS = 304; +exports.ERR_CONTRACT_RESERVED_EVENT = 305; +exports.ERR_CONTRACT_MISSING_DEPLOY_DATA = 306; +exports.ERR_CONTRACT_MISSING_ADDRESS = 307; +exports.ERR_CONTRACT_MISSING_FROM_ADDRESS = 308; +exports.ERR_CONTRACT_INSTANTIATION = 309; +exports.ERR_CONTRACT_EXECUTION_REVERTED = 310; +exports.ERR_CONTRACT_TX_DATA_AND_INPUT = 311; +// Transaction error codes +exports.ERR_TX = 400; +exports.ERR_TX_REVERT_INSTRUCTION = 401; +exports.ERR_TX_REVERT_TRANSACTION = 402; +exports.ERR_TX_NO_CONTRACT_ADDRESS = 403; +exports.ERR_TX_CONTRACT_NOT_STORED = 404; +exports.ERR_TX_REVERT_WITHOUT_REASON = 405; +exports.ERR_TX_OUT_OF_GAS = 406; +exports.ERR_RAW_TX_UNDEFINED = 407; +exports.ERR_TX_INVALID_SENDER = 408; +exports.ERR_TX_INVALID_CALL = 409; +exports.ERR_TX_MISSING_CUSTOM_CHAIN = 410; +exports.ERR_TX_MISSING_CUSTOM_CHAIN_ID = 411; +exports.ERR_TX_CHAIN_ID_MISMATCH = 412; +exports.ERR_TX_INVALID_CHAIN_INFO = 413; +exports.ERR_TX_MISSING_CHAIN_INFO = 414; +exports.ERR_TX_MISSING_GAS = 415; +exports.ERR_TX_INVALID_LEGACY_GAS = 416; +exports.ERR_TX_INVALID_FEE_MARKET_GAS = 417; +exports.ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = 418; +exports.ERR_TX_INVALID_LEGACY_FEE_MARKET = 419; +exports.ERR_TX_INVALID_OBJECT = 420; +exports.ERR_TX_INVALID_NONCE_OR_CHAIN_ID = 421; +exports.ERR_TX_UNABLE_TO_POPULATE_NONCE = 422; +exports.ERR_TX_UNSUPPORTED_EIP_1559 = 423; +exports.ERR_TX_UNSUPPORTED_TYPE = 424; +exports.ERR_TX_DATA_AND_INPUT = 425; +exports.ERR_TX_POLLING_TIMEOUT = 426; +exports.ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = 427; +exports.ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = 428; +exports.ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = 429; +exports.ERR_TX_NOT_FOUND = 430; +exports.ERR_TX_SEND_TIMEOUT = 431; +exports.ERR_TX_BLOCK_TIMEOUT = 432; +exports.ERR_TX_SIGNING = 433; +exports.ERR_TX_GAS_MISMATCH = 434; +exports.ERR_TX_CHAIN_MISMATCH = 435; +exports.ERR_TX_HARDFORK_MISMATCH = 436; +exports.ERR_TX_INVALID_RECEIVER = 437; +exports.ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = 438; +exports.ERR_TX_INVALID_PROPERTIES_FOR_TYPE = 439; +exports.ERR_TX_MISSING_GAS_INNER_ERROR = 440; +exports.ERR_TX_GAS_MISMATCH_INNER_ERROR = 441; +// Connection error codes +exports.ERR_CONN = 500; +exports.ERR_CONN_INVALID = 501; +exports.ERR_CONN_TIMEOUT = 502; +exports.ERR_CONN_NOT_OPEN = 503; +exports.ERR_CONN_CLOSE = 504; +exports.ERR_CONN_MAX_ATTEMPTS = 505; +exports.ERR_CONN_PENDING_REQUESTS = 506; +exports.ERR_REQ_ALREADY_SENT = 507; +// Provider error codes +exports.ERR_PROVIDER = 600; +exports.ERR_INVALID_PROVIDER = 601; +exports.ERR_INVALID_CLIENT = 602; +exports.ERR_SUBSCRIPTION = 603; +exports.ERR_WS_PROVIDER = 604; +// Account error codes +exports.ERR_PRIVATE_KEY_LENGTH = 701; +exports.ERR_INVALID_PRIVATE_KEY = 702; +exports.ERR_UNSUPPORTED_KDF = 703; +exports.ERR_KEY_DERIVATION_FAIL = 704; +exports.ERR_KEY_VERSION_UNSUPPORTED = 705; +exports.ERR_INVALID_PASSWORD = 706; +exports.ERR_IV_LENGTH = 707; +exports.ERR_INVALID_KEYSTORE = 708; +exports.ERR_PBKDF2_ITERATIONS = 709; +// Signature error codes +exports.ERR_SIGNATURE_FAILED = 801; +exports.ERR_INVALID_SIGNATURE = 802; +exports.GENESIS_BLOCK_NUMBER = '0x0'; +// RPC error codes (EIP-1193) +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors +exports.JSONRPC_ERR_REJECTED_REQUEST = 4001; +exports.JSONRPC_ERR_UNAUTHORIZED = 4100; +exports.JSONRPC_ERR_UNSUPPORTED_METHOD = 4200; +exports.JSONRPC_ERR_DISCONNECTED = 4900; +exports.JSONRPC_ERR_CHAIN_DISCONNECTED = 4901; +// ENS error codes +exports.ERR_ENS_CHECK_INTERFACE_SUPPORT = 901; +exports.ERR_ENS_UNSUPPORTED_NETWORK = 902; +exports.ERR_ENS_NETWORK_NOT_SYNCED = 903; +// Utils error codes +exports.ERR_INVALID_STRING = 1001; +exports.ERR_INVALID_BYTES = 1002; +exports.ERR_INVALID_NUMBER = 1003; +exports.ERR_INVALID_UNIT = 1004; +exports.ERR_INVALID_ADDRESS = 1005; +exports.ERR_INVALID_HEX = 1006; +exports.ERR_INVALID_TYPE = 1007; +exports.ERR_INVALID_BOOLEAN = 1008; +exports.ERR_INVALID_UNSIGNED_INTEGER = 1009; +exports.ERR_INVALID_SIZE = 1010; +exports.ERR_INVALID_LARGE_VALUE = 1011; +exports.ERR_INVALID_BLOCK = 1012; +exports.ERR_INVALID_TYPE_ABI = 1013; +exports.ERR_INVALID_NIBBLE_WIDTH = 1014; +// Validation error codes +exports.ERR_VALIDATION = 1100; +// Core error codes +exports.ERR_CORE_HARDFORK_MISMATCH = 1101; +exports.ERR_CORE_CHAIN_MISMATCH = 1102; +// Schema error codes +exports.ERR_SCHEMA_FORMAT = 1200; +// RPC error codes (EIP-1474) +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md +exports.ERR_RPC_INVALID_JSON = -32700; +exports.ERR_RPC_INVALID_REQUEST = -32600; +exports.ERR_RPC_INVALID_METHOD = -32601; +exports.ERR_RPC_INVALID_PARAMS = -32602; +exports.ERR_RPC_INTERNAL_ERROR = -32603; +exports.ERR_RPC_INVALID_INPUT = -32000; +exports.ERR_RPC_MISSING_RESOURCE = -32001; +exports.ERR_RPC_UNAVAILABLE_RESOURCE = -32002; +exports.ERR_RPC_TRANSACTION_REJECTED = -32003; +exports.ERR_RPC_UNSUPPORTED_METHOD = -32004; +exports.ERR_RPC_LIMIT_EXCEEDED = -32005; +exports.ERR_RPC_NOT_SUPPORTED = -32006; +//# sourceMappingURL=error_codes.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.js.map new file mode 100644 index 0000000..e8f399d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/error_codes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error_codes.js","sourceRoot":"","sources":["../../src/error_codes.ts"],"names":[],"mappings":";AAAA;;;;;;;;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AAC;AAChC,QAAA,qBAAqB,GAAG,CAAC,KAAK,CAAC;AAC/B,QAAA,wBAAwB,GAAG,CAAC,KAAK,CAAC;AAClC,QAAA,4BAA4B,GAAG,CAAC,KAAK,CAAC;AACtC,QAAA,4BAA4B,GAAG,CAAC,KAAK,CAAC;AACtC,QAAA,0BAA0B,GAAG,CAAC,KAAK,CAAC;AACpC,QAAA,sBAAsB,GAAG,CAAC,KAAK,CAAC;AAChC,QAAA,qBAAqB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.d.ts new file mode 100644 index 0000000..b8e95d1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.d.ts @@ -0,0 +1,37 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class PrivateKeyLengthError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class InvalidPrivateKeyError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class InvalidSignatureError extends BaseWeb3Error { + code: number; + constructor(errorDetails: string); +} +export declare class InvalidKdfError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class KeyDerivationError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class KeyStoreVersionError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class InvalidPasswordError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class IVLengthError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class PBKDF2IterationsError extends BaseWeb3Error { + code: number; + constructor(); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.js new file mode 100644 index 0000000..c5e5608 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.js @@ -0,0 +1,86 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PBKDF2IterationsError = exports.IVLengthError = exports.InvalidPasswordError = exports.KeyStoreVersionError = exports.KeyDerivationError = exports.InvalidKdfError = exports.InvalidSignatureError = exports.InvalidPrivateKeyError = exports.PrivateKeyLengthError = void 0; +/* eslint-disable max-classes-per-file */ +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class PrivateKeyLengthError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(`Private key must be 32 bytes.`); + this.code = error_codes_js_1.ERR_PRIVATE_KEY_LENGTH; + } +} +exports.PrivateKeyLengthError = PrivateKeyLengthError; +class InvalidPrivateKeyError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(`Invalid Private Key, Not a valid string or uint8Array`); + this.code = error_codes_js_1.ERR_INVALID_PRIVATE_KEY; + } +} +exports.InvalidPrivateKeyError = InvalidPrivateKeyError; +class InvalidSignatureError extends web3_error_base_js_1.BaseWeb3Error { + constructor(errorDetails) { + super(`"${errorDetails}"`); + this.code = error_codes_js_1.ERR_INVALID_SIGNATURE; + } +} +exports.InvalidSignatureError = InvalidSignatureError; +class InvalidKdfError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(`Invalid key derivation function`); + this.code = error_codes_js_1.ERR_UNSUPPORTED_KDF; + } +} +exports.InvalidKdfError = InvalidKdfError; +class KeyDerivationError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(`Key derivation failed - possibly wrong password`); + this.code = error_codes_js_1.ERR_KEY_DERIVATION_FAIL; + } +} +exports.KeyDerivationError = KeyDerivationError; +class KeyStoreVersionError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('Unsupported key store version'); + this.code = error_codes_js_1.ERR_KEY_VERSION_UNSUPPORTED; + } +} +exports.KeyStoreVersionError = KeyStoreVersionError; +class InvalidPasswordError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('Password cannot be empty'); + this.code = error_codes_js_1.ERR_INVALID_PASSWORD; + } +} +exports.InvalidPasswordError = InvalidPasswordError; +class IVLengthError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('Initialization vector must be 16 bytes'); + this.code = error_codes_js_1.ERR_IV_LENGTH; + } +} +exports.IVLengthError = IVLengthError; +class PBKDF2IterationsError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('c > 1000, pbkdf2 is less secure with less iterations'); + this.code = error_codes_js_1.ERR_PBKDF2_ITERATIONS; + } +} +exports.PBKDF2IterationsError = PBKDF2IterationsError; +//# sourceMappingURL=account_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.js.map new file mode 100644 index 0000000..db593f0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/account_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"account_errors.js","sourceRoot":"","sources":["../../../src/errors/account_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAyC;AAEzC,sDAU2B;AAC3B,8DAAsD;AAEtD,MAAa,qBAAsB,SAAQ,kCAAa;IAEvD;QACC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAFjC,SAAI,GAAG,uCAAsB,CAAC;IAGrC,CAAC;CACD;AALD,sDAKC;AAED,MAAa,sBAAuB,SAAQ,kCAAa;IAExD;QACC,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAFzD,SAAI,GAAG,wCAAuB,CAAC;IAGtC,CAAC;CACD;AALD,wDAKC;AAED,MAAa,qBAAsB,SAAQ,kCAAa;IAEvD,YAAmB,YAAoB;QACtC,KAAK,CAAC,IAAI,YAAY,GAAG,CAAC,CAAC;QAFrB,SAAI,GAAG,sCAAqB,CAAC;IAGpC,CAAC;CACD;AALD,sDAKC;AAED,MAAa,eAAgB,SAAQ,kCAAa;IAEjD;QACC,KAAK,CAAC,iCAAiC,CAAC,CAAC;QAFnC,SAAI,GAAG,oCAAmB,CAAC;IAGlC,CAAC;CACD;AALD,0CAKC;AAED,MAAa,kBAAmB,SAAQ,kCAAa;IAEpD;QACC,KAAK,CAAC,iDAAiD,CAAC,CAAC;QAFnD,SAAI,GAAG,wCAAuB,CAAC;IAGtC,CAAC;CACD;AALD,gDAKC;AAED,MAAa,oBAAqB,SAAQ,kCAAa;IAEtD;QACC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAFjC,SAAI,GAAG,4CAA2B,CAAC;IAG1C,CAAC;CACD;AALD,oDAKC;AAED,MAAa,oBAAqB,SAAQ,kCAAa;IAEtD;QACC,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAF5B,SAAI,GAAG,qCAAoB,CAAC;IAGnC,CAAC;CACD;AALD,oDAKC;AAED,MAAa,aAAc,SAAQ,kCAAa;IAE/C;QACC,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAF1C,SAAI,GAAG,8BAAa,CAAC;IAG5B,CAAC;CACD;AALD,sCAKC;AAED,MAAa,qBAAsB,SAAQ,kCAAa;IAEvD;QACC,KAAK,CAAC,sDAAsD,CAAC,CAAC;QAFxD,SAAI,GAAG,sCAAqB,CAAC;IAGpC,CAAC;CACD;AALD,sDAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.d.ts new file mode 100644 index 0000000..561eb7e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.d.ts @@ -0,0 +1,57 @@ +import { ConnectionEvent } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ConnectionError extends BaseWeb3Error { + code: number; + errorCode?: number; + errorReason?: string; + constructor(message: string, event?: ConnectionEvent); + toJSON(): { + errorCode: number | undefined; + errorReason: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class InvalidConnectionError extends ConnectionError { + host: string; + constructor(host: string, event?: ConnectionEvent); + toJSON(): { + host: string; + errorCode: number | undefined; + errorReason: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ConnectionTimeoutError extends ConnectionError { + duration: number; + constructor(duration: number); + toJSON(): { + duration: number; + errorCode: number | undefined; + errorReason: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ConnectionNotOpenError extends ConnectionError { + constructor(event?: ConnectionEvent); +} +export declare class ConnectionCloseError extends ConnectionError { + constructor(event?: ConnectionEvent); +} +export declare class MaxAttemptsReachedOnReconnectingError extends ConnectionError { + constructor(numberOfAttempts: number); +} +export declare class PendingRequestsOnReconnectingError extends ConnectionError { + constructor(); +} +export declare class RequestAlreadySentError extends ConnectionError { + constructor(id: number | string); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.js new file mode 100644 index 0000000..2de0dba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.js @@ -0,0 +1,94 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RequestAlreadySentError = exports.PendingRequestsOnReconnectingError = exports.MaxAttemptsReachedOnReconnectingError = exports.ConnectionCloseError = exports.ConnectionNotOpenError = exports.ConnectionTimeoutError = exports.InvalidConnectionError = exports.ConnectionError = void 0; +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class ConnectionError extends web3_error_base_js_1.BaseWeb3Error { + constructor(message, event) { + super(message); + this.code = error_codes_js_1.ERR_CONN; + if (event) { + this.errorCode = event.code; + this.errorReason = event.reason; + } + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { errorCode: this.errorCode, errorReason: this.errorReason }); + } +} +exports.ConnectionError = ConnectionError; +class InvalidConnectionError extends ConnectionError { + constructor(host, event) { + super(`CONNECTION ERROR: Couldn't connect to node ${host}.`, event); + this.host = host; + this.code = error_codes_js_1.ERR_CONN_INVALID; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { host: this.host }); + } +} +exports.InvalidConnectionError = InvalidConnectionError; +class ConnectionTimeoutError extends ConnectionError { + constructor(duration) { + super(`CONNECTION TIMEOUT: timeout of ${duration}ms achieved`); + this.duration = duration; + this.code = error_codes_js_1.ERR_CONN_TIMEOUT; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { duration: this.duration }); + } +} +exports.ConnectionTimeoutError = ConnectionTimeoutError; +class ConnectionNotOpenError extends ConnectionError { + constructor(event) { + super('Connection not open', event); + this.code = error_codes_js_1.ERR_CONN_NOT_OPEN; + } +} +exports.ConnectionNotOpenError = ConnectionNotOpenError; +class ConnectionCloseError extends ConnectionError { + constructor(event) { + var _a, _b; + super(`CONNECTION ERROR: The connection got closed with the close code ${(_a = event === null || event === void 0 ? void 0 : event.code) !== null && _a !== void 0 ? _a : ''} and the following reason string ${(_b = event === null || event === void 0 ? void 0 : event.reason) !== null && _b !== void 0 ? _b : ''}`, event); + this.code = error_codes_js_1.ERR_CONN_CLOSE; + } +} +exports.ConnectionCloseError = ConnectionCloseError; +class MaxAttemptsReachedOnReconnectingError extends ConnectionError { + constructor(numberOfAttempts) { + super(`Maximum number of reconnect attempts reached! (${numberOfAttempts})`); + this.code = error_codes_js_1.ERR_CONN_MAX_ATTEMPTS; + } +} +exports.MaxAttemptsReachedOnReconnectingError = MaxAttemptsReachedOnReconnectingError; +class PendingRequestsOnReconnectingError extends ConnectionError { + constructor() { + super('CONNECTION ERROR: Provider started to reconnect before the response got received!'); + this.code = error_codes_js_1.ERR_CONN_PENDING_REQUESTS; + } +} +exports.PendingRequestsOnReconnectingError = PendingRequestsOnReconnectingError; +class RequestAlreadySentError extends ConnectionError { + constructor(id) { + super(`Request already sent with following id: ${id}`); + this.code = error_codes_js_1.ERR_REQ_ALREADY_SENT; + } +} +exports.RequestAlreadySentError = RequestAlreadySentError; +//# sourceMappingURL=connection_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.js.map new file mode 100644 index 0000000..2b8721d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/connection_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_errors.js","sourceRoot":"","sources":["../../../src/errors/connection_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAKF,sDAS2B;AAC3B,8DAAsD;AAEtD,MAAa,eAAgB,SAAQ,kCAAa;IAKjD,YAAmB,OAAe,EAAE,KAAuB;QAC1D,KAAK,CAAC,OAAO,CAAC,CAAC;QALT,SAAI,GAAG,yBAAQ,CAAC;QAOtB,IAAI,KAAK,EAAE;YACV,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;YAC5B,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC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AAI,EAAE,EAAE,EACzD,KAAK,CACL,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,+BAAc,CAAC;IAC5B,CAAC;CACD;AAVD,oDAUC;AAED,MAAa,qCAAsC,SAAQ,eAAe;IACzE,YAAmB,gBAAwB;QAC1C,KAAK,CAAC,kDAAkD,gBAAgB,GAAG,CAAC,CAAC;QAC7E,IAAI,CAAC,IAAI,GAAG,sCAAqB,CAAC;IACnC,CAAC;CACD;AALD,sFAKC;AAED,MAAa,kCAAmC,SAAQ,eAAe;IACtE;QACC,KAAK,CAAC,mFAAmF,CAAC,CAAC;QAC3F,IAAI,CAAC,IAAI,GAAG,0CAAyB,CAAC;IACvC,CAAC;CACD;AALD,gFAKC;AAED,MAAa,uBAAwB,SAAQ,eAAe;IAC3D,YAAmB,EAAmB;QACrC,KAAK,CAAC,2CAA2C,EAAE,EAAE,CAAC,CAAC;QACvD,IAAI,CAAC,IAAI,GAAG,qCAAoB,CAAC;IAClC,CAAC;CACD;AALD,0DAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.d.ts new file mode 100644 index 0000000..1086b62 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.d.ts @@ -0,0 +1,120 @@ +import { JsonRpcError, TransactionReceipt, HexString } from 'web3-types'; +import { BaseWeb3Error, InvalidValueError } from '../web3_error_base.js'; +export declare class Web3ContractError extends BaseWeb3Error { + code: number; + receipt?: TransactionReceipt; + constructor(message: string, receipt?: TransactionReceipt); +} +export declare class ResolverMethodMissingError extends BaseWeb3Error { + address: string; + name: string; + code: number; + constructor(address: string, name: string); + toJSON(): { + address: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractMissingABIError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractOnceRequiresCallbackError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractEventDoesNotExistError extends BaseWeb3Error { + eventName: string; + code: number; + constructor(eventName: string); + toJSON(): { + eventName: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractReservedEventError extends BaseWeb3Error { + type: string; + code: number; + constructor(type: string); + toJSON(): { + type: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractMissingDeployDataError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractNoAddressDefinedError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractNoFromAddressDefinedError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractInstantiationError extends BaseWeb3Error { + code: number; +} +export declare type ProviderErrorData = HexString | { + data: HexString; +} | { + originalError: { + data: HexString; + }; +}; +/** + * This class is expected to be set as an `innerError` inside ContractExecutionError + * The properties would be typically decoded from the `data` if it was encoded according to EIP-838 + */ +export declare class Eip838ExecutionError extends Web3ContractError { + readonly name: string; + code: number; + data?: HexString; + errorName?: string; + errorSignature?: string; + errorArgs?: { + [K in string]: unknown; + }; + innerError: Eip838ExecutionError | undefined; + constructor(error: JsonRpcError | Eip838ExecutionError); + setDecodedProperties(errorName: string, errorSignature?: string, errorArgs?: { + [K in string]: unknown; + }): void; + toJSON(): { + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + data: string; + errorName?: string | undefined; + errorSignature?: string | undefined; + errorArgs?: { + [x: string]: unknown; + } | undefined; + }; +} +/** + * Used when an error is raised while executing a function inside a smart contract. + * The data is expected to be encoded according to EIP-848. + */ +export declare class ContractExecutionError extends Web3ContractError { + innerError: Eip838ExecutionError; + constructor(rpcError: JsonRpcError); +} +export declare class ContractTransactionDataAndInputError extends InvalidValueError { + code: number; + constructor(value: { + data: HexString | undefined; + input: HexString | undefined; + }); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.js new file mode 100644 index 0000000..bee71a7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.js @@ -0,0 +1,170 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractTransactionDataAndInputError = exports.ContractExecutionError = exports.Eip838ExecutionError = exports.ContractInstantiationError = exports.ContractNoFromAddressDefinedError = exports.ContractNoAddressDefinedError = exports.ContractMissingDeployDataError = exports.ContractReservedEventError = exports.ContractEventDoesNotExistError = exports.ContractOnceRequiresCallbackError = exports.ContractMissingABIError = exports.ResolverMethodMissingError = exports.Web3ContractError = void 0; +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class Web3ContractError extends web3_error_base_js_1.BaseWeb3Error { + constructor(message, receipt) { + super(message); + this.code = error_codes_js_1.ERR_CONTRACT; + this.receipt = receipt; + } +} +exports.Web3ContractError = Web3ContractError; +class ResolverMethodMissingError extends web3_error_base_js_1.BaseWeb3Error { + constructor(address, name) { + super(`The resolver at ${address} does not implement requested method: "${name}".`); + this.address = address; + this.name = name; + this.code = error_codes_js_1.ERR_CONTRACT_RESOLVER_MISSING; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { address: this.address, name: this.name }); + } +} +exports.ResolverMethodMissingError = ResolverMethodMissingError; +class ContractMissingABIError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('You must provide the json interface of the contract when instantiating a contract object.'); + this.code = error_codes_js_1.ERR_CONTRACT_ABI_MISSING; + } +} +exports.ContractMissingABIError = ContractMissingABIError; +class ContractOnceRequiresCallbackError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('Once requires a callback as the second parameter.'); + this.code = error_codes_js_1.ERR_CONTRACT_REQUIRED_CALLBACK; + } +} +exports.ContractOnceRequiresCallbackError = ContractOnceRequiresCallbackError; +class ContractEventDoesNotExistError extends web3_error_base_js_1.BaseWeb3Error { + constructor(eventName) { + super(`Event "${eventName}" doesn't exist in this contract.`); + this.eventName = eventName; + this.code = error_codes_js_1.ERR_CONTRACT_EVENT_NOT_EXISTS; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { eventName: this.eventName }); + } +} +exports.ContractEventDoesNotExistError = ContractEventDoesNotExistError; +class ContractReservedEventError extends web3_error_base_js_1.BaseWeb3Error { + constructor(type) { + super(`Event "${type}" doesn't exist in this contract.`); + this.type = type; + this.code = error_codes_js_1.ERR_CONTRACT_RESERVED_EVENT; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { type: this.type }); + } +} +exports.ContractReservedEventError = ContractReservedEventError; +class ContractMissingDeployDataError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(`No "data" specified in neither the given options, nor the default options.`); + this.code = error_codes_js_1.ERR_CONTRACT_MISSING_DEPLOY_DATA; + } +} +exports.ContractMissingDeployDataError = ContractMissingDeployDataError; +class ContractNoAddressDefinedError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super("This contract object doesn't have address set yet, please set an address first."); + this.code = error_codes_js_1.ERR_CONTRACT_MISSING_ADDRESS; + } +} +exports.ContractNoAddressDefinedError = ContractNoAddressDefinedError; +class ContractNoFromAddressDefinedError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('No "from" address specified in neither the given options, nor the default options.'); + this.code = error_codes_js_1.ERR_CONTRACT_MISSING_FROM_ADDRESS; + } +} +exports.ContractNoFromAddressDefinedError = ContractNoFromAddressDefinedError; +class ContractInstantiationError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_CONTRACT_INSTANTIATION; + } +} +exports.ContractInstantiationError = ContractInstantiationError; +/** + * This class is expected to be set as an `innerError` inside ContractExecutionError + * The properties would be typically decoded from the `data` if it was encoded according to EIP-838 + */ +class Eip838ExecutionError extends Web3ContractError { + constructor(error) { + super(error.message || 'Error'); + this.name = ('name' in error && error.name) || this.constructor.name; + this.stack = ('stack' in error && error.stack) || undefined; + this.code = error.code; + // get embedded error details got from some providers like MetaMask + // and set this.data from the inner error data for easier read. + // note: the data is a hex string inside either: + // error.data, error.data.data or error.data.originalError.data (https://github.com/web3/web3.js/issues/4454#issuecomment-1485953455) + if (typeof error.data === 'object') { + let originalError; + if ('originalError' in error.data) { + originalError = error.data.originalError; + } + else { + // Ganache has no `originalError` sub-object unlike others + originalError = error.data; + } + this.data = originalError.data; + this.innerError = new Eip838ExecutionError(originalError); + } + else { + this.data = error.data; + } + } + setDecodedProperties(errorName, errorSignature, errorArgs) { + this.errorName = errorName; + this.errorSignature = errorSignature; + this.errorArgs = errorArgs; + } + toJSON() { + let json = Object.assign(Object.assign({}, super.toJSON()), { data: this.data }); + if (this.errorName) { + json = Object.assign(Object.assign({}, json), { errorName: this.errorName, errorSignature: this.errorSignature, errorArgs: this.errorArgs }); + } + return json; + } +} +exports.Eip838ExecutionError = Eip838ExecutionError; +/** + * Used when an error is raised while executing a function inside a smart contract. + * The data is expected to be encoded according to EIP-848. + */ +class ContractExecutionError extends Web3ContractError { + constructor(rpcError) { + super('Error happened while trying to execute a function inside a smart contract'); + this.code = error_codes_js_1.ERR_CONTRACT_EXECUTION_REVERTED; + this.innerError = new Eip838ExecutionError(rpcError); + } +} +exports.ContractExecutionError = ContractExecutionError; +class ContractTransactionDataAndInputError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`data: ${(_a = value.data) !== null && _a !== void 0 ? _a : 'undefined'}, input: ${(_b = value.input) !== null && _b !== void 0 ? _b : 'undefined'}`, 'You can\'t have "data" and "input" as properties of a contract at the same time, please use either "data" or "input" instead.'); + this.code = error_codes_js_1.ERR_CONTRACT_TX_DATA_AND_INPUT; + } +} +exports.ContractTransactionDataAndInputError = ContractTransactionDataAndInputError; +//# sourceMappingURL=contract_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.js.map new file mode 100644 index 0000000..4107bb5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/contract_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract_errors.js","sourceRoot":"","sources":["../../../src/errors/contract_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAKF,sDAa2B;AAC3B,8DAAyE;AAEzE,MAAa,iBAAkB,SAAQ,kCAAa;IAInD,YAAmB,OAAe,EAAE,OAA4B;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QAJT,SAAI,GAAG,6BAAY,CAAC;QAM1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;CACD;AATD,8CASC;AACD,MAAa,0BAA2B,SAAQ,kCAAa;IAG5D,YAA0B,OAAe,EAAS,IAAY;QAC7D,KAAK,CAAC,mBAAmB,OAAO,0CAA0C,IAAI,IAAI,CAAC,CAAC;QAD3D,YAAO,GAAP,OAAO,CAAQ;QAAS,SAAI,GAAJ,IAAI,CAAQ;QAFvD,SAAI,GAAG,8CAA6B,CAAC;IAI5C,CAAC;IAEM,MAAM;QACZ,uCAAY,KAAK,CAAC,MAAM,EAAE,KAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,IAAG;IACtE,CAAC;CACD;AAVD,gEAUC;AAED,MAAa,uBAAwB,SAAQ,kCAAa;IAGzD;QACC,KAAK,CACJ,2FAA2F,CAC3F,CAAC;QALI,SAAI,GAAG,yCAA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,CAAC;IAEM,MAAM;QACZ,IAAI,IAAI,GAAG,gCACP,KAAK,CAAC,MAAM,EAAE,KACjB,IAAI,EAAE,IAAI,CAAC,IAAI,GAUf,CAAC;QAEF,IAAI,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,mCACA,IAAI,KACP,SAAS,EAAE,IAAI,CAAC,SAAS,EACzB,cAAc,EAAE,IAAI,CAAC,cAAc,EACnC,SAAS,EAAE,IAAI,CAAC,SAAS,GACzB,CAAC;SACF;QACD,OAAO,IAAI,CAAC;IACb,CAAC;CACD;AA1ED,oDA0EC;AAED;;;GAGG;AACH,MAAa,sBAAuB,SAAQ,iBAAiB;IAG5D,YAAmB,QAAsB;QACxC,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACnF,IAAI,CAAC,IAAI,GAAG,gDAA+B,CAAC;QAC5C,IAAI,CAAC,UAAU,GAAG,IAAI,oBAAoB,CAAC,QAA2C,CAAC,CAAC;IACzF,CAAC;CACD;AARD,wDAQC;AAED,MAAa,oCAAqC,SAAQ,sCAAiB;IAG1E,YAAmB,KAAoE;;QACtF,KAAK,CACJ,SAAS,MAAA,KAAK,CAAC,IAAI,mCAAI,WAAW,YAAY,MAAA,KAAK,CAAC,KAAK,mCAAI,WAAW,EAAE,EAC1E,+HAA+H,CAC/H,CAAC;QANI,SAAI,GAAG,+CAA8B,CAAC;IAO7C,CAAC;CACD;AATD,oFASC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.d.ts new file mode 100644 index 0000000..1c636dc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.d.ts @@ -0,0 +1,9 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ConfigHardforkMismatchError extends BaseWeb3Error { + code: number; + constructor(defaultHardfork: string, commonHardFork: string); +} +export declare class ConfigChainMismatchError extends BaseWeb3Error { + code: number; + constructor(defaultHardfork: string, commonHardFork: string); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.js new file mode 100644 index 0000000..c13c8be --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.js @@ -0,0 +1,37 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConfigChainMismatchError = exports.ConfigHardforkMismatchError = void 0; +/* eslint-disable max-classes-per-file */ +const web3_error_base_js_1 = require("../web3_error_base.js"); +const error_codes_js_1 = require("../error_codes.js"); +class ConfigHardforkMismatchError extends web3_error_base_js_1.BaseWeb3Error { + constructor(defaultHardfork, commonHardFork) { + super(`Web3Config hardfork doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`); + this.code = error_codes_js_1.ERR_CORE_HARDFORK_MISMATCH; + } +} +exports.ConfigHardforkMismatchError = ConfigHardforkMismatchError; +class ConfigChainMismatchError extends web3_error_base_js_1.BaseWeb3Error { + constructor(defaultHardfork, commonHardFork) { + super(`Web3Config chain doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`); + this.code = error_codes_js_1.ERR_CORE_HARDFORK_MISMATCH; + } +} +exports.ConfigChainMismatchError = ConfigChainMismatchError; +//# sourceMappingURL=core_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.js.map new file mode 100644 index 0000000..c7786ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/core_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core_errors.js","sourceRoot":"","sources":["../../../src/errors/core_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAyC;AAEzC,8DAAsD;AACtD,sDAA+D;AAE/D,MAAa,2BAA4B,SAAQ,kCAAa;IAG7D,YAAmB,eAAuB,EAAE,cAAsB;QACjE,KAAK,CACJ,uDAAuD,eAAe,wBAAwB,cAAc,EAAE,CAC9G,CAAC;QALI,SAAI,GAAG,2CAA0B,CAAC;IAMzC,CAAC;CACD;AARD,kEAQC;AAED,MAAa,wBAAyB,SAAQ,kCAAa;IAG1D,YAAmB,eAAuB,EAAE,cAAsB;QACjE,KAAK,CACJ,oDAAoD,eAAe,wBAAwB,cAAc,EAAE,CAC3G,CAAC;QALI,SAAI,GAAG,2CAA0B,CAAC;IAMzC,CAAC;CACD;AARD,4DAQC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.d.ts new file mode 100644 index 0000000..8035147 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.d.ts @@ -0,0 +1,13 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ENSCheckInterfaceSupportError extends BaseWeb3Error { + code: number; + constructor(errorDetails: string); +} +export declare class ENSUnsupportedNetworkError extends BaseWeb3Error { + code: number; + constructor(networkType: string); +} +export declare class ENSNetworkNotSyncedError extends BaseWeb3Error { + code: number; + constructor(); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.js new file mode 100644 index 0000000..46c96cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.js @@ -0,0 +1,44 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ENSNetworkNotSyncedError = exports.ENSUnsupportedNetworkError = exports.ENSCheckInterfaceSupportError = void 0; +/* eslint-disable max-classes-per-file */ +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class ENSCheckInterfaceSupportError extends web3_error_base_js_1.BaseWeb3Error { + constructor(errorDetails) { + super(`ENS resolver check interface support error. "${errorDetails}"`); + this.code = error_codes_js_1.ERR_ENS_CHECK_INTERFACE_SUPPORT; + } +} +exports.ENSCheckInterfaceSupportError = ENSCheckInterfaceSupportError; +class ENSUnsupportedNetworkError extends web3_error_base_js_1.BaseWeb3Error { + constructor(networkType) { + super(`ENS is not supported on network ${networkType}`); + this.code = error_codes_js_1.ERR_ENS_UNSUPPORTED_NETWORK; + } +} +exports.ENSUnsupportedNetworkError = ENSUnsupportedNetworkError; +class ENSNetworkNotSyncedError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(`Network not synced`); + this.code = error_codes_js_1.ERR_ENS_NETWORK_NOT_SYNCED; + } +} +exports.ENSNetworkNotSyncedError = ENSNetworkNotSyncedError; +//# sourceMappingURL=ens_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.js.map new file mode 100644 index 0000000..b487be3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/ens_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ens_errors.js","sourceRoot":"","sources":["../../../src/errors/ens_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAyC;AAEzC,sDAI2B;AAC3B,8DAAsD;AAEtD,MAAa,6BAA8B,SAAQ,kCAAa;IAE/D,YAAmB,YAAoB;QACtC,KAAK,CAAC,gDAAgD,YAAY,GAAG,CAAC,CAAC;QAFjE,SAAI,GAAG,gDAA+B,CAAC;IAG9C,CAAC;CACD;AALD,sEAKC;AAED,MAAa,0BAA2B,SAAQ,kCAAa;IAE5D,YAAmB,WAAmB;QACrC,KAAK,CAAC,mCAAmC,WAAW,EAAE,CAAC,CAAC;QAFlD,SAAI,GAAG,4CAA2B,CAAC;IAG1C,CAAC;CACD;AALD,gEAKC;AAED,MAAa,wBAAyB,SAAQ,kCAAa;IAE1D;QACC,KAAK,CAAC,oBAAoB,CAAC,CAAC;QAFtB,SAAI,GAAG,2CAA0B,CAAC;IAGzC,CAAC;CACD;AALD,4DAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.d.ts new file mode 100644 index 0000000..6026c4d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.d.ts @@ -0,0 +1,55 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class InvalidNumberOfParamsError extends BaseWeb3Error { + got: number; + expected: number; + method: string; + code: number; + constructor(got: number, expected: number, method: string); + toJSON(): { + got: number; + expected: number; + method: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class InvalidMethodParamsError extends BaseWeb3Error { + hint?: string | undefined; + code: number; + constructor(hint?: string | undefined); + toJSON(): { + hint: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class FormatterError extends BaseWeb3Error { + code: number; +} +export declare class MethodNotImplementedError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class OperationTimeoutError extends BaseWeb3Error { + code: number; +} +export declare class OperationAbortError extends BaseWeb3Error { + code: number; +} +export declare class AbiError extends BaseWeb3Error { + code: number; + readonly props: Record & { + name?: string; + }; + constructor(message: string, props?: Record & { + name?: string; + }); +} +export declare class ExistingPluginNamespaceError extends BaseWeb3Error { + code: number; + constructor(pluginNamespace: string); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.js new file mode 100644 index 0000000..7a4f65b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.js @@ -0,0 +1,90 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExistingPluginNamespaceError = exports.AbiError = exports.OperationAbortError = exports.OperationTimeoutError = exports.MethodNotImplementedError = exports.FormatterError = exports.InvalidMethodParamsError = exports.InvalidNumberOfParamsError = void 0; +/* eslint-disable max-classes-per-file */ +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class InvalidNumberOfParamsError extends web3_error_base_js_1.BaseWeb3Error { + constructor(got, expected, method) { + super(`Invalid number of parameters for "${method}". Got "${got}" expected "${expected}"!`); + this.got = got; + this.expected = expected; + this.method = method; + this.code = error_codes_js_1.ERR_PARAM; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { got: this.got, expected: this.expected, method: this.method }); + } +} +exports.InvalidNumberOfParamsError = InvalidNumberOfParamsError; +class InvalidMethodParamsError extends web3_error_base_js_1.BaseWeb3Error { + constructor(hint) { + super(`Invalid parameters passed. "${typeof hint !== 'undefined' ? hint : ''}"`); + this.hint = hint; + this.code = error_codes_js_1.ERR_INVALID_METHOD_PARAMS; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { hint: this.hint }); + } +} +exports.InvalidMethodParamsError = InvalidMethodParamsError; +class FormatterError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_FORMATTERS; + } +} +exports.FormatterError = FormatterError; +class MethodNotImplementedError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super("The method you're trying to call is not implemented."); + this.code = error_codes_js_1.ERR_METHOD_NOT_IMPLEMENTED; + } +} +exports.MethodNotImplementedError = MethodNotImplementedError; +class OperationTimeoutError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_OPERATION_TIMEOUT; + } +} +exports.OperationTimeoutError = OperationTimeoutError; +class OperationAbortError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_OPERATION_ABORT; + } +} +exports.OperationAbortError = OperationAbortError; +class AbiError extends web3_error_base_js_1.BaseWeb3Error { + constructor(message, props) { + super(message); + this.code = error_codes_js_1.ERR_ABI_ENCODING; + this.props = props !== null && props !== void 0 ? props : {}; + } +} +exports.AbiError = AbiError; +class ExistingPluginNamespaceError extends web3_error_base_js_1.BaseWeb3Error { + constructor(pluginNamespace) { + super(`A plugin with the namespace: ${pluginNamespace} has already been registered.`); + this.code = error_codes_js_1.ERR_EXISTING_PLUGIN_NAMESPACE; + } +} +exports.ExistingPluginNamespaceError = ExistingPluginNamespaceError; +//# sourceMappingURL=generic_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.js.map new file mode 100644 index 0000000..63470df --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/generic_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"generic_errors.js","sourceRoot":"","sources":["../../../src/errors/generic_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAyC;AAEzC,sDAS2B;AAC3B,8DAAsD;AAEtD,MAAa,0BAA2B,SAAQ,kCAAa;IAG5D,YAA0B,GAAW,EAAS,QAAgB,EAAS,MAAc;QACpF,KAAK,CAAC,qCAAqC,MAAM,WAAW,GAAG,eAAe,QAAQ,IAAI,CAAC,CAAC;QADnE,QAAG,GAAH,GAAG,CAAQ;QAAS,aAAQ,GAAR,QAAQ,CAAQ;QAAS,WAAM,GAAN,MAAM,CAAQ;QAF9E,SAAI,GAAG,0BAAS,CAAC;IAIxB,CAAC;IAEM,MAAM;QACZ,uCACI,KAAK,CAAC,MAAM,EAAE,KACjB,GAAG,EAAE,IAAI,CAAC,GAAG,EACb,QAAQ,EAAE,IAAI,CAAC,QAAQ,EACvB,MAAM,EAAE,IAAI,CAAC,MAAM,IAClB;IACH,CAAC;CACD;AAfD,gEAeC;AAED,MAAa,wBAAyB,SAAQ,kCAAa;IAG1D,YAA0B,IAAa;QACtC,KAAK,CAAC,+BAA+B,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QADxD,SAAI,GAAJ,IAAI,CAAS;QAFhC,SAAI,GAAG,0CAAyB,CAAC;IAIxC,CAAC;IAEM,MAAM;QACZ,uCACI,KAAK,CAAC,MAAM,EAAE,KACjB,IAAI,EAAE,IAAI,CAAC,IAAI,IACd;IACH,CAAC;CACD;AAbD,4DAaC;AAED,MAAa,cAAe,SAAQ,kCAAa;IAAjD;;QACQ,SAAI,GAAG,+BAAc,CAAC;IAC9B,CAAC;CAAA;AAFD,wCAEC;AAED,MAAa,yBAA0B,SAAQ,kCAAa;IAG3D;QACC,KAAK,CAAC,sDAAsD,CAAC,CAAC;QAHxD,SAAI,GAAG,2CAA0B,CAAC;IAIzC,CAAC;CACD;AAND,8DAMC;AAED,MAAa,qBAAsB,SAAQ,kCAAa;IAAxD;;QACQ,SAAI,GAAG,sCAAqB,CAAC;IACrC,CAAC;CAAA;AAFD,sDAEC;AAED,MAAa,mBAAoB,SAAQ,kCAAa;IAAtD;;QACQ,SAAI,GAAG,oCAAmB,CAAC;IACnC,CAAC;CAAA;AAFD,kDAEC;AAED,MAAa,QAAS,SAAQ,kCAAa;IAI1C,YAAmB,OAAe,EAAE,KAAmD;QACtF,KAAK,CAAC,OAAO,CAAC,CAAC;QAJT,SAAI,GAAG,iCAAgB,CAAC;QAK9B,IAAI,CAAC,KAAK,GAAG,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,EAAE,CAAC;IAC1B,CAAC;CACD;AARD,4BAQC;AAED,MAAa,4BAA6B,SAAQ,kCAAa;IAG9D,YAAmB,eAAuB;QACzC,KAAK,CAAC,gCAAgC,eAAe,+BAA+B,CAAC,CAAC;QAHhF,SAAI,GAAG,8CAA6B,CAAC;IAI5C,CAAC;CACD;AAND,oEAMC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.d.ts new file mode 100644 index 0000000..64713ce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.d.ts @@ -0,0 +1,19 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ProviderError extends BaseWeb3Error { + code: number; +} +export declare class InvalidProviderError extends BaseWeb3Error { + clientUrl: string; + code: number; + constructor(clientUrl: string); +} +export declare class InvalidClientError extends BaseWeb3Error { + code: number; + constructor(clientUrl: string); +} +export declare class SubscriptionError extends BaseWeb3Error { + code: number; +} +export declare class Web3WSProviderError extends BaseWeb3Error { + code: number; +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.js new file mode 100644 index 0000000..f76b2a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.js @@ -0,0 +1,59 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3WSProviderError = exports.SubscriptionError = exports.InvalidClientError = exports.InvalidProviderError = exports.ProviderError = void 0; +/* eslint-disable max-classes-per-file */ +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class ProviderError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_PROVIDER; + } +} +exports.ProviderError = ProviderError; +class InvalidProviderError extends web3_error_base_js_1.BaseWeb3Error { + constructor(clientUrl) { + super(`Provider with url "${clientUrl}" is not set or invalid`); + this.clientUrl = clientUrl; + this.code = error_codes_js_1.ERR_INVALID_PROVIDER; + } +} +exports.InvalidProviderError = InvalidProviderError; +class InvalidClientError extends web3_error_base_js_1.BaseWeb3Error { + constructor(clientUrl) { + super(`Client URL "${clientUrl}" is invalid.`); + this.code = error_codes_js_1.ERR_INVALID_CLIENT; + } +} +exports.InvalidClientError = InvalidClientError; +class SubscriptionError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_SUBSCRIPTION; + } +} +exports.SubscriptionError = SubscriptionError; +class Web3WSProviderError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_WS_PROVIDER; // this had duplicate code with generic provider + } +} +exports.Web3WSProviderError = Web3WSProviderError; +//# sourceMappingURL=provider_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.js.map new file mode 100644 index 0000000..168d7e1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/provider_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider_errors.js","sourceRoot":"","sources":["../../../src/errors/provider_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAyC;AAEzC,sDAM2B;AAC3B,8DAAsD;AAEtD,MAAa,aAAc,SAAQ,kCAAa;IAAhD;;QACQ,SAAI,GAAG,6BAAY,CAAC;IAC5B,CAAC;CAAA;AAFD,sCAEC;AAED,MAAa,oBAAqB,SAAQ,kCAAa;IAGtD,YAA0B,SAAiB;QAC1C,KAAK,CAAC,sBAAsB,SAAS,yBAAyB,CAAC,CAAC;QADvC,cAAS,GAAT,SAAS,CAAQ;QAFpC,SAAI,GAAG,qCAAoB,CAAC;IAInC,CAAC;CACD;AAND,oDAMC;AAED,MAAa,kBAAmB,SAAQ,kCAAa;IAGpD,YAAmB,SAAiB;QACnC,KAAK,CAAC,eAAe,SAAS,eAAe,CAAC,CAAC;QAHzC,SAAI,GAAG,mCAAkB,CAAC;IAIjC,CAAC;CACD;AAND,gDAMC;AAED,MAAa,iBAAkB,SAAQ,kCAAa;IAApD;;QACQ,SAAI,GAAG,iCAAgB,CAAC;IAChC,CAAC;CAAA;AAFD,8CAEC;AAED,MAAa,mBAAoB,SAAQ,kCAAa;IAAtD;;QACQ,SAAI,GAAG,gCAAe,CAAC,CAAC,gDAAgD;IAChF,CAAC;CAAA;AAFD,kDAEC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.d.ts new file mode 100644 index 0000000..ca5f30d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.d.ts @@ -0,0 +1,19 @@ +import { JsonRpcPayload, JsonRpcResponse } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ResponseError extends BaseWeb3Error { + code: number; + data?: ErrorType | ErrorType[]; + request?: JsonRpcPayload; + constructor(response: JsonRpcResponse, message?: string, request?: JsonRpcPayload); + toJSON(): { + data: ErrorType | ErrorType[] | undefined; + request: JsonRpcPayload | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class InvalidResponseError extends ResponseError { + constructor(result: JsonRpcResponse, request?: JsonRpcPayload); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.js new file mode 100644 index 0000000..f94200a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.js @@ -0,0 +1,74 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidResponseError = exports.ResponseError = void 0; +const web3_error_base_js_1 = require("../web3_error_base.js"); +const error_codes_js_1 = require("../error_codes.js"); +// To avoid circular package dependency, copied to code here. If you update this please update same function in `json_rpc.ts` +const isResponseWithError = (response) => !Array.isArray(response) && + response.jsonrpc === '2.0' && + !!response && + // eslint-disable-next-line no-null/no-null + (response.result === undefined || response.result === null) && + // JSON RPC consider "null" as valid response + 'error' in response && + (typeof response.id === 'number' || typeof response.id === 'string'); +const buildErrorMessage = (response) => isResponseWithError(response) ? response.error.message : ''; +class ResponseError extends web3_error_base_js_1.BaseWeb3Error { + constructor(response, message, request) { + var _a; + super(message !== null && message !== void 0 ? message : `Returned error: ${Array.isArray(response) + ? response.map(r => buildErrorMessage(r)).join(',') + : buildErrorMessage(response)}`); + this.code = error_codes_js_1.ERR_RESPONSE; + if (!message) { + this.data = Array.isArray(response) + ? response.map(r => { var _a; return (_a = r.error) === null || _a === void 0 ? void 0 : _a.data; }) + : (_a = response === null || response === void 0 ? void 0 : response.error) === null || _a === void 0 ? void 0 : _a.data; + } + this.request = request; + let errorOrErrors; + if (`error` in response) { + errorOrErrors = response.error; + } + else if (response instanceof Array) { + errorOrErrors = response.map(r => r.error); + } + this.innerError = errorOrErrors; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { data: this.data, request: this.request }); + } +} +exports.ResponseError = ResponseError; +class InvalidResponseError extends ResponseError { + constructor(result, request) { + super(result, undefined, request); + this.code = error_codes_js_1.ERR_INVALID_RESPONSE; + let errorOrErrors; + if (`error` in result) { + errorOrErrors = result.error; + } + else if (result instanceof Array) { + errorOrErrors = result.map(r => r.error); + } + this.innerError = errorOrErrors; + } +} +exports.InvalidResponseError = InvalidResponseError; +//# sourceMappingURL=response_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.js.map new file mode 100644 index 0000000..692affb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/response_errors.js.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,CAAC;CACD;AAnBD,oDAmBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.d.ts new file mode 100644 index 0000000..7c1e488 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.d.ts @@ -0,0 +1,13 @@ +/** + * A template string for a generic Rpc Error. The `*code*` will be replaced with the code number. + * Note: consider in next version that a spelling mistake could be corrected for `occured` and the value could be: + * `An Rpc error has occurred with a code of *code*` + */ +export declare const genericRpcErrorMessageTemplate = "An Rpc error has occured with a code of *code*"; +export declare const RpcErrorMessages: { + [key: number | string]: { + name?: string; + message: string; + description?: string; + }; +}; diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.js new file mode 100644 index 0000000..14669c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.js @@ -0,0 +1,184 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RpcErrorMessages = exports.genericRpcErrorMessageTemplate = void 0; +const error_codes_js_1 = require("../error_codes.js"); +/** + * A template string for a generic Rpc Error. The `*code*` will be replaced with the code number. + * Note: consider in next version that a spelling mistake could be corrected for `occured` and the value could be: + * `An Rpc error has occurred with a code of *code*` + */ +exports.genericRpcErrorMessageTemplate = 'An Rpc error has occured with a code of *code*'; +/* eslint-disable @typescript-eslint/naming-convention */ +exports.RpcErrorMessages = { + // EIP-1474 & JSON RPC 2.0 + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md + [error_codes_js_1.ERR_RPC_INVALID_JSON]: { + message: 'Parse error', + description: 'Invalid JSON', + }, + [error_codes_js_1.ERR_RPC_INVALID_REQUEST]: { + message: 'Invalid request', + description: 'JSON is not a valid request object ', + }, + [error_codes_js_1.ERR_RPC_INVALID_METHOD]: { + message: 'Method not found', + description: 'Method does not exist ', + }, + [error_codes_js_1.ERR_RPC_INVALID_PARAMS]: { + message: 'Invalid params', + description: 'Invalid method parameters', + }, + [error_codes_js_1.ERR_RPC_INTERNAL_ERROR]: { + message: 'Internal error', + description: 'Internal JSON-RPC error', + }, + [error_codes_js_1.ERR_RPC_INVALID_INPUT]: { + message: 'Invalid input', + description: 'Missing or invalid parameters', + }, + [error_codes_js_1.ERR_RPC_MISSING_RESOURCE]: { + message: 'Resource not found', + description: 'Requested resource not found', + }, + [error_codes_js_1.ERR_RPC_UNAVAILABLE_RESOURCE]: { + message: 'Resource unavailable', + description: 'Requested resource not available', + }, + [error_codes_js_1.ERR_RPC_TRANSACTION_REJECTED]: { + message: 'Transaction rejected', + description: 'Transaction creation failed', + }, + [error_codes_js_1.ERR_RPC_UNSUPPORTED_METHOD]: { + message: 'Method not supported', + description: 'Method is not implemented', + }, + [error_codes_js_1.ERR_RPC_LIMIT_EXCEEDED]: { + message: 'Limit exceeded', + description: 'Request exceeds defined limit', + }, + [error_codes_js_1.ERR_RPC_NOT_SUPPORTED]: { + message: 'JSON-RPC version not supported', + description: 'Version of JSON-RPC protocol is not supported', + }, + // EIP-1193 + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors + [error_codes_js_1.JSONRPC_ERR_REJECTED_REQUEST]: { + name: 'User Rejected Request', + message: 'The user rejected the request.', + }, + [error_codes_js_1.JSONRPC_ERR_UNAUTHORIZED]: { + name: 'Unauthorized', + message: 'The requested method and/or account has not been authorized by the user.', + }, + [error_codes_js_1.JSONRPC_ERR_UNSUPPORTED_METHOD]: { + name: 'Unsupported Method', + message: 'The Provider does not support the requested method.', + }, + [error_codes_js_1.JSONRPC_ERR_DISCONNECTED]: { + name: 'Disconnected', + message: 'The Provider is disconnected from all chains.', + }, + [error_codes_js_1.JSONRPC_ERR_CHAIN_DISCONNECTED]: { + name: 'Chain Disconnected', + message: 'The Provider is not connected to the requested chain.', + }, + // EIP-1193 - CloseEvent + // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code + '0-999': { + name: '', + message: 'Not used.', + }, + 1000: { + name: 'Normal Closure', + message: 'The connection successfully completed the purpose for which it was created.', + }, + 1001: { + name: 'Going Away', + message: 'The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection.', + }, + 1002: { + name: 'Protocol error', + message: 'The endpoint is terminating the connection due to a protocol error.', + }, + 1003: { + name: 'Unsupported Data', + message: 'The connection is being terminated because the endpoint received data of a type it cannot accept. (For example, a text-only endpoint received binary data.)', + }, + 1004: { + name: 'Reserved', + message: 'Reserved. A meaning might be defined in the future.', + }, + 1005: { + name: 'No Status Rcvd', + message: 'Reserved. Indicates that no status code was provided even though one was expected.', + }, + 1006: { + name: 'Abnormal Closure', + message: 'Reserved. Indicates that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected.', + }, + 1007: { + name: 'Invalid frame payload data', + message: 'The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).', + }, + 1008: { + name: 'Policy Violation', + message: 'The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.', + }, + 1009: { + name: 'Message Too Big', + message: 'The endpoint is terminating the connection because a data frame was received that is too large.', + }, + 1010: { + name: 'Mandatory Ext.', + message: "The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't.", + }, + 1011: { + name: 'Internal Error', + message: 'The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.', + }, + 1012: { + name: 'Service Restart', + message: 'The server is terminating the connection because it is restarting.', + }, + 1013: { + name: 'Try Again Later', + message: 'The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients.', + }, + 1014: { + name: 'Bad Gateway', + message: 'The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code.', + }, + 1015: { + name: 'TLS handshake', + message: "Reserved. Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).", + }, + '1016-2999': { + name: '', + message: 'For definition by future revisions of the WebSocket Protocol specification, and for definition by extension specifications.', + }, + '3000-3999': { + name: '', + message: 'For use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by the WebSocket protocol.', + }, + '4000-4999': { + name: '', + message: "For private use, and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by the WebSocket protocol.", + }, +}; +//# sourceMappingURL=rpc_error_messages.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.js.map new file mode 100644 index 0000000..8603289 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_error_messages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_error_messages.js","sourceRoot":"","sources":["../../../src/errors/rpc_error_messages.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,sDAkB2B;AAE3B;;;;GAIG;AACU,QAAA,8BAA8B,GAAG,gDAAgD,CAAC;AAE/F,yDAAyD;AAC5C,QAAA,gBAAgB,GAEzB;IACH,2BAA2B;IAC3B,gEAAgE;IAChE,CAAC,qCAAoB,CAAC,EAAE;QACvB,OAAO,EAAE,aAAa;QACtB,WAAW,EAAE,cAAc;KAC3B;IACD,CAAC,wCAAuB,CAAC,EAAE;QAC1B,OAAO,E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BAAiB;QACvB,OAAO,EAAE,oEAAoE;KAC7E;IACD,IAAI,EAAE;QACL,IAAI,EAAE,iBAAiB;QACvB,OAAO,EACN,sIAAsI;KACvI;IACD,IAAI,EAAE;QACL,IAAI,EAAE,aAAa;QACnB,OAAO,EACN,iJAAiJ;KAClJ;IACD,IAAI,EAAE;QACL,IAAI,EAAE,eAAe;QACrB,OAAO,EACN,kJAAkJ;KACnJ;IACD,WAAW,EAAE;QACZ,IAAI,EAAE,EAAE;QACR,OAAO,EACN,6HAA6H;KAC9H;IACD,WAAW,EAAE;QACZ,IAAI,EAAE,EAAE;QACR,OAAO,EACN,qLAAqL;KACtL;IACD,WAAW,EAAE;QACZ,IAAI,EAAE,EAAE;QACR,OAAO,EACN,qMAAqM;KACtM;CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.d.ts new file mode 100644 index 0000000..babdb03 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.d.ts @@ -0,0 +1,74 @@ +import { JsonRpcResponseWithError, JsonRpcId, JsonRpcError } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class RpcError extends BaseWeb3Error { + code: number; + id: JsonRpcId; + jsonrpc: string; + jsonRpcError: JsonRpcError; + constructor(rpcError: JsonRpcResponseWithError, message?: string); + toJSON(): { + error: JsonRpcError; + id: JsonRpcId; + jsonRpc: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class EIP1193ProviderRpcError extends BaseWeb3Error { + code: number; + data?: unknown; + constructor(code: number, data?: unknown); +} +export declare class ParseError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InvalidRequestError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class MethodNotFoundError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InvalidParamsError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InternalError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InvalidInputError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class MethodNotSupported extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class ResourceUnavailableError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class ResourcesNotFoundError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class VersionNotSupportedError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class TransactionRejectedError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class LimitExceededError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare const rpcErrorsMap: Map; diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.js new file mode 100644 index 0000000..1fa5654 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.js @@ -0,0 +1,169 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rpcErrorsMap = exports.LimitExceededError = exports.TransactionRejectedError = exports.VersionNotSupportedError = exports.ResourcesNotFoundError = exports.ResourceUnavailableError = exports.MethodNotSupported = exports.InvalidInputError = exports.InternalError = exports.InvalidParamsError = exports.MethodNotFoundError = exports.InvalidRequestError = exports.ParseError = exports.EIP1193ProviderRpcError = exports.RpcError = void 0; +const web3_error_base_js_1 = require("../web3_error_base.js"); +const error_codes_js_1 = require("../error_codes.js"); +const rpc_error_messages_js_1 = require("./rpc_error_messages.js"); +class RpcError extends web3_error_base_js_1.BaseWeb3Error { + constructor(rpcError, message) { + super(message !== null && message !== void 0 ? message : rpc_error_messages_js_1.genericRpcErrorMessageTemplate.replace('*code*', rpcError.error.code.toString())); + this.code = rpcError.error.code; + this.id = rpcError.id; + this.jsonrpc = rpcError.jsonrpc; + this.jsonRpcError = rpcError.error; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { error: this.jsonRpcError, id: this.id, jsonRpc: this.jsonrpc }); + } +} +exports.RpcError = RpcError; +class EIP1193ProviderRpcError extends web3_error_base_js_1.BaseWeb3Error { + constructor(code, data) { + var _a, _b, _c, _d; + if (!code) { + // this case should ideally not happen + super(); + } + else if ((_a = rpc_error_messages_js_1.RpcErrorMessages[code]) === null || _a === void 0 ? void 0 : _a.message) { + super(rpc_error_messages_js_1.RpcErrorMessages[code].message); + } + else { + // Retrieve the status code object for the given code from the table, by searching through the appropriate range + const statusCodeRange = Object.keys(rpc_error_messages_js_1.RpcErrorMessages).find(statusCode => typeof statusCode === 'string' && + code >= parseInt(statusCode.split('-')[0], 10) && + code <= parseInt(statusCode.split('-')[1], 10)); + super((_c = (_b = rpc_error_messages_js_1.RpcErrorMessages[statusCodeRange !== null && statusCodeRange !== void 0 ? statusCodeRange : '']) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : rpc_error_messages_js_1.genericRpcErrorMessageTemplate.replace('*code*', (_d = code === null || code === void 0 ? void 0 : code.toString()) !== null && _d !== void 0 ? _d : '""')); + } + this.code = code; + this.data = data; + } +} +exports.EIP1193ProviderRpcError = EIP1193ProviderRpcError; +class ParseError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_INVALID_JSON].message); + this.code = error_codes_js_1.ERR_RPC_INVALID_JSON; + } +} +exports.ParseError = ParseError; +class InvalidRequestError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_INVALID_REQUEST].message); + this.code = error_codes_js_1.ERR_RPC_INVALID_REQUEST; + } +} +exports.InvalidRequestError = InvalidRequestError; +class MethodNotFoundError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_INVALID_METHOD].message); + this.code = error_codes_js_1.ERR_RPC_INVALID_METHOD; + } +} +exports.MethodNotFoundError = MethodNotFoundError; +class InvalidParamsError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_INVALID_PARAMS].message); + this.code = error_codes_js_1.ERR_RPC_INVALID_PARAMS; + } +} +exports.InvalidParamsError = InvalidParamsError; +class InternalError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_INTERNAL_ERROR].message); + this.code = error_codes_js_1.ERR_RPC_INTERNAL_ERROR; + } +} +exports.InternalError = InternalError; +class InvalidInputError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_INVALID_INPUT].message); + this.code = error_codes_js_1.ERR_RPC_INVALID_INPUT; + } +} +exports.InvalidInputError = InvalidInputError; +class MethodNotSupported extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_UNSUPPORTED_METHOD].message); + this.code = error_codes_js_1.ERR_RPC_UNSUPPORTED_METHOD; + } +} +exports.MethodNotSupported = MethodNotSupported; +class ResourceUnavailableError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_UNAVAILABLE_RESOURCE].message); + this.code = error_codes_js_1.ERR_RPC_UNAVAILABLE_RESOURCE; + } +} +exports.ResourceUnavailableError = ResourceUnavailableError; +class ResourcesNotFoundError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_MISSING_RESOURCE].message); + this.code = error_codes_js_1.ERR_RPC_MISSING_RESOURCE; + } +} +exports.ResourcesNotFoundError = ResourcesNotFoundError; +class VersionNotSupportedError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_NOT_SUPPORTED].message); + this.code = error_codes_js_1.ERR_RPC_NOT_SUPPORTED; + } +} +exports.VersionNotSupportedError = VersionNotSupportedError; +class TransactionRejectedError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_TRANSACTION_REJECTED].message); + this.code = error_codes_js_1.ERR_RPC_TRANSACTION_REJECTED; + } +} +exports.TransactionRejectedError = TransactionRejectedError; +class LimitExceededError extends RpcError { + constructor(rpcError) { + super(rpcError, rpc_error_messages_js_1.RpcErrorMessages[error_codes_js_1.ERR_RPC_LIMIT_EXCEEDED].message); + this.code = error_codes_js_1.ERR_RPC_LIMIT_EXCEEDED; + } +} +exports.LimitExceededError = LimitExceededError; +exports.rpcErrorsMap = new Map(); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_INVALID_JSON, { error: ParseError }); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_INVALID_REQUEST, { + error: InvalidRequestError, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_INVALID_METHOD, { + error: MethodNotFoundError, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_INVALID_PARAMS, { error: InvalidParamsError }); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_INTERNAL_ERROR, { error: InternalError }); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_INVALID_INPUT, { error: InvalidInputError }); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_UNSUPPORTED_METHOD, { + error: MethodNotSupported, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_UNAVAILABLE_RESOURCE, { + error: ResourceUnavailableError, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_TRANSACTION_REJECTED, { + error: TransactionRejectedError, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_MISSING_RESOURCE, { + error: ResourcesNotFoundError, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_NOT_SUPPORTED, { + error: VersionNotSupportedError, +}); +exports.rpcErrorsMap.set(error_codes_js_1.ERR_RPC_LIMIT_EXCEEDED, { error: LimitExceededError }); +//# sourceMappingURL=rpc_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.js.map new file mode 100644 index 0000000..2c0b260 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/rpc_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_errors.js","sourceRoot":"","sources":["../../../src/errors/rpc_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAKF,8DAAsD;AACtD,sDAa2B;AAC3B,mEAA2F;AAE3F,MAAa,QAAS,SAAQ,kCAAa;IAK1C,YAAmB,QAAkC,EAAE,OAAgB;QACtE,KAAK,CACJ,OAAO,aAAP,OAAO,cAAP,OAAO,GACN,sDAA8B,CAAC,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CACjF,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC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EAAE,KAAK,EAAE,kBAAkB,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.d.ts new file mode 100644 index 0000000..82d8924 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.d.ts @@ -0,0 +1,13 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class SchemaFormatError extends BaseWeb3Error { + type: string; + code: number; + constructor(type: string); + toJSON(): { + type: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.js new file mode 100644 index 0000000..5e7430e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.js @@ -0,0 +1,33 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SchemaFormatError = void 0; +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class SchemaFormatError extends web3_error_base_js_1.BaseWeb3Error { + constructor(type) { + super(`Format for the type ${type} is unsupported`); + this.type = type; + this.code = error_codes_js_1.ERR_SCHEMA_FORMAT; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { type: this.type }); + } +} +exports.SchemaFormatError = SchemaFormatError; +//# sourceMappingURL=schema_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.js.map new file mode 100644 index 0000000..825d8e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/schema_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schema_errors.js","sourceRoot":"","sources":["../../../src/errors/schema_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,sDAAsD;AACtD,8DAAsD;AAEtD,MAAa,iBAAkB,SAAQ,kCAAa;IAGnD,YAA0B,IAAY;QACrC,KAAK,CAAC,uBAAuB,IAAI,iBAAiB,CAAC,CAAC;QAD3B,SAAI,GAAJ,IAAI,CAAQ;QAF/B,SAAI,GAAG,kCAAiB,CAAC;IAIhC,CAAC;IAEM,MAAM;QACZ,uCAAY,KAAK,CAAC,MAAM,EAAE,KAAE,IAAI,EAAE,IAAI,CAAC,IAAI,IAAG;IAC/C,CAAC;CAED;AAXD,8CAWC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.d.ts new file mode 100644 index 0000000..20335ac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.d.ts @@ -0,0 +1,4 @@ +import { InvalidValueError } from '../web3_error_base.js'; +export declare class SignatureError extends InvalidValueError { + code: number; +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.js new file mode 100644 index 0000000..03f2790 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.js @@ -0,0 +1,29 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SignatureError = void 0; +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class SignatureError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super(...arguments); + this.code = error_codes_js_1.ERR_SIGNATURE_FAILED; + } +} +exports.SignatureError = SignatureError; +//# sourceMappingURL=signature_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.js.map new file mode 100644 index 0000000..70d0c1b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/signature_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signature_errors.js","sourceRoot":"","sources":["../../../src/errors/signature_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,sDAAyD;AACzD,8DAA0D;AAE1D,MAAa,cAAe,SAAQ,sCAAiB;IAArD;;QACQ,SAAI,GAAG,qCAAoB,CAAC;IACpC,CAAC;CAAA;AAFD,wCAEC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.d.ts new file mode 100644 index 0000000..ac99984 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.d.ts @@ -0,0 +1,281 @@ +import { Bytes, HexString, Numbers, TransactionReceipt, Web3ValidationErrorObject } from 'web3-types'; +import { InvalidValueError, BaseWeb3Error } from '../web3_error_base.js'; +export declare class TransactionError extends BaseWeb3Error { + receipt?: ReceiptType | undefined; + code: number; + constructor(message: string, receipt?: ReceiptType | undefined); + toJSON(): { + receipt: ReceiptType | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class RevertInstructionError extends BaseWeb3Error { + reason: string; + signature: string; + code: number; + constructor(reason: string, signature: string); + toJSON(): { + reason: string; + signature: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class TransactionRevertInstructionError extends BaseWeb3Error { + reason: string; + signature?: string | undefined; + receipt?: ReceiptType | undefined; + data?: string | undefined; + code: number; + constructor(reason: string, signature?: string | undefined, receipt?: ReceiptType | undefined, data?: string | undefined); + toJSON(): { + reason: string; + signature: string | undefined; + receipt: ReceiptType | undefined; + data: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +/** + * This error is used when a transaction to a smart contract fails and + * a custom user error (https://blog.soliditylang.org/2021/04/21/custom-errors/) + * is able to be parsed from the revert reason + */ +export declare class TransactionRevertWithCustomError extends TransactionRevertInstructionError { + reason: string; + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; + signature?: string | undefined; + receipt?: ReceiptType | undefined; + data?: string | undefined; + code: number; + constructor(reason: string, customErrorName: string, customErrorDecodedSignature: string, customErrorArguments: Record, signature?: string | undefined, receipt?: ReceiptType | undefined, data?: string | undefined); + toJSON(): { + reason: string; + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; + signature: string | undefined; + receipt: ReceiptType | undefined; + data: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class NoContractAddressFoundError extends TransactionError { + constructor(receipt: TransactionReceipt); + toJSON(): { + receipt: TransactionReceipt | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractCodeNotStoredError extends TransactionError { + constructor(receipt: TransactionReceipt); +} +export declare class TransactionRevertedWithoutReasonError extends TransactionError { + constructor(receipt?: ReceiptType); +} +export declare class TransactionOutOfGasError extends TransactionError { + constructor(receipt: TransactionReceipt); +} +export declare class UndefinedRawTransactionError extends TransactionError { + constructor(); +} +export declare class TransactionNotFound extends TransactionError { + constructor(); +} +export declare class InvalidTransactionWithSender extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidTransactionWithReceiver extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidTransactionCall extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class MissingCustomChainError extends InvalidValueError { + code: number; + constructor(); +} +export declare class MissingCustomChainIdError extends InvalidValueError { + code: number; + constructor(); +} +export declare class ChainIdMismatchError extends InvalidValueError { + code: number; + constructor(value: { + txChainId: unknown; + customChainId: unknown; + }); +} +export declare class ChainMismatchError extends InvalidValueError { + code: number; + constructor(value: { + txChain: unknown; + baseChain: unknown; + }); +} +export declare class HardforkMismatchError extends InvalidValueError { + code: number; + constructor(value: { + txHardfork: unknown; + commonHardfork: unknown; + }); +} +export declare class CommonOrChainAndHardforkError extends InvalidValueError { + code: number; + constructor(); +} +export declare class MissingChainOrHardforkError extends InvalidValueError { + code: number; + constructor(value: { + chain: string | undefined; + hardfork: string | undefined; + }); +} +export declare class MissingGasInnerError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class MissingGasError extends InvalidValueError { + code: number; + constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class TransactionGasMismatchInnerError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class TransactionGasMismatchError extends InvalidValueError { + code: number; + constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class InvalidGasOrGasPrice extends InvalidValueError { + code: number; + constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + }); +} +export declare class InvalidMaxPriorityFeePerGasOrMaxFeePerGas extends InvalidValueError { + code: number; + constructor(value: { + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class Eip1559GasPriceError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class UnsupportedFeeMarketError extends InvalidValueError { + code: number; + constructor(value: { + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class InvalidTransactionObjectError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidNonceOrChainIdError extends InvalidValueError { + code: number; + constructor(value: { + nonce: Numbers | undefined; + chainId: Numbers | undefined; + }); +} +export declare class UnableToPopulateNonceError extends InvalidValueError { + code: number; + constructor(); +} +export declare class Eip1559NotSupportedError extends InvalidValueError { + code: number; + constructor(); +} +export declare class UnsupportedTransactionTypeError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class TransactionDataAndInputError extends InvalidValueError { + code: number; + constructor(value: { + data: HexString | undefined; + input: HexString | undefined; + }); +} +export declare class TransactionSendTimeoutError extends BaseWeb3Error { + code: number; + constructor(value: { + numberOfSeconds: number; + transactionHash?: Bytes; + }); +} +export declare class TransactionPollingTimeoutError extends BaseWeb3Error { + code: number; + constructor(value: { + numberOfSeconds: number; + transactionHash: Bytes; + }); +} +export declare class TransactionBlockTimeoutError extends BaseWeb3Error { + code: number; + constructor(value: { + starterBlockNumber: number; + numberOfBlocks: number; + transactionHash?: Bytes; + }); +} +export declare class TransactionMissingReceiptOrBlockHashError extends InvalidValueError { + code: number; + constructor(value: { + receipt: TransactionReceipt; + blockHash: Bytes; + transactionHash: Bytes; + }); +} +export declare class TransactionReceiptMissingBlockNumberError extends InvalidValueError { + code: number; + constructor(value: { + receipt: TransactionReceipt; + }); +} +export declare class TransactionSigningError extends BaseWeb3Error { + code: number; + constructor(errorDetails: string); +} +export declare class LocalWalletNotAvailableError extends InvalidValueError { + code: number; + constructor(); +} +export declare class InvalidPropertiesForTransactionTypeError extends BaseWeb3Error { + code: number; + constructor(validationError: Web3ValidationErrorObject[], txType: '0x0' | '0x1' | '0x2'); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.js new file mode 100644 index 0000000..326f264 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.js @@ -0,0 +1,368 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidPropertiesForTransactionTypeError = exports.LocalWalletNotAvailableError = exports.TransactionSigningError = exports.TransactionReceiptMissingBlockNumberError = exports.TransactionMissingReceiptOrBlockHashError = exports.TransactionBlockTimeoutError = exports.TransactionPollingTimeoutError = exports.TransactionSendTimeoutError = exports.TransactionDataAndInputError = exports.UnsupportedTransactionTypeError = exports.Eip1559NotSupportedError = exports.UnableToPopulateNonceError = exports.InvalidNonceOrChainIdError = exports.InvalidTransactionObjectError = exports.UnsupportedFeeMarketError = exports.Eip1559GasPriceError = exports.InvalidMaxPriorityFeePerGasOrMaxFeePerGas = exports.InvalidGasOrGasPrice = exports.TransactionGasMismatchError = exports.TransactionGasMismatchInnerError = exports.MissingGasError = exports.MissingGasInnerError = exports.MissingChainOrHardforkError = exports.CommonOrChainAndHardforkError = exports.HardforkMismatchError = exports.ChainMismatchError = exports.ChainIdMismatchError = exports.MissingCustomChainIdError = exports.MissingCustomChainError = exports.InvalidTransactionCall = exports.InvalidTransactionWithReceiver = exports.InvalidTransactionWithSender = exports.TransactionNotFound = exports.UndefinedRawTransactionError = exports.TransactionOutOfGasError = exports.TransactionRevertedWithoutReasonError = exports.ContractCodeNotStoredError = exports.NoContractAddressFoundError = exports.TransactionRevertWithCustomError = exports.TransactionRevertInstructionError = exports.RevertInstructionError = exports.TransactionError = void 0; +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class TransactionError extends web3_error_base_js_1.BaseWeb3Error { + constructor(message, receipt) { + super(message); + this.receipt = receipt; + this.code = error_codes_js_1.ERR_TX; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { receipt: this.receipt }); + } +} +exports.TransactionError = TransactionError; +class RevertInstructionError extends web3_error_base_js_1.BaseWeb3Error { + constructor(reason, signature) { + super(`Your request got reverted with the following reason string: ${reason}`); + this.reason = reason; + this.signature = signature; + this.code = error_codes_js_1.ERR_TX_REVERT_INSTRUCTION; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { reason: this.reason, signature: this.signature }); + } +} +exports.RevertInstructionError = RevertInstructionError; +class TransactionRevertInstructionError extends web3_error_base_js_1.BaseWeb3Error { + constructor(reason, signature, receipt, data) { + super(`Transaction has been reverted by the EVM${receipt === undefined ? '' : `:\n ${web3_error_base_js_1.BaseWeb3Error.convertToString(receipt)}`}`); + this.reason = reason; + this.signature = signature; + this.receipt = receipt; + this.data = data; + this.code = error_codes_js_1.ERR_TX_REVERT_TRANSACTION; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { reason: this.reason, signature: this.signature, receipt: this.receipt, data: this.data }); + } +} +exports.TransactionRevertInstructionError = TransactionRevertInstructionError; +/** + * This error is used when a transaction to a smart contract fails and + * a custom user error (https://blog.soliditylang.org/2021/04/21/custom-errors/) + * is able to be parsed from the revert reason + */ +class TransactionRevertWithCustomError extends TransactionRevertInstructionError { + constructor(reason, customErrorName, customErrorDecodedSignature, customErrorArguments, signature, receipt, data) { + super(reason); + this.reason = reason; + this.customErrorName = customErrorName; + this.customErrorDecodedSignature = customErrorDecodedSignature; + this.customErrorArguments = customErrorArguments; + this.signature = signature; + this.receipt = receipt; + this.data = data; + this.code = error_codes_js_1.ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { reason: this.reason, customErrorName: this.customErrorName, customErrorDecodedSignature: this.customErrorDecodedSignature, customErrorArguments: this.customErrorArguments, signature: this.signature, receipt: this.receipt, data: this.data }); + } +} +exports.TransactionRevertWithCustomError = TransactionRevertWithCustomError; +class NoContractAddressFoundError extends TransactionError { + constructor(receipt) { + super("The transaction receipt didn't contain a contract address.", receipt); + this.code = error_codes_js_1.ERR_TX_NO_CONTRACT_ADDRESS; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { receipt: this.receipt }); + } +} +exports.NoContractAddressFoundError = NoContractAddressFoundError; +class ContractCodeNotStoredError extends TransactionError { + constructor(receipt) { + super("The contract code couldn't be stored, please check your gas limit.", receipt); + this.code = error_codes_js_1.ERR_TX_CONTRACT_NOT_STORED; + } +} +exports.ContractCodeNotStoredError = ContractCodeNotStoredError; +class TransactionRevertedWithoutReasonError extends TransactionError { + constructor(receipt) { + super(`Transaction has been reverted by the EVM${receipt === undefined ? '' : `:\n ${web3_error_base_js_1.BaseWeb3Error.convertToString(receipt)}`}`, receipt); + this.code = error_codes_js_1.ERR_TX_REVERT_WITHOUT_REASON; + } +} +exports.TransactionRevertedWithoutReasonError = TransactionRevertedWithoutReasonError; +class TransactionOutOfGasError extends TransactionError { + constructor(receipt) { + super(`Transaction ran out of gas. Please provide more gas:\n ${JSON.stringify(receipt, undefined, 2)}`, receipt); + this.code = error_codes_js_1.ERR_TX_OUT_OF_GAS; + } +} +exports.TransactionOutOfGasError = TransactionOutOfGasError; +class UndefinedRawTransactionError extends TransactionError { + constructor() { + super(`Raw transaction undefined`); + this.code = error_codes_js_1.ERR_RAW_TX_UNDEFINED; + } +} +exports.UndefinedRawTransactionError = UndefinedRawTransactionError; +class TransactionNotFound extends TransactionError { + constructor() { + super('Transaction not found'); + this.code = error_codes_js_1.ERR_TX_NOT_FOUND; + } +} +exports.TransactionNotFound = TransactionNotFound; +class InvalidTransactionWithSender extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid transaction with invalid sender'); + this.code = error_codes_js_1.ERR_TX_INVALID_SENDER; + } +} +exports.InvalidTransactionWithSender = InvalidTransactionWithSender; +class InvalidTransactionWithReceiver extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid transaction with invalid receiver'); + this.code = error_codes_js_1.ERR_TX_INVALID_RECEIVER; + } +} +exports.InvalidTransactionWithReceiver = InvalidTransactionWithReceiver; +class InvalidTransactionCall extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid transaction call'); + this.code = error_codes_js_1.ERR_TX_INVALID_CALL; + } +} +exports.InvalidTransactionCall = InvalidTransactionCall; +class MissingCustomChainError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super('MissingCustomChainError', 'If tx.common is provided it must have tx.common.customChain'); + this.code = error_codes_js_1.ERR_TX_MISSING_CUSTOM_CHAIN; + } +} +exports.MissingCustomChainError = MissingCustomChainError; +class MissingCustomChainIdError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super('MissingCustomChainIdError', 'If tx.common is provided it must have tx.common.customChain and tx.common.customChain.chainId'); + this.code = error_codes_js_1.ERR_TX_MISSING_CUSTOM_CHAIN_ID; + } +} +exports.MissingCustomChainIdError = MissingCustomChainIdError; +class ChainIdMismatchError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(JSON.stringify(value), + // https://github.com/ChainSafe/web3.js/blob/8783f4d64e424456bdc53b34ef1142d0a7cee4d7/packages/web3-eth-accounts/src/index.js#L176 + 'Chain Id doesnt match in tx.chainId tx.common.customChain.chainId'); + this.code = error_codes_js_1.ERR_TX_CHAIN_ID_MISMATCH; + } +} +exports.ChainIdMismatchError = ChainIdMismatchError; +class ChainMismatchError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(JSON.stringify(value), 'Chain doesnt match in tx.chain tx.common.basechain'); + this.code = error_codes_js_1.ERR_TX_CHAIN_MISMATCH; + } +} +exports.ChainMismatchError = ChainMismatchError; +class HardforkMismatchError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(JSON.stringify(value), 'hardfork doesnt match in tx.hardfork tx.common.hardfork'); + this.code = error_codes_js_1.ERR_TX_HARDFORK_MISMATCH; + } +} +exports.HardforkMismatchError = HardforkMismatchError; +class CommonOrChainAndHardforkError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super('CommonOrChainAndHardforkError', 'Please provide the common object or the chain and hardfork property but not all together.'); + this.code = error_codes_js_1.ERR_TX_INVALID_CHAIN_INFO; + } +} +exports.CommonOrChainAndHardforkError = CommonOrChainAndHardforkError; +class MissingChainOrHardforkError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super('MissingChainOrHardforkError', `When specifying chain and hardfork, both values must be defined. Received "chain": ${(_a = value.chain) !== null && _a !== void 0 ? _a : 'undefined'}, "hardfork": ${(_b = value.hardfork) !== null && _b !== void 0 ? _b : 'undefined'}`); + this.code = error_codes_js_1.ERR_TX_MISSING_CHAIN_INFO; + } +} +exports.MissingChainOrHardforkError = MissingChainOrHardforkError; +class MissingGasInnerError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('Missing properties in transaction, either define "gas" and "gasPrice" for type 0 transactions or "gas", "maxPriorityFeePerGas" and "maxFeePerGas" for type 2 transactions'); + this.code = error_codes_js_1.ERR_TX_MISSING_GAS_INNER_ERROR; + } +} +exports.MissingGasInnerError = MissingGasInnerError; +class MissingGasError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b, _c, _d; + super(`gas: ${(_a = value.gas) !== null && _a !== void 0 ? _a : 'undefined'}, gasPrice: ${(_b = value.gasPrice) !== null && _b !== void 0 ? _b : 'undefined'}, maxPriorityFeePerGas: ${(_c = value.maxPriorityFeePerGas) !== null && _c !== void 0 ? _c : 'undefined'}, maxFeePerGas: ${(_d = value.maxFeePerGas) !== null && _d !== void 0 ? _d : 'undefined'}`, '"gas" is missing'); + this.code = error_codes_js_1.ERR_TX_MISSING_GAS; + this.innerError = new MissingGasInnerError(); + } +} +exports.MissingGasError = MissingGasError; +class TransactionGasMismatchInnerError extends web3_error_base_js_1.BaseWeb3Error { + constructor() { + super('Missing properties in transaction, either define "gas" and "gasPrice" for type 0 transactions or "gas", "maxPriorityFeePerGas" and "maxFeePerGas" for type 2 transactions, not both'); + this.code = error_codes_js_1.ERR_TX_GAS_MISMATCH_INNER_ERROR; + } +} +exports.TransactionGasMismatchInnerError = TransactionGasMismatchInnerError; +class TransactionGasMismatchError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b, _c, _d; + super(`gas: ${(_a = value.gas) !== null && _a !== void 0 ? _a : 'undefined'}, gasPrice: ${(_b = value.gasPrice) !== null && _b !== void 0 ? _b : 'undefined'}, maxPriorityFeePerGas: ${(_c = value.maxPriorityFeePerGas) !== null && _c !== void 0 ? _c : 'undefined'}, maxFeePerGas: ${(_d = value.maxFeePerGas) !== null && _d !== void 0 ? _d : 'undefined'}`, 'transaction must specify legacy or fee market gas properties, not both'); + this.code = error_codes_js_1.ERR_TX_GAS_MISMATCH; + this.innerError = new TransactionGasMismatchInnerError(); + } +} +exports.TransactionGasMismatchError = TransactionGasMismatchError; +class InvalidGasOrGasPrice extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`gas: ${(_a = value.gas) !== null && _a !== void 0 ? _a : 'undefined'}, gasPrice: ${(_b = value.gasPrice) !== null && _b !== void 0 ? _b : 'undefined'}`, 'Gas or gasPrice is lower than 0'); + this.code = error_codes_js_1.ERR_TX_INVALID_LEGACY_GAS; + } +} +exports.InvalidGasOrGasPrice = InvalidGasOrGasPrice; +class InvalidMaxPriorityFeePerGasOrMaxFeePerGas extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`maxPriorityFeePerGas: ${(_a = value.maxPriorityFeePerGas) !== null && _a !== void 0 ? _a : 'undefined'}, maxFeePerGas: ${(_b = value.maxFeePerGas) !== null && _b !== void 0 ? _b : 'undefined'}`, 'maxPriorityFeePerGas or maxFeePerGas is lower than 0'); + this.code = error_codes_js_1.ERR_TX_INVALID_FEE_MARKET_GAS; + } +} +exports.InvalidMaxPriorityFeePerGasOrMaxFeePerGas = InvalidMaxPriorityFeePerGasOrMaxFeePerGas; +class Eip1559GasPriceError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, "eip-1559 transactions don't support gasPrice"); + this.code = error_codes_js_1.ERR_TX_INVALID_FEE_MARKET_GAS_PRICE; + } +} +exports.Eip1559GasPriceError = Eip1559GasPriceError; +class UnsupportedFeeMarketError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`maxPriorityFeePerGas: ${(_a = value.maxPriorityFeePerGas) !== null && _a !== void 0 ? _a : 'undefined'}, maxFeePerGas: ${(_b = value.maxFeePerGas) !== null && _b !== void 0 ? _b : 'undefined'}`, "pre-eip-1559 transaction don't support maxFeePerGas/maxPriorityFeePerGas"); + this.code = error_codes_js_1.ERR_TX_INVALID_LEGACY_FEE_MARKET; + } +} +exports.UnsupportedFeeMarketError = UnsupportedFeeMarketError; +class InvalidTransactionObjectError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid transaction object'); + this.code = error_codes_js_1.ERR_TX_INVALID_OBJECT; + } +} +exports.InvalidTransactionObjectError = InvalidTransactionObjectError; +class InvalidNonceOrChainIdError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`nonce: ${(_a = value.nonce) !== null && _a !== void 0 ? _a : 'undefined'}, chainId: ${(_b = value.chainId) !== null && _b !== void 0 ? _b : 'undefined'}`, 'Nonce or chainId is lower than 0'); + this.code = error_codes_js_1.ERR_TX_INVALID_NONCE_OR_CHAIN_ID; + } +} +exports.InvalidNonceOrChainIdError = InvalidNonceOrChainIdError; +class UnableToPopulateNonceError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super('UnableToPopulateNonceError', 'unable to populate nonce, no from address available'); + this.code = error_codes_js_1.ERR_TX_UNABLE_TO_POPULATE_NONCE; + } +} +exports.UnableToPopulateNonceError = UnableToPopulateNonceError; +class Eip1559NotSupportedError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super('Eip1559NotSupportedError', "Network doesn't support eip-1559"); + this.code = error_codes_js_1.ERR_TX_UNSUPPORTED_EIP_1559; + } +} +exports.Eip1559NotSupportedError = Eip1559NotSupportedError; +class UnsupportedTransactionTypeError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'unsupported transaction type'); + this.code = error_codes_js_1.ERR_TX_UNSUPPORTED_TYPE; + } +} +exports.UnsupportedTransactionTypeError = UnsupportedTransactionTypeError; +class TransactionDataAndInputError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`data: ${(_a = value.data) !== null && _a !== void 0 ? _a : 'undefined'}, input: ${(_b = value.input) !== null && _b !== void 0 ? _b : 'undefined'}`, 'You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); + this.code = error_codes_js_1.ERR_TX_DATA_AND_INPUT; + } +} +exports.TransactionDataAndInputError = TransactionDataAndInputError; +class TransactionSendTimeoutError extends web3_error_base_js_1.BaseWeb3Error { + constructor(value) { + super(`The connected Ethereum Node did not respond within ${value.numberOfSeconds} seconds, please make sure your transaction was properly sent and you are connected to a healthy Node. Be aware that transaction might still be pending or mined!\n\tTransaction Hash: ${value.transactionHash ? value.transactionHash.toString() : 'not available'}`); + this.code = error_codes_js_1.ERR_TX_SEND_TIMEOUT; + } +} +exports.TransactionSendTimeoutError = TransactionSendTimeoutError; +function transactionTimeoutHint(transactionHash) { + return `Please make sure your transaction was properly sent and there are no previous pending transaction for the same account. However, be aware that it might still be mined!\n\tTransaction Hash: ${transactionHash ? transactionHash.toString() : 'not available'}`; +} +class TransactionPollingTimeoutError extends web3_error_base_js_1.BaseWeb3Error { + constructor(value) { + super(`Transaction was not mined within ${value.numberOfSeconds} seconds. ${transactionTimeoutHint(value.transactionHash)}`); + this.code = error_codes_js_1.ERR_TX_POLLING_TIMEOUT; + } +} +exports.TransactionPollingTimeoutError = TransactionPollingTimeoutError; +class TransactionBlockTimeoutError extends web3_error_base_js_1.BaseWeb3Error { + constructor(value) { + super(`Transaction started at ${value.starterBlockNumber} but was not mined within ${value.numberOfBlocks} blocks. ${transactionTimeoutHint(value.transactionHash)}`); + this.code = error_codes_js_1.ERR_TX_BLOCK_TIMEOUT; + } +} +exports.TransactionBlockTimeoutError = TransactionBlockTimeoutError; +class TransactionMissingReceiptOrBlockHashError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + var _a, _b; + super(`receipt: ${JSON.stringify(value.receipt)}, blockHash: ${(_a = value.blockHash) === null || _a === void 0 ? void 0 : _a.toString()}, transactionHash: ${(_b = value.transactionHash) === null || _b === void 0 ? void 0 : _b.toString()}`, `Receipt missing or blockHash null`); + this.code = error_codes_js_1.ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL; + } +} +exports.TransactionMissingReceiptOrBlockHashError = TransactionMissingReceiptOrBlockHashError; +class TransactionReceiptMissingBlockNumberError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(`receipt: ${JSON.stringify(value.receipt)}`, `Receipt missing block number`); + this.code = error_codes_js_1.ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER; + } +} +exports.TransactionReceiptMissingBlockNumberError = TransactionReceiptMissingBlockNumberError; +class TransactionSigningError extends web3_error_base_js_1.BaseWeb3Error { + constructor(errorDetails) { + super(`Invalid signature. "${errorDetails}"`); + this.code = error_codes_js_1.ERR_TX_SIGNING; + } +} +exports.TransactionSigningError = TransactionSigningError; +class LocalWalletNotAvailableError extends web3_error_base_js_1.InvalidValueError { + constructor() { + super('LocalWalletNotAvailableError', `Attempted to index account in local wallet, but no wallet is available`); + this.code = error_codes_js_1.ERR_TX_LOCAL_WALLET_NOT_AVAILABLE; + } +} +exports.LocalWalletNotAvailableError = LocalWalletNotAvailableError; +class InvalidPropertiesForTransactionTypeError extends web3_error_base_js_1.BaseWeb3Error { + constructor(validationError, txType) { + const invalidPropertyNames = []; + validationError.forEach(error => invalidPropertyNames.push(error.keyword)); + super(`The following properties are invalid for the transaction type ${txType}: ${invalidPropertyNames.join(', ')}`); + this.code = error_codes_js_1.ERR_TX_INVALID_PROPERTIES_FOR_TYPE; + } +} +exports.InvalidPropertiesForTransactionTypeError = InvalidPropertiesForTransactionTypeError; +//# sourceMappingURL=transaction_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.js.map new file mode 100644 index 0000000..2ad69c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/transaction_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction_errors.js","sourceRoot":"","sources":["../../../src/errors/transaction_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAWF,sDA2C2B;AAC3B,8DAAyE;AAEzE,MAAa,gBAAmD,SAAQ,kCAAa;IAGpF,YAAmB,OAAe,EAAS,OAAqB;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QAD2B,YAAO,GAAP,OAAO,CAAc;QAFzD,SAAI,GAAG,uBAAM,CAAC;IAIrB,CAAC;IAEM,MAAM;QACZ,uCAAY,KAAK,CAAC,MAAM,EAAE,KAAE,OAAO,EAAE,IAAI,CAAC,OAAO,IAAG;IACrD,CAAC;CACD;AAVD,4CAUC;AAED,MAAa,sBAAuB,SAAQ,kCAAa;IAGxD,YAA0B,MAAc,EAAS,SAAiB;QACjE,KAAK,CAAC,+DAA+D,MAAM,EAAE,CAAC,CAAC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D,CAAC;CACD;AATD,oEASC;AACD,MAAa,wCAAyC,SAAQ,kCAAa;IAG1E,YACC,eAA4C,EAC5C,MAA6B;QAE7B,MAAM,oBAAoB,GAAa,EAAE,CAAC;QAC1C,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3E,KAAK,CACJ,iEAAiE,MAAM,KAAK,oBAAoB,CAAC,IAAI,CACpG,IAAI,CACJ,EAAE,CACH,CAAC;QAZI,SAAI,GAAG,mDAAkC,CAAC;IAajD,CAAC;CACD;AAfD,4FAeC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.d.ts new file mode 100644 index 0000000..f2f9327 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.d.ts @@ -0,0 +1,57 @@ +import { InvalidValueError } from '../web3_error_base.js'; +export declare class InvalidBytesError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidNumberError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidAddressError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidStringError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidUnitError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class HexProcessingError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class NibbleWidthError extends InvalidValueError { + code: number; + constructor(value: string); +} +export declare class InvalidTypeError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidBooleanError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidUnsignedIntegerError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidSizeError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidLargeValueError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidBlockError extends InvalidValueError { + code: number; + constructor(value: string); +} +export declare class InvalidTypeAbiInputError extends InvalidValueError { + code: number; + constructor(value: string); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.js new file mode 100644 index 0000000..b0ab6c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.js @@ -0,0 +1,121 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidTypeAbiInputError = exports.InvalidBlockError = exports.InvalidLargeValueError = exports.InvalidSizeError = exports.InvalidUnsignedIntegerError = exports.InvalidBooleanError = exports.InvalidTypeError = exports.NibbleWidthError = exports.HexProcessingError = exports.InvalidUnitError = exports.InvalidStringError = exports.InvalidAddressError = exports.InvalidNumberError = exports.InvalidBytesError = void 0; +/* eslint-disable max-classes-per-file */ +const error_codes_js_1 = require("../error_codes.js"); +const web3_error_base_js_1 = require("../web3_error_base.js"); +class InvalidBytesError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'can not parse as byte data'); + this.code = error_codes_js_1.ERR_INVALID_BYTES; + } +} +exports.InvalidBytesError = InvalidBytesError; +class InvalidNumberError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'can not parse as number data'); + this.code = error_codes_js_1.ERR_INVALID_NUMBER; + } +} +exports.InvalidNumberError = InvalidNumberError; +class InvalidAddressError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid ethereum address'); + this.code = error_codes_js_1.ERR_INVALID_ADDRESS; + } +} +exports.InvalidAddressError = InvalidAddressError; +class InvalidStringError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'not a valid string'); + this.code = error_codes_js_1.ERR_INVALID_STRING; + } +} +exports.InvalidStringError = InvalidStringError; +class InvalidUnitError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid unit'); + this.code = error_codes_js_1.ERR_INVALID_UNIT; + } +} +exports.InvalidUnitError = InvalidUnitError; +class HexProcessingError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'can not be converted to hex'); + this.code = error_codes_js_1.ERR_INVALID_HEX; + } +} +exports.HexProcessingError = HexProcessingError; +class NibbleWidthError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'value greater than the nibble width'); + this.code = error_codes_js_1.ERR_INVALID_NIBBLE_WIDTH; + } +} +exports.NibbleWidthError = NibbleWidthError; +class InvalidTypeError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid type, type not supported'); + this.code = error_codes_js_1.ERR_INVALID_TYPE; + } +} +exports.InvalidTypeError = InvalidTypeError; +class InvalidBooleanError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'not a valid boolean.'); + this.code = error_codes_js_1.ERR_INVALID_BOOLEAN; + } +} +exports.InvalidBooleanError = InvalidBooleanError; +class InvalidUnsignedIntegerError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'not a valid unsigned integer.'); + this.code = error_codes_js_1.ERR_INVALID_UNSIGNED_INTEGER; + } +} +exports.InvalidUnsignedIntegerError = InvalidUnsignedIntegerError; +class InvalidSizeError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid size given.'); + this.code = error_codes_js_1.ERR_INVALID_SIZE; + } +} +exports.InvalidSizeError = InvalidSizeError; +class InvalidLargeValueError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'value is larger than size.'); + this.code = error_codes_js_1.ERR_INVALID_LARGE_VALUE; + } +} +exports.InvalidLargeValueError = InvalidLargeValueError; +class InvalidBlockError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'invalid string given'); + this.code = error_codes_js_1.ERR_INVALID_BLOCK; + } +} +exports.InvalidBlockError = InvalidBlockError; +class InvalidTypeAbiInputError extends web3_error_base_js_1.InvalidValueError { + constructor(value) { + super(value, 'components found but type is not tuple'); + this.code = error_codes_js_1.ERR_INVALID_TYPE_ABI; + } +} +exports.InvalidTypeAbiInputError = InvalidTypeAbiInputError; +//# sourceMappingURL=utils_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.js.map new file mode 100644 index 0000000..60f30cc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/errors/utils_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils_errors.js","sourceRoot":"","sources":["../../../src/errors/utils_errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAyC;AAEzC,sDAe2B;AAC3B,8DAA0D;AAE1D,MAAa,iBAAkB,SAAQ,sCAAiB;IAGvD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,4BAA4B,CAAC,CAAC;QAHrC,SAAI,GAAG,kCAAiB,CAAC;IAIhC,CAAC;CACD;AAND,8CAMC;AAED,MAAa,kBAAmB,SAAQ,sCAAiB;IAGxD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,8BAA8B,CAAC,CAAC;QAHvC,SAAI,GAAG,mCAAkB,CAAC;IAIjC,CAAC;CACD;AAND,gDAMC;AAED,MAAa,mBAAoB,SAAQ,sCAAiB;IAGzD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,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CAA4B,CAAC;IAI3C,CAAC;CACD;AAND,kEAMC;AAED,MAAa,gBAAiB,SAAQ,sCAAiB;IAGtD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,qBAAqB,CAAC,CAAC;QAH9B,SAAI,GAAG,iCAAgB,CAAC;IAI/B,CAAC;CACD;AAND,4CAMC;AAED,MAAa,sBAAuB,SAAQ,sCAAiB;IAG5D,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,4BAA4B,CAAC,CAAC;QAHrC,SAAI,GAAG,wCAAuB,CAAC;IAItC,CAAC;CACD;AAND,wDAMC;AAED,MAAa,iBAAkB,SAAQ,sCAAiB;IAGvD,YAAmB,KAAa;QAC/B,KAAK,CAAC,KAAK,EAAE,sBAAsB,CAAC,CAAC;QAH/B,SAAI,GAAG,kCAAiB,CAAC;IAIhC,CAAC;CACD;AAND,8CAMC;AAED,MAAa,wBAAyB,SAAQ,sCAAiB;IAG9D,YAAmB,KAAa;QAC/B,KAAK,CAAC,KAAK,EAAE,wCAAwC,CAAC,CAAC;QAHjD,SAAI,GAAG,qCAAoB,CAAC;IAInC,CAAC;CACD;AAND,4DAMC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.d.ts new file mode 100644 index 0000000..a42fd1b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.d.ts @@ -0,0 +1,16 @@ +export * from './error_codes.js'; +export * from './web3_error_base.js'; +export * from './errors/account_errors.js'; +export * from './errors/connection_errors.js'; +export * from './errors/contract_errors.js'; +export * from './errors/ens_errors.js'; +export * from './errors/generic_errors.js'; +export * from './errors/provider_errors.js'; +export * from './errors/signature_errors.js'; +export * from './errors/transaction_errors.js'; +export * from './errors/utils_errors.js'; +export * from './errors/response_errors.js'; +export * from './errors/core_errors.js'; +export * from './errors/rpc_errors.js'; +export * from './errors/rpc_error_messages.js'; +export * from './errors/schema_errors.js'; diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.js new file mode 100644 index 0000000..a72108e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.js @@ -0,0 +1,49 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./error_codes.js"), exports); +__exportStar(require("./web3_error_base.js"), exports); +__exportStar(require("./errors/account_errors.js"), exports); +__exportStar(require("./errors/connection_errors.js"), exports); +__exportStar(require("./errors/contract_errors.js"), exports); +__exportStar(require("./errors/ens_errors.js"), exports); +__exportStar(require("./errors/generic_errors.js"), exports); +__exportStar(require("./errors/provider_errors.js"), exports); +__exportStar(require("./errors/signature_errors.js"), exports); +__exportStar(require("./errors/transaction_errors.js"), exports); +__exportStar(require("./errors/utils_errors.js"), exports); +__exportStar(require("./errors/response_errors.js"), exports); +__exportStar(require("./errors/core_errors.js"), exports); +__exportStar(require("./errors/rpc_errors.js"), exports); +__exportStar(require("./errors/rpc_error_messages.js"), exports); +__exportStar(require("./errors/schema_errors.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.js.map new file mode 100644 index 0000000..fe84b5b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF,mDAAiC;AACjC,uDAAqC;AACrC,6DAA2C;AAC3C,gEAA8C;AAC9C,8DAA4C;AAC5C,yDAAuC;AACvC,6DAA2C;AAC3C,8DAA4C;AAC5C,+DAA6C;AAC7C,iEAA+C;AAC/C,2DAAyC;AACzC,8DAA4C;AAC5C,0DAAwC;AACxC,yDAAuC;AACvC,iEAA+C;AAC/C,4DAA0C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.d.ts new file mode 100644 index 0000000..33f4bdd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.d.ts @@ -0,0 +1,19 @@ +import { Web3Error } from 'web3-types'; +export declare abstract class BaseWeb3Error extends Error implements Web3Error { + readonly name: string; + abstract readonly code: number; + stack: string | undefined; + innerError: Error | Error[] | undefined; + constructor(msg?: string, innerError?: Error | Error[]); + static convertToString(value: unknown, unquotValue?: boolean): string; + toJSON(): { + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare abstract class InvalidValueError extends BaseWeb3Error { + readonly name: string; + constructor(value: unknown, msg: string); +} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.js b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.js new file mode 100644 index 0000000..1103108 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.js @@ -0,0 +1,59 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidValueError = exports.BaseWeb3Error = void 0; +class BaseWeb3Error extends Error { + constructor(msg, innerError) { + super(msg); + this.innerError = innerError; + this.name = this.constructor.name; + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(new.target.constructor); + } + else { + this.stack = new Error().stack; + } + } + static convertToString(value, unquotValue = false) { + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + if (value === null || value === undefined) + return 'undefined'; + const result = JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? v.toString() : v)); + return unquotValue && ['bigint', 'string'].includes(typeof value) + ? result.replace(/['\\"]+/g, '') + : result; + } + toJSON() { + return { + name: this.name, + code: this.code, + message: this.message, + innerError: this.innerError, + }; + } +} +exports.BaseWeb3Error = BaseWeb3Error; +class InvalidValueError extends BaseWeb3Error { + constructor(value, msg) { + super(`Invalid value given "${BaseWeb3Error.convertToString(value, true)}". Error: ${msg}.`); + this.name = this.constructor.name; + } +} +exports.InvalidValueError = InvalidValueError; +//# sourceMappingURL=web3_error_base.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.js.map b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.js.map new file mode 100644 index 0000000..02da1c9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/commonjs/web3_error_base.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_error_base.js","sourceRoot":"","sources":["../../src/web3_error_base.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAMF,MAAsB,aAAc,SAAQ,KAAK;IAMhD,YAAmB,GAAY,EAAE,UAA4B;QAC5D,KAAK,CAAC,GAAG,CAAC,CAAC;QACX,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAElC,IAAI,OAAO,KAAK,CAAC,iBAAiB,KAAK,UAAU,EAAE;YAClD,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;SAChD;aAAM;YACN,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC;SAC/B;IACF,CAAC;IAEM,MAAM,CAAC,eAAe,CAAC,KAAc,EAAE,WAAW,GAAG,KAAK;QAChE,kDAAkD;QAClD,2CAA2C;QAC3C,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,WAAW,CAAC;QAE9D,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAC5B,KAAK,EACL,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAY,CAC/D,CAAC;QAEF,OAAO,WAAW,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC;YAChE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;YAChC,CAAC,CAAC,MAAM,CAAC;IACX,CAAC;IAEM,MAAM;QACZ,OAAO;YACN,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,UAAU,EAAE,IAAI,CAAC,UAAU;SAC3B,CAAC;IACH,CAAC;CACD;AAzCD,sCAyCC;AAED,MAAsB,iBAAkB,SAAQ,aAAa;IAG5D,YAAmB,KAAc,EAAE,GAAW;QAC7C,KAAK,CACJ,wBAAwB,aAAa,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,aAAa,GAAG,GAAG,CACrF,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACnC,CAAC;CACD;AATD,8CASC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/error_codes.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/error_codes.js new file mode 100644 index 0000000..292eea6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/error_codes.js @@ -0,0 +1,161 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// Response error +export const ERR_RESPONSE = 100; +export const ERR_INVALID_RESPONSE = 101; +// Generic errors +export const ERR_PARAM = 200; +export const ERR_FORMATTERS = 201; +export const ERR_METHOD_NOT_IMPLEMENTED = 202; +export const ERR_OPERATION_TIMEOUT = 203; +export const ERR_OPERATION_ABORT = 204; +export const ERR_ABI_ENCODING = 205; +export const ERR_EXISTING_PLUGIN_NAMESPACE = 206; +export const ERR_INVALID_METHOD_PARAMS = 207; +// Contract error codes +export const ERR_CONTRACT = 300; +export const ERR_CONTRACT_RESOLVER_MISSING = 301; +export const ERR_CONTRACT_ABI_MISSING = 302; +export const ERR_CONTRACT_REQUIRED_CALLBACK = 303; +export const ERR_CONTRACT_EVENT_NOT_EXISTS = 304; +export const ERR_CONTRACT_RESERVED_EVENT = 305; +export const ERR_CONTRACT_MISSING_DEPLOY_DATA = 306; +export const ERR_CONTRACT_MISSING_ADDRESS = 307; +export const ERR_CONTRACT_MISSING_FROM_ADDRESS = 308; +export const ERR_CONTRACT_INSTANTIATION = 309; +export const ERR_CONTRACT_EXECUTION_REVERTED = 310; +export const ERR_CONTRACT_TX_DATA_AND_INPUT = 311; +// Transaction error codes +export const ERR_TX = 400; +export const ERR_TX_REVERT_INSTRUCTION = 401; +export const ERR_TX_REVERT_TRANSACTION = 402; +export const ERR_TX_NO_CONTRACT_ADDRESS = 403; +export const ERR_TX_CONTRACT_NOT_STORED = 404; +export const ERR_TX_REVERT_WITHOUT_REASON = 405; +export const ERR_TX_OUT_OF_GAS = 406; +export const ERR_RAW_TX_UNDEFINED = 407; +export const ERR_TX_INVALID_SENDER = 408; +export const ERR_TX_INVALID_CALL = 409; +export const ERR_TX_MISSING_CUSTOM_CHAIN = 410; +export const ERR_TX_MISSING_CUSTOM_CHAIN_ID = 411; +export const ERR_TX_CHAIN_ID_MISMATCH = 412; +export const ERR_TX_INVALID_CHAIN_INFO = 413; +export const ERR_TX_MISSING_CHAIN_INFO = 414; +export const ERR_TX_MISSING_GAS = 415; +export const ERR_TX_INVALID_LEGACY_GAS = 416; +export const ERR_TX_INVALID_FEE_MARKET_GAS = 417; +export const ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = 418; +export const ERR_TX_INVALID_LEGACY_FEE_MARKET = 419; +export const ERR_TX_INVALID_OBJECT = 420; +export const ERR_TX_INVALID_NONCE_OR_CHAIN_ID = 421; +export const ERR_TX_UNABLE_TO_POPULATE_NONCE = 422; +export const ERR_TX_UNSUPPORTED_EIP_1559 = 423; +export const ERR_TX_UNSUPPORTED_TYPE = 424; +export const ERR_TX_DATA_AND_INPUT = 425; +export const ERR_TX_POLLING_TIMEOUT = 426; +export const ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = 427; +export const ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = 428; +export const ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = 429; +export const ERR_TX_NOT_FOUND = 430; +export const ERR_TX_SEND_TIMEOUT = 431; +export const ERR_TX_BLOCK_TIMEOUT = 432; +export const ERR_TX_SIGNING = 433; +export const ERR_TX_GAS_MISMATCH = 434; +export const ERR_TX_CHAIN_MISMATCH = 435; +export const ERR_TX_HARDFORK_MISMATCH = 436; +export const ERR_TX_INVALID_RECEIVER = 437; +export const ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = 438; +export const ERR_TX_INVALID_PROPERTIES_FOR_TYPE = 439; +export const ERR_TX_MISSING_GAS_INNER_ERROR = 440; +export const ERR_TX_GAS_MISMATCH_INNER_ERROR = 441; +// Connection error codes +export const ERR_CONN = 500; +export const ERR_CONN_INVALID = 501; +export const ERR_CONN_TIMEOUT = 502; +export const ERR_CONN_NOT_OPEN = 503; +export const ERR_CONN_CLOSE = 504; +export const ERR_CONN_MAX_ATTEMPTS = 505; +export const ERR_CONN_PENDING_REQUESTS = 506; +export const ERR_REQ_ALREADY_SENT = 507; +// Provider error codes +export const ERR_PROVIDER = 600; +export const ERR_INVALID_PROVIDER = 601; +export const ERR_INVALID_CLIENT = 602; +export const ERR_SUBSCRIPTION = 603; +export const ERR_WS_PROVIDER = 604; +// Account error codes +export const ERR_PRIVATE_KEY_LENGTH = 701; +export const ERR_INVALID_PRIVATE_KEY = 702; +export const ERR_UNSUPPORTED_KDF = 703; +export const ERR_KEY_DERIVATION_FAIL = 704; +export const ERR_KEY_VERSION_UNSUPPORTED = 705; +export const ERR_INVALID_PASSWORD = 706; +export const ERR_IV_LENGTH = 707; +export const ERR_INVALID_KEYSTORE = 708; +export const ERR_PBKDF2_ITERATIONS = 709; +// Signature error codes +export const ERR_SIGNATURE_FAILED = 801; +export const ERR_INVALID_SIGNATURE = 802; +export const GENESIS_BLOCK_NUMBER = '0x0'; +// RPC error codes (EIP-1193) +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors +export const JSONRPC_ERR_REJECTED_REQUEST = 4001; +export const JSONRPC_ERR_UNAUTHORIZED = 4100; +export const JSONRPC_ERR_UNSUPPORTED_METHOD = 4200; +export const JSONRPC_ERR_DISCONNECTED = 4900; +export const JSONRPC_ERR_CHAIN_DISCONNECTED = 4901; +// ENS error codes +export const ERR_ENS_CHECK_INTERFACE_SUPPORT = 901; +export const ERR_ENS_UNSUPPORTED_NETWORK = 902; +export const ERR_ENS_NETWORK_NOT_SYNCED = 903; +// Utils error codes +export const ERR_INVALID_STRING = 1001; +export const ERR_INVALID_BYTES = 1002; +export const ERR_INVALID_NUMBER = 1003; +export const ERR_INVALID_UNIT = 1004; +export const ERR_INVALID_ADDRESS = 1005; +export const ERR_INVALID_HEX = 1006; +export const ERR_INVALID_TYPE = 1007; +export const ERR_INVALID_BOOLEAN = 1008; +export const ERR_INVALID_UNSIGNED_INTEGER = 1009; +export const ERR_INVALID_SIZE = 1010; +export const ERR_INVALID_LARGE_VALUE = 1011; +export const ERR_INVALID_BLOCK = 1012; +export const ERR_INVALID_TYPE_ABI = 1013; +export const ERR_INVALID_NIBBLE_WIDTH = 1014; +// Validation error codes +export const ERR_VALIDATION = 1100; +// Core error codes +export const ERR_CORE_HARDFORK_MISMATCH = 1101; +export const ERR_CORE_CHAIN_MISMATCH = 1102; +// Schema error codes +export const ERR_SCHEMA_FORMAT = 1200; +// RPC error codes (EIP-1474) +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md +export const ERR_RPC_INVALID_JSON = -32700; +export const ERR_RPC_INVALID_REQUEST = -32600; +export const ERR_RPC_INVALID_METHOD = -32601; +export const ERR_RPC_INVALID_PARAMS = -32602; +export const ERR_RPC_INTERNAL_ERROR = -32603; +export const ERR_RPC_INVALID_INPUT = -32000; +export const ERR_RPC_MISSING_RESOURCE = -32001; +export const ERR_RPC_UNAVAILABLE_RESOURCE = -32002; +export const ERR_RPC_TRANSACTION_REJECTED = -32003; +export const ERR_RPC_UNSUPPORTED_METHOD = -32004; +export const ERR_RPC_LIMIT_EXCEEDED = -32005; +export const ERR_RPC_NOT_SUPPORTED = -32006; +//# sourceMappingURL=error_codes.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/error_codes.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/error_codes.js.map new file mode 100644 index 0000000..90f695d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/error_codes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error_codes.js","sourceRoot":"","sources":["../../src/error_codes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,iBAAiB;AACjB,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,CAAC;AAChC,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAExC,iBAAiB;AACjB,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,CAAC;AAC7B,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAClC,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAC9C,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AACzC,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AACpC,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,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0B,GAAG,CAAC,KAAK,CAAC;AACjD,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,KAAK,CAAC;AAC7C,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/account_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/account_errors.js new file mode 100644 index 0000000..f727198 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/account_errors.js @@ -0,0 +1,74 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +import { ERR_PRIVATE_KEY_LENGTH, ERR_INVALID_PRIVATE_KEY, ERR_INVALID_SIGNATURE, ERR_UNSUPPORTED_KDF, ERR_KEY_DERIVATION_FAIL, ERR_KEY_VERSION_UNSUPPORTED, ERR_INVALID_PASSWORD, ERR_IV_LENGTH, ERR_PBKDF2_ITERATIONS, } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export class PrivateKeyLengthError extends BaseWeb3Error { + constructor() { + super(`Private key must be 32 bytes.`); + this.code = ERR_PRIVATE_KEY_LENGTH; + } +} +export class InvalidPrivateKeyError extends BaseWeb3Error { + constructor() { + super(`Invalid Private Key, Not a valid string or uint8Array`); + this.code = ERR_INVALID_PRIVATE_KEY; + } +} +export class InvalidSignatureError extends BaseWeb3Error { + constructor(errorDetails) { + super(`"${errorDetails}"`); + this.code = ERR_INVALID_SIGNATURE; + } +} +export class InvalidKdfError extends BaseWeb3Error { + constructor() { + super(`Invalid key derivation function`); + this.code = ERR_UNSUPPORTED_KDF; + } +} +export class KeyDerivationError extends BaseWeb3Error { + constructor() { + super(`Key derivation failed - possibly wrong password`); + this.code = ERR_KEY_DERIVATION_FAIL; + } +} +export class KeyStoreVersionError extends BaseWeb3Error { + constructor() { + super('Unsupported key store version'); + this.code = ERR_KEY_VERSION_UNSUPPORTED; + } +} +export class InvalidPasswordError extends BaseWeb3Error { + constructor() { + super('Password cannot be empty'); + this.code = ERR_INVALID_PASSWORD; + } +} +export class IVLengthError extends BaseWeb3Error { + constructor() { + super('Initialization vector must be 16 bytes'); + this.code = ERR_IV_LENGTH; + } +} +export class PBKDF2IterationsError extends BaseWeb3Error { + constructor() { + super('c > 1000, pbkdf2 is less secure with less iterations'); + this.code = ERR_PBKDF2_ITERATIONS; + } +} +//# sourceMappingURL=account_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/account_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/account_errors.js.map new file mode 100644 index 0000000..9bc061f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/account_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"account_errors.js","sourceRoot":"","sources":["../../../src/errors/account_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,yCAAyC;AAEzC,OAAO,EACN,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,EACvB,2BAA2B,EAC3B,oBAAoB,EACpB,aAAa,EACb,qBAAqB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,OAAO,qBAAsB,SAAQ,aAAa;IAEvD;QACC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAFjC,SAAI,GAAG,sBAAsB,CAAC;IAGrC,CAAC;CACD;AAED,MAAM,OAAO,sBAAuB,SAAQ,aAAa;IAExD;QACC,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAFzD,SAAI,GAAG,uBAAuB,CAAC;IAGtC,CAAC;CACD;AAED,MAAM,OAAO,qBAAsB,SAAQ,aAAa;IAEvD,YAAmB,YAAoB;QACtC,KAAK,CAAC,IAAI,YAAY,GAAG,CAAC,CAAC;QAFrB,SAAI,GAAG,qBAAqB,CAAC;IAGpC,CAAC;CACD;AAED,MAAM,OAAO,eAAgB,SAAQ,aAAa;IAEjD;QACC,KAAK,CAAC,iCAAiC,CAAC,CAAC;QAFnC,SAAI,GAAG,mBAAmB,CAAC;IAGlC,CAAC;CACD;AAED,MAAM,OAAO,kBAAmB,SAAQ,aAAa;IAEpD;QACC,KAAK,CAAC,iDAAiD,CAAC,CAAC;QAFnD,SAAI,GAAG,uBAAuB,CAAC;IAGtC,CAAC;CACD;AAED,MAAM,OAAO,oBAAqB,SAAQ,aAAa;IAEtD;QACC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAFjC,SAAI,GAAG,2BAA2B,CAAC;IAG1C,CAAC;CACD;AAED,MAAM,OAAO,oBAAqB,SAAQ,aAAa;IAEtD;QACC,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAF5B,SAAI,GAAG,oBAAoB,CAAC;IAGnC,CAAC;CACD;AAED,MAAM,OAAO,aAAc,SAAQ,aAAa;IAE/C;QACC,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAF1C,SAAI,GAAG,aAAa,CAAC;IAG5B,CAAC;CACD;AAED,MAAM,OAAO,qBAAsB,SAAQ,aAAa;IAEvD;QACC,KAAK,CAAC,sDAAsD,CAAC,CAAC;QAFxD,SAAI,GAAG,qBAAqB,CAAC;IAGpC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/connection_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/connection_errors.js new file mode 100644 index 0000000..bcebba8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/connection_errors.js @@ -0,0 +1,83 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ERR_CONN, ERR_CONN_INVALID, ERR_CONN_TIMEOUT, ERR_CONN_NOT_OPEN, ERR_CONN_CLOSE, ERR_CONN_MAX_ATTEMPTS, ERR_CONN_PENDING_REQUESTS, ERR_REQ_ALREADY_SENT, } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export class ConnectionError extends BaseWeb3Error { + constructor(message, event) { + super(message); + this.code = ERR_CONN; + if (event) { + this.errorCode = event.code; + this.errorReason = event.reason; + } + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { errorCode: this.errorCode, errorReason: this.errorReason }); + } +} +export class InvalidConnectionError extends ConnectionError { + constructor(host, event) { + super(`CONNECTION ERROR: Couldn't connect to node ${host}.`, event); + this.host = host; + this.code = ERR_CONN_INVALID; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { host: this.host }); + } +} +export class ConnectionTimeoutError extends ConnectionError { + constructor(duration) { + super(`CONNECTION TIMEOUT: timeout of ${duration}ms achieved`); + this.duration = duration; + this.code = ERR_CONN_TIMEOUT; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { duration: this.duration }); + } +} +export class ConnectionNotOpenError extends ConnectionError { + constructor(event) { + super('Connection not open', event); + this.code = ERR_CONN_NOT_OPEN; + } +} +export class ConnectionCloseError extends ConnectionError { + constructor(event) { + var _a, _b; + super(`CONNECTION ERROR: The connection got closed with the close code ${(_a = event === null || event === void 0 ? void 0 : event.code) !== null && _a !== void 0 ? _a : ''} and the following reason string ${(_b = event === null || event === void 0 ? void 0 : event.reason) !== null && _b !== void 0 ? _b : ''}`, event); + this.code = ERR_CONN_CLOSE; + } +} +export class MaxAttemptsReachedOnReconnectingError extends ConnectionError { + constructor(numberOfAttempts) { + super(`Maximum number of reconnect attempts reached! (${numberOfAttempts})`); + this.code = ERR_CONN_MAX_ATTEMPTS; + } +} +export class PendingRequestsOnReconnectingError extends ConnectionError { + constructor() { + super('CONNECTION ERROR: Provider started to reconnect before the response got received!'); + this.code = ERR_CONN_PENDING_REQUESTS; + } +} +export class RequestAlreadySentError extends ConnectionError { + constructor(id) { + super(`Request already sent with following id: ${id}`); + this.code = ERR_REQ_ALREADY_SENT; + } +} +//# sourceMappingURL=connection_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/connection_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/connection_errors.js.map new file mode 100644 index 0000000..2574f11 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/connection_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_errors.js","sourceRoot":"","sources":["../../../src/errors/connection_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAKF,OAAO,EACN,QAAQ,EACR,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,qBAAqB,EACrB,yBAAyB,EACzB,oBAAoB,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,OAAO,eAAgB,SAAQ,aAAa;IAKjD,YAAmB,OAAe,EAAE,KAAuB;QAC1D,KAAK,CAAC,OAAO,CAAC,CAAC;QALT,SAAI,GAAG,QAAQ,CAAC;QAOtB,IAAI,KAAK,EAAE;YACV,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;YAC5B,IAAI,CAAC,WAAW,GAAG,KAAK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zD,KAAK,CACL,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;IAC5B,CAAC;CACD;AAED,MAAM,OAAO,qCAAsC,SAAQ,eAAe;IACzE,YAAmB,gBAAwB;QAC1C,KAAK,CAAC,kDAAkD,gBAAgB,GAAG,CAAC,CAAC;QAC7E,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACnC,CAAC;CACD;AAED,MAAM,OAAO,kCAAmC,SAAQ,eAAe;IACtE;QACC,KAAK,CAAC,mFAAmF,CAAC,CAAC;QAC3F,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACvC,CAAC;CACD;AAED,MAAM,OAAO,uBAAwB,SAAQ,eAAe;IAC3D,YAAmB,EAAmB;QACrC,KAAK,CAAC,2CAA2C,EAAE,EAAE,CAAC,CAAC;QACvD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IAClC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/contract_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/contract_errors.js new file mode 100644 index 0000000..4dc58b1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/contract_errors.js @@ -0,0 +1,154 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ERR_CONTRACT, ERR_CONTRACT_ABI_MISSING, ERR_CONTRACT_EXECUTION_REVERTED, ERR_CONTRACT_EVENT_NOT_EXISTS, ERR_CONTRACT_INSTANTIATION, ERR_CONTRACT_MISSING_ADDRESS, ERR_CONTRACT_MISSING_DEPLOY_DATA, ERR_CONTRACT_MISSING_FROM_ADDRESS, ERR_CONTRACT_REQUIRED_CALLBACK, ERR_CONTRACT_RESERVED_EVENT, ERR_CONTRACT_RESOLVER_MISSING, ERR_CONTRACT_TX_DATA_AND_INPUT, } from '../error_codes.js'; +import { BaseWeb3Error, InvalidValueError } from '../web3_error_base.js'; +export class Web3ContractError extends BaseWeb3Error { + constructor(message, receipt) { + super(message); + this.code = ERR_CONTRACT; + this.receipt = receipt; + } +} +export class ResolverMethodMissingError extends BaseWeb3Error { + constructor(address, name) { + super(`The resolver at ${address} does not implement requested method: "${name}".`); + this.address = address; + this.name = name; + this.code = ERR_CONTRACT_RESOLVER_MISSING; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { address: this.address, name: this.name }); + } +} +export class ContractMissingABIError extends BaseWeb3Error { + constructor() { + super('You must provide the json interface of the contract when instantiating a contract object.'); + this.code = ERR_CONTRACT_ABI_MISSING; + } +} +export class ContractOnceRequiresCallbackError extends BaseWeb3Error { + constructor() { + super('Once requires a callback as the second parameter.'); + this.code = ERR_CONTRACT_REQUIRED_CALLBACK; + } +} +export class ContractEventDoesNotExistError extends BaseWeb3Error { + constructor(eventName) { + super(`Event "${eventName}" doesn't exist in this contract.`); + this.eventName = eventName; + this.code = ERR_CONTRACT_EVENT_NOT_EXISTS; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { eventName: this.eventName }); + } +} +export class ContractReservedEventError extends BaseWeb3Error { + constructor(type) { + super(`Event "${type}" doesn't exist in this contract.`); + this.type = type; + this.code = ERR_CONTRACT_RESERVED_EVENT; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { type: this.type }); + } +} +export class ContractMissingDeployDataError extends BaseWeb3Error { + constructor() { + super(`No "data" specified in neither the given options, nor the default options.`); + this.code = ERR_CONTRACT_MISSING_DEPLOY_DATA; + } +} +export class ContractNoAddressDefinedError extends BaseWeb3Error { + constructor() { + super("This contract object doesn't have address set yet, please set an address first."); + this.code = ERR_CONTRACT_MISSING_ADDRESS; + } +} +export class ContractNoFromAddressDefinedError extends BaseWeb3Error { + constructor() { + super('No "from" address specified in neither the given options, nor the default options.'); + this.code = ERR_CONTRACT_MISSING_FROM_ADDRESS; + } +} +export class ContractInstantiationError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_CONTRACT_INSTANTIATION; + } +} +/** + * This class is expected to be set as an `innerError` inside ContractExecutionError + * The properties would be typically decoded from the `data` if it was encoded according to EIP-838 + */ +export class Eip838ExecutionError extends Web3ContractError { + constructor(error) { + super(error.message || 'Error'); + this.name = ('name' in error && error.name) || this.constructor.name; + this.stack = ('stack' in error && error.stack) || undefined; + this.code = error.code; + // get embedded error details got from some providers like MetaMask + // and set this.data from the inner error data for easier read. + // note: the data is a hex string inside either: + // error.data, error.data.data or error.data.originalError.data (https://github.com/web3/web3.js/issues/4454#issuecomment-1485953455) + if (typeof error.data === 'object') { + let originalError; + if ('originalError' in error.data) { + originalError = error.data.originalError; + } + else { + // Ganache has no `originalError` sub-object unlike others + originalError = error.data; + } + this.data = originalError.data; + this.innerError = new Eip838ExecutionError(originalError); + } + else { + this.data = error.data; + } + } + setDecodedProperties(errorName, errorSignature, errorArgs) { + this.errorName = errorName; + this.errorSignature = errorSignature; + this.errorArgs = errorArgs; + } + toJSON() { + let json = Object.assign(Object.assign({}, super.toJSON()), { data: this.data }); + if (this.errorName) { + json = Object.assign(Object.assign({}, json), { errorName: this.errorName, errorSignature: this.errorSignature, errorArgs: this.errorArgs }); + } + return json; + } +} +/** + * Used when an error is raised while executing a function inside a smart contract. + * The data is expected to be encoded according to EIP-848. + */ +export class ContractExecutionError extends Web3ContractError { + constructor(rpcError) { + super('Error happened while trying to execute a function inside a smart contract'); + this.code = ERR_CONTRACT_EXECUTION_REVERTED; + this.innerError = new Eip838ExecutionError(rpcError); + } +} +export class ContractTransactionDataAndInputError extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`data: ${(_a = value.data) !== null && _a !== void 0 ? _a : 'undefined'}, input: ${(_b = value.input) !== null && _b !== void 0 ? _b : 'undefined'}`, 'You can\'t have "data" and "input" as properties of a contract at the same time, please use either "data" or "input" instead.'); + this.code = ERR_CONTRACT_TX_DATA_AND_INPUT; + } +} +//# sourceMappingURL=contract_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/contract_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/contract_errors.js.map new file mode 100644 index 0000000..52315c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/contract_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract_errors.js","sourceRoot":"","sources":["../../../src/errors/contract_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAKF,OAAO,EACN,YAAY,EACZ,wBAAwB,EACxB,+BAA+B,EAC/B,6BAA6B,EAC7B,0BAA0B,EAC1B,4BAA4B,EAC5B,gCAAgC,EAChC,iCAAiC,EACjC,8BAA8B,EAC9B,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,GAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAEzE,MAAM,OAAO,iBAAkB,SAAQ,aAAa;IAInD,YAAmB,OAAe,EAAE,OAA4B;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QAJT,SAAI,GAAG,YAAY,CAAC;QAM1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;CACD;AACD,MAAM,OAAO,0BAA2B,SAAQ,aAAa;IAG5D,YAA0B,OAAe,EAAS,IAAY;QAC7D,KAAK,CAAC,mBAAmB,OAAO,0CAA0C,IAAI,IAAI,CAAC,CAAC;QAD3D,YAAO,GAAP,OAAO,CAAQ;QAAS,SAAI,GAAJ,IAAI,CAAQ;QAFvD,SAAI,GAAG,6BAA6B,CAAC;IAI5C,CAAC;IA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EM,oBAAoB,CAC1B,SAAiB,EACjB,cAAuB,EACvB,SAAsC;QAEtC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC5B,CAAC;IAEM,MAAM;QACZ,IAAI,IAAI,GAAG,gCACP,KAAK,CAAC,MAAM,EAAE,KACjB,IAAI,EAAE,IAAI,CAAC,IAAI,GAUf,CAAC;QAEF,IAAI,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,mCACA,IAAI,KACP,SAAS,EAAE,IAAI,CAAC,SAAS,EACzB,cAAc,EAAE,IAAI,CAAC,cAAc,EACnC,SAAS,EAAE,IAAI,CAAC,SAAS,GACzB,CAAC;SACF;QACD,OAAO,IAAI,CAAC;IACb,CAAC;CACD;AAED;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,iBAAiB;IAG5D,YAAmB,QAAsB;QACxC,KAAK,CAAC,2EAA2E,CAAC,CAAC;QACnF,IAAI,CAAC,IAAI,GAAG,+BAA+B,CAAC;QAC5C,IAAI,CAAC,UAAU,GAAG,IAAI,oBAAoB,CAAC,QAA2C,CAAC,CAAC;IACzF,CAAC;CACD;AAED,MAAM,OAAO,oCAAqC,SAAQ,iBAAiB;IAG1E,YAAmB,KAAoE;;QACtF,KAAK,CACJ,SAAS,MAAA,KAAK,CAAC,IAAI,mCAAI,WAAW,YAAY,MAAA,KAAK,CAAC,KAAK,mCAAI,WAAW,EAAE,EAC1E,+HAA+H,CAC/H,CAAC;QANI,SAAI,GAAG,8BAA8B,CAAC;IAO7C,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/core_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/core_errors.js new file mode 100644 index 0000000..e583b51 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/core_errors.js @@ -0,0 +1,32 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +import { BaseWeb3Error } from '../web3_error_base.js'; +import { ERR_CORE_HARDFORK_MISMATCH } from '../error_codes.js'; +export class ConfigHardforkMismatchError extends BaseWeb3Error { + constructor(defaultHardfork, commonHardFork) { + super(`Web3Config hardfork doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`); + this.code = ERR_CORE_HARDFORK_MISMATCH; + } +} +export class ConfigChainMismatchError extends BaseWeb3Error { + constructor(defaultHardfork, commonHardFork) { + super(`Web3Config chain doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`); + this.code = ERR_CORE_HARDFORK_MISMATCH; + } +} +//# sourceMappingURL=core_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/core_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/core_errors.js.map new file mode 100644 index 0000000..a768ad8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/core_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core_errors.js","sourceRoot":"","sources":["../../../src/errors/core_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,yCAAyC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAE/D,MAAM,OAAO,2BAA4B,SAAQ,aAAa;IAG7D,YAAmB,eAAuB,EAAE,cAAsB;QACjE,KAAK,CACJ,uDAAuD,eAAe,wBAAwB,cAAc,EAAE,CAC9G,CAAC;QALI,SAAI,GAAG,0BAA0B,CAAC;IAMzC,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,aAAa;IAG1D,YAAmB,eAAuB,EAAE,cAAsB;QACjE,KAAK,CACJ,oDAAoD,eAAe,wBAAwB,cAAc,EAAE,CAC3G,CAAC;QALI,SAAI,GAAG,0BAA0B,CAAC;IAMzC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/ens_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/ens_errors.js new file mode 100644 index 0000000..93da070 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/ens_errors.js @@ -0,0 +1,38 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +import { ERR_ENS_CHECK_INTERFACE_SUPPORT, ERR_ENS_NETWORK_NOT_SYNCED, ERR_ENS_UNSUPPORTED_NETWORK, } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export class ENSCheckInterfaceSupportError extends BaseWeb3Error { + constructor(errorDetails) { + super(`ENS resolver check interface support error. "${errorDetails}"`); + this.code = ERR_ENS_CHECK_INTERFACE_SUPPORT; + } +} +export class ENSUnsupportedNetworkError extends BaseWeb3Error { + constructor(networkType) { + super(`ENS is not supported on network ${networkType}`); + this.code = ERR_ENS_UNSUPPORTED_NETWORK; + } +} +export class ENSNetworkNotSyncedError extends BaseWeb3Error { + constructor() { + super(`Network not synced`); + this.code = ERR_ENS_NETWORK_NOT_SYNCED; + } +} +//# sourceMappingURL=ens_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/ens_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/ens_errors.js.map new file mode 100644 index 0000000..b9bbd9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/ens_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ens_errors.js","sourceRoot":"","sources":["../../../src/errors/ens_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,yCAAyC;AAEzC,OAAO,EACN,+BAA+B,EAC/B,0BAA0B,EAC1B,2BAA2B,GAC3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,OAAO,6BAA8B,SAAQ,aAAa;IAE/D,YAAmB,YAAoB;QACtC,KAAK,CAAC,gDAAgD,YAAY,GAAG,CAAC,CAAC;QAFjE,SAAI,GAAG,+BAA+B,CAAC;IAG9C,CAAC;CACD;AAED,MAAM,OAAO,0BAA2B,SAAQ,aAAa;IAE5D,YAAmB,WAAmB;QACrC,KAAK,CAAC,mCAAmC,WAAW,EAAE,CAAC,CAAC;QAFlD,SAAI,GAAG,2BAA2B,CAAC;IAG1C,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,aAAa;IAE1D;QACC,KAAK,CAAC,oBAAoB,CAAC,CAAC;QAFtB,SAAI,GAAG,0BAA0B,CAAC;IAGzC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/generic_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/generic_errors.js new file mode 100644 index 0000000..6285850 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/generic_errors.js @@ -0,0 +1,79 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +import { ERR_ABI_ENCODING, ERR_FORMATTERS, ERR_METHOD_NOT_IMPLEMENTED, ERR_OPERATION_ABORT, ERR_OPERATION_TIMEOUT, ERR_PARAM, ERR_EXISTING_PLUGIN_NAMESPACE, ERR_INVALID_METHOD_PARAMS, } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export class InvalidNumberOfParamsError extends BaseWeb3Error { + constructor(got, expected, method) { + super(`Invalid number of parameters for "${method}". Got "${got}" expected "${expected}"!`); + this.got = got; + this.expected = expected; + this.method = method; + this.code = ERR_PARAM; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { got: this.got, expected: this.expected, method: this.method }); + } +} +export class InvalidMethodParamsError extends BaseWeb3Error { + constructor(hint) { + super(`Invalid parameters passed. "${typeof hint !== 'undefined' ? hint : ''}"`); + this.hint = hint; + this.code = ERR_INVALID_METHOD_PARAMS; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { hint: this.hint }); + } +} +export class FormatterError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_FORMATTERS; + } +} +export class MethodNotImplementedError extends BaseWeb3Error { + constructor() { + super("The method you're trying to call is not implemented."); + this.code = ERR_METHOD_NOT_IMPLEMENTED; + } +} +export class OperationTimeoutError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_OPERATION_TIMEOUT; + } +} +export class OperationAbortError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_OPERATION_ABORT; + } +} +export class AbiError extends BaseWeb3Error { + constructor(message, props) { + super(message); + this.code = ERR_ABI_ENCODING; + this.props = props !== null && props !== void 0 ? props : {}; + } +} +export class ExistingPluginNamespaceError extends BaseWeb3Error { + constructor(pluginNamespace) { + super(`A plugin with the namespace: ${pluginNamespace} has already been registered.`); + this.code = ERR_EXISTING_PLUGIN_NAMESPACE; + } +} +//# sourceMappingURL=generic_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/generic_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/generic_errors.js.map new file mode 100644 index 0000000..74acc0f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/generic_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"generic_errors.js","sourceRoot":"","sources":["../../../src/errors/generic_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,yCAAyC;AAEzC,OAAO,EACN,gBAAgB,EAChB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,EACnB,qBAAqB,EACrB,SAAS,EACT,6BAA6B,EAC7B,yBAAyB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,OAAO,0BAA2B,SAAQ,aAAa;IAG5D,YAA0B,GAAW,EAAS,QAAgB,EAAS,MAAc;QACpF,KAAK,CAAC,qCAAqC,MAAM,WAAW,GAAG,eAAe,QAAQ,IAAI,CAAC,CAAC;QADnE,QAAG,GAAH,GAAG,CAAQ;QAAS,aAAQ,GAAR,QAAQ,CAAQ;QAAS,WAAM,GAAN,MAAM,CAAQ;QAF9E,SAAI,GAAG,SAAS,CAAC;IAIxB,CAAC;IAEM,MAAM;QACZ,uCACI,KAAK,CAAC,MAAM,EAAE,KACjB,GAAG,EAAE,IAAI,CAAC,GAAG,EACb,QAAQ,EAAE,IAAI,CAAC,QAAQ,EACvB,MAAM,EAAE,IAAI,CAAC,MAAM,IAClB;IACH,CAAC;CACD;AAED,M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ider_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/provider_errors.js new file mode 100644 index 0000000..01604c3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/provider_errors.js @@ -0,0 +1,51 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +import { ERR_PROVIDER, ERR_INVALID_PROVIDER, ERR_INVALID_CLIENT, ERR_SUBSCRIPTION, ERR_WS_PROVIDER, } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export class ProviderError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_PROVIDER; + } +} +export class InvalidProviderError extends BaseWeb3Error { + constructor(clientUrl) { + super(`Provider with url "${clientUrl}" is not set or invalid`); + this.clientUrl = clientUrl; + this.code = ERR_INVALID_PROVIDER; + } +} +export class InvalidClientError extends BaseWeb3Error { + constructor(clientUrl) { + super(`Client URL "${clientUrl}" is invalid.`); + this.code = ERR_INVALID_CLIENT; + } +} +export class SubscriptionError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_SUBSCRIPTION; + } +} +export class Web3WSProviderError extends BaseWeb3Error { + constructor() { + super(...arguments); + this.code = ERR_WS_PROVIDER; // this had duplicate code with generic provider + } +} +//# sourceMappingURL=provider_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/provider_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/provider_errors.js.map new file mode 100644 index 0000000..cf192cb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/provider_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider_errors.js","sourceRoot":"","sources":["../../../src/errors/provider_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,yCAAyC;AAEzC,OAAO,EACN,YAAY,EACZ,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,OAAO,aAAc,SAAQ,aAAa;IAAhD;;QACQ,SAAI,GAAG,YAAY,CAAC;IAC5B,CAAC;CAAA;AAED,MAAM,OAAO,oBAAqB,SAAQ,aAAa;IAGtD,YAA0B,SAAiB;QAC1C,KAAK,CAAC,sBAAsB,SAAS,yBAAyB,CAAC,CAAC;QADvC,cAAS,GAAT,SAAS,CAAQ;QAFpC,SAAI,GAAG,oBAAoB,CAAC;IAInC,CAAC;CACD;AAED,MAAM,OAAO,kBAAmB,SAAQ,aAAa;IAGpD,YAAmB,SAAiB;QACnC,KAAK,CAAC,eAAe,SAAS,eAAe,CAAC,CAAC;QAHzC,SAAI,GAAG,kBAAkB,CAAC;IAIjC,CAAC;CACD;AAED,MAAM,OAAO,iBAAkB,SAAQ,aAAa;IAApD;;QACQ,SAAI,GAAG,gBAAgB,CAAC;IAChC,CAAC;CAAA;AAED,MAAM,OAAO,mBAAoB,SAAQ,aAAa;IAAtD;;QACQ,SAAI,GAAG,eAAe,CAAC,CAAC,gDAAgD;IAChF,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/response_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/response_errors.js new file mode 100644 index 0000000..5ae927d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/response_errors.js @@ -0,0 +1,69 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { BaseWeb3Error } from '../web3_error_base.js'; +import { ERR_INVALID_RESPONSE, ERR_RESPONSE } from '../error_codes.js'; +// To avoid circular package dependency, copied to code here. If you update this please update same function in `json_rpc.ts` +const isResponseWithError = (response) => !Array.isArray(response) && + response.jsonrpc === '2.0' && + !!response && + // eslint-disable-next-line no-null/no-null + (response.result === undefined || response.result === null) && + // JSON RPC consider "null" as valid response + 'error' in response && + (typeof response.id === 'number' || typeof response.id === 'string'); +const buildErrorMessage = (response) => isResponseWithError(response) ? response.error.message : ''; +export class ResponseError extends BaseWeb3Error { + constructor(response, message, request) { + var _a; + super(message !== null && message !== void 0 ? message : `Returned error: ${Array.isArray(response) + ? response.map(r => buildErrorMessage(r)).join(',') + : buildErrorMessage(response)}`); + this.code = ERR_RESPONSE; + if (!message) { + this.data = Array.isArray(response) + ? response.map(r => { var _a; return (_a = r.error) === null || _a === void 0 ? void 0 : _a.data; }) + : (_a = response === null || response === void 0 ? void 0 : response.error) === null || _a === void 0 ? void 0 : _a.data; + } + this.request = request; + let errorOrErrors; + if (`error` in response) { + errorOrErrors = response.error; + } + else if (response instanceof Array) { + errorOrErrors = response.map(r => r.error); + } + this.innerError = errorOrErrors; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { data: this.data, request: this.request }); + } +} +export class InvalidResponseError extends ResponseError { + constructor(result, request) { + super(result, undefined, request); + this.code = ERR_INVALID_RESPONSE; + let errorOrErrors; + if (`error` in result) { + errorOrErrors = result.error; + } + else if (result instanceof Array) { + errorOrErrors = result.map(r => r.error); + } + this.innerError = errorOrErrors; + } +} +//# sourceMappingURL=response_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/response_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/response_errors.js.map new file mode 100644 index 0000000..dac9aed --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/response_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"response_errors.js","sourceRoot":"","sources":["../../../src/errors/response_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AASF,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEvE,6HAA6H;AAC7H,MAAM,mBAAmB,GAAG,CAC3B,QAAwC,EACM,EAAE,CAChD,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,OAAO,KAAK,KAAK;IAC1B,CAAC,CAAC,QAAQ;IACV,2CAA2C;IAC3C,CAAC,QAAQ,CAAC,MAAM,KAAK,SAAS,IAAI,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC;IAC3D,6CAA6C;IAC7C,OAAO,IAAI,QAAQ;IACnB,CAAC,OAAO,QAAQ,CAAC,EAAE,KAAK,QAAQ,IAAI,OAAO,QAAQ,CAAC,EAAE,KAAK,QAAQ,CAAC,CAAC;AAEtE,MAAM,iBAAiB,GAAG,CAAC,QAA2C,EAAU,EAAE,CACjF,mBAAmB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;AAE7D,MAAM,OAAO,aAA0D,SAAQ,aAAa;IAK3F,YACC,QAA6C,EAC7C,OAAgB,EAChB,OAAqC;;QAErC,KAAK,CACJ,OAAO,aAAP,OAAO,cAAP,OAAO,GACN,mBACC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;YACtB,CAAC,CAAC,QAAQ,CAAC,GAAG,C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,IAAI,MAAM,EAAE;YACtB,aAAa,GAAG,MAAM,CAAC,KAAqB,CAAC;SAC7C;aAAM,IAAI,MAAM,YAAY,KAAK,EAAE;YACnC,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAmB,CAAC;SAC3D;QAED,IAAI,CAAC,UAAU,GAAG,aAA4C,CAAC;IAChE,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_error_messages.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_error_messages.js new file mode 100644 index 0000000..a6c295d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_error_messages.js @@ -0,0 +1,181 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ERR_RPC_INTERNAL_ERROR, ERR_RPC_INVALID_INPUT, ERR_RPC_INVALID_JSON, ERR_RPC_INVALID_METHOD, ERR_RPC_INVALID_PARAMS, ERR_RPC_INVALID_REQUEST, ERR_RPC_LIMIT_EXCEEDED, ERR_RPC_MISSING_RESOURCE, ERR_RPC_NOT_SUPPORTED, ERR_RPC_TRANSACTION_REJECTED, ERR_RPC_UNAVAILABLE_RESOURCE, ERR_RPC_UNSUPPORTED_METHOD, JSONRPC_ERR_CHAIN_DISCONNECTED, JSONRPC_ERR_DISCONNECTED, JSONRPC_ERR_REJECTED_REQUEST, JSONRPC_ERR_UNAUTHORIZED, JSONRPC_ERR_UNSUPPORTED_METHOD, } from '../error_codes.js'; +/** + * A template string for a generic Rpc Error. The `*code*` will be replaced with the code number. + * Note: consider in next version that a spelling mistake could be corrected for `occured` and the value could be: + * `An Rpc error has occurred with a code of *code*` + */ +export const genericRpcErrorMessageTemplate = 'An Rpc error has occured with a code of *code*'; +/* eslint-disable @typescript-eslint/naming-convention */ +export const RpcErrorMessages = { + // EIP-1474 & JSON RPC 2.0 + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md + [ERR_RPC_INVALID_JSON]: { + message: 'Parse error', + description: 'Invalid JSON', + }, + [ERR_RPC_INVALID_REQUEST]: { + message: 'Invalid request', + description: 'JSON is not a valid request object ', + }, + [ERR_RPC_INVALID_METHOD]: { + message: 'Method not found', + description: 'Method does not exist ', + }, + [ERR_RPC_INVALID_PARAMS]: { + message: 'Invalid params', + description: 'Invalid method parameters', + }, + [ERR_RPC_INTERNAL_ERROR]: { + message: 'Internal error', + description: 'Internal JSON-RPC error', + }, + [ERR_RPC_INVALID_INPUT]: { + message: 'Invalid input', + description: 'Missing or invalid parameters', + }, + [ERR_RPC_MISSING_RESOURCE]: { + message: 'Resource not found', + description: 'Requested resource not found', + }, + [ERR_RPC_UNAVAILABLE_RESOURCE]: { + message: 'Resource unavailable', + description: 'Requested resource not available', + }, + [ERR_RPC_TRANSACTION_REJECTED]: { + message: 'Transaction rejected', + description: 'Transaction creation failed', + }, + [ERR_RPC_UNSUPPORTED_METHOD]: { + message: 'Method not supported', + description: 'Method is not implemented', + }, + [ERR_RPC_LIMIT_EXCEEDED]: { + message: 'Limit exceeded', + description: 'Request exceeds defined limit', + }, + [ERR_RPC_NOT_SUPPORTED]: { + message: 'JSON-RPC version not supported', + description: 'Version of JSON-RPC protocol is not supported', + }, + // EIP-1193 + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors + [JSONRPC_ERR_REJECTED_REQUEST]: { + name: 'User Rejected Request', + message: 'The user rejected the request.', + }, + [JSONRPC_ERR_UNAUTHORIZED]: { + name: 'Unauthorized', + message: 'The requested method and/or account has not been authorized by the user.', + }, + [JSONRPC_ERR_UNSUPPORTED_METHOD]: { + name: 'Unsupported Method', + message: 'The Provider does not support the requested method.', + }, + [JSONRPC_ERR_DISCONNECTED]: { + name: 'Disconnected', + message: 'The Provider is disconnected from all chains.', + }, + [JSONRPC_ERR_CHAIN_DISCONNECTED]: { + name: 'Chain Disconnected', + message: 'The Provider is not connected to the requested chain.', + }, + // EIP-1193 - CloseEvent + // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code + '0-999': { + name: '', + message: 'Not used.', + }, + 1000: { + name: 'Normal Closure', + message: 'The connection successfully completed the purpose for which it was created.', + }, + 1001: { + name: 'Going Away', + message: 'The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection.', + }, + 1002: { + name: 'Protocol error', + message: 'The endpoint is terminating the connection due to a protocol error.', + }, + 1003: { + name: 'Unsupported Data', + message: 'The connection is being terminated because the endpoint received data of a type it cannot accept. (For example, a text-only endpoint received binary data.)', + }, + 1004: { + name: 'Reserved', + message: 'Reserved. A meaning might be defined in the future.', + }, + 1005: { + name: 'No Status Rcvd', + message: 'Reserved. Indicates that no status code was provided even though one was expected.', + }, + 1006: { + name: 'Abnormal Closure', + message: 'Reserved. Indicates that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected.', + }, + 1007: { + name: 'Invalid frame payload data', + message: 'The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).', + }, + 1008: { + name: 'Policy Violation', + message: 'The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.', + }, + 1009: { + name: 'Message Too Big', + message: 'The endpoint is terminating the connection because a data frame was received that is too large.', + }, + 1010: { + name: 'Mandatory Ext.', + message: "The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't.", + }, + 1011: { + name: 'Internal Error', + message: 'The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.', + }, + 1012: { + name: 'Service Restart', + message: 'The server is terminating the connection because it is restarting.', + }, + 1013: { + name: 'Try Again Later', + message: 'The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients.', + }, + 1014: { + name: 'Bad Gateway', + message: 'The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code.', + }, + 1015: { + name: 'TLS handshake', + message: "Reserved. Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).", + }, + '1016-2999': { + name: '', + message: 'For definition by future revisions of the WebSocket Protocol specification, and for definition by extension specifications.', + }, + '3000-3999': { + name: '', + message: 'For use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by the WebSocket protocol.', + }, + '4000-4999': { + name: '', + message: "For private use, and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by the WebSocket protocol.", + }, +}; +//# sourceMappingURL=rpc_error_messages.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_error_messages.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_error_messages.js.map new file mode 100644 index 0000000..8a2ae26 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_error_messages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_error_messages.js","sourceRoot":"","sources":["../../../src/errors/rpc_error_messages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EACN,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,sBAAsB,EACtB,sBAAsB,EACtB,uBAAuB,EACvB,sBAAsB,EACtB,wBAAwB,EACxB,qBAAqB,EACrB,4BAA4B,EAC5B,4BAA4B,EAC5B,0BAA0B,EAC1B,8BAA8B,EAC9B,wBAAwB,EACxB,4BAA4B,EAC5B,wBAAwB,EACxB,8BAA8B,GAC9B,MAAM,mBAAmB,CAAC;AAE3B;;;;GAIG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAA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,IAAI,EAAE,iBAAiB;QACvB,OAAO,EACN,iGAAiG;KAClG;IACD,IAAI,EAAE;QACL,IAAI,EAAE,gBAAgB;QACtB,OAAO,EACN,oIAAoI;KACrI;IACD,IAAI,EAAE;QACL,IAAI,EAAE,gBAAgB;QACtB,OAAO,EACN,wIAAwI;KACzI;IACD,IAAI,EAAE;QACL,IAAI,EAAE,iBAAiB;QACvB,OAAO,EAAE,oEAAoE;KAC7E;IACD,IAAI,EAAE;QACL,IAAI,EAAE,iBAAiB;QACvB,OAAO,EACN,sIAAsI;KACvI;IACD,IAAI,EAAE;QACL,IAAI,EAAE,aAAa;QACnB,OAAO,EACN,iJAAiJ;KAClJ;IACD,IAAI,EAAE;QACL,IAAI,EAAE,eAAe;QACrB,OAAO,EACN,kJAAkJ;KACnJ;IACD,WAAW,EAAE;QACZ,IAAI,EAAE,EAAE;QACR,OAAO,EACN,6HAA6H;KAC9H;IACD,WAAW,EAAE;QACZ,IAAI,EAAE,EAAE;QACR,OAAO,EACN,qLAAqL;KACtL;IACD,WAAW,EAAE;QACZ,IAAI,EAAE,EAAE;QACR,OAAO,EACN,qMAAqM;KACtM;CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_errors.js new file mode 100644 index 0000000..333508a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_errors.js @@ -0,0 +1,152 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { BaseWeb3Error } from '../web3_error_base.js'; +import { ERR_RPC_INTERNAL_ERROR, ERR_RPC_INVALID_INPUT, ERR_RPC_INVALID_JSON, ERR_RPC_INVALID_METHOD, ERR_RPC_INVALID_PARAMS, ERR_RPC_INVALID_REQUEST, ERR_RPC_LIMIT_EXCEEDED, ERR_RPC_MISSING_RESOURCE, ERR_RPC_NOT_SUPPORTED, ERR_RPC_TRANSACTION_REJECTED, ERR_RPC_UNAVAILABLE_RESOURCE, ERR_RPC_UNSUPPORTED_METHOD, } from '../error_codes.js'; +import { RpcErrorMessages, genericRpcErrorMessageTemplate } from './rpc_error_messages.js'; +export class RpcError extends BaseWeb3Error { + constructor(rpcError, message) { + super(message !== null && message !== void 0 ? message : genericRpcErrorMessageTemplate.replace('*code*', rpcError.error.code.toString())); + this.code = rpcError.error.code; + this.id = rpcError.id; + this.jsonrpc = rpcError.jsonrpc; + this.jsonRpcError = rpcError.error; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { error: this.jsonRpcError, id: this.id, jsonRpc: this.jsonrpc }); + } +} +export class EIP1193ProviderRpcError extends BaseWeb3Error { + constructor(code, data) { + var _a, _b, _c, _d; + if (!code) { + // this case should ideally not happen + super(); + } + else if ((_a = RpcErrorMessages[code]) === null || _a === void 0 ? void 0 : _a.message) { + super(RpcErrorMessages[code].message); + } + else { + // Retrieve the status code object for the given code from the table, by searching through the appropriate range + const statusCodeRange = Object.keys(RpcErrorMessages).find(statusCode => typeof statusCode === 'string' && + code >= parseInt(statusCode.split('-')[0], 10) && + code <= parseInt(statusCode.split('-')[1], 10)); + super((_c = (_b = RpcErrorMessages[statusCodeRange !== null && statusCodeRange !== void 0 ? statusCodeRange : '']) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : genericRpcErrorMessageTemplate.replace('*code*', (_d = code === null || code === void 0 ? void 0 : code.toString()) !== null && _d !== void 0 ? _d : '""')); + } + this.code = code; + this.data = data; + } +} +export class ParseError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_JSON].message); + this.code = ERR_RPC_INVALID_JSON; + } +} +export class InvalidRequestError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_REQUEST].message); + this.code = ERR_RPC_INVALID_REQUEST; + } +} +export class MethodNotFoundError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_METHOD].message); + this.code = ERR_RPC_INVALID_METHOD; + } +} +export class InvalidParamsError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_PARAMS].message); + this.code = ERR_RPC_INVALID_PARAMS; + } +} +export class InternalError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INTERNAL_ERROR].message); + this.code = ERR_RPC_INTERNAL_ERROR; + } +} +export class InvalidInputError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_INPUT].message); + this.code = ERR_RPC_INVALID_INPUT; + } +} +export class MethodNotSupported extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_UNSUPPORTED_METHOD].message); + this.code = ERR_RPC_UNSUPPORTED_METHOD; + } +} +export class ResourceUnavailableError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_UNAVAILABLE_RESOURCE].message); + this.code = ERR_RPC_UNAVAILABLE_RESOURCE; + } +} +export class ResourcesNotFoundError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_MISSING_RESOURCE].message); + this.code = ERR_RPC_MISSING_RESOURCE; + } +} +export class VersionNotSupportedError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_NOT_SUPPORTED].message); + this.code = ERR_RPC_NOT_SUPPORTED; + } +} +export class TransactionRejectedError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_TRANSACTION_REJECTED].message); + this.code = ERR_RPC_TRANSACTION_REJECTED; + } +} +export class LimitExceededError extends RpcError { + constructor(rpcError) { + super(rpcError, RpcErrorMessages[ERR_RPC_LIMIT_EXCEEDED].message); + this.code = ERR_RPC_LIMIT_EXCEEDED; + } +} +export const rpcErrorsMap = new Map(); +rpcErrorsMap.set(ERR_RPC_INVALID_JSON, { error: ParseError }); +rpcErrorsMap.set(ERR_RPC_INVALID_REQUEST, { + error: InvalidRequestError, +}); +rpcErrorsMap.set(ERR_RPC_INVALID_METHOD, { + error: MethodNotFoundError, +}); +rpcErrorsMap.set(ERR_RPC_INVALID_PARAMS, { error: InvalidParamsError }); +rpcErrorsMap.set(ERR_RPC_INTERNAL_ERROR, { error: InternalError }); +rpcErrorsMap.set(ERR_RPC_INVALID_INPUT, { error: InvalidInputError }); +rpcErrorsMap.set(ERR_RPC_UNSUPPORTED_METHOD, { + error: MethodNotSupported, +}); +rpcErrorsMap.set(ERR_RPC_UNAVAILABLE_RESOURCE, { + error: ResourceUnavailableError, +}); +rpcErrorsMap.set(ERR_RPC_TRANSACTION_REJECTED, { + error: TransactionRejectedError, +}); +rpcErrorsMap.set(ERR_RPC_MISSING_RESOURCE, { + error: ResourcesNotFoundError, +}); +rpcErrorsMap.set(ERR_RPC_NOT_SUPPORTED, { + error: VersionNotSupportedError, +}); +rpcErrorsMap.set(ERR_RPC_LIMIT_EXCEEDED, { error: LimitExceededError }); +//# sourceMappingURL=rpc_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_errors.js.map new file mode 100644 index 0000000..8be79e8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/rpc_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_errors.js","sourceRoot":"","sources":["../../../src/errors/rpc_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAKF,OAAO,EAAE,aAAa,EAAE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E,YAAY,CAAC,GAAG,CAAC,0BAA0B,EAAE;IAC5C,KAAK,EAAE,kBAAkB;CACzB,CAAC,CAAC;AACH,YAAY,CAAC,GAAG,CAAC,4BAA4B,EAAE;IAC9C,KAAK,EAAE,wBAAwB;CAC/B,CAAC,CAAC;AACH,YAAY,CAAC,GAAG,CAAC,4BAA4B,EAAE;IAC9C,KAAK,EAAE,wBAAwB;CAC/B,CAAC,CAAC;AACH,YAAY,CAAC,GAAG,CAAC,wBAAwB,EAAE;IAC1C,KAAK,EAAE,sBAAsB;CAC7B,CAAC,CAAC;AACH,YAAY,CAAC,GAAG,CAAC,qBAAqB,EAAE;IACvC,KAAK,EAAE,wBAAwB;CAC/B,CAAC,CAAC;AACH,YAAY,CAAC,GAAG,CAAC,sBAAsB,EAAE,EAAE,KAAK,EAAE,kBAAkB,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/schema_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/schema_errors.js new file mode 100644 index 0000000..8b303ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/schema_errors.js @@ -0,0 +1,29 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ERR_SCHEMA_FORMAT } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export class SchemaFormatError extends BaseWeb3Error { + constructor(type) { + super(`Format for the type ${type} is unsupported`); + this.type = type; + this.code = ERR_SCHEMA_FORMAT; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { type: this.type }); + } +} +//# sourceMappingURL=schema_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/schema_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/schema_errors.js.map new file mode 100644 index 0000000..814ec37 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/schema_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schema_errors.js","sourceRoot":"","sources":["../../../src/errors/schema_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,MAAM,OAAO,iBAAkB,SAAQ,aAAa;IAGnD,YAA0B,IAAY;QACrC,KAAK,CAAC,uBAAuB,IAAI,iBAAiB,CAAC,CAAC;QAD3B,SAAI,GAAJ,IAAI,CAAQ;QAF/B,SAAI,GAAG,iBAAiB,CAAC;IAIhC,CAAC;IAEM,MAAM;QACZ,uCAAY,KAAK,CAAC,MAAM,EAAE,KAAE,IAAI,EAAE,IAAI,CAAC,IAAI,IAAG;IAC/C,CAAC;CAED"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/signature_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/signature_errors.js new file mode 100644 index 0000000..a9fa35f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/signature_errors.js @@ -0,0 +1,25 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ERR_SIGNATURE_FAILED } from '../error_codes.js'; +import { InvalidValueError } from '../web3_error_base.js'; +export class SignatureError extends InvalidValueError { + constructor() { + super(...arguments); + this.code = ERR_SIGNATURE_FAILED; + } +} +//# sourceMappingURL=signature_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/signature_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/signature_errors.js.map new file mode 100644 index 0000000..76ad47f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/signature_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signature_errors.js","sourceRoot":"","sources":["../../../src/errors/signature_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,MAAM,OAAO,cAAe,SAAQ,iBAAiB;IAArD;;QACQ,SAAI,GAAG,oBAAoB,CAAC;IACpC,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/transaction_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/transaction_errors.js new file mode 100644 index 0000000..a4716d1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/transaction_errors.js @@ -0,0 +1,323 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ERR_RAW_TX_UNDEFINED, ERR_TX, ERR_TX_BLOCK_TIMEOUT, ERR_TX_CONTRACT_NOT_STORED, ERR_TX_CHAIN_ID_MISMATCH, ERR_TX_DATA_AND_INPUT, ERR_TX_GAS_MISMATCH, ERR_TX_CHAIN_MISMATCH, ERR_TX_HARDFORK_MISMATCH, ERR_TX_INVALID_CALL, ERR_TX_INVALID_CHAIN_INFO, ERR_TX_INVALID_FEE_MARKET_GAS, ERR_TX_INVALID_FEE_MARKET_GAS_PRICE, ERR_TX_INVALID_LEGACY_FEE_MARKET, ERR_TX_INVALID_LEGACY_GAS, ERR_TX_INVALID_NONCE_OR_CHAIN_ID, ERR_TX_INVALID_OBJECT, ERR_TX_INVALID_SENDER, ERR_TX_INVALID_RECEIVER, ERR_TX_LOCAL_WALLET_NOT_AVAILABLE, ERR_TX_MISSING_CHAIN_INFO, ERR_TX_MISSING_CUSTOM_CHAIN, ERR_TX_MISSING_CUSTOM_CHAIN_ID, ERR_TX_MISSING_GAS, ERR_TX_NO_CONTRACT_ADDRESS, ERR_TX_NOT_FOUND, ERR_TX_OUT_OF_GAS, ERR_TX_POLLING_TIMEOUT, ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER, ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL, ERR_TX_REVERT_INSTRUCTION, ERR_TX_REVERT_TRANSACTION, ERR_TX_REVERT_WITHOUT_REASON, ERR_TX_SEND_TIMEOUT, ERR_TX_SIGNING, ERR_TX_UNABLE_TO_POPULATE_NONCE, ERR_TX_UNSUPPORTED_EIP_1559, ERR_TX_UNSUPPORTED_TYPE, ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR, ERR_TX_INVALID_PROPERTIES_FOR_TYPE, ERR_TX_MISSING_GAS_INNER_ERROR, ERR_TX_GAS_MISMATCH_INNER_ERROR, } from '../error_codes.js'; +import { InvalidValueError, BaseWeb3Error } from '../web3_error_base.js'; +export class TransactionError extends BaseWeb3Error { + constructor(message, receipt) { + super(message); + this.receipt = receipt; + this.code = ERR_TX; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { receipt: this.receipt }); + } +} +export class RevertInstructionError extends BaseWeb3Error { + constructor(reason, signature) { + super(`Your request got reverted with the following reason string: ${reason}`); + this.reason = reason; + this.signature = signature; + this.code = ERR_TX_REVERT_INSTRUCTION; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { reason: this.reason, signature: this.signature }); + } +} +export class TransactionRevertInstructionError extends BaseWeb3Error { + constructor(reason, signature, receipt, data) { + super(`Transaction has been reverted by the EVM${receipt === undefined ? '' : `:\n ${BaseWeb3Error.convertToString(receipt)}`}`); + this.reason = reason; + this.signature = signature; + this.receipt = receipt; + this.data = data; + this.code = ERR_TX_REVERT_TRANSACTION; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { reason: this.reason, signature: this.signature, receipt: this.receipt, data: this.data }); + } +} +/** + * This error is used when a transaction to a smart contract fails and + * a custom user error (https://blog.soliditylang.org/2021/04/21/custom-errors/) + * is able to be parsed from the revert reason + */ +export class TransactionRevertWithCustomError extends TransactionRevertInstructionError { + constructor(reason, customErrorName, customErrorDecodedSignature, customErrorArguments, signature, receipt, data) { + super(reason); + this.reason = reason; + this.customErrorName = customErrorName; + this.customErrorDecodedSignature = customErrorDecodedSignature; + this.customErrorArguments = customErrorArguments; + this.signature = signature; + this.receipt = receipt; + this.data = data; + this.code = ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { reason: this.reason, customErrorName: this.customErrorName, customErrorDecodedSignature: this.customErrorDecodedSignature, customErrorArguments: this.customErrorArguments, signature: this.signature, receipt: this.receipt, data: this.data }); + } +} +export class NoContractAddressFoundError extends TransactionError { + constructor(receipt) { + super("The transaction receipt didn't contain a contract address.", receipt); + this.code = ERR_TX_NO_CONTRACT_ADDRESS; + } + toJSON() { + return Object.assign(Object.assign({}, super.toJSON()), { receipt: this.receipt }); + } +} +export class ContractCodeNotStoredError extends TransactionError { + constructor(receipt) { + super("The contract code couldn't be stored, please check your gas limit.", receipt); + this.code = ERR_TX_CONTRACT_NOT_STORED; + } +} +export class TransactionRevertedWithoutReasonError extends TransactionError { + constructor(receipt) { + super(`Transaction has been reverted by the EVM${receipt === undefined ? '' : `:\n ${BaseWeb3Error.convertToString(receipt)}`}`, receipt); + this.code = ERR_TX_REVERT_WITHOUT_REASON; + } +} +export class TransactionOutOfGasError extends TransactionError { + constructor(receipt) { + super(`Transaction ran out of gas. Please provide more gas:\n ${JSON.stringify(receipt, undefined, 2)}`, receipt); + this.code = ERR_TX_OUT_OF_GAS; + } +} +export class UndefinedRawTransactionError extends TransactionError { + constructor() { + super(`Raw transaction undefined`); + this.code = ERR_RAW_TX_UNDEFINED; + } +} +export class TransactionNotFound extends TransactionError { + constructor() { + super('Transaction not found'); + this.code = ERR_TX_NOT_FOUND; + } +} +export class InvalidTransactionWithSender extends InvalidValueError { + constructor(value) { + super(value, 'invalid transaction with invalid sender'); + this.code = ERR_TX_INVALID_SENDER; + } +} +export class InvalidTransactionWithReceiver extends InvalidValueError { + constructor(value) { + super(value, 'invalid transaction with invalid receiver'); + this.code = ERR_TX_INVALID_RECEIVER; + } +} +export class InvalidTransactionCall extends InvalidValueError { + constructor(value) { + super(value, 'invalid transaction call'); + this.code = ERR_TX_INVALID_CALL; + } +} +export class MissingCustomChainError extends InvalidValueError { + constructor() { + super('MissingCustomChainError', 'If tx.common is provided it must have tx.common.customChain'); + this.code = ERR_TX_MISSING_CUSTOM_CHAIN; + } +} +export class MissingCustomChainIdError extends InvalidValueError { + constructor() { + super('MissingCustomChainIdError', 'If tx.common is provided it must have tx.common.customChain and tx.common.customChain.chainId'); + this.code = ERR_TX_MISSING_CUSTOM_CHAIN_ID; + } +} +export class ChainIdMismatchError extends InvalidValueError { + constructor(value) { + super(JSON.stringify(value), + // https://github.com/ChainSafe/web3.js/blob/8783f4d64e424456bdc53b34ef1142d0a7cee4d7/packages/web3-eth-accounts/src/index.js#L176 + 'Chain Id doesnt match in tx.chainId tx.common.customChain.chainId'); + this.code = ERR_TX_CHAIN_ID_MISMATCH; + } +} +export class ChainMismatchError extends InvalidValueError { + constructor(value) { + super(JSON.stringify(value), 'Chain doesnt match in tx.chain tx.common.basechain'); + this.code = ERR_TX_CHAIN_MISMATCH; + } +} +export class HardforkMismatchError extends InvalidValueError { + constructor(value) { + super(JSON.stringify(value), 'hardfork doesnt match in tx.hardfork tx.common.hardfork'); + this.code = ERR_TX_HARDFORK_MISMATCH; + } +} +export class CommonOrChainAndHardforkError extends InvalidValueError { + constructor() { + super('CommonOrChainAndHardforkError', 'Please provide the common object or the chain and hardfork property but not all together.'); + this.code = ERR_TX_INVALID_CHAIN_INFO; + } +} +export class MissingChainOrHardforkError extends InvalidValueError { + constructor(value) { + var _a, _b; + super('MissingChainOrHardforkError', `When specifying chain and hardfork, both values must be defined. Received "chain": ${(_a = value.chain) !== null && _a !== void 0 ? _a : 'undefined'}, "hardfork": ${(_b = value.hardfork) !== null && _b !== void 0 ? _b : 'undefined'}`); + this.code = ERR_TX_MISSING_CHAIN_INFO; + } +} +export class MissingGasInnerError extends BaseWeb3Error { + constructor() { + super('Missing properties in transaction, either define "gas" and "gasPrice" for type 0 transactions or "gas", "maxPriorityFeePerGas" and "maxFeePerGas" for type 2 transactions'); + this.code = ERR_TX_MISSING_GAS_INNER_ERROR; + } +} +export class MissingGasError extends InvalidValueError { + constructor(value) { + var _a, _b, _c, _d; + super(`gas: ${(_a = value.gas) !== null && _a !== void 0 ? _a : 'undefined'}, gasPrice: ${(_b = value.gasPrice) !== null && _b !== void 0 ? _b : 'undefined'}, maxPriorityFeePerGas: ${(_c = value.maxPriorityFeePerGas) !== null && _c !== void 0 ? _c : 'undefined'}, maxFeePerGas: ${(_d = value.maxFeePerGas) !== null && _d !== void 0 ? _d : 'undefined'}`, '"gas" is missing'); + this.code = ERR_TX_MISSING_GAS; + this.innerError = new MissingGasInnerError(); + } +} +export class TransactionGasMismatchInnerError extends BaseWeb3Error { + constructor() { + super('Missing properties in transaction, either define "gas" and "gasPrice" for type 0 transactions or "gas", "maxPriorityFeePerGas" and "maxFeePerGas" for type 2 transactions, not both'); + this.code = ERR_TX_GAS_MISMATCH_INNER_ERROR; + } +} +export class TransactionGasMismatchError extends InvalidValueError { + constructor(value) { + var _a, _b, _c, _d; + super(`gas: ${(_a = value.gas) !== null && _a !== void 0 ? _a : 'undefined'}, gasPrice: ${(_b = value.gasPrice) !== null && _b !== void 0 ? _b : 'undefined'}, maxPriorityFeePerGas: ${(_c = value.maxPriorityFeePerGas) !== null && _c !== void 0 ? _c : 'undefined'}, maxFeePerGas: ${(_d = value.maxFeePerGas) !== null && _d !== void 0 ? _d : 'undefined'}`, 'transaction must specify legacy or fee market gas properties, not both'); + this.code = ERR_TX_GAS_MISMATCH; + this.innerError = new TransactionGasMismatchInnerError(); + } +} +export class InvalidGasOrGasPrice extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`gas: ${(_a = value.gas) !== null && _a !== void 0 ? _a : 'undefined'}, gasPrice: ${(_b = value.gasPrice) !== null && _b !== void 0 ? _b : 'undefined'}`, 'Gas or gasPrice is lower than 0'); + this.code = ERR_TX_INVALID_LEGACY_GAS; + } +} +export class InvalidMaxPriorityFeePerGasOrMaxFeePerGas extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`maxPriorityFeePerGas: ${(_a = value.maxPriorityFeePerGas) !== null && _a !== void 0 ? _a : 'undefined'}, maxFeePerGas: ${(_b = value.maxFeePerGas) !== null && _b !== void 0 ? _b : 'undefined'}`, 'maxPriorityFeePerGas or maxFeePerGas is lower than 0'); + this.code = ERR_TX_INVALID_FEE_MARKET_GAS; + } +} +export class Eip1559GasPriceError extends InvalidValueError { + constructor(value) { + super(value, "eip-1559 transactions don't support gasPrice"); + this.code = ERR_TX_INVALID_FEE_MARKET_GAS_PRICE; + } +} +export class UnsupportedFeeMarketError extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`maxPriorityFeePerGas: ${(_a = value.maxPriorityFeePerGas) !== null && _a !== void 0 ? _a : 'undefined'}, maxFeePerGas: ${(_b = value.maxFeePerGas) !== null && _b !== void 0 ? _b : 'undefined'}`, "pre-eip-1559 transaction don't support maxFeePerGas/maxPriorityFeePerGas"); + this.code = ERR_TX_INVALID_LEGACY_FEE_MARKET; + } +} +export class InvalidTransactionObjectError extends InvalidValueError { + constructor(value) { + super(value, 'invalid transaction object'); + this.code = ERR_TX_INVALID_OBJECT; + } +} +export class InvalidNonceOrChainIdError extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`nonce: ${(_a = value.nonce) !== null && _a !== void 0 ? _a : 'undefined'}, chainId: ${(_b = value.chainId) !== null && _b !== void 0 ? _b : 'undefined'}`, 'Nonce or chainId is lower than 0'); + this.code = ERR_TX_INVALID_NONCE_OR_CHAIN_ID; + } +} +export class UnableToPopulateNonceError extends InvalidValueError { + constructor() { + super('UnableToPopulateNonceError', 'unable to populate nonce, no from address available'); + this.code = ERR_TX_UNABLE_TO_POPULATE_NONCE; + } +} +export class Eip1559NotSupportedError extends InvalidValueError { + constructor() { + super('Eip1559NotSupportedError', "Network doesn't support eip-1559"); + this.code = ERR_TX_UNSUPPORTED_EIP_1559; + } +} +export class UnsupportedTransactionTypeError extends InvalidValueError { + constructor(value) { + super(value, 'unsupported transaction type'); + this.code = ERR_TX_UNSUPPORTED_TYPE; + } +} +export class TransactionDataAndInputError extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`data: ${(_a = value.data) !== null && _a !== void 0 ? _a : 'undefined'}, input: ${(_b = value.input) !== null && _b !== void 0 ? _b : 'undefined'}`, 'You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); + this.code = ERR_TX_DATA_AND_INPUT; + } +} +export class TransactionSendTimeoutError extends BaseWeb3Error { + constructor(value) { + super(`The connected Ethereum Node did not respond within ${value.numberOfSeconds} seconds, please make sure your transaction was properly sent and you are connected to a healthy Node. Be aware that transaction might still be pending or mined!\n\tTransaction Hash: ${value.transactionHash ? value.transactionHash.toString() : 'not available'}`); + this.code = ERR_TX_SEND_TIMEOUT; + } +} +function transactionTimeoutHint(transactionHash) { + return `Please make sure your transaction was properly sent and there are no previous pending transaction for the same account. However, be aware that it might still be mined!\n\tTransaction Hash: ${transactionHash ? transactionHash.toString() : 'not available'}`; +} +export class TransactionPollingTimeoutError extends BaseWeb3Error { + constructor(value) { + super(`Transaction was not mined within ${value.numberOfSeconds} seconds. ${transactionTimeoutHint(value.transactionHash)}`); + this.code = ERR_TX_POLLING_TIMEOUT; + } +} +export class TransactionBlockTimeoutError extends BaseWeb3Error { + constructor(value) { + super(`Transaction started at ${value.starterBlockNumber} but was not mined within ${value.numberOfBlocks} blocks. ${transactionTimeoutHint(value.transactionHash)}`); + this.code = ERR_TX_BLOCK_TIMEOUT; + } +} +export class TransactionMissingReceiptOrBlockHashError extends InvalidValueError { + constructor(value) { + var _a, _b; + super(`receipt: ${JSON.stringify(value.receipt)}, blockHash: ${(_a = value.blockHash) === null || _a === void 0 ? void 0 : _a.toString()}, transactionHash: ${(_b = value.transactionHash) === null || _b === void 0 ? void 0 : _b.toString()}`, `Receipt missing or blockHash null`); + this.code = ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL; + } +} +export class TransactionReceiptMissingBlockNumberError extends InvalidValueError { + constructor(value) { + super(`receipt: ${JSON.stringify(value.receipt)}`, `Receipt missing block number`); + this.code = ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER; + } +} +export class TransactionSigningError extends BaseWeb3Error { + constructor(errorDetails) { + super(`Invalid signature. "${errorDetails}"`); + this.code = ERR_TX_SIGNING; + } +} +export class LocalWalletNotAvailableError extends InvalidValueError { + constructor() { + super('LocalWalletNotAvailableError', `Attempted to index account in local wallet, but no wallet is available`); + this.code = ERR_TX_LOCAL_WALLET_NOT_AVAILABLE; + } +} +export class InvalidPropertiesForTransactionTypeError extends BaseWeb3Error { + constructor(validationError, txType) { + const invalidPropertyNames = []; + validationError.forEach(error => invalidPropertyNames.push(error.keyword)); + super(`The following properties are invalid for the transaction type ${txType}: ${invalidPropertyNames.join(', ')}`); + this.code = ERR_TX_INVALID_PROPERTIES_FOR_TYPE; + } +} +//# sourceMappingURL=transaction_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/transaction_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/transaction_errors.js.map new file mode 100644 index 0000000..967a11f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/transaction_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction_errors.js","sourceRoot":"","sources":["../../../src/errors/transaction_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAWF,OAAO,EACN,oBAAoB,EACpB,MAAM,EACN,oBAAoB,EACpB,0BAA0B,EAC1B,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,mBAAmB,EACnB,yBAAyB,EACzB,6BAA6B,EAC7B,mCAAmC,EACnC,gCAAgC,EAChC,yBAAyB,EACzB,gCAAgC,EAChC,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,EACvB,iCAAiC,EACjC,yBAAyB,EACzB,2BAA2B,EAC3B,8BAA8B,EAC9B,kBAAkB,EAClB,0BAA0B,EAC1B,gBAAgB,EAChB,iBAAiB,EACjB,sBAAsB,EACtB,mCAAmC,EACnC,wCAAwC,EACxC,yBAAyB,EACzB,yBAAyB,EACzB,4BAA4B,EAC5B,mBAAmB,EACnB,cAAc,EACd,+BAA+B,EAC/B,2BAA2B,EAC3B,uBAAuB,EACvB,sCAAsC,EACtC,kCAAkC,EAClC,8BAA8B,EAC9B,+BAA+B,GAC/B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEzE,MAAM,OAAO,gBAAmD,SAAQ,aAAa;IAGpF,YAAmB,OAAe,EAAS,OAAqB;QAC/D,KAAK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,EAC9B,wEAAwE,CACxE,CAAC;QANI,SAAI,GAAG,iCAAiC,CAAC;IAOhD,CAAC;CACD;AACD,MAAM,OAAO,wCAAyC,SAAQ,aAAa;IAG1E,YACC,eAA4C,EAC5C,MAA6B;QAE7B,MAAM,oBAAoB,GAAa,EAAE,CAAC;QAC1C,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3E,KAAK,CACJ,iEAAiE,MAAM,KAAK,oBAAoB,CAAC,IAAI,CACpG,IAAI,CACJ,EAAE,CACH,CAAC;QAZI,SAAI,GAAG,kCAAkC,CAAC;IAajD,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/utils_errors.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/utils_errors.js new file mode 100644 index 0000000..278db61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/utils_errors.js @@ -0,0 +1,104 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +import { ERR_INVALID_BYTES, ERR_INVALID_NUMBER, ERR_INVALID_ADDRESS, ERR_INVALID_BLOCK, ERR_INVALID_BOOLEAN, ERR_INVALID_HEX, ERR_INVALID_LARGE_VALUE, ERR_INVALID_NIBBLE_WIDTH, ERR_INVALID_SIZE, ERR_INVALID_STRING, ERR_INVALID_TYPE, ERR_INVALID_TYPE_ABI, ERR_INVALID_UNIT, ERR_INVALID_UNSIGNED_INTEGER, } from '../error_codes.js'; +import { InvalidValueError } from '../web3_error_base.js'; +export class InvalidBytesError extends InvalidValueError { + constructor(value) { + super(value, 'can not parse as byte data'); + this.code = ERR_INVALID_BYTES; + } +} +export class InvalidNumberError extends InvalidValueError { + constructor(value) { + super(value, 'can not parse as number data'); + this.code = ERR_INVALID_NUMBER; + } +} +export class InvalidAddressError extends InvalidValueError { + constructor(value) { + super(value, 'invalid ethereum address'); + this.code = ERR_INVALID_ADDRESS; + } +} +export class InvalidStringError extends InvalidValueError { + constructor(value) { + super(value, 'not a valid string'); + this.code = ERR_INVALID_STRING; + } +} +export class InvalidUnitError extends InvalidValueError { + constructor(value) { + super(value, 'invalid unit'); + this.code = ERR_INVALID_UNIT; + } +} +export class HexProcessingError extends InvalidValueError { + constructor(value) { + super(value, 'can not be converted to hex'); + this.code = ERR_INVALID_HEX; + } +} +export class NibbleWidthError extends InvalidValueError { + constructor(value) { + super(value, 'value greater than the nibble width'); + this.code = ERR_INVALID_NIBBLE_WIDTH; + } +} +export class InvalidTypeError extends InvalidValueError { + constructor(value) { + super(value, 'invalid type, type not supported'); + this.code = ERR_INVALID_TYPE; + } +} +export class InvalidBooleanError extends InvalidValueError { + constructor(value) { + super(value, 'not a valid boolean.'); + this.code = ERR_INVALID_BOOLEAN; + } +} +export class InvalidUnsignedIntegerError extends InvalidValueError { + constructor(value) { + super(value, 'not a valid unsigned integer.'); + this.code = ERR_INVALID_UNSIGNED_INTEGER; + } +} +export class InvalidSizeError extends InvalidValueError { + constructor(value) { + super(value, 'invalid size given.'); + this.code = ERR_INVALID_SIZE; + } +} +export class InvalidLargeValueError extends InvalidValueError { + constructor(value) { + super(value, 'value is larger than size.'); + this.code = ERR_INVALID_LARGE_VALUE; + } +} +export class InvalidBlockError extends InvalidValueError { + constructor(value) { + super(value, 'invalid string given'); + this.code = ERR_INVALID_BLOCK; + } +} +export class InvalidTypeAbiInputError extends InvalidValueError { + constructor(value) { + super(value, 'components found but type is not tuple'); + this.code = ERR_INVALID_TYPE_ABI; + } +} +//# sourceMappingURL=utils_errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/utils_errors.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/utils_errors.js.map new file mode 100644 index 0000000..52af7ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/errors/utils_errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils_errors.js","sourceRoot":"","sources":["../../../src/errors/utils_errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,yCAAyC;AAEzC,OAAO,EACN,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,uBAAuB,EACvB,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,oBAAoB,EACpB,gBAAgB,EAChB,4BAA4B,GAC5B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,MAAM,OAAO,iBAAkB,SAAQ,iBAAiB;IAGvD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,4BAA4B,CAAC,CAAC;QAHrC,SAAI,GAAG,iBAAiB,CAAC;IAIhC,CAAC;CACD;AAED,MAAM,OAAO,kBAAmB,SAAQ,iBAAiB;IAGxD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,8BAA8B,CAAC,CAAC;QAHvC,SAAI,GAAG,kBAAkB,CAAC;IAIjC,CAAC;CACD;AAED,MAAM,OAAO,mBAAoB,SAAQ,iBAAiB;IAGzD,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,0BAA0B,CAAC,CAAC;QAHnC,SAAI,GAAG,mBAAmB,CAAC;IAIlC,CAAC;CACD;AAED,MAAM,OAAO,kBAAmB,SAAQ,iBAAiB;IAGxD,YAAmB,KAAc;QAChC,KAAK,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AAED,MAAM,OAAO,sBAAuB,SAAQ,iBAAiB;IAG5D,YAAmB,KAAc;QAChC,KAAK,CAAC,KAAK,EAAE,4BAA4B,CAAC,CAAC;QAHrC,SAAI,GAAG,uBAAuB,CAAC;IAItC,CAAC;CACD;AAED,MAAM,OAAO,iBAAkB,SAAQ,iBAAiB;IAGvD,YAAmB,KAAa;QAC/B,KAAK,CAAC,KAAK,EAAE,sBAAsB,CAAC,CAAC;QAH/B,SAAI,GAAG,iBAAiB,CAAC;IAIhC,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,iBAAiB;IAG9D,YAAmB,KAAa;QAC/B,KAAK,CAAC,KAAK,EAAE,wCAAwC,CAAC,CAAC;QAHjD,SAAI,GAAG,oBAAoB,CAAC;IAInC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/index.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/index.js new file mode 100644 index 0000000..5a96dd4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/index.js @@ -0,0 +1,33 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './error_codes.js'; +export * from './web3_error_base.js'; +export * from './errors/account_errors.js'; +export * from './errors/connection_errors.js'; +export * from './errors/contract_errors.js'; +export * from './errors/ens_errors.js'; +export * from './errors/generic_errors.js'; +export * from './errors/provider_errors.js'; +export * from './errors/signature_errors.js'; +export * from './errors/transaction_errors.js'; +export * from './errors/utils_errors.js'; +export * from './errors/response_errors.js'; +export * from './errors/core_errors.js'; +export * from './errors/rpc_errors.js'; +export * from './errors/rpc_error_messages.js'; +export * from './errors/schema_errors.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/index.js.map new file mode 100644 index 0000000..ca50395 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,0BAA0B,CAAC;AACzC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,2BAA2B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/package.json b/test/merkletreejs/node_modules/web3-errors/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/web3_error_base.js b/test/merkletreejs/node_modules/web3-errors/lib/esm/web3_error_base.js new file mode 100644 index 0000000..d98ffb6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/web3_error_base.js @@ -0,0 +1,54 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export class BaseWeb3Error extends Error { + constructor(msg, innerError) { + super(msg); + this.innerError = innerError; + this.name = this.constructor.name; + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(new.target.constructor); + } + else { + this.stack = new Error().stack; + } + } + static convertToString(value, unquotValue = false) { + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + if (value === null || value === undefined) + return 'undefined'; + const result = JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? v.toString() : v)); + return unquotValue && ['bigint', 'string'].includes(typeof value) + ? result.replace(/['\\"]+/g, '') + : result; + } + toJSON() { + return { + name: this.name, + code: this.code, + message: this.message, + innerError: this.innerError, + }; + } +} +export class InvalidValueError extends BaseWeb3Error { + constructor(value, msg) { + super(`Invalid value given "${BaseWeb3Error.convertToString(value, true)}". Error: ${msg}.`); + this.name = this.constructor.name; + } +} +//# sourceMappingURL=web3_error_base.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/esm/web3_error_base.js.map b/test/merkletreejs/node_modules/web3-errors/lib/esm/web3_error_base.js.map new file mode 100644 index 0000000..9a11c1e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/esm/web3_error_base.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_error_base.js","sourceRoot":"","sources":["../../src/web3_error_base.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAMF,MAAM,OAAgB,aAAc,SAAQ,KAAK;IAMhD,YAAmB,GAAY,EAAE,UAA4B;QAC5D,KAAK,CAAC,GAAG,CAAC,CAAC;QACX,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GA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,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACnC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/error_codes.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/error_codes.d.ts new file mode 100644 index 0000000..686e14a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/error_codes.d.ts @@ -0,0 +1,128 @@ +export declare const ERR_RESPONSE = 100; +export declare const ERR_INVALID_RESPONSE = 101; +export declare const ERR_PARAM = 200; +export declare const ERR_FORMATTERS = 201; +export declare const ERR_METHOD_NOT_IMPLEMENTED = 202; +export declare const ERR_OPERATION_TIMEOUT = 203; +export declare const ERR_OPERATION_ABORT = 204; +export declare const ERR_ABI_ENCODING = 205; +export declare const ERR_EXISTING_PLUGIN_NAMESPACE = 206; +export declare const ERR_INVALID_METHOD_PARAMS = 207; +export declare const ERR_CONTRACT = 300; +export declare const ERR_CONTRACT_RESOLVER_MISSING = 301; +export declare const ERR_CONTRACT_ABI_MISSING = 302; +export declare const ERR_CONTRACT_REQUIRED_CALLBACK = 303; +export declare const ERR_CONTRACT_EVENT_NOT_EXISTS = 304; +export declare const ERR_CONTRACT_RESERVED_EVENT = 305; +export declare const ERR_CONTRACT_MISSING_DEPLOY_DATA = 306; +export declare const ERR_CONTRACT_MISSING_ADDRESS = 307; +export declare const ERR_CONTRACT_MISSING_FROM_ADDRESS = 308; +export declare const ERR_CONTRACT_INSTANTIATION = 309; +export declare const ERR_CONTRACT_EXECUTION_REVERTED = 310; +export declare const ERR_CONTRACT_TX_DATA_AND_INPUT = 311; +export declare const ERR_TX = 400; +export declare const ERR_TX_REVERT_INSTRUCTION = 401; +export declare const ERR_TX_REVERT_TRANSACTION = 402; +export declare const ERR_TX_NO_CONTRACT_ADDRESS = 403; +export declare const ERR_TX_CONTRACT_NOT_STORED = 404; +export declare const ERR_TX_REVERT_WITHOUT_REASON = 405; +export declare const ERR_TX_OUT_OF_GAS = 406; +export declare const ERR_RAW_TX_UNDEFINED = 407; +export declare const ERR_TX_INVALID_SENDER = 408; +export declare const ERR_TX_INVALID_CALL = 409; +export declare const ERR_TX_MISSING_CUSTOM_CHAIN = 410; +export declare const ERR_TX_MISSING_CUSTOM_CHAIN_ID = 411; +export declare const ERR_TX_CHAIN_ID_MISMATCH = 412; +export declare const ERR_TX_INVALID_CHAIN_INFO = 413; +export declare const ERR_TX_MISSING_CHAIN_INFO = 414; +export declare const ERR_TX_MISSING_GAS = 415; +export declare const ERR_TX_INVALID_LEGACY_GAS = 416; +export declare const ERR_TX_INVALID_FEE_MARKET_GAS = 417; +export declare const ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = 418; +export declare const ERR_TX_INVALID_LEGACY_FEE_MARKET = 419; +export declare const ERR_TX_INVALID_OBJECT = 420; +export declare const ERR_TX_INVALID_NONCE_OR_CHAIN_ID = 421; +export declare const ERR_TX_UNABLE_TO_POPULATE_NONCE = 422; +export declare const ERR_TX_UNSUPPORTED_EIP_1559 = 423; +export declare const ERR_TX_UNSUPPORTED_TYPE = 424; +export declare const ERR_TX_DATA_AND_INPUT = 425; +export declare const ERR_TX_POLLING_TIMEOUT = 426; +export declare const ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = 427; +export declare const ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = 428; +export declare const ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = 429; +export declare const ERR_TX_NOT_FOUND = 430; +export declare const ERR_TX_SEND_TIMEOUT = 431; +export declare const ERR_TX_BLOCK_TIMEOUT = 432; +export declare const ERR_TX_SIGNING = 433; +export declare const ERR_TX_GAS_MISMATCH = 434; +export declare const ERR_TX_CHAIN_MISMATCH = 435; +export declare const ERR_TX_HARDFORK_MISMATCH = 436; +export declare const ERR_TX_INVALID_RECEIVER = 437; +export declare const ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = 438; +export declare const ERR_TX_INVALID_PROPERTIES_FOR_TYPE = 439; +export declare const ERR_TX_MISSING_GAS_INNER_ERROR = 440; +export declare const ERR_TX_GAS_MISMATCH_INNER_ERROR = 441; +export declare const ERR_CONN = 500; +export declare const ERR_CONN_INVALID = 501; +export declare const ERR_CONN_TIMEOUT = 502; +export declare const ERR_CONN_NOT_OPEN = 503; +export declare const ERR_CONN_CLOSE = 504; +export declare const ERR_CONN_MAX_ATTEMPTS = 505; +export declare const ERR_CONN_PENDING_REQUESTS = 506; +export declare const ERR_REQ_ALREADY_SENT = 507; +export declare const ERR_PROVIDER = 600; +export declare const ERR_INVALID_PROVIDER = 601; +export declare const ERR_INVALID_CLIENT = 602; +export declare const ERR_SUBSCRIPTION = 603; +export declare const ERR_WS_PROVIDER = 604; +export declare const ERR_PRIVATE_KEY_LENGTH = 701; +export declare const ERR_INVALID_PRIVATE_KEY = 702; +export declare const ERR_UNSUPPORTED_KDF = 703; +export declare const ERR_KEY_DERIVATION_FAIL = 704; +export declare const ERR_KEY_VERSION_UNSUPPORTED = 705; +export declare const ERR_INVALID_PASSWORD = 706; +export declare const ERR_IV_LENGTH = 707; +export declare const ERR_INVALID_KEYSTORE = 708; +export declare const ERR_PBKDF2_ITERATIONS = 709; +export declare const ERR_SIGNATURE_FAILED = 801; +export declare const ERR_INVALID_SIGNATURE = 802; +export declare const GENESIS_BLOCK_NUMBER = "0x0"; +export declare const JSONRPC_ERR_REJECTED_REQUEST = 4001; +export declare const JSONRPC_ERR_UNAUTHORIZED = 4100; +export declare const JSONRPC_ERR_UNSUPPORTED_METHOD = 4200; +export declare const JSONRPC_ERR_DISCONNECTED = 4900; +export declare const JSONRPC_ERR_CHAIN_DISCONNECTED = 4901; +export declare const ERR_ENS_CHECK_INTERFACE_SUPPORT = 901; +export declare const ERR_ENS_UNSUPPORTED_NETWORK = 902; +export declare const ERR_ENS_NETWORK_NOT_SYNCED = 903; +export declare const ERR_INVALID_STRING = 1001; +export declare const ERR_INVALID_BYTES = 1002; +export declare const ERR_INVALID_NUMBER = 1003; +export declare const ERR_INVALID_UNIT = 1004; +export declare const ERR_INVALID_ADDRESS = 1005; +export declare const ERR_INVALID_HEX = 1006; +export declare const ERR_INVALID_TYPE = 1007; +export declare const ERR_INVALID_BOOLEAN = 1008; +export declare const ERR_INVALID_UNSIGNED_INTEGER = 1009; +export declare const ERR_INVALID_SIZE = 1010; +export declare const ERR_INVALID_LARGE_VALUE = 1011; +export declare const ERR_INVALID_BLOCK = 1012; +export declare const ERR_INVALID_TYPE_ABI = 1013; +export declare const ERR_INVALID_NIBBLE_WIDTH = 1014; +export declare const ERR_VALIDATION = 1100; +export declare const ERR_CORE_HARDFORK_MISMATCH = 1101; +export declare const ERR_CORE_CHAIN_MISMATCH = 1102; +export declare const ERR_SCHEMA_FORMAT = 1200; +export declare const ERR_RPC_INVALID_JSON = -32700; +export declare const ERR_RPC_INVALID_REQUEST = -32600; +export declare const ERR_RPC_INVALID_METHOD = -32601; +export declare const ERR_RPC_INVALID_PARAMS = -32602; +export declare const ERR_RPC_INTERNAL_ERROR = -32603; +export declare const ERR_RPC_INVALID_INPUT = -32000; +export declare const ERR_RPC_MISSING_RESOURCE = -32001; +export declare const ERR_RPC_UNAVAILABLE_RESOURCE = -32002; +export declare const ERR_RPC_TRANSACTION_REJECTED = -32003; +export declare const ERR_RPC_UNSUPPORTED_METHOD = -32004; +export declare const ERR_RPC_LIMIT_EXCEEDED = -32005; +export declare const ERR_RPC_NOT_SUPPORTED = -32006; +//# sourceMappingURL=error_codes.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/error_codes.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/error_codes.d.ts.map new file mode 100644 index 0000000..755832d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/error_codes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error_codes.d.ts","sourceRoot":"","sources":["../../src/error_codes.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,YAAY,MAAM,CAAC;A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web3-errors/lib/types/errors/account_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/account_errors.d.ts new file mode 100644 index 0000000..c8b79ac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/account_errors.d.ts @@ -0,0 +1,38 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class PrivateKeyLengthError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class InvalidPrivateKeyError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class InvalidSignatureError extends BaseWeb3Error { + code: number; + constructor(errorDetails: string); +} +export declare class InvalidKdfError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class KeyDerivationError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class KeyStoreVersionError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class InvalidPasswordError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class IVLengthError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class PBKDF2IterationsError extends BaseWeb3Error { + code: number; + constructor(); +} +//# sourceMappingURL=account_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/account_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/account_errors.d.ts.map new file mode 100644 index 0000000..e57b5d3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/account_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"account_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/account_errors.ts"],"names":[],"mappings":"AA8BA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,qBAAa,qBAAsB,SAAQ,aAAa;IAChD,IAAI,SAA0B;;CAIrC;AAED,qBAAa,sBAAuB,SAAQ,aAAa;IACjD,IAAI,SAA2B;;CAItC;AAED,qBAAa,qBAAsB,SAAQ,aAAa;IAChD,IAAI,SAAyB;gBACjB,YAAY,EAAE,MAAM;CAGvC;AAED,qBAAa,eAAgB,SAAQ,aAAa;IAC1C,IAAI,SAAuB;;CAIlC;AAED,qBAAa,kBAAmB,SAAQ,aAAa;IAC7C,IAAI,SAA2B;;CAItC;AAED,qBAAa,oBAAqB,SAAQ,aAAa;IAC/C,IAAI,SAA+B;;CAI1C;AAED,qBAAa,oBAAqB,SAAQ,aAAa;IAC/C,IAAI,SAAwB;;CAInC;AAED,qBAAa,aAAc,SAAQ,aAAa;IACxC,IAAI,SAAiB;;CAI5B;AAED,qBAAa,qBAAsB,SAAQ,aAAa;IAChD,IAAI,SAAyB;;CAIpC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/connection_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/connection_errors.d.ts new file mode 100644 index 0000000..4d8f14c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/connection_errors.d.ts @@ -0,0 +1,58 @@ +import { ConnectionEvent } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ConnectionError extends BaseWeb3Error { + code: number; + errorCode?: number; + errorReason?: string; + constructor(message: string, event?: ConnectionEvent); + toJSON(): { + errorCode: number | undefined; + errorReason: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class InvalidConnectionError extends ConnectionError { + host: string; + constructor(host: string, event?: ConnectionEvent); + toJSON(): { + host: string; + errorCode: number | undefined; + errorReason: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ConnectionTimeoutError extends ConnectionError { + duration: number; + constructor(duration: number); + toJSON(): { + duration: number; + errorCode: number | undefined; + errorReason: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ConnectionNotOpenError extends ConnectionError { + constructor(event?: ConnectionEvent); +} +export declare class ConnectionCloseError extends ConnectionError { + constructor(event?: ConnectionEvent); +} +export declare class MaxAttemptsReachedOnReconnectingError extends ConnectionError { + constructor(numberOfAttempts: number); +} +export declare class PendingRequestsOnReconnectingError extends ConnectionError { + constructor(); +} +export declare class RequestAlreadySentError extends ConnectionError { + constructor(id: number | string); +} +//# sourceMappingURL=connection_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/connection_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/connection_errors.d.ts.map new file mode 100644 index 0000000..aa21012 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/connection_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/connection_errors.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAW7C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,qBAAa,eAAgB,SAAQ,aAAa;IAC1C,IAAI,SAAY;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;gBAET,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,eAAe;IASpD,MAAM;;;;;;;;CAGb;AAED,qBAAa,sBAAuB,SAAQ,eAAe;IAChC,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,eAAe;IAKxD,MAAM;;;;;;;;;CAGb;AAED,qBAAa,sBAAuB,SAAQ,eAAe;IAChC,QAAQ,EAAE,MAAM;gBAAhB,QAAQ,EAAE,MAAM;IAKnC,MAAM;;;;;;;;;CAGb;AAED,qBAAa,sBAAuB,SAAQ,eAAe;gBACvC,KAAK,CAAC,EAAE,eAAe;CAI1C;AAED,qBAAa,oBAAqB,SAAQ,eAAe;gBACrC,KAAK,CAAC,EAAE,eAAe;CAS1C;AAED,qBAAa,qCAAsC,SAAQ,eAAe;gBACtD,gBAAgB,EAAE,MAAM;CAI3C;AAED,qBAAa,kCAAmC,SAAQ,eAAe;;CAKtE;AAED,qBAAa,uBAAwB,SAAQ,eAAe;gBACxC,EAAE,EAAE,MAAM,GAAG,MAAM;CAItC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/contract_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/contract_errors.d.ts new file mode 100644 index 0000000..5000362 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/contract_errors.d.ts @@ -0,0 +1,121 @@ +import { JsonRpcError, TransactionReceipt, HexString } from 'web3-types'; +import { BaseWeb3Error, InvalidValueError } from '../web3_error_base.js'; +export declare class Web3ContractError extends BaseWeb3Error { + code: number; + receipt?: TransactionReceipt; + constructor(message: string, receipt?: TransactionReceipt); +} +export declare class ResolverMethodMissingError extends BaseWeb3Error { + address: string; + name: string; + code: number; + constructor(address: string, name: string); + toJSON(): { + address: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractMissingABIError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractOnceRequiresCallbackError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractEventDoesNotExistError extends BaseWeb3Error { + eventName: string; + code: number; + constructor(eventName: string); + toJSON(): { + eventName: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractReservedEventError extends BaseWeb3Error { + type: string; + code: number; + constructor(type: string); + toJSON(): { + type: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractMissingDeployDataError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractNoAddressDefinedError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractNoFromAddressDefinedError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class ContractInstantiationError extends BaseWeb3Error { + code: number; +} +export declare type ProviderErrorData = HexString | { + data: HexString; +} | { + originalError: { + data: HexString; + }; +}; +/** + * This class is expected to be set as an `innerError` inside ContractExecutionError + * The properties would be typically decoded from the `data` if it was encoded according to EIP-838 + */ +export declare class Eip838ExecutionError extends Web3ContractError { + readonly name: string; + code: number; + data?: HexString; + errorName?: string; + errorSignature?: string; + errorArgs?: { + [K in string]: unknown; + }; + innerError: Eip838ExecutionError | undefined; + constructor(error: JsonRpcError | Eip838ExecutionError); + setDecodedProperties(errorName: string, errorSignature?: string, errorArgs?: { + [K in string]: unknown; + }): void; + toJSON(): { + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + data: string; + errorName?: string | undefined; + errorSignature?: string | undefined; + errorArgs?: { + [x: string]: unknown; + } | undefined; + }; +} +/** + * Used when an error is raised while executing a function inside a smart contract. + * The data is expected to be encoded according to EIP-848. + */ +export declare class ContractExecutionError extends Web3ContractError { + innerError: Eip838ExecutionError; + constructor(rpcError: JsonRpcError); +} +export declare class ContractTransactionDataAndInputError extends InvalidValueError { + code: number; + constructor(value: { + data: HexString | undefined; + input: HexString | undefined; + }); +} +//# sourceMappingURL=contract_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/contract_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/contract_errors.d.ts.map new file mode 100644 index 0000000..a5efa86 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/contract_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"contract_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/contract_errors.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAezE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAEzE,qBAAa,iBAAkB,SAAQ,aAAa;IAC5C,IAAI,SAAgB;IACpB,OAAO,CAAC,EAAE,kBAAkB,CAAC;gBAEjB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,kBAAkB;CAKhE;AACD,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M,GAAG,OAAO;KAAE,CAAC;IAGvC,UAAU,EAAE,oBAAoB,GAAG,SAAS,CAAC;gBAEjC,KAAK,EAAE,YAAY,CAAC,iBAAiB,CAAC,GAAG,oBAAoB;IA4BzE,oBAAoB,CAC1B,SAAS,EAAE,MAAM,EACjB,cAAc,CAAC,EAAE,MAAM,EACvB,SAAS,CAAC,EAAE;SAAG,CAAC,IAAI,MAAM,GAAG,OAAO;KAAE;IAOhC,MAAM;cAKL,MAAM;cACN,MAAM;iBACH,MAAM;oBACH,KAAK,GAAG,KAAK,EAAE,GAAG,SAAS;cACjC,MAAM;;;;;;;CAgBd;AAED;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,iBAAiB;IACrD,UAAU,EAAE,oBAAoB,CAAC;gBAErB,QAAQ,EAAE,YAAY;CAKzC;AAED,qBAAa,oCAAqC,SAAQ,iBAAiB;IACnE,IAAI,SAAkC;gBAE1B,KAAK,EAAE;QAAE,IAAI,EAAE,SAAS,GAAG,SAAS,CAAC;QAAC,KAAK,EAAE,SAAS,GAAG,SAAS,CAAA;KAAE;CAMvF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/core_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/core_errors.d.ts new file mode 100644 index 0000000..2348798 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/core_errors.d.ts @@ -0,0 +1,10 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ConfigHardforkMismatchError extends BaseWeb3Error { + code: number; + constructor(defaultHardfork: string, commonHardFork: string); +} +export declare class ConfigChainMismatchError extends BaseWeb3Error { + code: number; + constructor(defaultHardfork: string, commonHardFork: string); +} +//# sourceMappingURL=core_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/core_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/core_errors.d.ts.map new file mode 100644 index 0000000..4df0453 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/core_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"core_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/core_errors.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAGtD,qBAAa,2BAA4B,SAAQ,aAAa;IACtD,IAAI,SAA8B;gBAEtB,eAAe,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM;CAKlE;AAED,qBAAa,wBAAyB,SAAQ,aAAa;IACnD,IAAI,SAA8B;gBAEtB,eAAe,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM;CAKlE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/ens_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/ens_errors.d.ts new file mode 100644 index 0000000..95b8b17 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/ens_errors.d.ts @@ -0,0 +1,14 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ENSCheckInterfaceSupportError extends BaseWeb3Error { + code: number; + constructor(errorDetails: string); +} +export declare class ENSUnsupportedNetworkError extends BaseWeb3Error { + code: number; + constructor(networkType: string); +} +export declare class ENSNetworkNotSyncedError extends BaseWeb3Error { + code: number; + constructor(); +} +//# sourceMappingURL=ens_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/ens_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/ens_errors.d.ts.map new file mode 100644 index 0000000..fc6326c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/ens_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ens_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/ens_errors.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,qBAAa,6BAA8B,SAAQ,aAAa;IACxD,IAAI,SAAmC;gBAC3B,YAAY,EAAE,MAAM;CAGvC;AAED,qBAAa,0BAA2B,SAAQ,aAAa;IACrD,IAAI,SAA+B;gBACvB,WAAW,EAAE,MAAM;CAGtC;AAED,qBAAa,wBAAyB,SAAQ,aAAa;IACnD,IAAI,SAA8B;;CAIzC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/generic_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/generic_errors.d.ts new file mode 100644 index 0000000..6e397da --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/generic_errors.d.ts @@ -0,0 +1,56 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class InvalidNumberOfParamsError extends BaseWeb3Error { + got: number; + expected: number; + method: string; + code: number; + constructor(got: number, expected: number, method: string); + toJSON(): { + got: number; + expected: number; + method: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class InvalidMethodParamsError extends BaseWeb3Error { + hint?: string | undefined; + code: number; + constructor(hint?: string | undefined); + toJSON(): { + hint: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class FormatterError extends BaseWeb3Error { + code: number; +} +export declare class MethodNotImplementedError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class OperationTimeoutError extends BaseWeb3Error { + code: number; +} +export declare class OperationAbortError extends BaseWeb3Error { + code: number; +} +export declare class AbiError extends BaseWeb3Error { + code: number; + readonly props: Record & { + name?: string; + }; + constructor(message: string, props?: Record & { + name?: string; + }); +} +export declare class ExistingPluginNamespaceError extends BaseWeb3Error { + code: number; + constructor(pluginNamespace: string); +} +//# sourceMappingURL=generic_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/generic_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/generic_errors.d.ts.map new file mode 100644 index 0000000..a388d5c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/generic_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"generic_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/generic_errors.ts"],"names":[],"mappings":"AA6BA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,qBAAa,0BAA2B,SAAQ,aAAa;IAGlC,GAAG,EAAE,MAAM;IAAS,QAAQ,EAAE,MAAM;IAAS,MAAM,EAAE,MAAM;IAF9E,IAAI,SAAa;gBAEE,GAAG,EAAE,MAAM,EAAS,QAAQ,EAAE,MAAM,EAAS,MAAM,EAAE,MAAM;IAI9E,MAAM;;;;;;;;;CAQb;AAED,qBAAa,wBAAyB,SAAQ,aAAa;IAGhC,IAAI,CAAC;IAFxB,IAAI,SAA6B;gBAEd,IAAI,CAAC,oBAAQ;IAIhC,MAAM;;;;;;;CAMb;AAED,qBAAa,cAAe,SAAQ,aAAa;IACzC,IAAI,SAAkB;CAC7B;AAED,qBAAa,yBAA0B,SAAQ,aAAa;IACpD,IAAI,SAA8B;;CAKzC;AAED,qBAAa,qBAAsB,SAAQ,aAAa;IAChD,IAAI,SAAyB;CACpC;AAED,qBAAa,mBAAoB,SAAQ,aAAa;IAC9C,IAAI,SAAuB;CAClC;AAED,qBAAa,QAAS,SAAQ,aAAa;IACnC,IAAI,SAAoB;IAC/B,SAAgB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;gBAEhD,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE;CAIvF;AAED,qBAAa,4BAA6B,SAAQ,aAAa;IACvD,IAAI,SAAiC;gBAEzB,eAAe,EAAE,MAAM;CAG1C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/provider_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/provider_errors.d.ts new file mode 100644 index 0000000..4da6f4c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/provider_errors.d.ts @@ -0,0 +1,20 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ProviderError extends BaseWeb3Error { + code: number; +} +export declare class InvalidProviderError extends BaseWeb3Error { + clientUrl: string; + code: number; + constructor(clientUrl: string); +} +export declare class InvalidClientError extends BaseWeb3Error { + code: number; + constructor(clientUrl: string); +} +export declare class SubscriptionError extends BaseWeb3Error { + code: number; +} +export declare class Web3WSProviderError extends BaseWeb3Error { + code: number; +} +//# sourceMappingURL=provider_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/provider_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/provider_errors.d.ts.map new file mode 100644 index 0000000..caee0fe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/provider_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/provider_errors.ts"],"names":[],"mappings":"AA0BA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,qBAAa,aAAc,SAAQ,aAAa;IACxC,IAAI,SAAgB;CAC3B;AAED,qBAAa,oBAAqB,SAAQ,aAAa;IAG5B,SAAS,EAAE,MAAM;IAFpC,IAAI,SAAwB;gBAET,SAAS,EAAE,MAAM;CAG3C;AAED,qBAAa,kBAAmB,SAAQ,aAAa;IAC7C,IAAI,SAAsB;gBAEd,SAAS,EAAE,MAAM;CAGpC;AAED,qBAAa,iBAAkB,SAAQ,aAAa;IAC5C,IAAI,SAAoB;CAC/B;AAED,qBAAa,mBAAoB,SAAQ,aAAa;IAC9C,IAAI,SAAmB;CAC9B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/response_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/response_errors.d.ts new file mode 100644 index 0000000..2c0d64f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/response_errors.d.ts @@ -0,0 +1,20 @@ +import { JsonRpcPayload, JsonRpcResponse } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class ResponseError extends BaseWeb3Error { + code: number; + data?: ErrorType | ErrorType[]; + request?: JsonRpcPayload; + constructor(response: JsonRpcResponse, message?: string, request?: JsonRpcPayload); + toJSON(): { + data: ErrorType | ErrorType[] | undefined; + request: JsonRpcPayload | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class InvalidResponseError extends ResponseError { + constructor(result: JsonRpcResponse, request?: JsonRpcPayload); +} +//# sourceMappingURL=response_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/response_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/response_errors.d.ts.map new file mode 100644 index 0000000..817794e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/response_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"response_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/response_errors.ts"],"names":[],"mappings":"AAkBA,OAAO,EAEN,cAAc,EACd,eAAe,EAEf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAmBtD,qBAAa,aAAa,CAAC,SAAS,GAAG,OAAO,EAAE,WAAW,GAAG,OAAO,CAAE,SAAQ,aAAa;IACpF,IAAI,SAAgB;IACpB,IAAI,CAAC,EAAE,SAAS,GAAG,SAAS,EAAE,CAAC;IAC/B,OAAO,CAAC,EAAE,cAAc,CAAC,WAAW,CAAC,CAAC;gBAG5C,QAAQ,EAAE,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC,EAC7C,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,cAAc,CAAC,WAAW,CAAC;IA4B/B,MAAM;;;;;;;;CAGb;AAED,qBAAa,oBAAoB,CAAC,SAAS,GAAG,OAAO,EAAE,WAAW,GAAG,OAAO,CAAE,SAAQ,aAAa,CAClG,SAAS,EACT,WAAW,CACX;gBAEC,MAAM,EAAE,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC,EAC3C,OAAO,CAAC,EAAE,cAAc,CAAC,WAAW,CAAC;CAatC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_error_messages.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_error_messages.d.ts new file mode 100644 index 0000000..1784acd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_error_messages.d.ts @@ -0,0 +1,14 @@ +/** + * A template string for a generic Rpc Error. The `*code*` will be replaced with the code number. + * Note: consider in next version that a spelling mistake could be corrected for `occured` and the value could be: + * `An Rpc error has occurred with a code of *code*` + */ +export declare const genericRpcErrorMessageTemplate = "An Rpc error has occured with a code of *code*"; +export declare const RpcErrorMessages: { + [key: number | string]: { + name?: string; + message: string; + description?: string; + }; +}; +//# sourceMappingURL=rpc_error_messages.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_error_messages.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_error_messages.d.ts.map new file mode 100644 index 0000000..c674054 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_error_messages.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_error_messages.d.ts","sourceRoot":"","sources":["../../../src/errors/rpc_error_messages.ts"],"names":[],"mappings":"AAqCA;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,mDAAmD,CAAC;AAG/F,eAAO,MAAM,gBAAgB,EAAE;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CA8KjF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_errors.d.ts new file mode 100644 index 0000000..cddebd8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_errors.d.ts @@ -0,0 +1,75 @@ +import { JsonRpcResponseWithError, JsonRpcId, JsonRpcError } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class RpcError extends BaseWeb3Error { + code: number; + id: JsonRpcId; + jsonrpc: string; + jsonRpcError: JsonRpcError; + constructor(rpcError: JsonRpcResponseWithError, message?: string); + toJSON(): { + error: JsonRpcError; + id: JsonRpcId; + jsonRpc: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class EIP1193ProviderRpcError extends BaseWeb3Error { + code: number; + data?: unknown; + constructor(code: number, data?: unknown); +} +export declare class ParseError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InvalidRequestError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class MethodNotFoundError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InvalidParamsError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InternalError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class InvalidInputError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class MethodNotSupported extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class ResourceUnavailableError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class ResourcesNotFoundError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class VersionNotSupportedError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class TransactionRejectedError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare class LimitExceededError extends RpcError { + code: number; + constructor(rpcError: JsonRpcResponseWithError); +} +export declare const rpcErrorsMap: Map; +//# sourceMappingURL=rpc_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_errors.d.ts.map new file mode 100644 index 0000000..c0aa697 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/rpc_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/rpc_errors.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,wBAAwB,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAiBtD,qBAAa,QAAS,SAAQ,aAAa;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,SAAS,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,YAAY,CAAC;gBACf,QAAQ,EAAE,wBAAwB,EAAE,OAAO,CAAC,EAAE,MAAM;IAWhE,MAAM;;;;;;;;;CAGb;AAED,qBAAa,uBAAwB,SAAQ,aAAa;IAClD,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;gBAEH,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO;CAsB/C;AAED,qBAAa,UAAW,SAAQ,QAAQ;IAChC,IAAI,SAAwB;gBAChB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;IACzC,IAAI,SAA2B;gBACnB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;IACzC,IAAI,SAA0B;gBAClB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,kBAAmB,SAAQ,QAAQ;IACxC,IAAI,SAA0B;gBAClB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,aAAc,SAAQ,QAAQ;IACnC,IAAI,SAA0B;gBAClB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,iBAAkB,SAAQ,QAAQ;IACvC,IAAI,SAAyB;gBACjB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,kBAAmB,SAAQ,QAAQ;IACxC,IAAI,SAA8B;gBACtB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,wBAAyB,SAAQ,QAAQ;IAC9C,IAAI,SAAgC;gBACxB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,sBAAuB,SAAQ,QAAQ;IAC5C,IAAI,SAA4B;gBACpB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,wBAAyB,SAAQ,QAAQ;IAC9C,IAAI,SAAyB;gBACjB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,wBAAyB,SAAQ,QAAQ;IAC9C,IAAI,SAAgC;gBACxB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,qBAAa,kBAAmB,SAAQ,QAAQ;IACxC,IAAI,SAA0B;gBAClB,QAAQ,EAAE,wBAAwB;CAGrD;AAED,eAAO,MAAM,YAAY;WAA4B,eAAe;EAAK,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/schema_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/schema_errors.d.ts new file mode 100644 index 0000000..a48694c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/schema_errors.d.ts @@ -0,0 +1,14 @@ +import { BaseWeb3Error } from '../web3_error_base.js'; +export declare class SchemaFormatError extends BaseWeb3Error { + type: string; + code: number; + constructor(type: string); + toJSON(): { + type: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +//# sourceMappingURL=schema_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/schema_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/schema_errors.d.ts.map new file mode 100644 index 0000000..89ca44f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/schema_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"schema_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/schema_errors.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,qBAAa,iBAAkB,SAAQ,aAAa;IAGzB,IAAI,EAAE,MAAM;IAF/B,IAAI,SAAqB;gBAEN,IAAI,EAAE,MAAM;IAI/B,MAAM;;;;;;;CAIb"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/signature_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/signature_errors.d.ts new file mode 100644 index 0000000..cfab9a4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/signature_errors.d.ts @@ -0,0 +1,5 @@ +import { InvalidValueError } from '../web3_error_base.js'; +export declare class SignatureError extends InvalidValueError { + code: number; +} +//# sourceMappingURL=signature_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/signature_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/signature_errors.d.ts.map new file mode 100644 index 0000000..d58426d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/signature_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"signature_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/signature_errors.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,qBAAa,cAAe,SAAQ,iBAAiB;IAC7C,IAAI,SAAwB;CACnC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/transaction_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/transaction_errors.d.ts new file mode 100644 index 0000000..88a0a37 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/transaction_errors.d.ts @@ -0,0 +1,282 @@ +import { Bytes, HexString, Numbers, TransactionReceipt, Web3ValidationErrorObject } from 'web3-types'; +import { InvalidValueError, BaseWeb3Error } from '../web3_error_base.js'; +export declare class TransactionError extends BaseWeb3Error { + receipt?: ReceiptType | undefined; + code: number; + constructor(message: string, receipt?: ReceiptType | undefined); + toJSON(): { + receipt: ReceiptType | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class RevertInstructionError extends BaseWeb3Error { + reason: string; + signature: string; + code: number; + constructor(reason: string, signature: string); + toJSON(): { + reason: string; + signature: string; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class TransactionRevertInstructionError extends BaseWeb3Error { + reason: string; + signature?: string | undefined; + receipt?: ReceiptType | undefined; + data?: string | undefined; + code: number; + constructor(reason: string, signature?: string | undefined, receipt?: ReceiptType | undefined, data?: string | undefined); + toJSON(): { + reason: string; + signature: string | undefined; + receipt: ReceiptType | undefined; + data: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +/** + * This error is used when a transaction to a smart contract fails and + * a custom user error (https://blog.soliditylang.org/2021/04/21/custom-errors/) + * is able to be parsed from the revert reason + */ +export declare class TransactionRevertWithCustomError extends TransactionRevertInstructionError { + reason: string; + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; + signature?: string | undefined; + receipt?: ReceiptType | undefined; + data?: string | undefined; + code: number; + constructor(reason: string, customErrorName: string, customErrorDecodedSignature: string, customErrorArguments: Record, signature?: string | undefined, receipt?: ReceiptType | undefined, data?: string | undefined); + toJSON(): { + reason: string; + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; + signature: string | undefined; + receipt: ReceiptType | undefined; + data: string | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class NoContractAddressFoundError extends TransactionError { + constructor(receipt: TransactionReceipt); + toJSON(): { + receipt: TransactionReceipt | undefined; + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare class ContractCodeNotStoredError extends TransactionError { + constructor(receipt: TransactionReceipt); +} +export declare class TransactionRevertedWithoutReasonError extends TransactionError { + constructor(receipt?: ReceiptType); +} +export declare class TransactionOutOfGasError extends TransactionError { + constructor(receipt: TransactionReceipt); +} +export declare class UndefinedRawTransactionError extends TransactionError { + constructor(); +} +export declare class TransactionNotFound extends TransactionError { + constructor(); +} +export declare class InvalidTransactionWithSender extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidTransactionWithReceiver extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidTransactionCall extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class MissingCustomChainError extends InvalidValueError { + code: number; + constructor(); +} +export declare class MissingCustomChainIdError extends InvalidValueError { + code: number; + constructor(); +} +export declare class ChainIdMismatchError extends InvalidValueError { + code: number; + constructor(value: { + txChainId: unknown; + customChainId: unknown; + }); +} +export declare class ChainMismatchError extends InvalidValueError { + code: number; + constructor(value: { + txChain: unknown; + baseChain: unknown; + }); +} +export declare class HardforkMismatchError extends InvalidValueError { + code: number; + constructor(value: { + txHardfork: unknown; + commonHardfork: unknown; + }); +} +export declare class CommonOrChainAndHardforkError extends InvalidValueError { + code: number; + constructor(); +} +export declare class MissingChainOrHardforkError extends InvalidValueError { + code: number; + constructor(value: { + chain: string | undefined; + hardfork: string | undefined; + }); +} +export declare class MissingGasInnerError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class MissingGasError extends InvalidValueError { + code: number; + constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class TransactionGasMismatchInnerError extends BaseWeb3Error { + code: number; + constructor(); +} +export declare class TransactionGasMismatchError extends InvalidValueError { + code: number; + constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class InvalidGasOrGasPrice extends InvalidValueError { + code: number; + constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + }); +} +export declare class InvalidMaxPriorityFeePerGasOrMaxFeePerGas extends InvalidValueError { + code: number; + constructor(value: { + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class Eip1559GasPriceError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class UnsupportedFeeMarketError extends InvalidValueError { + code: number; + constructor(value: { + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }); +} +export declare class InvalidTransactionObjectError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidNonceOrChainIdError extends InvalidValueError { + code: number; + constructor(value: { + nonce: Numbers | undefined; + chainId: Numbers | undefined; + }); +} +export declare class UnableToPopulateNonceError extends InvalidValueError { + code: number; + constructor(); +} +export declare class Eip1559NotSupportedError extends InvalidValueError { + code: number; + constructor(); +} +export declare class UnsupportedTransactionTypeError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class TransactionDataAndInputError extends InvalidValueError { + code: number; + constructor(value: { + data: HexString | undefined; + input: HexString | undefined; + }); +} +export declare class TransactionSendTimeoutError extends BaseWeb3Error { + code: number; + constructor(value: { + numberOfSeconds: number; + transactionHash?: Bytes; + }); +} +export declare class TransactionPollingTimeoutError extends BaseWeb3Error { + code: number; + constructor(value: { + numberOfSeconds: number; + transactionHash: Bytes; + }); +} +export declare class TransactionBlockTimeoutError extends BaseWeb3Error { + code: number; + constructor(value: { + starterBlockNumber: number; + numberOfBlocks: number; + transactionHash?: Bytes; + }); +} +export declare class TransactionMissingReceiptOrBlockHashError extends InvalidValueError { + code: number; + constructor(value: { + receipt: TransactionReceipt; + blockHash: Bytes; + transactionHash: Bytes; + }); +} +export declare class TransactionReceiptMissingBlockNumberError extends InvalidValueError { + code: number; + constructor(value: { + receipt: TransactionReceipt; + }); +} +export declare class TransactionSigningError extends BaseWeb3Error { + code: number; + constructor(errorDetails: string); +} +export declare class LocalWalletNotAvailableError extends InvalidValueError { + code: number; + constructor(); +} +export declare class InvalidPropertiesForTransactionTypeError extends BaseWeb3Error { + code: number; + constructor(validationError: Web3ValidationErrorObject[], txType: '0x0' | '0x1' | '0x2'); +} +//# sourceMappingURL=transaction_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/transaction_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/transaction_errors.d.ts.map new file mode 100644 index 0000000..878e33a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/transaction_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/transaction_errors.ts"],"names":[],"mappings":"AAmBA,OAAO,EACN,KAAK,EACL,SAAS,EACT,OAAO,EACP,kBAAkB,EAClB,yBAAyB,EACzB,MAAM,YAAY,CAAC;AA6CpB,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEzE,qBAAa,gBAAgB,CAAC,WAAW,GAAG,kBAAkB,CAAE,SAAQ,aAAa;IAGzC,OAAO,CAAC;IAF5C,IAAI,SAAU;gBAEF,OAAO,EAAE,MAAM,EAAS,OAAO,CAAC,yBAAa;IAIzD,MAAM;;;;;;;CAG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,EAAE,KAAK,CAAC;KACxB;CAOD;AAED,qBAAa,yCAA0C,SAAQ,iBAAiB;IACxE,IAAI,SAA4C;gBAEpC,KAAK,EAAE;QACzB,OAAO,EAAE,kBAAkB,CAAC;QAC5B,SAAS,EAAE,KAAK,CAAC;QACjB,eAAe,EAAE,KAAK,CAAC;KACvB;CAQD;AAED,qBAAa,yCAA0C,SAAQ,iBAAiB;IACxE,IAAI,SAAuC;gBAE/B,KAAK,EAAE;QAAE,OAAO,EAAE,kBAAkB,CAAA;KAAE;CAGzD;AAED,qBAAa,uBAAwB,SAAQ,aAAa;IAClD,IAAI,SAAkB;gBACV,YAAY,EAAE,MAAM;CAGvC;AAED,qBAAa,4BAA6B,SAAQ,iBAAiB;IAC3D,IAAI,SAAqC;;CAQhD;AACD,qBAAa,wCAAyC,SAAQ,aAAa;IACnE,IAAI,SAAsC;gBAGhD,eAAe,EAAE,yBAAyB,EAAE,EAC5C,MAAM,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK;CAU9B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/utils_errors.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/utils_errors.d.ts new file mode 100644 index 0000000..ae649a7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/utils_errors.d.ts @@ -0,0 +1,58 @@ +import { InvalidValueError } from '../web3_error_base.js'; +export declare class InvalidBytesError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidNumberError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidAddressError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidStringError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidUnitError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class HexProcessingError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class NibbleWidthError extends InvalidValueError { + code: number; + constructor(value: string); +} +export declare class InvalidTypeError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidBooleanError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidUnsignedIntegerError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidSizeError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidLargeValueError extends InvalidValueError { + code: number; + constructor(value: unknown); +} +export declare class InvalidBlockError extends InvalidValueError { + code: number; + constructor(value: string); +} +export declare class InvalidTypeAbiInputError extends InvalidValueError { + code: number; + constructor(value: string); +} +//# sourceMappingURL=utils_errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/errors/utils_errors.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/utils_errors.d.ts.map new file mode 100644 index 0000000..4e87ff5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/errors/utils_errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils_errors.d.ts","sourceRoot":"","sources":["../../../src/errors/utils_errors.ts"],"names":[],"mappings":"AAmCA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,qBAAa,iBAAkB,SAAQ,iBAAiB;IAChD,IAAI,SAAqB;gBAEb,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,kBAAmB,SAAQ,iBAAiB;IACjD,IAAI,SAAsB;gBAEd,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,mBAAoB,SAAQ,iBAAiB;IAClD,IAAI,SAAuB;gBAEf,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,kBAAmB,SAAQ,iBAAiB;IACjD,IAAI,SAAsB;gBAEd,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,gBAAiB,SAAQ,iBAAiB;IAC/C,IAAI,SAAoB;gBAEZ,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,kBAAmB,SAAQ,iBAAiB;IACjD,IAAI,SAAmB;gBAEX,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,gBAAiB,SAAQ,iBAAiB;IAC/C,IAAI,SAA4B;gBAEpB,KAAK,EAAE,MAAM;CAGhC;AAED,qBAAa,gBAAiB,SAAQ,iBAAiB;IAC/C,IAAI,SAAoB;gBAEZ,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,mBAAoB,SAAQ,iBAAiB;IAClD,IAAI,SAAuB;gBAEf,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,2BAA4B,SAAQ,iBAAiB;IAC1D,IAAI,SAAgC;gBAExB,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,gBAAiB,SAAQ,iBAAiB;IAC/C,IAAI,SAAoB;gBAEZ,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,sBAAuB,SAAQ,iBAAiB;IACrD,IAAI,SAA2B;gBAEnB,KAAK,EAAE,OAAO;CAGjC;AAED,qBAAa,iBAAkB,SAAQ,iBAAiB;IAChD,IAAI,SAAqB;gBAEb,KAAK,EAAE,MAAM;CAGhC;AAED,qBAAa,wBAAyB,SAAQ,iBAAiB;IACvD,IAAI,SAAwB;gBAEhB,KAAK,EAAE,MAAM;CAGhC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/index.d.ts new file mode 100644 index 0000000..73600a7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/index.d.ts @@ -0,0 +1,17 @@ +export * from './error_codes.js'; +export * from './web3_error_base.js'; +export * from './errors/account_errors.js'; +export * from './errors/connection_errors.js'; +export * from './errors/contract_errors.js'; +export * from './errors/ens_errors.js'; +export * from './errors/generic_errors.js'; +export * from './errors/provider_errors.js'; +export * from './errors/signature_errors.js'; +export * from './errors/transaction_errors.js'; +export * from './errors/utils_errors.js'; +export * from './errors/response_errors.js'; +export * from './errors/core_errors.js'; +export * from './errors/rpc_errors.js'; +export * from './errors/rpc_error_messages.js'; +export * from './errors/schema_errors.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/index.d.ts.map new file mode 100644 index 0000000..4239ff7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,0BAA0B,CAAC;AACzC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,2BAA2B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/web3_error_base.d.ts b/test/merkletreejs/node_modules/web3-errors/lib/types/web3_error_base.d.ts new file mode 100644 index 0000000..a651fe7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/web3_error_base.d.ts @@ -0,0 +1,20 @@ +import { Web3Error } from 'web3-types'; +export declare abstract class BaseWeb3Error extends Error implements Web3Error { + readonly name: string; + abstract readonly code: number; + stack: string | undefined; + innerError: Error | Error[] | undefined; + constructor(msg?: string, innerError?: Error | Error[]); + static convertToString(value: unknown, unquotValue?: boolean): string; + toJSON(): { + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + }; +} +export declare abstract class InvalidValueError extends BaseWeb3Error { + readonly name: string; + constructor(value: unknown, msg: string); +} +//# sourceMappingURL=web3_error_base.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/lib/types/web3_error_base.d.ts.map b/test/merkletreejs/node_modules/web3-errors/lib/types/web3_error_base.d.ts.map new file mode 100644 index 0000000..112490b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/lib/types/web3_error_base.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_error_base.d.ts","sourceRoot":"","sources":["../../src/web3_error_base.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,8BAAsB,aAAc,SAAQ,KAAM,YAAW,SAAS;IACrE,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B,kBAAyB,IAAI,EAAE,MAAM,CAAC;IAC/B,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,UAAU,EAAE,KAAK,GAAG,KAAK,EAAE,GAAG,SAAS,CAAC;gBAE5B,GAAG,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,KAAK,GAAG,KAAK,EAAE;WAY/C,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,WAAW,UAAQ;IAe1D,MAAM;;;;;;CAQb;AAED,8BAAsB,iBAAkB,SAAQ,aAAa;IAC5D,SAAgB,IAAI,EAAE,MAAM,CAAC;gBAEV,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM;CAM9C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/package.json b/test/merkletreejs/node_modules/web3-errors/package.json new file mode 100644 index 0000000..dc43687 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/package.json @@ -0,0 +1,61 @@ +{ + "name": "web3-errors", + "version": "1.1.4", + "description": "This package has web3 error classes", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "dependencies": { + "web3-types": "^1.3.1" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "gitHead": "a616752f406a8f52f754c5d2fb7343ff8c811b23" +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/error_codes.ts b/test/merkletreejs/node_modules/web3-errors/src/error_codes.ts new file mode 100644 index 0000000..c9ff68f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/error_codes.ts @@ -0,0 +1,182 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// Response error +export const ERR_RESPONSE = 100; +export const ERR_INVALID_RESPONSE = 101; + +// Generic errors +export const ERR_PARAM = 200; +export const ERR_FORMATTERS = 201; +export const ERR_METHOD_NOT_IMPLEMENTED = 202; +export const ERR_OPERATION_TIMEOUT = 203; +export const ERR_OPERATION_ABORT = 204; +export const ERR_ABI_ENCODING = 205; +export const ERR_EXISTING_PLUGIN_NAMESPACE = 206; +export const ERR_INVALID_METHOD_PARAMS = 207; + +// Contract error codes +export const ERR_CONTRACT = 300; +export const ERR_CONTRACT_RESOLVER_MISSING = 301; +export const ERR_CONTRACT_ABI_MISSING = 302; +export const ERR_CONTRACT_REQUIRED_CALLBACK = 303; +export const ERR_CONTRACT_EVENT_NOT_EXISTS = 304; +export const ERR_CONTRACT_RESERVED_EVENT = 305; +export const ERR_CONTRACT_MISSING_DEPLOY_DATA = 306; +export const ERR_CONTRACT_MISSING_ADDRESS = 307; +export const ERR_CONTRACT_MISSING_FROM_ADDRESS = 308; +export const ERR_CONTRACT_INSTANTIATION = 309; +export const ERR_CONTRACT_EXECUTION_REVERTED = 310; +export const ERR_CONTRACT_TX_DATA_AND_INPUT = 311; + +// Transaction error codes +export const ERR_TX = 400; +export const ERR_TX_REVERT_INSTRUCTION = 401; +export const ERR_TX_REVERT_TRANSACTION = 402; +export const ERR_TX_NO_CONTRACT_ADDRESS = 403; +export const ERR_TX_CONTRACT_NOT_STORED = 404; +export const ERR_TX_REVERT_WITHOUT_REASON = 405; +export const ERR_TX_OUT_OF_GAS = 406; +export const ERR_RAW_TX_UNDEFINED = 407; + +export const ERR_TX_INVALID_SENDER = 408; +export const ERR_TX_INVALID_CALL = 409; +export const ERR_TX_MISSING_CUSTOM_CHAIN = 410; +export const ERR_TX_MISSING_CUSTOM_CHAIN_ID = 411; +export const ERR_TX_CHAIN_ID_MISMATCH = 412; +export const ERR_TX_INVALID_CHAIN_INFO = 413; +export const ERR_TX_MISSING_CHAIN_INFO = 414; +export const ERR_TX_MISSING_GAS = 415; +export const ERR_TX_INVALID_LEGACY_GAS = 416; +export const ERR_TX_INVALID_FEE_MARKET_GAS = 417; +export const ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = 418; +export const ERR_TX_INVALID_LEGACY_FEE_MARKET = 419; +export const ERR_TX_INVALID_OBJECT = 420; +export const ERR_TX_INVALID_NONCE_OR_CHAIN_ID = 421; +export const ERR_TX_UNABLE_TO_POPULATE_NONCE = 422; +export const ERR_TX_UNSUPPORTED_EIP_1559 = 423; +export const ERR_TX_UNSUPPORTED_TYPE = 424; +export const ERR_TX_DATA_AND_INPUT = 425; +export const ERR_TX_POLLING_TIMEOUT = 426; +export const ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = 427; +export const ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = 428; + +export const ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = 429; + +export const ERR_TX_NOT_FOUND = 430; +export const ERR_TX_SEND_TIMEOUT = 431; +export const ERR_TX_BLOCK_TIMEOUT = 432; + +export const ERR_TX_SIGNING = 433; +export const ERR_TX_GAS_MISMATCH = 434; + +export const ERR_TX_CHAIN_MISMATCH = 435; +export const ERR_TX_HARDFORK_MISMATCH = 436; +export const ERR_TX_INVALID_RECEIVER = 437; +export const ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = 438; +export const ERR_TX_INVALID_PROPERTIES_FOR_TYPE = 439; + +export const ERR_TX_MISSING_GAS_INNER_ERROR = 440; +export const ERR_TX_GAS_MISMATCH_INNER_ERROR = 441; +// Connection error codes +export const ERR_CONN = 500; +export const ERR_CONN_INVALID = 501; +export const ERR_CONN_TIMEOUT = 502; +export const ERR_CONN_NOT_OPEN = 503; +export const ERR_CONN_CLOSE = 504; +export const ERR_CONN_MAX_ATTEMPTS = 505; +export const ERR_CONN_PENDING_REQUESTS = 506; +export const ERR_REQ_ALREADY_SENT = 507; + +// Provider error codes +export const ERR_PROVIDER = 600; +export const ERR_INVALID_PROVIDER = 601; +export const ERR_INVALID_CLIENT = 602; +export const ERR_SUBSCRIPTION = 603; +export const ERR_WS_PROVIDER = 604; + +// Account error codes +export const ERR_PRIVATE_KEY_LENGTH = 701; +export const ERR_INVALID_PRIVATE_KEY = 702; +export const ERR_UNSUPPORTED_KDF = 703; +export const ERR_KEY_DERIVATION_FAIL = 704; +export const ERR_KEY_VERSION_UNSUPPORTED = 705; +export const ERR_INVALID_PASSWORD = 706; +export const ERR_IV_LENGTH = 707; +export const ERR_INVALID_KEYSTORE = 708; +export const ERR_PBKDF2_ITERATIONS = 709; + +// Signature error codes +export const ERR_SIGNATURE_FAILED = 801; +export const ERR_INVALID_SIGNATURE = 802; + +export const GENESIS_BLOCK_NUMBER = '0x0'; + +// RPC error codes (EIP-1193) +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors +export const JSONRPC_ERR_REJECTED_REQUEST = 4001; +export const JSONRPC_ERR_UNAUTHORIZED = 4100; +export const JSONRPC_ERR_UNSUPPORTED_METHOD = 4200; +export const JSONRPC_ERR_DISCONNECTED = 4900; +export const JSONRPC_ERR_CHAIN_DISCONNECTED = 4901; + +// ENS error codes +export const ERR_ENS_CHECK_INTERFACE_SUPPORT = 901; +export const ERR_ENS_UNSUPPORTED_NETWORK = 902; +export const ERR_ENS_NETWORK_NOT_SYNCED = 903; + +// Utils error codes +export const ERR_INVALID_STRING = 1001; +export const ERR_INVALID_BYTES = 1002; +export const ERR_INVALID_NUMBER = 1003; +export const ERR_INVALID_UNIT = 1004; +export const ERR_INVALID_ADDRESS = 1005; +export const ERR_INVALID_HEX = 1006; +export const ERR_INVALID_TYPE = 1007; +export const ERR_INVALID_BOOLEAN = 1008; +export const ERR_INVALID_UNSIGNED_INTEGER = 1009; +export const ERR_INVALID_SIZE = 1010; +export const ERR_INVALID_LARGE_VALUE = 1011; +export const ERR_INVALID_BLOCK = 1012; +export const ERR_INVALID_TYPE_ABI = 1013; +export const ERR_INVALID_NIBBLE_WIDTH = 1014; + +// Validation error codes +export const ERR_VALIDATION = 1100; + + +// Core error codes +export const ERR_CORE_HARDFORK_MISMATCH = 1101; +export const ERR_CORE_CHAIN_MISMATCH = 1102; + +// Schema error codes +export const ERR_SCHEMA_FORMAT = 1200; + +// RPC error codes (EIP-1474) +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md +export const ERR_RPC_INVALID_JSON = -32700; +export const ERR_RPC_INVALID_REQUEST = -32600; +export const ERR_RPC_INVALID_METHOD = -32601; +export const ERR_RPC_INVALID_PARAMS = -32602; +export const ERR_RPC_INTERNAL_ERROR = -32603; +export const ERR_RPC_INVALID_INPUT = -32000; +export const ERR_RPC_MISSING_RESOURCE = -32001; +export const ERR_RPC_UNAVAILABLE_RESOURCE = -32002; +export const ERR_RPC_TRANSACTION_REJECTED = -32003; +export const ERR_RPC_UNSUPPORTED_METHOD = -32004; +export const ERR_RPC_LIMIT_EXCEEDED = -32005; +export const ERR_RPC_NOT_SUPPORTED = -32006; diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/account_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/account_errors.ts new file mode 100644 index 0000000..9d0d0c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/account_errors.ts @@ -0,0 +1,94 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { + ERR_PRIVATE_KEY_LENGTH, + ERR_INVALID_PRIVATE_KEY, + ERR_INVALID_SIGNATURE, + ERR_UNSUPPORTED_KDF, + ERR_KEY_DERIVATION_FAIL, + ERR_KEY_VERSION_UNSUPPORTED, + ERR_INVALID_PASSWORD, + ERR_IV_LENGTH, + ERR_PBKDF2_ITERATIONS, +} from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; + +export class PrivateKeyLengthError extends BaseWeb3Error { + public code = ERR_PRIVATE_KEY_LENGTH; + public constructor() { + super(`Private key must be 32 bytes.`); + } +} + +export class InvalidPrivateKeyError extends BaseWeb3Error { + public code = ERR_INVALID_PRIVATE_KEY; + public constructor() { + super(`Invalid Private Key, Not a valid string or uint8Array`); + } +} + +export class InvalidSignatureError extends BaseWeb3Error { + public code = ERR_INVALID_SIGNATURE; + public constructor(errorDetails: string) { + super(`"${errorDetails}"`); + } +} + +export class InvalidKdfError extends BaseWeb3Error { + public code = ERR_UNSUPPORTED_KDF; + public constructor() { + super(`Invalid key derivation function`); + } +} + +export class KeyDerivationError extends BaseWeb3Error { + public code = ERR_KEY_DERIVATION_FAIL; + public constructor() { + super(`Key derivation failed - possibly wrong password`); + } +} + +export class KeyStoreVersionError extends BaseWeb3Error { + public code = ERR_KEY_VERSION_UNSUPPORTED; + public constructor() { + super('Unsupported key store version'); + } +} + +export class InvalidPasswordError extends BaseWeb3Error { + public code = ERR_INVALID_PASSWORD; + public constructor() { + super('Password cannot be empty'); + } +} + +export class IVLengthError extends BaseWeb3Error { + public code = ERR_IV_LENGTH; + public constructor() { + super('Initialization vector must be 16 bytes'); + } +} + +export class PBKDF2IterationsError extends BaseWeb3Error { + public code = ERR_PBKDF2_ITERATIONS; + public constructor() { + super('c > 1000, pbkdf2 is less secure with less iterations'); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/connection_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/connection_errors.ts new file mode 100644 index 0000000..d9d8208 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/connection_errors.ts @@ -0,0 +1,112 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { ConnectionEvent } from 'web3-types'; +import { + ERR_CONN, + ERR_CONN_INVALID, + ERR_CONN_TIMEOUT, + ERR_CONN_NOT_OPEN, + ERR_CONN_CLOSE, + ERR_CONN_MAX_ATTEMPTS, + ERR_CONN_PENDING_REQUESTS, + ERR_REQ_ALREADY_SENT, +} from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; + +export class ConnectionError extends BaseWeb3Error { + public code = ERR_CONN; + public errorCode?: number; + public errorReason?: string; + + public constructor(message: string, event?: ConnectionEvent) { + super(message); + + if (event) { + this.errorCode = event.code; + this.errorReason = event.reason; + } + } + + public toJSON() { + return { ...super.toJSON(), errorCode: this.errorCode, errorReason: this.errorReason }; + } +} + +export class InvalidConnectionError extends ConnectionError { + public constructor(public host: string, event?: ConnectionEvent) { + super(`CONNECTION ERROR: Couldn't connect to node ${host}.`, event); + this.code = ERR_CONN_INVALID; + } + + public toJSON() { + return { ...super.toJSON(), host: this.host }; + } +} + +export class ConnectionTimeoutError extends ConnectionError { + public constructor(public duration: number) { + super(`CONNECTION TIMEOUT: timeout of ${duration}ms achieved`); + this.code = ERR_CONN_TIMEOUT; + } + + public toJSON() { + return { ...super.toJSON(), duration: this.duration }; + } +} + +export class ConnectionNotOpenError extends ConnectionError { + public constructor(event?: ConnectionEvent) { + super('Connection not open', event); + this.code = ERR_CONN_NOT_OPEN; + } +} + +export class ConnectionCloseError extends ConnectionError { + public constructor(event?: ConnectionEvent) { + super( + `CONNECTION ERROR: The connection got closed with the close code ${ + event?.code ?? '' + } and the following reason string ${event?.reason ?? ''}`, + event, + ); + this.code = ERR_CONN_CLOSE; + } +} + +export class MaxAttemptsReachedOnReconnectingError extends ConnectionError { + public constructor(numberOfAttempts: number) { + super(`Maximum number of reconnect attempts reached! (${numberOfAttempts})`); + this.code = ERR_CONN_MAX_ATTEMPTS; + } +} + +export class PendingRequestsOnReconnectingError extends ConnectionError { + public constructor() { + super('CONNECTION ERROR: Provider started to reconnect before the response got received!'); + this.code = ERR_CONN_PENDING_REQUESTS; + } +} + +export class RequestAlreadySentError extends ConnectionError { + public constructor(id: number | string) { + super(`Request already sent with following id: ${id}`); + this.code = ERR_REQ_ALREADY_SENT; + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/contract_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/contract_errors.ts new file mode 100644 index 0000000..98a3824 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/contract_errors.ts @@ -0,0 +1,237 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { JsonRpcError, TransactionReceipt, HexString } from 'web3-types'; +import { + ERR_CONTRACT, + ERR_CONTRACT_ABI_MISSING, + ERR_CONTRACT_EXECUTION_REVERTED, + ERR_CONTRACT_EVENT_NOT_EXISTS, + ERR_CONTRACT_INSTANTIATION, + ERR_CONTRACT_MISSING_ADDRESS, + ERR_CONTRACT_MISSING_DEPLOY_DATA, + ERR_CONTRACT_MISSING_FROM_ADDRESS, + ERR_CONTRACT_REQUIRED_CALLBACK, + ERR_CONTRACT_RESERVED_EVENT, + ERR_CONTRACT_RESOLVER_MISSING, + ERR_CONTRACT_TX_DATA_AND_INPUT, +} from '../error_codes.js'; +import { BaseWeb3Error, InvalidValueError } from '../web3_error_base.js'; + +export class Web3ContractError extends BaseWeb3Error { + public code = ERR_CONTRACT; + public receipt?: TransactionReceipt; + + public constructor(message: string, receipt?: TransactionReceipt) { + super(message); + + this.receipt = receipt; + } +} +export class ResolverMethodMissingError extends BaseWeb3Error { + public code = ERR_CONTRACT_RESOLVER_MISSING; + + public constructor(public address: string, public name: string) { + super(`The resolver at ${address} does not implement requested method: "${name}".`); + } + + public toJSON() { + return { ...super.toJSON(), address: this.address, name: this.name }; + } +} + +export class ContractMissingABIError extends BaseWeb3Error { + public code = ERR_CONTRACT_ABI_MISSING; + + public constructor() { + super( + 'You must provide the json interface of the contract when instantiating a contract object.', + ); + } +} + +export class ContractOnceRequiresCallbackError extends BaseWeb3Error { + public code = ERR_CONTRACT_REQUIRED_CALLBACK; + + public constructor() { + super('Once requires a callback as the second parameter.'); + } +} + +export class ContractEventDoesNotExistError extends BaseWeb3Error { + public code = ERR_CONTRACT_EVENT_NOT_EXISTS; + + public constructor(public eventName: string) { + super(`Event "${eventName}" doesn't exist in this contract.`); + } + + public toJSON() { + return { ...super.toJSON(), eventName: this.eventName }; + } +} + +export class ContractReservedEventError extends BaseWeb3Error { + public code = ERR_CONTRACT_RESERVED_EVENT; + + public constructor(public type: string) { + super(`Event "${type}" doesn't exist in this contract.`); + } + + public toJSON() { + return { ...super.toJSON(), type: this.type }; + } +} + +export class ContractMissingDeployDataError extends BaseWeb3Error { + public code = ERR_CONTRACT_MISSING_DEPLOY_DATA; + + public constructor() { + super(`No "data" specified in neither the given options, nor the default options.`); + } +} + +export class ContractNoAddressDefinedError extends BaseWeb3Error { + public code = ERR_CONTRACT_MISSING_ADDRESS; + + public constructor() { + super("This contract object doesn't have address set yet, please set an address first."); + } +} + +export class ContractNoFromAddressDefinedError extends BaseWeb3Error { + public code = ERR_CONTRACT_MISSING_FROM_ADDRESS; + + public constructor() { + super('No "from" address specified in neither the given options, nor the default options.'); + } +} + +export class ContractInstantiationError extends BaseWeb3Error { + public code = ERR_CONTRACT_INSTANTIATION; +} + +export type ProviderErrorData = + | HexString + | { data: HexString } + | { originalError: { data: HexString } }; + +/** + * This class is expected to be set as an `innerError` inside ContractExecutionError + * The properties would be typically decoded from the `data` if it was encoded according to EIP-838 + */ +export class Eip838ExecutionError extends Web3ContractError { + public readonly name: string; + public code: number; + public data?: HexString; + public errorName?: string; + public errorSignature?: string; + public errorArgs?: { [K in string]: unknown }; + + // eslint-disable-next-line no-use-before-define + public innerError: Eip838ExecutionError | undefined; + + public constructor(error: JsonRpcError | Eip838ExecutionError) { + super(error.message || 'Error'); + + this.name = ('name' in error && error.name) || this.constructor.name; + this.stack = ('stack' in error && error.stack) || undefined; + this.code = error.code; + + // get embedded error details got from some providers like MetaMask + // and set this.data from the inner error data for easier read. + // note: the data is a hex string inside either: + // error.data, error.data.data or error.data.originalError.data (https://github.com/web3/web3.js/issues/4454#issuecomment-1485953455) + if (typeof error.data === 'object') { + let originalError: { data: string }; + if ('originalError' in error.data) { + originalError = error.data.originalError; + } else { + // Ganache has no `originalError` sub-object unlike others + originalError = error.data; + } + this.data = originalError.data; + this.innerError = new Eip838ExecutionError( + originalError as JsonRpcError, + ); + } else { + this.data = error.data; + } + } + + public setDecodedProperties( + errorName: string, + errorSignature?: string, + errorArgs?: { [K in string]: unknown }, + ) { + this.errorName = errorName; + this.errorSignature = errorSignature; + this.errorArgs = errorArgs; + } + + public toJSON() { + let json = { + ...super.toJSON(), + data: this.data, + } as { + name: string; + code: number; + message: string; + innerError: Error | Error[] | undefined; + data: string; + errorName?: string; + errorSignature?: string; + errorArgs?: { [K in string]: unknown }; + }; + + if (this.errorName) { + json = { + ...json, + errorName: this.errorName, + errorSignature: this.errorSignature, + errorArgs: this.errorArgs, + }; + } + return json; + } +} + +/** + * Used when an error is raised while executing a function inside a smart contract. + * The data is expected to be encoded according to EIP-848. + */ +export class ContractExecutionError extends Web3ContractError { + public innerError: Eip838ExecutionError; + + public constructor(rpcError: JsonRpcError) { + super('Error happened while trying to execute a function inside a smart contract'); + this.code = ERR_CONTRACT_EXECUTION_REVERTED; + this.innerError = new Eip838ExecutionError(rpcError as JsonRpcError); + } +} + +export class ContractTransactionDataAndInputError extends InvalidValueError { + public code = ERR_CONTRACT_TX_DATA_AND_INPUT; + + public constructor(value: { data: HexString | undefined; input: HexString | undefined }) { + super( + `data: ${value.data ?? 'undefined'}, input: ${value.input ?? 'undefined'}`, + 'You can\'t have "data" and "input" as properties of a contract at the same time, please use either "data" or "input" instead.', + ); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/core_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/core_errors.ts new file mode 100644 index 0000000..5adb6f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/core_errors.ts @@ -0,0 +1,41 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { BaseWeb3Error } from '../web3_error_base.js'; +import { ERR_CORE_HARDFORK_MISMATCH } from '../error_codes.js'; + +export class ConfigHardforkMismatchError extends BaseWeb3Error { + public code = ERR_CORE_HARDFORK_MISMATCH; + + public constructor(defaultHardfork: string, commonHardFork: string) { + super( + `Web3Config hardfork doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`, + ); + } +} + +export class ConfigChainMismatchError extends BaseWeb3Error { + public code = ERR_CORE_HARDFORK_MISMATCH; + + public constructor(defaultHardfork: string, commonHardFork: string) { + super( + `Web3Config chain doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`, + ); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/ens_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/ens_errors.ts new file mode 100644 index 0000000..20a5796 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/ens_errors.ts @@ -0,0 +1,46 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { + ERR_ENS_CHECK_INTERFACE_SUPPORT, + ERR_ENS_NETWORK_NOT_SYNCED, + ERR_ENS_UNSUPPORTED_NETWORK, +} from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; + +export class ENSCheckInterfaceSupportError extends BaseWeb3Error { + public code = ERR_ENS_CHECK_INTERFACE_SUPPORT; + public constructor(errorDetails: string) { + super(`ENS resolver check interface support error. "${errorDetails}"`); + } +} + +export class ENSUnsupportedNetworkError extends BaseWeb3Error { + public code = ERR_ENS_UNSUPPORTED_NETWORK; + public constructor(networkType: string) { + super(`ENS is not supported on network ${networkType}`); + } +} + +export class ENSNetworkNotSyncedError extends BaseWeb3Error { + public code = ERR_ENS_NETWORK_NOT_SYNCED; + public constructor() { + super(`Network not synced`); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/generic_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/generic_errors.ts new file mode 100644 index 0000000..1e246bf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/generic_errors.ts @@ -0,0 +1,100 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { + ERR_ABI_ENCODING, + ERR_FORMATTERS, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OPERATION_ABORT, + ERR_OPERATION_TIMEOUT, + ERR_PARAM, + ERR_EXISTING_PLUGIN_NAMESPACE, + ERR_INVALID_METHOD_PARAMS, +} from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; + +export class InvalidNumberOfParamsError extends BaseWeb3Error { + public code = ERR_PARAM; + + public constructor(public got: number, public expected: number, public method: string) { + super(`Invalid number of parameters for "${method}". Got "${got}" expected "${expected}"!`); + } + + public toJSON() { + return { + ...super.toJSON(), + got: this.got, + expected: this.expected, + method: this.method, + }; + } +} + +export class InvalidMethodParamsError extends BaseWeb3Error { + public code = ERR_INVALID_METHOD_PARAMS; + + public constructor(public hint?: string) { + super(`Invalid parameters passed. "${typeof hint !== 'undefined' ? hint : ''}"`); + } + + public toJSON() { + return { + ...super.toJSON(), + hint: this.hint, + }; + } +} + +export class FormatterError extends BaseWeb3Error { + public code = ERR_FORMATTERS; +} + +export class MethodNotImplementedError extends BaseWeb3Error { + public code = ERR_METHOD_NOT_IMPLEMENTED; + + public constructor() { + super("The method you're trying to call is not implemented."); + } +} + +export class OperationTimeoutError extends BaseWeb3Error { + public code = ERR_OPERATION_TIMEOUT; +} + +export class OperationAbortError extends BaseWeb3Error { + public code = ERR_OPERATION_ABORT; +} + +export class AbiError extends BaseWeb3Error { + public code = ERR_ABI_ENCODING; + public readonly props: Record & { name?: string }; + + public constructor(message: string, props?: Record & { name?: string }) { + super(message); + this.props = props ?? {}; + } +} + +export class ExistingPluginNamespaceError extends BaseWeb3Error { + public code = ERR_EXISTING_PLUGIN_NAMESPACE; + + public constructor(pluginNamespace: string) { + super(`A plugin with the namespace: ${pluginNamespace} has already been registered.`); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/provider_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/provider_errors.ts new file mode 100644 index 0000000..bbaadf9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/provider_errors.ts @@ -0,0 +1,55 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { + ERR_PROVIDER, + ERR_INVALID_PROVIDER, + ERR_INVALID_CLIENT, + ERR_SUBSCRIPTION, + ERR_WS_PROVIDER, +} from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; + +export class ProviderError extends BaseWeb3Error { + public code = ERR_PROVIDER; +} + +export class InvalidProviderError extends BaseWeb3Error { + public code = ERR_INVALID_PROVIDER; + + public constructor(public clientUrl: string) { + super(`Provider with url "${clientUrl}" is not set or invalid`); + } +} + +export class InvalidClientError extends BaseWeb3Error { + public code = ERR_INVALID_CLIENT; + + public constructor(clientUrl: string) { + super(`Client URL "${clientUrl}" is invalid.`); + } +} + +export class SubscriptionError extends BaseWeb3Error { + public code = ERR_SUBSCRIPTION; +} + +export class Web3WSProviderError extends BaseWeb3Error { + public code = ERR_WS_PROVIDER; // this had duplicate code with generic provider +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/response_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/response_errors.ts new file mode 100644 index 0000000..95d08b9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/response_errors.ts @@ -0,0 +1,104 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// eslint-disable-next-line max-classes-per-file +import { + JsonRpcError, + JsonRpcPayload, + JsonRpcResponse, + JsonRpcResponseWithError, +} from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +import { ERR_INVALID_RESPONSE, ERR_RESPONSE } from '../error_codes.js'; + +// To avoid circular package dependency, copied to code here. If you update this please update same function in `json_rpc.ts` +const isResponseWithError = ( + response: JsonRpcResponse, +): response is JsonRpcResponseWithError => + !Array.isArray(response) && + response.jsonrpc === '2.0' && + !!response && + // eslint-disable-next-line no-null/no-null + (response.result === undefined || response.result === null) && + // JSON RPC consider "null" as valid response + 'error' in response && + (typeof response.id === 'number' || typeof response.id === 'string'); + +const buildErrorMessage = (response: JsonRpcResponse): string => + isResponseWithError(response) ? response.error.message : ''; + +export class ResponseError extends BaseWeb3Error { + public code = ERR_RESPONSE; + public data?: ErrorType | ErrorType[]; + public request?: JsonRpcPayload; + + public constructor( + response: JsonRpcResponse, + message?: string, + request?: JsonRpcPayload, + ) { + super( + message ?? + `Returned error: ${ + Array.isArray(response) + ? response.map(r => buildErrorMessage(r)).join(',') + : buildErrorMessage(response) + }`, + ); + + if (!message) { + this.data = Array.isArray(response) + ? response.map(r => r.error?.data as ErrorType) + : response?.error?.data; + } + + this.request = request; + let errorOrErrors: JsonRpcError | JsonRpcError[] | undefined; + if (`error` in response) { + errorOrErrors = response.error as JsonRpcError; + } else if (response instanceof Array) { + errorOrErrors = response.map(r => r.error) as JsonRpcError[]; + } + + this.innerError = errorOrErrors as Error | Error[] | undefined; + } + + public toJSON() { + return { ...super.toJSON(), data: this.data, request: this.request }; + } +} + +export class InvalidResponseError extends ResponseError< + ErrorType, + RequestType +> { + public constructor( + result: JsonRpcResponse, + request?: JsonRpcPayload, + ) { + super(result, undefined, request); + this.code = ERR_INVALID_RESPONSE; + let errorOrErrors: JsonRpcError | JsonRpcError[] | undefined; + if (`error` in result) { + errorOrErrors = result.error as JsonRpcError; + } else if (result instanceof Array) { + errorOrErrors = result.map(r => r.error) as JsonRpcError[]; + } + + this.innerError = errorOrErrors as Error | Error[] | undefined; + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/rpc_error_messages.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/rpc_error_messages.ts new file mode 100644 index 0000000..f61c5a4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/rpc_error_messages.ts @@ -0,0 +1,221 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + ERR_RPC_INTERNAL_ERROR, + ERR_RPC_INVALID_INPUT, + ERR_RPC_INVALID_JSON, + ERR_RPC_INVALID_METHOD, + ERR_RPC_INVALID_PARAMS, + ERR_RPC_INVALID_REQUEST, + ERR_RPC_LIMIT_EXCEEDED, + ERR_RPC_MISSING_RESOURCE, + ERR_RPC_NOT_SUPPORTED, + ERR_RPC_TRANSACTION_REJECTED, + ERR_RPC_UNAVAILABLE_RESOURCE, + ERR_RPC_UNSUPPORTED_METHOD, + JSONRPC_ERR_CHAIN_DISCONNECTED, + JSONRPC_ERR_DISCONNECTED, + JSONRPC_ERR_REJECTED_REQUEST, + JSONRPC_ERR_UNAUTHORIZED, + JSONRPC_ERR_UNSUPPORTED_METHOD, +} from '../error_codes.js'; + +/** + * A template string for a generic Rpc Error. The `*code*` will be replaced with the code number. + * Note: consider in next version that a spelling mistake could be corrected for `occured` and the value could be: + * `An Rpc error has occurred with a code of *code*` + */ +export const genericRpcErrorMessageTemplate = 'An Rpc error has occured with a code of *code*'; + +/* eslint-disable @typescript-eslint/naming-convention */ +export const RpcErrorMessages: { + [key: number | string]: { name?: string; message: string; description?: string }; +} = { + // EIP-1474 & JSON RPC 2.0 + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md + [ERR_RPC_INVALID_JSON]: { + message: 'Parse error', + description: 'Invalid JSON', + }, + [ERR_RPC_INVALID_REQUEST]: { + message: 'Invalid request', + description: 'JSON is not a valid request object ', + }, + [ERR_RPC_INVALID_METHOD]: { + message: 'Method not found', + description: 'Method does not exist ', + }, + [ERR_RPC_INVALID_PARAMS]: { + message: 'Invalid params', + description: 'Invalid method parameters', + }, + [ERR_RPC_INTERNAL_ERROR]: { + message: 'Internal error', + description: 'Internal JSON-RPC error', + }, + + [ERR_RPC_INVALID_INPUT]: { + message: 'Invalid input', + description: 'Missing or invalid parameters', + }, + [ERR_RPC_MISSING_RESOURCE]: { + message: 'Resource not found', + description: 'Requested resource not found', + }, + [ERR_RPC_UNAVAILABLE_RESOURCE]: { + message: 'Resource unavailable', + description: 'Requested resource not available', + }, + [ERR_RPC_TRANSACTION_REJECTED]: { + message: 'Transaction rejected', + description: 'Transaction creation failed', + }, + [ERR_RPC_UNSUPPORTED_METHOD]: { + message: 'Method not supported', + description: 'Method is not implemented', + }, + [ERR_RPC_LIMIT_EXCEEDED]: { + message: 'Limit exceeded', + description: 'Request exceeds defined limit', + }, + [ERR_RPC_NOT_SUPPORTED]: { + message: 'JSON-RPC version not supported', + description: 'Version of JSON-RPC protocol is not supported', + }, + + // EIP-1193 + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors + [JSONRPC_ERR_REJECTED_REQUEST]: { + name: 'User Rejected Request', + message: 'The user rejected the request.', + }, + [JSONRPC_ERR_UNAUTHORIZED]: { + name: 'Unauthorized', + message: 'The requested method and/or account has not been authorized by the user.', + }, + [JSONRPC_ERR_UNSUPPORTED_METHOD]: { + name: 'Unsupported Method', + message: 'The Provider does not support the requested method.', + }, + [JSONRPC_ERR_DISCONNECTED]: { + name: 'Disconnected', + message: 'The Provider is disconnected from all chains.', + }, + [JSONRPC_ERR_CHAIN_DISCONNECTED]: { + name: 'Chain Disconnected', + message: 'The Provider is not connected to the requested chain.', + }, + + // EIP-1193 - CloseEvent + // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code + '0-999': { + name: '', + message: 'Not used.', + }, + 1000: { + name: 'Normal Closure', + message: 'The connection successfully completed the purpose for which it was created.', + }, + 1001: { + name: 'Going Away', + message: + 'The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection.', + }, + 1002: { + name: 'Protocol error', + message: 'The endpoint is terminating the connection due to a protocol error.', + }, + 1003: { + name: 'Unsupported Data', + message: + 'The connection is being terminated because the endpoint received data of a type it cannot accept. (For example, a text-only endpoint received binary data.)', + }, + 1004: { + name: 'Reserved', + message: 'Reserved. A meaning might be defined in the future.', + }, + 1005: { + name: 'No Status Rcvd', + message: + 'Reserved. Indicates that no status code was provided even though one was expected.', + }, + 1006: { + name: 'Abnormal Closure', + message: + 'Reserved. Indicates that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected.', + }, + 1007: { + name: 'Invalid frame payload data', + message: + 'The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).', + }, + 1008: { + name: 'Policy Violation', + message: + 'The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.', + }, + 1009: { + name: 'Message Too Big', + message: + 'The endpoint is terminating the connection because a data frame was received that is too large.', + }, + 1010: { + name: 'Mandatory Ext.', + message: + "The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't.", + }, + 1011: { + name: 'Internal Error', + message: + 'The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.', + }, + 1012: { + name: 'Service Restart', + message: 'The server is terminating the connection because it is restarting.', + }, + 1013: { + name: 'Try Again Later', + message: + 'The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients.', + }, + 1014: { + name: 'Bad Gateway', + message: + 'The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code.', + }, + 1015: { + name: 'TLS handshake', + message: + "Reserved. Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).", + }, + '1016-2999': { + name: '', + message: + 'For definition by future revisions of the WebSocket Protocol specification, and for definition by extension specifications.', + }, + '3000-3999': { + name: '', + message: + 'For use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by the WebSocket protocol.', + }, + '4000-4999': { + name: '', + message: + "For private use, and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by the WebSocket protocol.", + }, +}; diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/rpc_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/rpc_errors.ts new file mode 100644 index 0000000..d7f7e89 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/rpc_errors.ts @@ -0,0 +1,197 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { JsonRpcResponseWithError, JsonRpcId, JsonRpcError } from 'web3-types'; +import { BaseWeb3Error } from '../web3_error_base.js'; +import { + ERR_RPC_INTERNAL_ERROR, + ERR_RPC_INVALID_INPUT, + ERR_RPC_INVALID_JSON, + ERR_RPC_INVALID_METHOD, + ERR_RPC_INVALID_PARAMS, + ERR_RPC_INVALID_REQUEST, + ERR_RPC_LIMIT_EXCEEDED, + ERR_RPC_MISSING_RESOURCE, + ERR_RPC_NOT_SUPPORTED, + ERR_RPC_TRANSACTION_REJECTED, + ERR_RPC_UNAVAILABLE_RESOURCE, + ERR_RPC_UNSUPPORTED_METHOD, +} from '../error_codes.js'; +import { RpcErrorMessages, genericRpcErrorMessageTemplate } from './rpc_error_messages.js'; + +export class RpcError extends BaseWeb3Error { + public code: number; + public id: JsonRpcId; + public jsonrpc: string; + public jsonRpcError: JsonRpcError; + public constructor(rpcError: JsonRpcResponseWithError, message?: string) { + super( + message ?? + genericRpcErrorMessageTemplate.replace('*code*', rpcError.error.code.toString()), + ); + this.code = rpcError.error.code; + this.id = rpcError.id; + this.jsonrpc = rpcError.jsonrpc; + this.jsonRpcError = rpcError.error; + } + + public toJSON() { + return { ...super.toJSON(), error: this.jsonRpcError, id: this.id, jsonRpc: this.jsonrpc }; + } +} + +export class EIP1193ProviderRpcError extends BaseWeb3Error { + public code: number; + public data?: unknown; + + public constructor(code: number, data?: unknown) { + if (!code) { + // this case should ideally not happen + super(); + } else if (RpcErrorMessages[code]?.message) { + super(RpcErrorMessages[code].message); + } else { + // Retrieve the status code object for the given code from the table, by searching through the appropriate range + const statusCodeRange = Object.keys(RpcErrorMessages).find( + statusCode => + typeof statusCode === 'string' && + code >= parseInt(statusCode.split('-')[0], 10) && + code <= parseInt(statusCode.split('-')[1], 10), + ); + super( + RpcErrorMessages[statusCodeRange ?? '']?.message ?? + genericRpcErrorMessageTemplate.replace('*code*', code?.toString() ?? '""'), + ); + } + this.code = code; + this.data = data; + } +} + +export class ParseError extends RpcError { + public code = ERR_RPC_INVALID_JSON; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_JSON].message); + } +} + +export class InvalidRequestError extends RpcError { + public code = ERR_RPC_INVALID_REQUEST; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_REQUEST].message); + } +} + +export class MethodNotFoundError extends RpcError { + public code = ERR_RPC_INVALID_METHOD; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_METHOD].message); + } +} + +export class InvalidParamsError extends RpcError { + public code = ERR_RPC_INVALID_PARAMS; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_PARAMS].message); + } +} + +export class InternalError extends RpcError { + public code = ERR_RPC_INTERNAL_ERROR; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INTERNAL_ERROR].message); + } +} + +export class InvalidInputError extends RpcError { + public code = ERR_RPC_INVALID_INPUT; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_INVALID_INPUT].message); + } +} + +export class MethodNotSupported extends RpcError { + public code = ERR_RPC_UNSUPPORTED_METHOD; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_UNSUPPORTED_METHOD].message); + } +} + +export class ResourceUnavailableError extends RpcError { + public code = ERR_RPC_UNAVAILABLE_RESOURCE; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_UNAVAILABLE_RESOURCE].message); + } +} + +export class ResourcesNotFoundError extends RpcError { + public code = ERR_RPC_MISSING_RESOURCE; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_MISSING_RESOURCE].message); + } +} + +export class VersionNotSupportedError extends RpcError { + public code = ERR_RPC_NOT_SUPPORTED; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_NOT_SUPPORTED].message); + } +} + +export class TransactionRejectedError extends RpcError { + public code = ERR_RPC_TRANSACTION_REJECTED; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_TRANSACTION_REJECTED].message); + } +} + +export class LimitExceededError extends RpcError { + public code = ERR_RPC_LIMIT_EXCEEDED; + public constructor(rpcError: JsonRpcResponseWithError) { + super(rpcError, RpcErrorMessages[ERR_RPC_LIMIT_EXCEEDED].message); + } +} + +export const rpcErrorsMap = new Map(); +rpcErrorsMap.set(ERR_RPC_INVALID_JSON, { error: ParseError }); +rpcErrorsMap.set(ERR_RPC_INVALID_REQUEST, { + error: InvalidRequestError, +}); +rpcErrorsMap.set(ERR_RPC_INVALID_METHOD, { + error: MethodNotFoundError, +}); +rpcErrorsMap.set(ERR_RPC_INVALID_PARAMS, { error: InvalidParamsError }); +rpcErrorsMap.set(ERR_RPC_INTERNAL_ERROR, { error: InternalError }); +rpcErrorsMap.set(ERR_RPC_INVALID_INPUT, { error: InvalidInputError }); +rpcErrorsMap.set(ERR_RPC_UNSUPPORTED_METHOD, { + error: MethodNotSupported, +}); +rpcErrorsMap.set(ERR_RPC_UNAVAILABLE_RESOURCE, { + error: ResourceUnavailableError, +}); +rpcErrorsMap.set(ERR_RPC_TRANSACTION_REJECTED, { + error: TransactionRejectedError, +}); +rpcErrorsMap.set(ERR_RPC_MISSING_RESOURCE, { + error: ResourcesNotFoundError, +}); +rpcErrorsMap.set(ERR_RPC_NOT_SUPPORTED, { + error: VersionNotSupportedError, +}); +rpcErrorsMap.set(ERR_RPC_LIMIT_EXCEEDED, { error: LimitExceededError }); diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/schema_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/schema_errors.ts new file mode 100644 index 0000000..4d61684 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/schema_errors.ts @@ -0,0 +1,32 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ERR_SCHEMA_FORMAT } from '../error_codes.js'; +import { BaseWeb3Error } from '../web3_error_base.js'; + +export class SchemaFormatError extends BaseWeb3Error { + public code = ERR_SCHEMA_FORMAT; + + public constructor(public type: string) { + super(`Format for the type ${type} is unsupported`); + } + + public toJSON() { + return { ...super.toJSON(), type: this.type }; + } + +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/signature_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/signature_errors.ts new file mode 100644 index 0000000..c5a0717 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/signature_errors.ts @@ -0,0 +1,23 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ERR_SIGNATURE_FAILED } from '../error_codes.js'; +import { InvalidValueError } from '../web3_error_base.js'; + +export class SignatureError extends InvalidValueError { + public code = ERR_SIGNATURE_FAILED; +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/transaction_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/transaction_errors.ts new file mode 100644 index 0000000..69c5637 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/transaction_errors.ts @@ -0,0 +1,589 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { + Bytes, + HexString, + Numbers, + TransactionReceipt, + Web3ValidationErrorObject, +} from 'web3-types'; +import { + ERR_RAW_TX_UNDEFINED, + ERR_TX, + ERR_TX_BLOCK_TIMEOUT, + ERR_TX_CONTRACT_NOT_STORED, + ERR_TX_CHAIN_ID_MISMATCH, + ERR_TX_DATA_AND_INPUT, + ERR_TX_GAS_MISMATCH, + ERR_TX_CHAIN_MISMATCH, + ERR_TX_HARDFORK_MISMATCH, + ERR_TX_INVALID_CALL, + ERR_TX_INVALID_CHAIN_INFO, + ERR_TX_INVALID_FEE_MARKET_GAS, + ERR_TX_INVALID_FEE_MARKET_GAS_PRICE, + ERR_TX_INVALID_LEGACY_FEE_MARKET, + ERR_TX_INVALID_LEGACY_GAS, + ERR_TX_INVALID_NONCE_OR_CHAIN_ID, + ERR_TX_INVALID_OBJECT, + ERR_TX_INVALID_SENDER, + ERR_TX_INVALID_RECEIVER, + ERR_TX_LOCAL_WALLET_NOT_AVAILABLE, + ERR_TX_MISSING_CHAIN_INFO, + ERR_TX_MISSING_CUSTOM_CHAIN, + ERR_TX_MISSING_CUSTOM_CHAIN_ID, + ERR_TX_MISSING_GAS, + ERR_TX_NO_CONTRACT_ADDRESS, + ERR_TX_NOT_FOUND, + ERR_TX_OUT_OF_GAS, + ERR_TX_POLLING_TIMEOUT, + ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER, + ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL, + ERR_TX_REVERT_INSTRUCTION, + ERR_TX_REVERT_TRANSACTION, + ERR_TX_REVERT_WITHOUT_REASON, + ERR_TX_SEND_TIMEOUT, + ERR_TX_SIGNING, + ERR_TX_UNABLE_TO_POPULATE_NONCE, + ERR_TX_UNSUPPORTED_EIP_1559, + ERR_TX_UNSUPPORTED_TYPE, + ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR, + ERR_TX_INVALID_PROPERTIES_FOR_TYPE, + ERR_TX_MISSING_GAS_INNER_ERROR, + ERR_TX_GAS_MISMATCH_INNER_ERROR, +} from '../error_codes.js'; +import { InvalidValueError, BaseWeb3Error } from '../web3_error_base.js'; + +export class TransactionError extends BaseWeb3Error { + public code = ERR_TX; + + public constructor(message: string, public receipt?: ReceiptType) { + super(message); + } + + public toJSON() { + return { ...super.toJSON(), receipt: this.receipt }; + } +} + +export class RevertInstructionError extends BaseWeb3Error { + public code = ERR_TX_REVERT_INSTRUCTION; + + public constructor(public reason: string, public signature: string) { + super(`Your request got reverted with the following reason string: ${reason}`); + } + + public toJSON() { + return { ...super.toJSON(), reason: this.reason, signature: this.signature }; + } +} + +export class TransactionRevertInstructionError< + ReceiptType = TransactionReceipt, +> extends BaseWeb3Error { + public code = ERR_TX_REVERT_TRANSACTION; + + public constructor( + public reason: string, + public signature?: string, + public receipt?: ReceiptType, + public data?: string, + ) { + super( + `Transaction has been reverted by the EVM${ + receipt === undefined ? '' : `:\n ${BaseWeb3Error.convertToString(receipt)}` + }`, + ); + } + + public toJSON() { + return { + ...super.toJSON(), + reason: this.reason, + signature: this.signature, + receipt: this.receipt, + data: this.data, + }; + } +} + +/** + * This error is used when a transaction to a smart contract fails and + * a custom user error (https://blog.soliditylang.org/2021/04/21/custom-errors/) + * is able to be parsed from the revert reason + */ +export class TransactionRevertWithCustomError< + ReceiptType = TransactionReceipt, +> extends TransactionRevertInstructionError { + public code = ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR; + + public constructor( + public reason: string, + public customErrorName: string, + public customErrorDecodedSignature: string, + public customErrorArguments: Record, + public signature?: string, + public receipt?: ReceiptType, + public data?: string, + ) { + super(reason); + } + + public toJSON() { + return { + ...super.toJSON(), + reason: this.reason, + customErrorName: this.customErrorName, + customErrorDecodedSignature: this.customErrorDecodedSignature, + customErrorArguments: this.customErrorArguments, + signature: this.signature, + receipt: this.receipt, + data: this.data, + }; + } +} + +export class NoContractAddressFoundError extends TransactionError { + public constructor(receipt: TransactionReceipt) { + super("The transaction receipt didn't contain a contract address.", receipt); + this.code = ERR_TX_NO_CONTRACT_ADDRESS; + } + + public toJSON() { + return { ...super.toJSON(), receipt: this.receipt }; + } +} + +export class ContractCodeNotStoredError extends TransactionError { + public constructor(receipt: TransactionReceipt) { + super("The contract code couldn't be stored, please check your gas limit.", receipt); + this.code = ERR_TX_CONTRACT_NOT_STORED; + } +} + +export class TransactionRevertedWithoutReasonError< + ReceiptType = TransactionReceipt, +> extends TransactionError { + public constructor(receipt?: ReceiptType) { + super( + `Transaction has been reverted by the EVM${ + receipt === undefined ? '' : `:\n ${BaseWeb3Error.convertToString(receipt)}` + }`, + receipt, + ); + this.code = ERR_TX_REVERT_WITHOUT_REASON; + } +} + +export class TransactionOutOfGasError extends TransactionError { + public constructor(receipt: TransactionReceipt) { + super( + `Transaction ran out of gas. Please provide more gas:\n ${JSON.stringify( + receipt, + undefined, + 2, + )}`, + receipt, + ); + this.code = ERR_TX_OUT_OF_GAS; + } +} + +export class UndefinedRawTransactionError extends TransactionError { + public constructor() { + super(`Raw transaction undefined`); + this.code = ERR_RAW_TX_UNDEFINED; + } +} +export class TransactionNotFound extends TransactionError { + public constructor() { + super('Transaction not found'); + this.code = ERR_TX_NOT_FOUND; + } +} + +export class InvalidTransactionWithSender extends InvalidValueError { + public code = ERR_TX_INVALID_SENDER; + + public constructor(value: unknown) { + super(value, 'invalid transaction with invalid sender'); + } +} +export class InvalidTransactionWithReceiver extends InvalidValueError { + public code = ERR_TX_INVALID_RECEIVER; + + public constructor(value: unknown) { + super(value, 'invalid transaction with invalid receiver'); + } +} +export class InvalidTransactionCall extends InvalidValueError { + public code = ERR_TX_INVALID_CALL; + + public constructor(value: unknown) { + super(value, 'invalid transaction call'); + } +} + +export class MissingCustomChainError extends InvalidValueError { + public code = ERR_TX_MISSING_CUSTOM_CHAIN; + + public constructor() { + super( + 'MissingCustomChainError', + 'If tx.common is provided it must have tx.common.customChain', + ); + } +} + +export class MissingCustomChainIdError extends InvalidValueError { + public code = ERR_TX_MISSING_CUSTOM_CHAIN_ID; + + public constructor() { + super( + 'MissingCustomChainIdError', + 'If tx.common is provided it must have tx.common.customChain and tx.common.customChain.chainId', + ); + } +} + +export class ChainIdMismatchError extends InvalidValueError { + public code = ERR_TX_CHAIN_ID_MISMATCH; + + public constructor(value: { txChainId: unknown; customChainId: unknown }) { + super( + JSON.stringify(value), + // https://github.com/ChainSafe/web3.js/blob/8783f4d64e424456bdc53b34ef1142d0a7cee4d7/packages/web3-eth-accounts/src/index.js#L176 + 'Chain Id doesnt match in tx.chainId tx.common.customChain.chainId', + ); + } +} + +export class ChainMismatchError extends InvalidValueError { + public code = ERR_TX_CHAIN_MISMATCH; + + public constructor(value: { txChain: unknown; baseChain: unknown }) { + super(JSON.stringify(value), 'Chain doesnt match in tx.chain tx.common.basechain'); + } +} + +export class HardforkMismatchError extends InvalidValueError { + public code = ERR_TX_HARDFORK_MISMATCH; + + public constructor(value: { txHardfork: unknown; commonHardfork: unknown }) { + super(JSON.stringify(value), 'hardfork doesnt match in tx.hardfork tx.common.hardfork'); + } +} + +export class CommonOrChainAndHardforkError extends InvalidValueError { + public code = ERR_TX_INVALID_CHAIN_INFO; + + public constructor() { + super( + 'CommonOrChainAndHardforkError', + 'Please provide the common object or the chain and hardfork property but not all together.', + ); + } +} + +export class MissingChainOrHardforkError extends InvalidValueError { + public code = ERR_TX_MISSING_CHAIN_INFO; + + public constructor(value: { chain: string | undefined; hardfork: string | undefined }) { + super( + 'MissingChainOrHardforkError', + `When specifying chain and hardfork, both values must be defined. Received "chain": ${ + value.chain ?? 'undefined' + }, "hardfork": ${value.hardfork ?? 'undefined'}`, + ); + } +} + +export class MissingGasInnerError extends BaseWeb3Error { + public code = ERR_TX_MISSING_GAS_INNER_ERROR; + + public constructor() { + super( + 'Missing properties in transaction, either define "gas" and "gasPrice" for type 0 transactions or "gas", "maxPriorityFeePerGas" and "maxFeePerGas" for type 2 transactions', + ); + } +} + +export class MissingGasError extends InvalidValueError { + public code = ERR_TX_MISSING_GAS; + + public constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }) { + super( + `gas: ${value.gas ?? 'undefined'}, gasPrice: ${ + value.gasPrice ?? 'undefined' + }, maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${ + value.maxFeePerGas ?? 'undefined' + }`, + '"gas" is missing', + ); + this.innerError = new MissingGasInnerError(); + } +} + +export class TransactionGasMismatchInnerError extends BaseWeb3Error { + public code = ERR_TX_GAS_MISMATCH_INNER_ERROR; + + public constructor() { + super( + 'Missing properties in transaction, either define "gas" and "gasPrice" for type 0 transactions or "gas", "maxPriorityFeePerGas" and "maxFeePerGas" for type 2 transactions, not both', + ); + } +} + +export class TransactionGasMismatchError extends InvalidValueError { + public code = ERR_TX_GAS_MISMATCH; + + public constructor(value: { + gas: Numbers | undefined; + gasPrice: Numbers | undefined; + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }) { + super( + `gas: ${value.gas ?? 'undefined'}, gasPrice: ${ + value.gasPrice ?? 'undefined' + }, maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${ + value.maxFeePerGas ?? 'undefined' + }`, + 'transaction must specify legacy or fee market gas properties, not both', + ); + this.innerError = new TransactionGasMismatchInnerError(); + } +} + +export class InvalidGasOrGasPrice extends InvalidValueError { + public code = ERR_TX_INVALID_LEGACY_GAS; + + public constructor(value: { gas: Numbers | undefined; gasPrice: Numbers | undefined }) { + super( + `gas: ${value.gas ?? 'undefined'}, gasPrice: ${value.gasPrice ?? 'undefined'}`, + 'Gas or gasPrice is lower than 0', + ); + } +} + +export class InvalidMaxPriorityFeePerGasOrMaxFeePerGas extends InvalidValueError { + public code = ERR_TX_INVALID_FEE_MARKET_GAS; + + public constructor(value: { + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }) { + super( + `maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${ + value.maxFeePerGas ?? 'undefined' + }`, + 'maxPriorityFeePerGas or maxFeePerGas is lower than 0', + ); + } +} + +export class Eip1559GasPriceError extends InvalidValueError { + public code = ERR_TX_INVALID_FEE_MARKET_GAS_PRICE; + + public constructor(value: unknown) { + super(value, "eip-1559 transactions don't support gasPrice"); + } +} + +export class UnsupportedFeeMarketError extends InvalidValueError { + public code = ERR_TX_INVALID_LEGACY_FEE_MARKET; + + public constructor(value: { + maxPriorityFeePerGas: Numbers | undefined; + maxFeePerGas: Numbers | undefined; + }) { + super( + `maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${ + value.maxFeePerGas ?? 'undefined' + }`, + "pre-eip-1559 transaction don't support maxFeePerGas/maxPriorityFeePerGas", + ); + } +} + +export class InvalidTransactionObjectError extends InvalidValueError { + public code = ERR_TX_INVALID_OBJECT; + + public constructor(value: unknown) { + super(value, 'invalid transaction object'); + } +} + +export class InvalidNonceOrChainIdError extends InvalidValueError { + public code = ERR_TX_INVALID_NONCE_OR_CHAIN_ID; + + public constructor(value: { nonce: Numbers | undefined; chainId: Numbers | undefined }) { + super( + `nonce: ${value.nonce ?? 'undefined'}, chainId: ${value.chainId ?? 'undefined'}`, + 'Nonce or chainId is lower than 0', + ); + } +} + +export class UnableToPopulateNonceError extends InvalidValueError { + public code = ERR_TX_UNABLE_TO_POPULATE_NONCE; + + public constructor() { + super('UnableToPopulateNonceError', 'unable to populate nonce, no from address available'); + } +} + +export class Eip1559NotSupportedError extends InvalidValueError { + public code = ERR_TX_UNSUPPORTED_EIP_1559; + + public constructor() { + super('Eip1559NotSupportedError', "Network doesn't support eip-1559"); + } +} + +export class UnsupportedTransactionTypeError extends InvalidValueError { + public code = ERR_TX_UNSUPPORTED_TYPE; + + public constructor(value: unknown) { + super(value, 'unsupported transaction type'); + } +} + +export class TransactionDataAndInputError extends InvalidValueError { + public code = ERR_TX_DATA_AND_INPUT; + + public constructor(value: { data: HexString | undefined; input: HexString | undefined }) { + super( + `data: ${value.data ?? 'undefined'}, input: ${value.input ?? 'undefined'}`, + 'You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.', + ); + } +} + +export class TransactionSendTimeoutError extends BaseWeb3Error { + public code = ERR_TX_SEND_TIMEOUT; + + public constructor(value: { numberOfSeconds: number; transactionHash?: Bytes }) { + super( + `The connected Ethereum Node did not respond within ${ + value.numberOfSeconds + } seconds, please make sure your transaction was properly sent and you are connected to a healthy Node. Be aware that transaction might still be pending or mined!\n\tTransaction Hash: ${ + value.transactionHash ? value.transactionHash.toString() : 'not available' + }`, + ); + } +} + +function transactionTimeoutHint(transactionHash?: Bytes) { + return `Please make sure your transaction was properly sent and there are no previous pending transaction for the same account. However, be aware that it might still be mined!\n\tTransaction Hash: ${ + transactionHash ? transactionHash.toString() : 'not available' + }`; +} + +export class TransactionPollingTimeoutError extends BaseWeb3Error { + public code = ERR_TX_POLLING_TIMEOUT; + + public constructor(value: { numberOfSeconds: number; transactionHash: Bytes }) { + super( + `Transaction was not mined within ${ + value.numberOfSeconds + } seconds. ${transactionTimeoutHint(value.transactionHash)}`, + ); + } +} + +export class TransactionBlockTimeoutError extends BaseWeb3Error { + public code = ERR_TX_BLOCK_TIMEOUT; + + public constructor(value: { + starterBlockNumber: number; + numberOfBlocks: number; + transactionHash?: Bytes; + }) { + super( + `Transaction started at ${value.starterBlockNumber} but was not mined within ${ + value.numberOfBlocks + } blocks. ${transactionTimeoutHint(value.transactionHash)}`, + ); + } +} + +export class TransactionMissingReceiptOrBlockHashError extends InvalidValueError { + public code = ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL; + + public constructor(value: { + receipt: TransactionReceipt; + blockHash: Bytes; + transactionHash: Bytes; + }) { + super( + `receipt: ${JSON.stringify( + value.receipt, + )}, blockHash: ${value.blockHash?.toString()}, transactionHash: ${value.transactionHash?.toString()}`, + `Receipt missing or blockHash null`, + ); + } +} + +export class TransactionReceiptMissingBlockNumberError extends InvalidValueError { + public code = ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER; + + public constructor(value: { receipt: TransactionReceipt }) { + super(`receipt: ${JSON.stringify(value.receipt)}`, `Receipt missing block number`); + } +} + +export class TransactionSigningError extends BaseWeb3Error { + public code = ERR_TX_SIGNING; + public constructor(errorDetails: string) { + super(`Invalid signature. "${errorDetails}"`); + } +} + +export class LocalWalletNotAvailableError extends InvalidValueError { + public code = ERR_TX_LOCAL_WALLET_NOT_AVAILABLE; + + public constructor() { + super( + 'LocalWalletNotAvailableError', + `Attempted to index account in local wallet, but no wallet is available`, + ); + } +} +export class InvalidPropertiesForTransactionTypeError extends BaseWeb3Error { + public code = ERR_TX_INVALID_PROPERTIES_FOR_TYPE; + + public constructor( + validationError: Web3ValidationErrorObject[], + txType: '0x0' | '0x1' | '0x2', + ) { + const invalidPropertyNames: string[] = []; + validationError.forEach(error => invalidPropertyNames.push(error.keyword)); + super( + `The following properties are invalid for the transaction type ${txType}: ${invalidPropertyNames.join( + ', ', + )}`, + ); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/errors/utils_errors.ts b/test/merkletreejs/node_modules/web3-errors/src/errors/utils_errors.ts new file mode 100644 index 0000000..b93ff96 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/errors/utils_errors.ts @@ -0,0 +1,148 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { + ERR_INVALID_BYTES, + ERR_INVALID_NUMBER, + ERR_INVALID_ADDRESS, + ERR_INVALID_BLOCK, + ERR_INVALID_BOOLEAN, + ERR_INVALID_HEX, + ERR_INVALID_LARGE_VALUE, + ERR_INVALID_NIBBLE_WIDTH, + ERR_INVALID_SIZE, + ERR_INVALID_STRING, + ERR_INVALID_TYPE, + ERR_INVALID_TYPE_ABI, + ERR_INVALID_UNIT, + ERR_INVALID_UNSIGNED_INTEGER, +} from '../error_codes.js'; +import { InvalidValueError } from '../web3_error_base.js'; + +export class InvalidBytesError extends InvalidValueError { + public code = ERR_INVALID_BYTES; + + public constructor(value: unknown) { + super(value, 'can not parse as byte data'); + } +} + +export class InvalidNumberError extends InvalidValueError { + public code = ERR_INVALID_NUMBER; + + public constructor(value: unknown) { + super(value, 'can not parse as number data'); + } +} + +export class InvalidAddressError extends InvalidValueError { + public code = ERR_INVALID_ADDRESS; + + public constructor(value: unknown) { + super(value, 'invalid ethereum address'); + } +} + +export class InvalidStringError extends InvalidValueError { + public code = ERR_INVALID_STRING; + + public constructor(value: unknown) { + super(value, 'not a valid string'); + } +} + +export class InvalidUnitError extends InvalidValueError { + public code = ERR_INVALID_UNIT; + + public constructor(value: unknown) { + super(value, 'invalid unit'); + } +} + +export class HexProcessingError extends InvalidValueError { + public code = ERR_INVALID_HEX; + + public constructor(value: unknown) { + super(value, 'can not be converted to hex'); + } +} + +export class NibbleWidthError extends InvalidValueError { + public code = ERR_INVALID_NIBBLE_WIDTH; + + public constructor(value: string) { + super(value, 'value greater than the nibble width'); + } +} + +export class InvalidTypeError extends InvalidValueError { + public code = ERR_INVALID_TYPE; + + public constructor(value: unknown) { + super(value, 'invalid type, type not supported'); + } +} + +export class InvalidBooleanError extends InvalidValueError { + public code = ERR_INVALID_BOOLEAN; + + public constructor(value: unknown) { + super(value, 'not a valid boolean.'); + } +} + +export class InvalidUnsignedIntegerError extends InvalidValueError { + public code = ERR_INVALID_UNSIGNED_INTEGER; + + public constructor(value: unknown) { + super(value, 'not a valid unsigned integer.'); + } +} + +export class InvalidSizeError extends InvalidValueError { + public code = ERR_INVALID_SIZE; + + public constructor(value: unknown) { + super(value, 'invalid size given.'); + } +} + +export class InvalidLargeValueError extends InvalidValueError { + public code = ERR_INVALID_LARGE_VALUE; + + public constructor(value: unknown) { + super(value, 'value is larger than size.'); + } +} + +export class InvalidBlockError extends InvalidValueError { + public code = ERR_INVALID_BLOCK; + + public constructor(value: string) { + super(value, 'invalid string given'); + } +} + +export class InvalidTypeAbiInputError extends InvalidValueError { + public code = ERR_INVALID_TYPE_ABI; + + public constructor(value: string) { + super(value, 'components found but type is not tuple'); + } +} diff --git a/test/merkletreejs/node_modules/web3-errors/src/index.ts b/test/merkletreejs/node_modules/web3-errors/src/index.ts new file mode 100644 index 0000000..2e4ef7a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/index.ts @@ -0,0 +1,33 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './error_codes.js'; +export * from './web3_error_base.js'; +export * from './errors/account_errors.js'; +export * from './errors/connection_errors.js'; +export * from './errors/contract_errors.js'; +export * from './errors/ens_errors.js'; +export * from './errors/generic_errors.js'; +export * from './errors/provider_errors.js'; +export * from './errors/signature_errors.js'; +export * from './errors/transaction_errors.js'; +export * from './errors/utils_errors.js'; +export * from './errors/response_errors.js'; +export * from './errors/core_errors.js'; +export * from './errors/rpc_errors.js'; +export * from './errors/rpc_error_messages.js'; +export * from './errors/schema_errors.js'; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-errors/src/web3_error_base.ts b/test/merkletreejs/node_modules/web3-errors/src/web3_error_base.ts new file mode 100644 index 0000000..72a6fd0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-errors/src/web3_error_base.ts @@ -0,0 +1,74 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* eslint-disable max-classes-per-file */ + +import { Web3Error } from 'web3-types'; + +export abstract class BaseWeb3Error extends Error implements Web3Error { + public readonly name: string; + public abstract readonly code: number; + public stack: string | undefined; + public innerError: Error | Error[] | undefined; + + public constructor(msg?: string, innerError?: Error | Error[]) { + super(msg); + this.innerError = innerError; + this.name = this.constructor.name; + + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(new.target.constructor); + } else { + this.stack = new Error().stack; + } + } + + public static convertToString(value: unknown, unquotValue = false) { + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + if (value === null || value === undefined) return 'undefined'; + + const result = JSON.stringify( + value, + (_, v) => (typeof v === 'bigint' ? v.toString() : v) as unknown, + ); + + return unquotValue && ['bigint', 'string'].includes(typeof value) + ? result.replace(/['\\"]+/g, '') + : result; + } + + public toJSON() { + return { + name: this.name, + code: this.code, + message: this.message, + innerError: this.innerError, + }; + } +} + +export abstract class InvalidValueError extends BaseWeb3Error { + public readonly name: string; + + public constructor(value: unknown, msg: string) { + super( + `Invalid value given "${BaseWeb3Error.convertToString(value, true)}". Error: ${msg}.`, + ); + this.name = this.constructor.name; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/LICENSE b/test/merkletreejs/node_modules/web3-eth-abi/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth-abi/README.md b/test/merkletreejs/node_modules/web3-eth-abi/README.md new file mode 100644 index 0000000..bbeb96b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Web3-Eth-Abi + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth-abi` contains functions for the encode and decode EVM in/output. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth-abi) or using [Yarn](https://yarnpkg.com/package/web3-eth-abi) + +### Using NPM + +```bash +npm install web3-eth-abi +``` + +### Using Yarn + +```bash +yarn add web3-eth-abi +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth-abi +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-abi%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth-abi +[downloads-image]: https://img.shields.io/npm/dm/web3-eth-abi?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.d.ts new file mode 100644 index 0000000..18369cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.d.ts @@ -0,0 +1,5 @@ +import { AbiErrorFragment } from 'web3-types'; +/** + * Encodes the error name to its ABI signature, which are the sha3 hash of the error name including input types. + */ +export declare const encodeErrorSignature: (functionName: string | AbiErrorFragment) => string; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.js new file mode 100644 index 0000000..c2ff96f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.js @@ -0,0 +1,40 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeErrorSignature = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +const utils_js_1 = require("../utils.js"); +/** + * Encodes the error name to its ABI signature, which are the sha3 hash of the error name including input types. + */ +const encodeErrorSignature = (functionName) => { + if (typeof functionName !== 'string' && !(0, utils_js_1.isAbiErrorFragment)(functionName)) { + throw new web3_errors_1.AbiError('Invalid parameter value in encodeErrorSignature'); + } + let name; + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = (0, utils_js_1.jsonInterfaceMethodToString)(functionName); + } + else { + name = functionName; + } + return (0, web3_utils_1.sha3Raw)(name); +}; +exports.encodeErrorSignature = encodeErrorSignature; +//# sourceMappingURL=errors_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.js.map new file mode 100644 index 0000000..27eae9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/errors_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors_api.js","sourceRoot":"","sources":["../../../src/api/errors_api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAqC;AACrC,6CAAuC;AAEvC,0CAA8E;AAE9E;;GAEG;AACI,MAAM,oBAAoB,GAAG,CAAC,YAAuC,EAAU,EAAE;IACvF,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,IAAA,6BAAkB,EAAC,YAAY,CAAC,EAAE;QAC1E,MAAM,IAAI,sBAAQ,CAAC,iDAAiD,CAAC,CAAC;KACtE;IAED,IAAI,IAAY,CAAC;IAEjB,IAAI,YAAY,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,IAAI,OAAO,YAAY,KAAK,QAAQ,CAAC,EAAE;QAC7F,IAAI,GAAG,IAAA,sCAA2B,EAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACN,IAAI,GAAG,YAAY,CAAC;KACpB;IAED,OAAO,IAAA,oBAAO,EAAC,IAAI,CAAC,CAAC;AACtB,CAAC,CAAC;AAdW,QAAA,oBAAoB,wBAc/B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.d.ts new file mode 100644 index 0000000..75b6199 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.d.ts @@ -0,0 +1,51 @@ +import { AbiEventFragment } from 'web3-types'; +/** + * Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types. + * @param functionName - The event name to encode, or the {@link AbiEventFragment} object of the event. If string, it has to be in the form of `eventName(param1Type,param2Type,...)`. eg: myEvent(uint256,bytes32). + * @returns - The ABI signature of the event. + * + * @example + * ```ts + * const event = web3.eth.abi.encodeEventSignature({ + * name: "myEvent", + * type: "event", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "bytes32", + * name: "myBytes", + * }, + * ], + * }); + * console.log(event); + * > 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 + * + * const event = web3.eth.abi.encodeEventSignature({ + * inputs: [ + * { + * indexed: true, + * name: "from", + * type: "address", + * }, + * { + * indexed: true, + * name: "to", + * type: "address", + * }, + * { + * indexed: false, + * name: "value", + * type: "uint256", + * }, + * ], + * name: "Transfer", + * type: "event", + * }); + * console.log(event); + * > 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + * ``` + */ +export declare const encodeEventSignature: (functionName: string | AbiEventFragment) => string; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.js new file mode 100644 index 0000000..78cd2c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.js @@ -0,0 +1,86 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeEventSignature = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +const utils_js_1 = require("../utils.js"); +/** + * Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types. + * @param functionName - The event name to encode, or the {@link AbiEventFragment} object of the event. If string, it has to be in the form of `eventName(param1Type,param2Type,...)`. eg: myEvent(uint256,bytes32). + * @returns - The ABI signature of the event. + * + * @example + * ```ts + * const event = web3.eth.abi.encodeEventSignature({ + * name: "myEvent", + * type: "event", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "bytes32", + * name: "myBytes", + * }, + * ], + * }); + * console.log(event); + * > 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 + * + * const event = web3.eth.abi.encodeEventSignature({ + * inputs: [ + * { + * indexed: true, + * name: "from", + * type: "address", + * }, + * { + * indexed: true, + * name: "to", + * type: "address", + * }, + * { + * indexed: false, + * name: "value", + * type: "uint256", + * }, + * ], + * name: "Transfer", + * type: "event", + * }); + * console.log(event); + * > 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + * ``` + */ +const encodeEventSignature = (functionName) => { + if (typeof functionName !== 'string' && !(0, utils_js_1.isAbiEventFragment)(functionName)) { + throw new web3_errors_1.AbiError('Invalid parameter value in encodeEventSignature'); + } + let name; + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = (0, utils_js_1.jsonInterfaceMethodToString)(functionName); + } + else { + name = functionName; + } + return (0, web3_utils_1.sha3Raw)(name); +}; +exports.encodeEventSignature = encodeEventSignature; +//# sourceMappingURL=events_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.js.map new file mode 100644 index 0000000..71d1030 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/events_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events_api.js","sourceRoot":"","sources":["../../../src/api/events_api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAqC;AACrC,6CAAuC;AAEvC,0CAA8E;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACI,MAAM,oBAAoB,GAAG,CAAC,YAAuC,EAAU,EAAE;IACvF,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,IAAA,6BAAkB,EAAC,YAAY,CAAC,EAAE;QAC1E,MAAM,IAAI,sBAAQ,CAAC,iDAAiD,CAAC,CAAC;KACtE;IAED,IAAI,IAAY,CAAC;IAEjB,IAAI,YAAY,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,IAAI,OAAO,YAAY,KAAK,QAAQ,CAAC,EAAE;QAC7F,IAAI,GAAG,IAAA,sCAA2B,EAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACN,IAAI,GAAG,YAAY,CAAC;KACpB;IAED,OAAO,IAAA,oBAAO,EAAC,IAAI,CAAC,CAAC;AACtB,CAAC,CAAC;AAdW,QAAA,oBAAoB,wBAc/B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.d.ts new file mode 100644 index 0000000..7db9fef --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.d.ts @@ -0,0 +1,90 @@ +import { AbiFunctionFragment } from 'web3-types'; +/** + * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. + * @param functionName - The function name to encode or the `JSON interface` object of the function. + * If the passed parameter is a string, it has to be in the form of `functionName(param1Type,param2Type,...)`. eg: myFunction(uint256,uint32[],bytes10,bytes) + * @returns - The ABI signature of the function. + * @example + * ```ts + * const signature = web3.eth.abi.encodeFunctionSignature({ + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }); + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)') + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('safeTransferFrom(address,address,uint256,bytes)'); + * console.log(signature); + * > 0xb88d4fde + * ``` + */ +export declare const encodeFunctionSignature: (functionName: string | AbiFunctionFragment) => string; +/** + * Encodes a function call using its `JSON interface` object and given parameters. + * @param jsonInterface - The `JSON interface` object of the function. + * @param params - The parameters to encode + * @returns - The ABI encoded function call, which, means the function signature and the parameters passed. + * @example + * ```ts + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }, + * ["2345675643", "Hello!%"] + * ); + * console.log(sig); + * > 0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * + * + * + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * inputs: [ + * { + * name: "account", + * type: "address", + * }, + * ], + * name: "balanceOf", + * outputs: [ + * { + * name: "", + * type: "uint256", + * }, + * ], + * stateMutability: "view", + * type: "function", + * }, + * ["0x1234567890123456789012345678901234567890"] + * ); + * + * console.log(sig); + * > 0x70a082310000000000000000000000001234567890123456789012345678901234567890 + * ``` + */ +export declare const encodeFunctionCall: (jsonInterface: AbiFunctionFragment, params: unknown[]) => string; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.js new file mode 100644 index 0000000..c6df7f1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.js @@ -0,0 +1,135 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeFunctionCall = exports.encodeFunctionSignature = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("../utils.js"); +const parameters_api_js_1 = require("./parameters_api.js"); +// todo Add link to JSON interface documentation +/** + * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. + * @param functionName - The function name to encode or the `JSON interface` object of the function. + * If the passed parameter is a string, it has to be in the form of `functionName(param1Type,param2Type,...)`. eg: myFunction(uint256,uint32[],bytes10,bytes) + * @returns - The ABI signature of the function. + * @example + * ```ts + * const signature = web3.eth.abi.encodeFunctionSignature({ + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }); + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)') + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('safeTransferFrom(address,address,uint256,bytes)'); + * console.log(signature); + * > 0xb88d4fde + * ``` + */ +const encodeFunctionSignature = (functionName) => { + if (typeof functionName !== 'string' && !(0, utils_js_1.isAbiFunctionFragment)(functionName)) { + throw new web3_errors_1.AbiError('Invalid parameter value in encodeFunctionSignature'); + } + let name; + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = (0, utils_js_1.jsonInterfaceMethodToString)(functionName); + } + else { + name = functionName; + } + return (0, web3_utils_1.sha3Raw)(name).slice(0, 10); +}; +exports.encodeFunctionSignature = encodeFunctionSignature; +// todo Add link to JSON interface documentation +/** + * Encodes a function call using its `JSON interface` object and given parameters. + * @param jsonInterface - The `JSON interface` object of the function. + * @param params - The parameters to encode + * @returns - The ABI encoded function call, which, means the function signature and the parameters passed. + * @example + * ```ts + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }, + * ["2345675643", "Hello!%"] + * ); + * console.log(sig); + * > 0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * + * + * + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * inputs: [ + * { + * name: "account", + * type: "address", + * }, + * ], + * name: "balanceOf", + * outputs: [ + * { + * name: "", + * type: "uint256", + * }, + * ], + * stateMutability: "view", + * type: "function", + * }, + * ["0x1234567890123456789012345678901234567890"] + * ); + * + * console.log(sig); + * > 0x70a082310000000000000000000000001234567890123456789012345678901234567890 + * ``` + */ +const encodeFunctionCall = (jsonInterface, params) => { + var _a; + if (!(0, utils_js_1.isAbiFunctionFragment)(jsonInterface)) { + throw new web3_errors_1.AbiError('Invalid parameter value in encodeFunctionCall'); + } + return `${(0, exports.encodeFunctionSignature)(jsonInterface)}${(0, parameters_api_js_1.encodeParameters)((_a = jsonInterface.inputs) !== null && _a !== void 0 ? _a : [], params !== null && params !== void 0 ? params : []).replace('0x', '')}`; +}; +exports.encodeFunctionCall = encodeFunctionCall; +//# sourceMappingURL=functions_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.js.map new file mode 100644 index 0000000..02cbca0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/functions_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"functions_api.js","sourceRoot":"","sources":["../../../src/api/functions_api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAAuC;AACvC,2CAAqC;AAErC,0CAAiF;AACjF,2DAAuD;AAEvD,gDAAgD;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACI,MAAM,uBAAuB,GAAG,CAAC,YAA0C,EAAU,EAAE;IAC7F,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,IAAA,gCAAqB,EAAC,YAAY,CAAC,EAAE;QAC7E,MAAM,IAAI,sBAAQ,CAAC,oDAAoD,CAAC,CAAC;KACzE;IAED,IAAI,IAAY,CAAC;IAEjB,IAAI,YAAY,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,IAAI,OAAO,YAAY,KAAK,QAAQ,CAAC,EAAE;QAC7F,IAAI,GAAG,IAAA,sCAA2B,EAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACN,IAAI,GAAG,YAAY,CAAC;KACpB;IAED,OAAO,IAAA,oBAAO,EAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC,CAAC;AAdW,QAAA,uBAAuB,2BAclC;AAEF,gDAAgD;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACI,MAAM,kBAAkB,GAAG,CACjC,aAAkC,EAClC,MAAiB,EACR,EAAE;;IACX,IAAI,CAAC,IAAA,gCAAqB,EAAC,aAAa,CAAC,EAAE;QAC1C,MAAM,IAAI,sBAAQ,CAAC,+CAA+C,CAAC,CAAC;KACpE;IAED,OAAO,GAAG,IAAA,+BAAuB,EAAC,aAAa,CAAC,GAAG,IAAA,oCAAgB,EAClE,MAAA,aAAa,CAAC,MAAM,mCAAI,EAAE,EAC1B,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CACZ,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;AACvB,CAAC,CAAC;AAZW,QAAA,kBAAkB,sBAY7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.d.ts new file mode 100644 index 0000000..fd35531 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.d.ts @@ -0,0 +1,45 @@ +import { HexString, AbiParameter, DecodedParams } from 'web3-types'; +/** + * Decodes ABI-encoded log data and indexed topic data. + * @param inputs - A {@link AbiParameter} input array. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param data - The ABI byte code in the `data` field of a log. + * @param topics - An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0] + * @returns - The result object containing the decoded parameters. + * + * @example + * ```ts + * let res = web3.eth.abi.decodeLog( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * indexed: true, + * }, + * { + * type: "uint8", + * name: "mySmallNumber", + * indexed: true, + * }, + * ], + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000", + * [ + * "0x000000000000000000000000000000000000000000000000000000000000f310", + * "0x0000000000000000000000000000000000000000000000000000000000000010", + * ] + * ); + * > { + * '0': 'Hello%!', + * '1': 62224n, + * '2': 16n, + * __length__: 3, + * myString: 'Hello%!', + * myNumber: 62224n, + * mySmallNumber: 16n + * } + * ``` + */ +export declare const decodeLog: (inputs: Array, data: HexString, topics: string | string[]) => ReturnType_1; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.js new file mode 100644 index 0000000..c31615a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.js @@ -0,0 +1,107 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeLog = void 0; +const parameters_api_js_1 = require("./parameters_api.js"); +const STATIC_TYPES = ['bool', 'string', 'int', 'uint', 'address', 'fixed', 'ufixed']; +const _decodeParameter = (inputType, clonedTopic) => inputType === 'string' ? clonedTopic : (0, parameters_api_js_1.decodeParameter)(inputType, clonedTopic); +/** + * Decodes ABI-encoded log data and indexed topic data. + * @param inputs - A {@link AbiParameter} input array. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param data - The ABI byte code in the `data` field of a log. + * @param topics - An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0] + * @returns - The result object containing the decoded parameters. + * + * @example + * ```ts + * let res = web3.eth.abi.decodeLog( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * indexed: true, + * }, + * { + * type: "uint8", + * name: "mySmallNumber", + * indexed: true, + * }, + * ], + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000", + * [ + * "0x000000000000000000000000000000000000000000000000000000000000f310", + * "0x0000000000000000000000000000000000000000000000000000000000000010", + * ] + * ); + * > { + * '0': 'Hello%!', + * '1': 62224n, + * '2': 16n, + * __length__: 3, + * myString: 'Hello%!', + * myNumber: 62224n, + * mySmallNumber: 16n + * } + * ``` + */ +const decodeLog = (inputs, data, topics) => { + const clonedTopics = Array.isArray(topics) ? topics : [topics]; + const indexedInputs = {}; + const nonIndexedInputs = {}; + for (const [i, input] of inputs.entries()) { + if (input.indexed) { + indexedInputs[i] = input; + } + else { + nonIndexedInputs[i] = input; + } + } + const decodedNonIndexedInputs = data + ? (0, parameters_api_js_1.decodeParametersWith)(Object.values(nonIndexedInputs), data, true) + : { __length__: 0 }; + // If topics are more than indexed inputs, that means first topic is the event signature + const offset = clonedTopics.length - Object.keys(indexedInputs).length; + const decodedIndexedInputs = Object.values(indexedInputs).map((input, index) => STATIC_TYPES.some(s => input.type.startsWith(s)) + ? _decodeParameter(input.type, clonedTopics[index + offset]) + : clonedTopics[index + offset]); + const returnValues = { __length__: 0 }; + let indexedCounter = 0; + let nonIndexedCounter = 0; + for (const [i, res] of inputs.entries()) { + returnValues[i] = res.type === 'string' ? '' : undefined; + if (indexedInputs[i]) { + returnValues[i] = decodedIndexedInputs[indexedCounter]; + indexedCounter += 1; + } + if (nonIndexedInputs[i]) { + returnValues[i] = decodedNonIndexedInputs[String(nonIndexedCounter)]; + nonIndexedCounter += 1; + } + if (res.name) { + returnValues[res.name] = returnValues[i]; + } + returnValues.__length__ += 1; + } + return returnValues; +}; +exports.decodeLog = decodeLog; +//# sourceMappingURL=logs_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.js.map new file mode 100644 index 0000000..78d7d66 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/logs_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logs_api.js","sourceRoot":"","sources":["../../../src/api/logs_api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,2DAA4E;AAE5E,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAErF,MAAM,gBAAgB,GAAG,CAAC,SAAiB,EAAE,WAAmB,EAAE,EAAE,CACnE,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAA,mCAAe,EAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACI,MAAM,SAAS,GAAG,CACxB,MAA2B,EAC3B,IAAe,EACf,MAAyB,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D,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,IAAI,iBAAiB,GAAG,CAAC,CAAC;IAE1B,KAAK,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE;QACxC,YAAY,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;QAEzD,IAAI,aAAa,CAAC,CAAC,CAAC,EAAE;YACrB,YAAY,CAAC,CAAC,CAAC,GAAG,oBAAoB,CAAC,cAAc,CAAC,CAAC;YACvD,cAAc,IAAI,CAAC,CAAC;SACpB;QAED,IAAI,gBAAgB,CAAC,CAAC,CAAC,EAAE;YACxB,YAAY,CAAC,CAAC,CAAC,GAAG,uBAAuB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC;YACrE,iBAAiB,IAAI,CAAC,CAAC;SACvB;QAED,IAAI,GAAG,CAAC,IAAI,EAAE;YACb,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;SACzC;QAED,YAAY,CAAC,UAAU,IAAI,CAAC,CAAC;KAC7B;IAED,OAAO,YAA0B,CAAC;AACnC,CAAC,CAAC;AAzDW,QAAA,SAAS,aAyDpB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.d.ts new file mode 100644 index 0000000..abaafee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.d.ts @@ -0,0 +1,254 @@ +import { AbiInput, HexString } from 'web3-types'; +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - An array of {@link AbiInput}. See [Solidity's documentation](https://solidity.readthedocs.io/en/v0.5.3/abi-spec.html#json) for more details. + * @param params - The actual parameters to encode. + * @returns - The ABI encoded parameters + * @example + * ```ts + * const res = web3.eth.abi.encodeParameters( + * ["uint256", "string"], + * ["2345675643", "Hello!%"] + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * ``` + */ +export declare const encodeParameters: (abi: ReadonlyArray, params: unknown[]) => string; +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param param - The actual parameter to encode. + * @returns - The ABI encoded parameter + * @example + * ```ts + * const res = web3.eth.abi.encodeParameter("uint256", "2345675643"); + * console.log(res); + * 0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("uint", "2345675643"); + * + * console.log(res); + * >0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("bytes32", "0xdf3234"); + * + * console.log(res); + * >0xdf32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes", "0xdf3234"); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes32[]", ["0xdf3234", "0xfdfd"]); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * { + * propertyOne: 42, + * propertyTwo: 56, + * childStruct: { + * propertyOne: 45, + * propertyTwo: 78, + * }, + * } + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e + * ``` + */ +export declare const encodeParameter: (abi: AbiInput, param: unknown) => string; +/** + * Should be used to decode list of params + */ +export declare const decodeParametersWith: (abis: AbiInput[], bytes: HexString, loose: boolean) => { + [key: string]: unknown; + __length__: number; +}; +/** + * Should be used to decode list of params + */ +/** + * Decodes ABI encoded parameters to its JavaScript types. + * @param abi - An array of {@link AbiInput}. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The result object containing the decoded parameters. + * @example + * ```ts + * let res = web3.eth.abi.decodeParameters( + * ["string", "uint256"], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { '0': 'Hello!%!', '1': 234n, __length__: 2 } + * + * let res = web3.eth.abi.decodeParameters( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * }, + * ], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { + * '0': 'Hello!%!', + * '1': 234n, + * __length__: 2, + * myString: 'Hello!%!', + * myNumber: 234n + * } + * + * const res = web3.eth.abi.decodeParameters( + * [ + * "uint8[]", + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * ], + * "0x00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000018" + * ); + * console.log(res); + * > + * '0': [ 42n, 24n ], + * '1': { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * }, + * __length__: 2, + * ParentStruct: { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * } + *} + * ``` + */ +export declare const decodeParameters: (abi: AbiInput[], bytes: HexString) => { + [key: string]: unknown; + __length__: number; +}; +/** + * Should be used to decode bytes to plain param + */ +/** + * Decodes an ABI encoded parameter to its JavaScript type. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The decoded parameter + * @example + * ```ts + * const res = web3.eth.abi.decodeParameter( + * "uint256", + * "0x0000000000000000000000000000000000000000000000000000000000000010" + * ); + * console.log(res); + * > 16n + * + * const res = web3.eth.abi.decodeParameter( + * "string", + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * + * console.log(res); + * > Hello!%! + * + * const res = web3.eth.abi.decodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * "0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e" + * ); + * + * console.log(res); + * { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + *} + * ``` + */ +export declare const decodeParameter: (abi: AbiInput, bytes: HexString) => unknown; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.js new file mode 100644 index 0000000..a4a3762 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.js @@ -0,0 +1,291 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeParameter = exports.decodeParameters = exports.decodeParametersWith = exports.encodeParameter = exports.encodeParameters = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const decode_js_1 = require("../coders/decode.js"); +const encode_js_1 = require("../coders/encode.js"); +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - An array of {@link AbiInput}. See [Solidity's documentation](https://solidity.readthedocs.io/en/v0.5.3/abi-spec.html#json) for more details. + * @param params - The actual parameters to encode. + * @returns - The ABI encoded parameters + * @example + * ```ts + * const res = web3.eth.abi.encodeParameters( + * ["uint256", "string"], + * ["2345675643", "Hello!%"] + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * ``` + */ +const encodeParameters = (abi, params) => (0, encode_js_1.encodeParameters)(abi, params); +exports.encodeParameters = encodeParameters; +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param param - The actual parameter to encode. + * @returns - The ABI encoded parameter + * @example + * ```ts + * const res = web3.eth.abi.encodeParameter("uint256", "2345675643"); + * console.log(res); + * 0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("uint", "2345675643"); + * + * console.log(res); + * >0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("bytes32", "0xdf3234"); + * + * console.log(res); + * >0xdf32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes", "0xdf3234"); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes32[]", ["0xdf3234", "0xfdfd"]); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * { + * propertyOne: 42, + * propertyTwo: 56, + * childStruct: { + * propertyOne: 45, + * propertyTwo: 78, + * }, + * } + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e + * ``` + */ +const encodeParameter = (abi, param) => (0, exports.encodeParameters)([abi], [param]); +exports.encodeParameter = encodeParameter; +/** + * Should be used to decode list of params + */ +const decodeParametersWith = (abis, bytes, loose) => { + try { + if (abis.length > 0 && (!bytes || bytes === '0x' || bytes === '0X')) { + throw new web3_errors_1.AbiError("Returned values aren't valid, did it run Out of Gas? " + + 'You might also see this error if you are not using the ' + + 'correct ABI for the contract you are retrieving data from, ' + + 'requesting data from a block number that does not exist, ' + + 'or querying a node which is not fully synced.'); + } + return (0, decode_js_1.decodeParameters)(abis, `0x${bytes.replace(/0x/i, '')}`, loose); + } + catch (err) { + throw new web3_errors_1.AbiError(`Parameter decoding error: ${err.message}`, { + internalErr: err, + }); + } +}; +exports.decodeParametersWith = decodeParametersWith; +/** + * Should be used to decode list of params + */ +/** + * Decodes ABI encoded parameters to its JavaScript types. + * @param abi - An array of {@link AbiInput}. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The result object containing the decoded parameters. + * @example + * ```ts + * let res = web3.eth.abi.decodeParameters( + * ["string", "uint256"], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { '0': 'Hello!%!', '1': 234n, __length__: 2 } + * + * let res = web3.eth.abi.decodeParameters( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * }, + * ], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { + * '0': 'Hello!%!', + * '1': 234n, + * __length__: 2, + * myString: 'Hello!%!', + * myNumber: 234n + * } + * + * const res = web3.eth.abi.decodeParameters( + * [ + * "uint8[]", + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * ], + * "0x00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000018" + * ); + * console.log(res); + * > + * '0': [ 42n, 24n ], + * '1': { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * }, + * __length__: 2, + * ParentStruct: { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * } + *} + * ``` + */ +const decodeParameters = (abi, bytes) => (0, exports.decodeParametersWith)(abi, bytes, false); +exports.decodeParameters = decodeParameters; +/** + * Should be used to decode bytes to plain param + */ +/** + * Decodes an ABI encoded parameter to its JavaScript type. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The decoded parameter + * @example + * ```ts + * const res = web3.eth.abi.decodeParameter( + * "uint256", + * "0x0000000000000000000000000000000000000000000000000000000000000010" + * ); + * console.log(res); + * > 16n + * + * const res = web3.eth.abi.decodeParameter( + * "string", + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * + * console.log(res); + * > Hello!%! + * + * const res = web3.eth.abi.decodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * "0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e" + * ); + * + * console.log(res); + * { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + *} + * ``` + */ +const decodeParameter = (abi, bytes) => (0, exports.decodeParameters)([abi], bytes)['0']; +exports.decodeParameter = decodeParameter; +//# sourceMappingURL=parameters_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.js.map new file mode 100644 index 0000000..9794dd2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/api/parameters_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parameters_api.js","sourceRoot":"","sources":["../../../src/api/parameters_api.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,mDAAmF;AACnF,mDAAmF;AAEnF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,gBAAgB,GAAG,CAAC,GAA4B,EAAE,MAAiB,EAAU,EAAE,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,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AAHhF,QAAA,gBAAgB,oBAGgE;AAE7F;;GAEG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACI,MAAM,eAAe,GAAG,CAAC,GAAa,EAAE,KAAgB,EAAW,EAAE,CAC3E,IAAA,wBAAgB,EAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC;AADxB,QAAA,eAAe,mBACS"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.d.ts new file mode 100644 index 0000000..4785165 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.d.ts @@ -0,0 +1,4 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeAddress(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeAddress(_param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.js new file mode 100644 index 0000000..d7585d7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeAddress = exports.encodeAddress = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const utils_js_1 = require("../utils.js"); +const ADDRESS_BYTES_COUNT = 20; +const ADDRESS_OFFSET = utils_js_1.WORD_SIZE - ADDRESS_BYTES_COUNT; +function encodeAddress(param, input) { + if (typeof input !== 'string') { + throw new web3_errors_1.AbiError('address type expects string as input type', { + value: input, + name: param.name, + type: param.type, + }); + } + let address = input.toLowerCase(); + if (!address.startsWith('0x')) { + address = `0x${address}`; + } + if (!(0, web3_validator_1.isAddress)(address)) { + throw new web3_errors_1.AbiError('provided input is not valid address', { + value: input, + name: param.name, + type: param.type, + }); + } + // for better performance, we could convert hex to destination bytes directly (encoded var) + const addressBytes = web3_validator_1.utils.hexToUint8Array(address); + // expand address to WORD_SIZE + const encoded = (0, utils_js_1.alloc)(utils_js_1.WORD_SIZE); + encoded.set(addressBytes, ADDRESS_OFFSET); + return { + dynamic: false, + encoded, + }; +} +exports.encodeAddress = encodeAddress; +function decodeAddress(_param, bytes) { + const addressBytes = bytes.subarray(ADDRESS_OFFSET, utils_js_1.WORD_SIZE); + if (addressBytes.length !== ADDRESS_BYTES_COUNT) { + throw new web3_errors_1.AbiError('Invalid decoding input, not enough bytes to decode address', { bytes }); + } + const result = web3_validator_1.utils.uint8ArrayToHexString(addressBytes); + // should we check is decoded value is valid address? + // if(!isAddress(result)) { + // throw new AbiError("encoded data is not valid address", { + // address: result, + // }); + // } + return { + result: (0, web3_utils_1.toChecksumAddress)(result), + encoded: bytes.subarray(utils_js_1.WORD_SIZE), + consumed: utils_js_1.WORD_SIZE, + }; +} +exports.decodeAddress = decodeAddress; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.js.map new file mode 100644 index 0000000..b895367 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../../src/coders/base/address.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,2CAA+C;AAC/C,mDAAkD;AAElD,0CAA+C;AAE/C,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,cAAc,GAAG,oBAAS,GAAG,mBAAmB,CAAC;AAEvD,SAAgB,aAAa,CAAC,KAAmB,EAAE,KAAc;IAChE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,MAAM,IAAI,sBAAQ,CAAC,2CAA2C,EAAE;YAC/D,KAAK,EAAE,KAAK;YACZ,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,IAAI,EAAE,KAAK,CAAC,IAAI;SAChB,CAAC,CAAC;KACH;IACD,IAAI,OAAO,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IAClC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC9B,OAAO,GAAG,KAAK,OAAO,EAAE,CAAC;KACzB;IACD,IAAI,CAAC,IAAA,0BAAS,EAAC,OAAO,CAAC,EAAE;QACxB,MAAM,IAAI,sBAAQ,CAAC,qCAAqC,EAAE;YACzD,KAAK,EAAE,KAAK;YACZ,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,IAAI,EAAE,KAAK,CAAC,IAAI;SAChB,CAAC,CAAC;KACH;IACD,2FAA2F;IAC3F,MAAM,YAAY,GAAG,sBAAK,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;IACpD,8BAA8B;IAC9B,MAAM,OAAO,GAAG,IAAA,gBAAK,EAAC,oBAAS,CAAC,CAAC;IACjC,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC;IAC1C,OAAO;QACN,OAAO,EAAE,KAAK;QACd,OAAO;KACP,CAAC;AACH,CAAC;AA5BD,sCA4BC;AAED,SAAgB,aAAa,CAAC,MAAoB,EAAE,KAAiB;IACpE,MAAM,YAAY,GAAG,KAAK,CAAC,QAAQ,CAAC,cAAc,EAAE,oBAAS,CAAC,CAAC;IAC/D,IAAI,YAAY,CAAC,MAAM,KAAK,mBAAmB,EAAE;QAChD,MAAM,IAAI,sBAAQ,CAAC,4DAA4D,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;KAC5F;IACD,MAAM,MAAM,GAAG,sBAAK,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;IAEzD,qDAAqD;IACrD,2BAA2B;IAC3B,gEAAgE;IAChE,2BAA2B;IAC3B,UAAU;IACV,IAAI;IACJ,OAAO;QACN,MAAM,EAAE,IAAA,8BAAiB,EAAC,MAAM,CAAC;QACjC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,oBAAS,CAAC;QAClC,QAAQ,EAAE,oBAAS;KACnB,CAAC;AACH,CAAC;AAlBD,sCAkBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.d.ts new file mode 100644 index 0000000..d977c92 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.d.ts @@ -0,0 +1,4 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeArray(param: AbiParameter, values: unknown): EncoderResult; +export declare function decodeArray(param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.js new file mode 100644 index 0000000..c49063c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.js @@ -0,0 +1,106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeArray = exports.encodeArray = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +// eslint-disable-next-line import/no-cycle +const index_js_1 = require("./index.js"); +const utils_js_1 = require("../utils.js"); +const number_js_1 = require("./number.js"); +const utils_js_2 = require("./utils.js"); +function encodeArray(param, values) { + if (!Array.isArray(values)) { + throw new web3_errors_1.AbiError('Expected value to be array', { abi: param, values }); + } + const { size, param: arrayItemParam } = (0, utils_js_1.extractArrayType)(param); + const encodedParams = values.map(v => (0, index_js_1.encodeParamFromAbiParameter)(arrayItemParam, v)); + const dynamic = size === -1; + const dynamicItems = encodedParams.length > 0 && encodedParams[0].dynamic; + if (!dynamic && values.length !== size) { + throw new web3_errors_1.AbiError("Given arguments count doesn't match array length", { + arrayLength: size, + argumentsLength: values.length, + }); + } + if (dynamic || dynamicItems) { + const encodingResult = (0, utils_js_2.encodeDynamicParams)(encodedParams); + if (dynamic) { + const encodedLength = (0, index_js_1.encodeNumber)({ type: 'uint256', name: '' }, encodedParams.length).encoded; + return { + dynamic: true, + encoded: encodedParams.length > 0 + ? (0, web3_utils_1.uint8ArrayConcat)(encodedLength, encodingResult) + : encodedLength, + }; + } + return { + dynamic: true, + encoded: encodingResult, + }; + } + return { + dynamic: false, + encoded: (0, web3_utils_1.uint8ArrayConcat)(...encodedParams.map(p => p.encoded)), + }; +} +exports.encodeArray = encodeArray; +function decodeArray(param, bytes) { + // eslint-disable-next-line prefer-const + let { size, param: arrayItemParam } = (0, utils_js_1.extractArrayType)(param); + const dynamic = size === -1; + let consumed = 0; + const result = []; + let remaining = bytes; + // dynamic array, we need to decode length + if (dynamic) { + const lengthResult = (0, number_js_1.decodeNumber)({ type: 'uint32', name: '' }, bytes); + size = Number(lengthResult.result); + consumed = lengthResult.consumed; + remaining = lengthResult.encoded; + } + const hasDynamicChild = (0, utils_js_1.isDynamic)(arrayItemParam); + if (hasDynamicChild) { + // known length but dynamic child, each child is actually head element with encoded offset + for (let i = 0; i < size; i += 1) { + const offsetResult = (0, number_js_1.decodeNumber)({ type: 'uint32', name: '' }, remaining.subarray(i * utils_js_1.WORD_SIZE)); + consumed += offsetResult.consumed; + const decodedChildResult = (0, index_js_1.decodeParamFromAbiParameter)(arrayItemParam, remaining.subarray(Number(offsetResult.result))); + consumed += decodedChildResult.consumed; + result.push(decodedChildResult.result); + } + return { + result, + encoded: remaining.subarray(consumed), + consumed, + }; + } + for (let i = 0; i < size; i += 1) { + // decode static params + const decodedChildResult = (0, index_js_1.decodeParamFromAbiParameter)(arrayItemParam, bytes.subarray(consumed)); + consumed += decodedChildResult.consumed; + result.push(decodedChildResult.result); + } + return { + result, + encoded: bytes.subarray(consumed), + consumed, + }; +} +exports.decodeArray = decodeArray; +//# sourceMappingURL=array.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.js.map new file mode 100644 index 0000000..abcf764 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"array.js","sourceRoot":"","sources":["../../../../src/coders/base/array.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,2CAA8C;AAC9C,2CAA2C;AAC3C,yCAAoG;AAEpG,0CAAqE;AACrE,2CAA2C;AAC3C,yCAAiD;AAEjD,SAAgB,WAAW,CAAC,KAAmB,EAAE,MA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AAC,CACjC,CAAC;YACF,QAAQ,IAAI,YAAY,CAAC,QAAQ,CAAC;YAClC,MAAM,kBAAkB,GAAG,IAAA,sCAA2B,EACrD,cAAc,EACd,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAC/C,CAAC;YACF,QAAQ,IAAI,kBAAkB,CAAC,QAAQ,CAAC;YACxC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;SACvC;QACD,OAAO;YACN,MAAM;YACN,OAAO,EAAE,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACrC,QAAQ;SACR,CAAC;KACF;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE;QACjC,uBAAuB;QACvB,MAAM,kBAAkB,GAAG,IAAA,sCAA2B,EACrD,cAAc,EACd,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CACxB,CAAC;QACF,QAAQ,IAAI,kBAAkB,CAAC,QAAQ,CAAC;QACxC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;KACvC;IACD,OAAO;QACN,MAAM;QACN,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACjC,QAAQ;KACR,CAAC;AACH,CAAC;AApDD,kCAoDC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.d.ts new file mode 100644 index 0000000..9c0fdfb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.d.ts @@ -0,0 +1,4 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeBoolean(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeBool(_param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.js new file mode 100644 index 0000000..b9294fb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeBool = exports.encodeBoolean = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("../utils.js"); +const number_js_1 = require("./number.js"); +function encodeBoolean(param, input) { + let value; + try { + value = (0, web3_utils_1.toBool)(input); + } + catch (e) { + if (e instanceof web3_errors_1.InvalidBooleanError) { + throw new web3_errors_1.AbiError('provided input is not valid boolean value', { + type: param.type, + value: input, + name: param.name, + }); + } + } + return (0, number_js_1.encodeNumber)({ type: 'uint8', name: '' }, Number(value)); +} +exports.encodeBoolean = encodeBoolean; +function decodeBool(_param, bytes) { + const numberResult = (0, number_js_1.decodeNumber)({ type: 'uint8', name: '' }, bytes); + if (numberResult.result > 1 || numberResult.result < 0) { + throw new web3_errors_1.AbiError('Invalid boolean value encoded', { + boolBytes: bytes.subarray(0, utils_js_1.WORD_SIZE), + numberResult, + }); + } + return { + result: numberResult.result === BigInt(1), + encoded: numberResult.encoded, + consumed: utils_js_1.WORD_SIZE, + }; +} +exports.decodeBool = decodeBool; +//# sourceMappingURL=bool.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.js.map new file mode 100644 index 0000000..44c5414 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bool.js","sourceRoot":"","sources":["../../../../src/coders/base/bool.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAA4D;AAE5D,2CAAoC;AAEpC,0CAAwC;AACxC,2CAAyD;AAEzD,SAAgB,aAAa,CAAC,KAAmB,EAAE,KAAc;IAChE,IAAI,KAAK,CAAC;IACV,IAAI;QACH,KAAK,GAAG,IAAA,mBAAM,EAAC,KAAK,CAAC,CAAC;KACtB;IAAC,OAAO,CAAC,EAAE;QACX,IAAI,CAAC,YAAY,iCAAmB,EAAE;YACrC,MAAM,IAAI,sBAAQ,CAAC,2CAA2C,EAAE;gBAC/D,IAAI,EAAE,KAAK,CAAC,IAAI;gBAChB,KAAK,EAAE,KAAK;gBACZ,IAAI,EAAE,KAAK,CAAC,IAAI;aAChB,CAAC,CAAC;SACH;KACD;IAED,OAAO,IAAA,wBAAY,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACjE,CAAC;AAfD,sCAeC;AAED,SAAgB,UAAU,CAAC,MAAoB,EAAE,KAAiB;IACjE,MAAM,YAAY,GAAG,IAAA,wBAAY,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACtE,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE;QACvD,MAAM,IAAI,sBAAQ,CAAC,+BAA+B,EAAE;YACnD,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,oBAAS,CAAC;YACvC,YAAY;SACZ,CAAC,CAAC;KACH;IACD,OAAO;QACN,MAAM,EAAE,YAAY,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC;QACzC,OAAO,EAAE,YAAY,CAAC,OAAO;QAC7B,QAAQ,EAAE,oBAAS;KACnB,CAAC;AACH,CAAC;AAbD,gCAaC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.d.ts new file mode 100644 index 0000000..f20ee09 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.d.ts @@ -0,0 +1,4 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeBytes(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeBytes(param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.js new file mode 100644 index 0000000..d875bbf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.js @@ -0,0 +1,101 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeBytes = exports.encodeBytes = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const utils_js_1 = require("../utils.js"); +const number_js_1 = require("./number.js"); +const MAX_STATIC_BYTES_COUNT = 32; +function encodeBytes(param, input) { + // hack for odd length hex strings + if (typeof input === 'string' && input.length % 2 !== 0) { + // eslint-disable-next-line no-param-reassign + input += '0'; + } + if (!(0, web3_validator_1.isBytes)(input)) { + throw new web3_errors_1.AbiError('provided input is not valid bytes value', { + type: param.type, + value: input, + name: param.name, + }); + } + const bytes = (0, web3_utils_1.bytesToUint8Array)(input); + const [, size] = param.type.split('bytes'); + // fixed size + if (size) { + if (Number(size) > MAX_STATIC_BYTES_COUNT || Number(size) < 1) { + throw new web3_errors_1.AbiError('invalid bytes type. Static byte type can have between 1 and 32 bytes', { + type: param.type, + }); + } + if (Number(size) < bytes.length) { + throw new web3_errors_1.AbiError('provided input size is different than type size', { + type: param.type, + value: input, + name: param.name, + }); + } + const encoded = (0, utils_js_1.alloc)(utils_js_1.WORD_SIZE); + encoded.set(bytes); + return { + dynamic: false, + encoded, + }; + } + const partsLength = Math.ceil(bytes.length / utils_js_1.WORD_SIZE); + // one word for length of data + WORD for each part of actual data + const encoded = (0, utils_js_1.alloc)(utils_js_1.WORD_SIZE + partsLength * utils_js_1.WORD_SIZE); + encoded.set((0, number_js_1.encodeNumber)({ type: 'uint32', name: '' }, bytes.length).encoded); + encoded.set(bytes, utils_js_1.WORD_SIZE); + return { + dynamic: true, + encoded, + }; +} +exports.encodeBytes = encodeBytes; +function decodeBytes(param, bytes) { + const [, sizeString] = param.type.split('bytes'); + let size = Number(sizeString); + let remainingBytes = bytes; + let partsCount = 1; + let consumed = 0; + if (!size) { + // dynamic bytes + const result = (0, number_js_1.decodeNumber)({ type: 'uint32', name: '' }, remainingBytes); + size = Number(result.result); + consumed += result.consumed; + remainingBytes = result.encoded; + partsCount = Math.ceil(size / utils_js_1.WORD_SIZE); + } + if (size > bytes.length) { + throw new web3_errors_1.AbiError('there is not enough data to decode', { + type: param.type, + encoded: bytes, + size, + }); + } + return { + result: (0, web3_utils_1.bytesToHex)(remainingBytes.subarray(0, size)), + encoded: remainingBytes.subarray(partsCount * utils_js_1.WORD_SIZE), + consumed: consumed + partsCount * utils_js_1.WORD_SIZE, + }; +} +exports.decodeBytes = decodeBytes; +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.js.map new file mode 100644 index 0000000..97efa6f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../../src/coders/base/bytes.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,2CAA2D;AAC3D,mDAA0D;AAE1D,0CAA+C;AAC/C,2CAAyD;AAEzD,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAElC,SAAgB,WAAW,CAAC,KAAmB,EAAE,KAAc;IAC9D,kCAAkC;IAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE;QACxD,6CAA6C;QAC7C,KAAK,IAAI,GAAG,CAAC;KACb;IACD,IAAI,CAAC,IAAA,wBAAO,EAAC,KAAwB,CAAC,EAAE;QACvC,MAAM,IAAI,sBAAQ,CAAC,yCAAyC,EAAE;YAC7D,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,KAAK,EAAE,KAAK;YACZ,IAAI,EAAE,KAAK,CAAC,IAAI;SAChB,CAAC,CAAC;KACH;IACD,MAAM,KAAK,GAAG,IAAA,8BAAiB,EAAC,KAAc,CAAC,CAAC;IAChD,MAAM,CAAC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3C,aAAa;IACb,IAAI,IAAI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CAAC,OAAO,CAAC,CAAC;IACjD,IAAI,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IAC9B,IAAI,cAAc,GAAG,KAAK,CAAC;IAC3B,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,CAAC,IAAI,EAAE;QACV,gBAAgB;QAChB,MAAM,MAAM,GAAG,IAAA,wBAAY,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,cAAc,CAAC,CAAC;QAC1E,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7B,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC;QAC5B,cAAc,GAAG,MAAM,CAAC,OAAO,CAAC;QAChC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,oBAAS,CAAC,CAAC;KACzC;IACD,IAAI,IAAI,GAAG,KAAK,CAAC,MAAM,EAAE;QACxB,MAAM,IAAI,sBAAQ,CAAC,oCAAoC,EAAE;YACxD,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,OAAO,EAAE,KAAK;YACd,IAAI;SACJ,CAAC,CAAC;KACH;IAED,OAAO;QACN,MAAM,EAAE,IAAA,uBAAU,EAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACpD,OAAO,EAAE,cAAc,CAAC,QAAQ,CAAC,UAAU,GAAG,oBAAS,CAAC;QACxD,QAAQ,EAAE,QAAQ,GAAG,UAAU,GAAG,oBAAS;KAC3C,CAAC;AACH,CAAC;AA3BD,kCA2BC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.d.ts new file mode 100644 index 0000000..6cfb923 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.d.ts @@ -0,0 +1,11 @@ +import { AbiParameter } from 'web3-types'; +import { EncoderResult, DecoderResult } from '../types.js'; +export { encodeAddress, decodeAddress } from './address.js'; +export { encodeBoolean, decodeBool } from './bool.js'; +export { encodeBytes, decodeBytes } from './bytes.js'; +export { encodeNumber, decodeNumber } from './number.js'; +export { encodeString, decodeString } from './string.js'; +export { encodeTuple, decodeTuple } from './tuple.js'; +export { encodeArray, decodeArray } from './array.js'; +export declare function encodeParamFromAbiParameter(param: AbiParameter, value: unknown): EncoderResult; +export declare function decodeParamFromAbiParameter(param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.js new file mode 100644 index 0000000..c4f39c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.js @@ -0,0 +1,102 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeParamFromAbiParameter = exports.encodeParamFromAbiParameter = exports.decodeArray = exports.encodeArray = exports.decodeTuple = exports.encodeTuple = exports.decodeString = exports.encodeString = exports.decodeNumber = exports.encodeNumber = exports.decodeBytes = exports.encodeBytes = exports.decodeBool = exports.encodeBoolean = exports.decodeAddress = exports.encodeAddress = void 0; +const address_js_1 = require("./address.js"); +const bool_js_1 = require("./bool.js"); +const bytes_js_1 = require("./bytes.js"); +const number_js_1 = require("./number.js"); +const string_js_1 = require("./string.js"); +// eslint-disable-next-line import/no-cycle +const tuple_js_1 = require("./tuple.js"); +// eslint-disable-next-line import/no-cycle +const array_js_1 = require("./array.js"); +var address_js_2 = require("./address.js"); +Object.defineProperty(exports, "encodeAddress", { enumerable: true, get: function () { return address_js_2.encodeAddress; } }); +Object.defineProperty(exports, "decodeAddress", { enumerable: true, get: function () { return address_js_2.decodeAddress; } }); +var bool_js_2 = require("./bool.js"); +Object.defineProperty(exports, "encodeBoolean", { enumerable: true, get: function () { return bool_js_2.encodeBoolean; } }); +Object.defineProperty(exports, "decodeBool", { enumerable: true, get: function () { return bool_js_2.decodeBool; } }); +var bytes_js_2 = require("./bytes.js"); +Object.defineProperty(exports, "encodeBytes", { enumerable: true, get: function () { return bytes_js_2.encodeBytes; } }); +Object.defineProperty(exports, "decodeBytes", { enumerable: true, get: function () { return bytes_js_2.decodeBytes; } }); +var number_js_2 = require("./number.js"); +Object.defineProperty(exports, "encodeNumber", { enumerable: true, get: function () { return number_js_2.encodeNumber; } }); +Object.defineProperty(exports, "decodeNumber", { enumerable: true, get: function () { return number_js_2.decodeNumber; } }); +var string_js_2 = require("./string.js"); +Object.defineProperty(exports, "encodeString", { enumerable: true, get: function () { return string_js_2.encodeString; } }); +Object.defineProperty(exports, "decodeString", { enumerable: true, get: function () { return string_js_2.decodeString; } }); +// eslint-disable-next-line import/no-cycle +var tuple_js_2 = require("./tuple.js"); +Object.defineProperty(exports, "encodeTuple", { enumerable: true, get: function () { return tuple_js_2.encodeTuple; } }); +Object.defineProperty(exports, "decodeTuple", { enumerable: true, get: function () { return tuple_js_2.decodeTuple; } }); +// eslint-disable-next-line import/no-cycle +var array_js_2 = require("./array.js"); +Object.defineProperty(exports, "encodeArray", { enumerable: true, get: function () { return array_js_2.encodeArray; } }); +Object.defineProperty(exports, "decodeArray", { enumerable: true, get: function () { return array_js_2.decodeArray; } }); +function encodeParamFromAbiParameter(param, value) { + if (param.type === 'string') { + return (0, string_js_1.encodeString)(param, value); + } + if (param.type === 'bool') { + return (0, bool_js_1.encodeBoolean)(param, value); + } + if (param.type === 'address') { + return (0, address_js_1.encodeAddress)(param, value); + } + if (param.type === 'tuple') { + return (0, tuple_js_1.encodeTuple)(param, value); + } + if (param.type.endsWith(']')) { + return (0, array_js_1.encodeArray)(param, value); + } + if (param.type.startsWith('bytes')) { + return (0, bytes_js_1.encodeBytes)(param, value); + } + if (param.type.startsWith('uint') || param.type.startsWith('int')) { + return (0, number_js_1.encodeNumber)(param, value); + } + throw new Error('Unsupported'); +} +exports.encodeParamFromAbiParameter = encodeParamFromAbiParameter; +function decodeParamFromAbiParameter(param, bytes) { + if (param.type === 'string') { + return (0, string_js_1.decodeString)(param, bytes); + } + if (param.type === 'bool') { + return (0, bool_js_1.decodeBool)(param, bytes); + } + if (param.type === 'address') { + return (0, address_js_1.decodeAddress)(param, bytes); + } + if (param.type === 'tuple') { + return (0, tuple_js_1.decodeTuple)(param, bytes); + } + if (param.type.endsWith(']')) { + return (0, array_js_1.decodeArray)(param, bytes); + } + if (param.type.startsWith('bytes')) { + return (0, bytes_js_1.decodeBytes)(param, bytes); + } + if (param.type.startsWith('uint') || param.type.startsWith('int')) { + return (0, number_js_1.decodeNumber)(param, bytes); + } + throw new Error('Unsupported'); +} +exports.decodeParamFromAbiParameter = decodeParamFromAbiParameter; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.js.map new file mode 100644 index 0000000..8e255d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/coders/base/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAIF,6CAA4D;AAC5D,uCAAsD;AACtD,yCAAsD;AACtD,2CAAyD;AACzD,2CAAyD;AACzD,2CAA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C,KAAK,CAAC,EAAE;QAClE,OAAO,IAAA,wBAAY,EAAC,KAAK,EAAE,KAAK,CAAC,CAAC;KAClC;IACD,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;AAChC,CAAC;AAvBD,kEAuBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.d.ts new file mode 100644 index 0000000..e1e4a17 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.d.ts @@ -0,0 +1,4 @@ +import type { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeNumber(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeNumber(param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.js new file mode 100644 index 0000000..7dc939e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.js @@ -0,0 +1,116 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeNumber = exports.encodeNumber = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const utils_js_1 = require("../utils.js"); +const numbersLimits_js_1 = require("./numbersLimits.js"); +// eslint-disable-next-line no-bitwise +const mask = BigInt(1) << BigInt(256); +function bigIntToUint8Array(value, byteLength = utils_js_1.WORD_SIZE) { + let hexValue; + if (value < 0) { + hexValue = (mask + value).toString(16); + } + else { + hexValue = value.toString(16); + } + hexValue = (0, web3_utils_1.padLeft)(hexValue, byteLength * 2); + return web3_validator_1.utils.hexToUint8Array(hexValue); +} +function uint8ArrayToBigInt(value, max) { + const hexValue = web3_validator_1.utils.uint8ArrayToHexString(value); + const result = BigInt(hexValue); + if (result <= max) + return result; + return result - mask; +} +function encodeNumber(param, input) { + let value; + try { + value = (0, web3_utils_1.toBigInt)(input); + } + catch (e) { + throw new web3_errors_1.AbiError('provided input is not number value', { + type: param.type, + value: input, + name: param.name, + }); + } + const limit = numbersLimits_js_1.numberLimits.get(param.type); + if (!limit) { + throw new web3_errors_1.AbiError('provided abi contains invalid number datatype', { type: param.type }); + } + if (value < limit.min) { + throw new web3_errors_1.AbiError('provided input is less then minimum for given type', { + type: param.type, + value: input, + name: param.name, + minimum: limit.min.toString(), + }); + } + if (value > limit.max) { + throw new web3_errors_1.AbiError('provided input is greater then maximum for given type', { + type: param.type, + value: input, + name: param.name, + maximum: limit.max.toString(), + }); + } + return { + dynamic: false, + encoded: bigIntToUint8Array(value), + }; +} +exports.encodeNumber = encodeNumber; +function decodeNumber(param, bytes) { + if (bytes.length < utils_js_1.WORD_SIZE) { + throw new web3_errors_1.AbiError('Not enough bytes left to decode', { param, bytesLeft: bytes.length }); + } + const boolBytes = bytes.subarray(0, utils_js_1.WORD_SIZE); + const limit = numbersLimits_js_1.numberLimits.get(param.type); + if (!limit) { + throw new web3_errors_1.AbiError('provided abi contains invalid number datatype', { type: param.type }); + } + const numberResult = uint8ArrayToBigInt(boolBytes, limit.max); + if (numberResult < limit.min) { + throw new web3_errors_1.AbiError('decoded value is less then minimum for given type', { + type: param.type, + value: numberResult, + name: param.name, + minimum: limit.min.toString(), + }); + } + if (numberResult > limit.max) { + throw new web3_errors_1.AbiError('decoded value is greater then maximum for given type', { + type: param.type, + value: numberResult, + name: param.name, + maximum: limit.max.toString(), + }); + } + return { + result: numberResult, + encoded: bytes.subarray(utils_js_1.WORD_SIZE), + consumed: utils_js_1.WORD_SIZE, + }; +} +exports.decodeNumber = decodeNumber; +//# sourceMappingURL=number.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.js.map new file mode 100644 index 0000000..4de5317 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"number.js","sourceRoot":"","sources":["../../../../src/coders/base/number.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAAuC;AAEvC,2CAA+C;AAC/C,mDAAuC;AAEvC,0CAAwC;AACxC,yDAAkD;AAElD,sCAAsC;AACtC,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;AAEtC,SAAS,kBAAkB,CAAC,KAAa,EAAE,UAAU,GAAG,oBAAS;IAChE,IAAI,QAAQ,CAAC;IACb,IAAI,KAAK,GAAG,CAAC,EAAE;QACd,QAAQ,GAAG,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;KACvC;SAAM;QACN,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;KAC9B;IACD,QAAQ,GAAG,IAAA,oBAAO,EAAC,QAAQ,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC7C,OAAO,sBAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAiB,EAAE,GAAW;IACzD,MAAM,QAAQ,GAAG,sBAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC;IACpD,MAAM,M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7B,CAAC,CAAC;KACH;IACD,OAAO;QACN,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,oBAAS,CAAC;QAClC,QAAQ,EAAE,oBAAS;KACnB,CAAC;AACH,CAAC;AAhCD,oCAgCC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.d.ts new file mode 100644 index 0000000..63a34af --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.d.ts @@ -0,0 +1,4 @@ +export declare const numberLimits: Map; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.js new file mode 100644 index 0000000..035c022 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.js @@ -0,0 +1,40 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numberLimits = void 0; +/* + * this variable contains the precalculated limits for all the numbers for uint and int types +*/ +exports.numberLimits = new Map(); +let base = BigInt(256); // 2 ^ 8 = 256 +for (let i = 8; i <= 256; i += 8) { + exports.numberLimits.set(`uint${i}`, { + min: BigInt(0), + max: base - BigInt(1), + }); + exports.numberLimits.set(`int${i}`, { + min: -base / BigInt(2), + max: base / BigInt(2) - BigInt(1), + }); + base *= BigInt(256); +} +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +exports.numberLimits.set(`int`, exports.numberLimits.get('int256')); +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +exports.numberLimits.set(`uint`, exports.numberLimits.get('uint256')); +//# sourceMappingURL=numbersLimits.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.js.map new file mode 100644 index 0000000..1355b03 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/numbersLimits.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numbersLimits.js","sourceRoot":"","sources":["../../../../src/coders/base/numbersLimits.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF;;EAEE;AACW,QAAA,YAAY,GAAG,IAAI,GAAG,EAAwC,CAAC;AAE5E,IAAI,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc;AACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE;IACjC,oBAAY,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE;QAC5B,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;QACd,GAAG,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC;KACrB,CAAC,CAAC;IACH,oBAAY,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE;QAC3B,GAAG,EAAE,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC;QACtB,GAAG,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;KACjC,CAAC,CAAC;IACH,IAAI,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;CACpB;AAED,oEAAoE;AACpE,oBAAY,CAAC,GAAG,CAAC,KAAK,EAAE,oBAAY,CAAC,GAAG,CAAC,QAAQ,CAAE,CAAC,CAAC;AACrD,oEAAoE;AACpE,oBAAY,CAAC,GAAG,CAAC,MAAM,EAAE,oBAAY,CAAC,GAAG,CAAC,SAAS,CAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.d.ts new file mode 100644 index 0000000..743afe9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.d.ts @@ -0,0 +1,4 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeString(_param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeString(_param: AbiParameter, bytes: Uint8Array): DecoderResult; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.js new file mode 100644 index 0000000..7521827 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeString = exports.encodeString = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const bytes_js_1 = require("./bytes.js"); +function encodeString(_param, input) { + if (typeof input !== 'string') { + throw new web3_errors_1.AbiError('invalid input, should be string', { input }); + } + const bytes = (0, web3_utils_1.utf8ToBytes)(input); + return (0, bytes_js_1.encodeBytes)({ type: 'bytes', name: '' }, bytes); +} +exports.encodeString = encodeString; +function decodeString(_param, bytes) { + const r = (0, bytes_js_1.decodeBytes)({ type: 'bytes', name: '' }, bytes); + return { + result: (0, web3_utils_1.hexToUtf8)(r.result), + encoded: r.encoded, + consumed: r.consumed, + }; +} +exports.decodeString = decodeString; +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.js.map new file mode 100644 index 0000000..802a6dc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../../src/coders/base/string.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,2CAAoD;AAEpD,yCAAsD;AAEtD,SAAgB,YAAY,CAAC,MAAoB,EAAE,KAAc;IAChE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,MAAM,IAAI,sBAAQ,CAAC,iCAAiC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;KACjE;IACD,MAAM,KAAK,GAAG,IAAA,wBAAW,EAAC,KAAK,CAAC,CAAC;IACjC,OAAO,IAAA,sBAAW,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;AACxD,CAAC;AAND,oCAMC;AAED,SAAgB,YAAY,CAAC,MAAoB,EAAE,KAAiB;IACnE,MAAM,CAAC,GAAG,IAAA,sBAAW,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC1D,OAAO;QACN,MAAM,EAAE,IAAA,sBAAS,EAAC,CAAC,CAAC,MAAM,CAAC;QAC3B,OAAO,EAAE,CAAC,CAAC,OAAO;QAClB,QAAQ,EAAE,CAAC,CAAC,QAAQ;KACpB,CAAC;AACH,CAAC;AAPD,oCAOC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.d.ts new file mode 100644 index 0000000..c3e4bf2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.d.ts @@ -0,0 +1,7 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeTuple(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeTuple(param: AbiParameter, bytes: Uint8Array): DecoderResult<{ + [key: string]: unknown; + __length__: number; +}>; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.js new file mode 100644 index 0000000..8caec36 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.js @@ -0,0 +1,123 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeTuple = exports.encodeTuple = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +// eslint-disable-next-line import/no-cycle +const index_js_1 = require("./index.js"); +const utils_js_1 = require("./utils.js"); +const utils_js_2 = require("../utils.js"); +const number_js_1 = require("./number.js"); +function encodeTuple(param, input) { + var _a, _b, _c; + let dynamic = false; + if (!Array.isArray(input) && typeof input !== 'object') { + throw new web3_errors_1.AbiError('param must be either Array or Object', { + param, + input, + }); + } + const narrowedInput = input; + const encoded = []; + for (let i = 0; i < ((_b = (_a = param.components) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); i += 1) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const paramComponent = param.components[i]; + let result; + if (Array.isArray(narrowedInput)) { + if (i >= narrowedInput.length) { + throw new web3_errors_1.AbiError('input param length missmatch', { + param, + input, + }); + } + result = (0, index_js_1.encodeParamFromAbiParameter)(paramComponent, narrowedInput[i]); + } + else { + const paramInput = narrowedInput[(_c = paramComponent.name) !== null && _c !== void 0 ? _c : '']; + // eslint-disable-next-line no-null/no-null + if (paramInput === undefined || paramInput === null) { + throw new web3_errors_1.AbiError('missing input defined in abi', { + param, + input, + paramName: paramComponent.name, + }); + } + result = (0, index_js_1.encodeParamFromAbiParameter)(paramComponent, paramInput); + } + if (result.dynamic) { + dynamic = true; + } + encoded.push(result); + } + if (dynamic) { + return { + dynamic: true, + encoded: (0, utils_js_1.encodeDynamicParams)(encoded), + }; + } + return { + dynamic: false, + encoded: (0, web3_utils_1.uint8ArrayConcat)(...encoded.map(e => e.encoded)), + }; +} +exports.encodeTuple = encodeTuple; +function decodeTuple(param, bytes) { + const result = { + __length__: 0, + }; + // tracks how much static params consumed bytes + let consumed = 0; + if (!param.components) { + return { + result, + encoded: bytes, + consumed, + }; + } + // track how much dynamic params consumed bytes + let dynamicConsumed = 0; + for (const [index, childParam] of param.components.entries()) { + let decodedResult; + if ((0, utils_js_2.isDynamic)(childParam)) { + // if dynamic, we will have offset encoded + const offsetResult = (0, number_js_1.decodeNumber)({ type: 'uint32', name: '' }, bytes.subarray(consumed)); + // offset counts from start of original byte sequence + decodedResult = (0, index_js_1.decodeParamFromAbiParameter)(childParam, bytes.subarray(Number(offsetResult.result))); + consumed += offsetResult.consumed; + dynamicConsumed += decodedResult.consumed; + } + else { + // static param, just decode + decodedResult = (0, index_js_1.decodeParamFromAbiParameter)(childParam, bytes.subarray(consumed)); + consumed += decodedResult.consumed; + } + result.__length__ += 1; + result[index] = decodedResult.result; + if (childParam.name && childParam.name !== '') { + result[childParam.name] = decodedResult.result; + } + } + return { + encoded: bytes.subarray(consumed + dynamicConsumed), + result, + consumed: consumed + dynamicConsumed, + }; +} +exports.decodeTuple = decodeTuple; +//# sourceMappingURL=tuple.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.js.map new file mode 100644 index 0000000..852945a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/tuple.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.js","sourceRoot":"","sources":["../../../../src/coders/base/tuple.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,2CAA8C;AAE9C,2CAA2C;AAC3C,yCAAsF;AACtF,yCAAiD;AACjD,0CAAwC;AACxC,2CAA2C;AAE3C,SAAgB,WAAW,CAAC,KAAmB,EAAE,KAAc;;IAC9D,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QACvD,MAAM,IAAI,sBAAQ,CAAC,sCAAsC,EAAE;YAC1D,KAAK;YACL,KAAK;SACL,CAAC,CAAC;KACH;IACD,MAAM,aAAa,GAAG,KAAiD,CAAC;IACxE,MAAM,OAAO,GAAyB,EAAE,CAAC;IACzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,MAAA,MAAA,KAAK,CAAC,UAAU,0CAAE,MAAM,mCAAI,CA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,IAAI,IAAI,UAAU,CAAC,IAAI,KAAK,EAAE,EAAE;YAC9C,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC;SAC/C;KACD;IACD,OAAO;QACN,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,GAAG,eAAe,CAAC;QACnD,MAAM;QACN,QAAQ,EAAE,QAAQ,GAAG,eAAe;KACpC,CAAC;AACH,CAAC;AAnDD,kCAmDC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.d.ts new file mode 100644 index 0000000..e0dec03 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.d.ts @@ -0,0 +1,2 @@ +import { EncoderResult } from '../types.js'; +export declare function encodeDynamicParams(encodedParams: ReadonlyArray): Uint8Array; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.js new file mode 100644 index 0000000..26a5a7c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeDynamicParams = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("../utils.js"); +const number_js_1 = require("./number.js"); +function encodeDynamicParams(encodedParams) { + let staticSize = 0; + let dynamicSize = 0; + const staticParams = []; + const dynamicParams = []; + // figure out static size + for (const encodedParam of encodedParams) { + if (encodedParam.dynamic) { + staticSize += utils_js_1.WORD_SIZE; + } + else { + staticSize += encodedParam.encoded.length; + } + } + for (const encodedParam of encodedParams) { + if (encodedParam.dynamic) { + staticParams.push((0, number_js_1.encodeNumber)({ type: 'uint256', name: '' }, staticSize + dynamicSize)); + dynamicParams.push(encodedParam); + dynamicSize += encodedParam.encoded.length; + } + else { + staticParams.push(encodedParam); + } + } + return (0, web3_utils_1.uint8ArrayConcat)(...staticParams.map(p => p.encoded), ...dynamicParams.map(p => p.encoded)); +} +exports.encodeDynamicParams = encodeDynamicParams; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.js.map new file mode 100644 index 0000000..2644c6e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/base/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/coders/base/utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,2CAA8C;AAE9C,0CAAwC;AACxC,2CAA2C;AAE3C,SAAgB,mBAAmB,CAAC,aAA2C;IAC9E,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,YAAY,GAAoB,EAAE,CAAC;IACzC,MAAM,aAAa,GAAoB,EAAE,CAAC;IAC1C,yBAAyB;IACzB,KAAK,MAAM,YAAY,IAAI,aAAa,EAAE;QACzC,IAAI,YAAY,CAAC,OAAO,EAAE;YACzB,UAAU,IAAI,oBAAS,CAAC;SACxB;aAAM;YACN,UAAU,IAAI,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC;SAC1C;KACD;IAED,KAAK,MAAM,YAAY,IAAI,aAAa,EAAE;QACzC,IAAI,YAAY,CAAC,OAAO,EAAE;YACzB,YAAY,CAAC,IAAI,CAChB,IAAA,wBAAY,EAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,UAAU,GAAG,WAAW,CAAC,CACrE,CAAC;YACF,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YACjC,WAAW,IAAI,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC;SAC3C;aAAM;YACN,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;SAChC;KACD;IACD,OAAO,IAAA,6BAAgB,EACtB,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EACnC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CACpC,CAAC;AACH,CAAC;AA7BD,kDA6BC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.d.ts new file mode 100644 index 0000000..a6f5308 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.d.ts @@ -0,0 +1,5 @@ +import { AbiInput, HexString } from 'web3-types'; +export declare function decodeParameters(abis: AbiInput[], bytes: HexString, _loose: boolean): { + [key: string]: unknown; + __length__: number; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.js new file mode 100644 index 0000000..2c87757 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.js @@ -0,0 +1,29 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeParameters = void 0; +const web3_validator_1 = require("web3-validator"); +const tuple_js_1 = require("./base/tuple.js"); +const utils_js_1 = require("./utils.js"); +function decodeParameters(abis, bytes, _loose) { + const abiParams = (0, utils_js_1.toAbiParams)(abis); + const bytesArray = web3_validator_1.utils.hexToUint8Array(bytes); + return (0, tuple_js_1.decodeTuple)({ type: 'tuple', name: '', components: abiParams }, bytesArray).result; +} +exports.decodeParameters = decodeParameters; +//# sourceMappingURL=decode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.js.map new file mode 100644 index 0000000..a12a288 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/decode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode.js","sourceRoot":"","sources":["../../../src/coders/decode.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,mDAAuC;AACvC,8CAA8C;AAC9C,yCAAyC;AAEzC,SAAgB,gBAAgB,CAC/B,IAAgB,EAChB,KAAgB,EAChB,MAAe;IAEf,MAAM,SAAS,GAAG,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC;IACpC,MAAM,UAAU,GAAG,sBAAK,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAEhD,OAAO,IAAA,sBAAW,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC,MAAM,CAAC;AAC3F,CAAC;AATD,4CASC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.d.ts new file mode 100644 index 0000000..3362e2e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.d.ts @@ -0,0 +1,2 @@ +import { AbiInput } from 'web3-types'; +export declare function encodeParameters(abi: ReadonlyArray, params: unknown[]): string; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.js new file mode 100644 index 0000000..e97ea04 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeParameters = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_validator_1 = require("web3-validator"); +const index_js_1 = require("./base/index.js"); +const utils_js_1 = require("./utils.js"); +function encodeParameters(abi, params) { + if (abi.length !== params.length) { + throw new web3_errors_1.AbiError('Invalid number of values received for given ABI', { + expected: abi.length, + received: params.length, + }); + } + const abiParams = (0, utils_js_1.toAbiParams)(abi); + return web3_validator_1.utils.uint8ArrayToHexString((0, index_js_1.encodeTuple)({ type: 'tuple', name: '', components: abiParams }, params).encoded); +} +exports.encodeParameters = encodeParameters; +//# sourceMappingURL=encode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.js.map new file mode 100644 index 0000000..1d96861 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/encode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode.js","sourceRoot":"","sources":["../../../src/coders/encode.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAuC;AAEvC,mDAAuC;AACvC,8CAA8C;AAC9C,yCAAyC;AAEzC,SAAgB,gBAAgB,CAAC,GAA4B,EAAE,MAAiB;IAC/E,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE;QACjC,MAAM,IAAI,sBAAQ,CAAC,iDAAiD,EAAE;YACrE,QAAQ,EAAE,GAAG,CAAC,MAAM;YACpB,QAAQ,EAAE,MAAM,CAAC,MAAM;SACvB,CAAC,CAAC;KACH;IACD,MAAM,SAAS,GAAG,IAAA,sBAAW,EAAC,GAAG,CAAC,CAAC;IACnC,OAAO,sBAAK,CAAC,qBAAqB,CACjC,IAAA,sBAAW,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,OAAO,CAC/E,CAAC;AACH,CAAC;AAXD,4CAWC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.d.ts new file mode 100644 index 0000000..245f8a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.d.ts @@ -0,0 +1,16 @@ +export declare type EncoderResult = { + dynamic: boolean; + encoded: Uint8Array; +}; +export declare type DecoderResult = { + result: T; + encoded: Uint8Array; + consumed: number; +}; +export declare type NumberType = { + signed: boolean; + byteLength: number; +}; +export declare type BytesType = { + size?: number; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.js.map new file mode 100644 index 0000000..9bc8b09 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/coders/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.d.ts new file mode 100644 index 0000000..f7dabe8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.d.ts @@ -0,0 +1,23 @@ +import { AbiParameter as ExternalAbiParameter } from 'abitype'; +import { AbiInput, AbiParameter } from 'web3-types'; +export declare const WORD_SIZE = 32; +export declare function alloc(size?: number): Uint8Array; +/** + * Where possible returns a Uint8Array of the requested size that references + * uninitialized memory. Only use if you are certain you will immediately + * overwrite every value in the returned `Uint8Array`. + */ +export declare function allocUnsafe(size?: number): Uint8Array; +export declare function convertExternalAbiParameter(abiParam: ExternalAbiParameter): AbiParameter; +export declare function isAbiParameter(param: unknown): param is AbiParameter; +export declare function toAbiParams(abi: ReadonlyArray): ReadonlyArray; +export declare function extractArrayType(param: AbiParameter): { + size: number; + param: AbiParameter; +}; +/** + * Param is dynamic if it's dynamic base type or if some of his children (components, array items) + * is of dynamic type + * @param param + */ +export declare function isDynamic(param: AbiParameter): boolean; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.js new file mode 100644 index 0000000..69da9af --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.js @@ -0,0 +1,115 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isDynamic = exports.extractArrayType = exports.toAbiParams = exports.isAbiParameter = exports.convertExternalAbiParameter = exports.allocUnsafe = exports.alloc = exports.WORD_SIZE = void 0; +const abitype_1 = require("abitype"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("../utils.js"); +exports.WORD_SIZE = 32; +function alloc(size = 0) { + var _a; + if (((_a = globalThis.Buffer) === null || _a === void 0 ? void 0 : _a.alloc) !== undefined) { + const buf = globalThis.Buffer.alloc(size); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + return new Uint8Array(size); +} +exports.alloc = alloc; +/** + * Where possible returns a Uint8Array of the requested size that references + * uninitialized memory. Only use if you are certain you will immediately + * overwrite every value in the returned `Uint8Array`. + */ +function allocUnsafe(size = 0) { + var _a; + if (((_a = globalThis.Buffer) === null || _a === void 0 ? void 0 : _a.allocUnsafe) !== undefined) { + const buf = globalThis.Buffer.allocUnsafe(size); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + return new Uint8Array(size); +} +exports.allocUnsafe = allocUnsafe; +function convertExternalAbiParameter(abiParam) { + var _a, _b; + return Object.assign(Object.assign({}, abiParam), { name: (_a = abiParam.name) !== null && _a !== void 0 ? _a : '', components: (_b = abiParam.components) === null || _b === void 0 ? void 0 : _b.map(c => convertExternalAbiParameter(c)) }); +} +exports.convertExternalAbiParameter = convertExternalAbiParameter; +function isAbiParameter(param) { + return (!(0, web3_utils_1.isNullish)(param) && + typeof param === 'object' && + !(0, web3_utils_1.isNullish)(param.type) && + typeof param.type === 'string'); +} +exports.isAbiParameter = isAbiParameter; +function toAbiParams(abi) { + return abi.map(input => { + var _a; + if (isAbiParameter(input)) { + return input; + } + if (typeof input === 'string') { + return convertExternalAbiParameter((0, abitype_1.parseAbiParameter)(input.replace(/tuple/, ''))); + } + if ((0, utils_js_1.isSimplifiedStructFormat)(input)) { + const structName = Object.keys(input)[0]; + const structInfo = (0, utils_js_1.mapStructNameAndType)(structName); + structInfo.name = (_a = structInfo.name) !== null && _a !== void 0 ? _a : ''; + return Object.assign(Object.assign({}, structInfo), { components: (0, utils_js_1.mapStructToCoderFormat)(input[structName]) }); + } + throw new web3_errors_1.AbiError('Invalid abi'); + }); +} +exports.toAbiParams = toAbiParams; +function extractArrayType(param) { + const arrayParenthesisStart = param.type.lastIndexOf('['); + const arrayParamType = param.type.substring(0, arrayParenthesisStart); + const sizeString = param.type.substring(arrayParenthesisStart); + let size = -1; + if (sizeString !== '[]') { + size = Number(sizeString.slice(1, -1)); + // eslint-disable-next-line no-restricted-globals + if (isNaN(size)) { + throw new web3_errors_1.AbiError('Invalid fixed array size', { size: sizeString }); + } + } + return { + param: { type: arrayParamType, name: '', components: param.components }, + size, + }; +} +exports.extractArrayType = extractArrayType; +/** + * Param is dynamic if it's dynamic base type or if some of his children (components, array items) + * is of dynamic type + * @param param + */ +function isDynamic(param) { + var _a, _b; + if (param.type === 'string' || param.type === 'bytes' || param.type.endsWith('[]')) + return true; + if (param.type === 'tuple') { + return (_b = (_a = param.components) === null || _a === void 0 ? void 0 : _a.some(isDynamic)) !== null && _b !== void 0 ? _b : false; + } + if (param.type.endsWith(']')) { + return isDynamic(extractArrayType(param).param); + } + return false; +} +exports.isDynamic = isDynamic; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.js.map new file mode 100644 index 0000000..d8b290d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/coders/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/coders/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,qCAAkF;AAClF,6CAAuC;AAEvC,2CAAuC;AACvC,0CAIqB;AAER,QAAA,SAAS,GAAG,EAAE,CAAC;AAE5B,SAAgB,KAAK,CAAC,IAAI,GAAG,CAAC;;IAC7B,IAAI,CAAA,MAAA,UAAU,CAAC,MAAM,0CAAE,KAAK,MAAK,SAAS,EAAE;QAC3C,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;KAClE;IAED,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAPD,sBAOC;AAED;;;;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;AAhBD,4CAgBC;AAED;;;;GAIG;AACH,SAAgB,SAAS,CAAC,KAAmB;;IAC5C,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAChG,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;QAC3B,OAAO,MAAA,MAAA,KAAK,CAAC,UAAU,0CAAE,IAAI,CAAC,SAAS,CAAC,mCAAI,KAAK,CAAC;KAClD;IACD,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QAC7B,OAAO,SAAS,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;KAChD;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AATD,8BASC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.d.ts new file mode 100644 index 0000000..36a2305 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.d.ts @@ -0,0 +1,3 @@ +import { Eip838ExecutionError } from 'web3-errors'; +import { AbiErrorFragment } from 'web3-types'; +export declare const decodeContractErrorData: (errorsAbi: AbiErrorFragment[], error: Eip838ExecutionError) => void; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.js new file mode 100644 index 0000000..3b91a08 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.js @@ -0,0 +1,47 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeContractErrorData = void 0; +const errors_api_js_1 = require("./api/errors_api.js"); +const parameters_api_js_1 = require("./api/parameters_api.js"); +const utils_js_1 = require("./utils.js"); +const decodeContractErrorData = (errorsAbi, error) => { + if (error === null || error === void 0 ? void 0 : error.data) { + let errorName; + let errorSignature; + let errorArgs; + try { + const errorSha = error.data.slice(0, 10); + const errorAbi = errorsAbi.find(abi => (0, errors_api_js_1.encodeErrorSignature)(abi).startsWith(errorSha)); + if (errorAbi === null || errorAbi === void 0 ? void 0 : errorAbi.inputs) { + errorName = errorAbi.name; + errorSignature = (0, utils_js_1.jsonInterfaceMethodToString)(errorAbi); + // decode abi.inputs according to EIP-838 + errorArgs = (0, parameters_api_js_1.decodeParameters)([...errorAbi.inputs], error.data.substring(10)); + } + } + catch (err) { + console.error(err); + } + if (errorName) { + error.setDecodedProperties(errorName, errorSignature, errorArgs); + } + } +}; +exports.decodeContractErrorData = decodeContractErrorData; +//# sourceMappingURL=decode_contract_error_data.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.js.map new file mode 100644 index 0000000..84f2547 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/decode_contract_error_data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_contract_error_data.js","sourceRoot":"","sources":["../../src/decode_contract_error_data.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAKF,uDAA2D;AAC3D,+DAA2D;AAC3D,yCAAyD;AAElD,MAAM,uBAAuB,GAAG,CACtC,SAA6B,EAC7B,KAA2B,EAC1B,EAAE;IACH,IAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE;QAChB,IAAI,SAA6B,CAAC;QAClC,IAAI,cAAkC,CAAC;QACvC,IAAI,SAAiD,CAAC;QACtD,IAAI;YACH,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACzC,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAA,oCAAoB,EAAC,GAAG,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC;YAEvF,IAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,EAAE;gBACrB,SAAS,GAAG,QAAQ,CAAC,IAAI,CAAC;gBAC1B,cAAc,GAAG,IAAA,sCAA2B,EAAC,QAAQ,CAAC,CAAC;gBACvD,yCAAyC;gBACzC,SAAS,GAAG,IAAA,oCAAgB,EAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;aAC7E;SACD;QAAC,OAAO,GAAG,EAAE;YACb,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SACnB;QACD,IAAI,SAAS,EAAE;YACd,KAAK,CAAC,oBAAoB,CAAC,SAAS,EAAE,cAAc,EAAE,SAAS,CAAC,CAAC;SACjE;KACD;AACF,CAAC,CAAC;AAzBW,QAAA,uBAAuB,2BAyBlC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.d.ts new file mode 100644 index 0000000..da3f6a6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.d.ts @@ -0,0 +1,9 @@ +/** + * @note This code was taken from: https://github.com/Mrtenz/eip-712/tree/master + */ +import { Eip712TypedData } from 'web3-types'; +/** + * Get the EIP-191 encoded message to sign, from the typedData object. If `hash` is enabled, the message will be hashed + * with Keccak256. + */ +export declare const getMessage: (typedData: Eip712TypedData, hash?: boolean) => string; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.js new file mode 100644 index 0000000..648942e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.js @@ -0,0 +1,136 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMessage = void 0; +const web3_utils_1 = require("web3-utils"); +const encode_js_1 = require("./coders/encode.js"); +const TYPE_REGEX = /^\w+/; +const ARRAY_REGEX = /^(.*)\[([0-9]*?)]$/; +/** + * Get the dependencies of a struct type. If a struct has the same dependency multiple times, it's only included once + * in the resulting array. + */ +const getDependencies = (typedData, type, dependencies = []) => { + const match = type.match(TYPE_REGEX); + const actualType = match[0]; + if (dependencies.includes(actualType)) { + return dependencies; + } + if (!typedData.types[actualType]) { + return dependencies; + } + return [ + actualType, + ...typedData.types[actualType].reduce((previous, _type) => [ + ...previous, + ...getDependencies(typedData, _type.type, previous).filter(dependency => !previous.includes(dependency)), + ], []), + ]; +}; +/** + * Encode a type to a string. All dependant types are alphabetically sorted. + * + * @param {TypedData} typedData + * @param {string} type + * @param {Options} [options] + * @return {string} + */ +const encodeType = (typedData, type) => { + const [primary, ...dependencies] = getDependencies(typedData, type); + // eslint-disable-next-line @typescript-eslint/require-array-sort-compare + const types = [primary, ...dependencies.sort()]; + return types + .map(dependency => + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${dependency}(${typedData.types[dependency].map(_type => `${_type.type} ${_type.name}`)})`) + .join(''); +}; +/** + * Get a type string as hash. + */ +const getTypeHash = (typedData, type) => (0, web3_utils_1.keccak256)(encodeType(typedData, type)); +/** + * Get encoded data as a hash. The data should be a key -> value object with all the required values. All dependant + * types are automatically encoded. + */ +const getStructHash = (typedData, type, data) => (0, web3_utils_1.keccak256)(encodeData(typedData, type, data)); +/** + * Get the EIP-191 encoded message to sign, from the typedData object. If `hash` is enabled, the message will be hashed + * with Keccak256. + */ +const getMessage = (typedData, hash) => { + const EIP_191_PREFIX = '1901'; + const message = `0x${EIP_191_PREFIX}${getStructHash(typedData, 'EIP712Domain', typedData.domain).substring(2)}${getStructHash(typedData, typedData.primaryType, typedData.message).substring(2)}`; + if (hash) { + return (0, web3_utils_1.keccak256)(message); + } + return message; +}; +exports.getMessage = getMessage; +/** + * Encodes a single value to an ABI serialisable string, number or Buffer. Returns the data as tuple, which consists of + * an array of ABI compatible types, and an array of corresponding values. + */ +const encodeValue = (typedData, type, data) => { + const match = type.match(ARRAY_REGEX); + // Checks for array types + if (match) { + const arrayType = match[1]; + const length = Number(match[2]) || undefined; + if (!Array.isArray(data)) { + throw new Error('Cannot encode data: value is not of array type'); + } + if (length && data.length !== length) { + throw new Error(`Cannot encode data: expected length of ${length}, but got ${data.length}`); + } + const encodedData = data.map(item => encodeValue(typedData, arrayType, item)); + const types = encodedData.map(item => item[0]); + const values = encodedData.map(item => item[1]); + return ['bytes32', (0, web3_utils_1.keccak256)((0, encode_js_1.encodeParameters)(types, values))]; + } + if (typedData.types[type]) { + return ['bytes32', getStructHash(typedData, type, data)]; + } + // Strings and arbitrary byte arrays are hashed to bytes32 + if (type === 'string') { + return ['bytes32', (0, web3_utils_1.keccak256)(data)]; + } + if (type === 'bytes') { + return ['bytes32', (0, web3_utils_1.keccak256)(data)]; + } + return [type, data]; +}; +/** + * Encode the data to an ABI encoded Buffer. The data should be a key -> value object with all the required values. All + * dependant types are automatically encoded. + */ +const encodeData = (typedData, type, data) => { + const [types, values] = typedData.types[type].reduce(([_types, _values], field) => { + if ((0, web3_utils_1.isNullish)(data[field.name]) || (0, web3_utils_1.isNullish)(data[field.name])) { + throw new Error(`Cannot encode data: missing data for '${field.name}'`); + } + const value = data[field.name]; + const [_type, encodedValue] = encodeValue(typedData, field.type, value); + return [ + [..._types, _type], + [..._values, encodedValue], + ]; + }, [['bytes32'], [getTypeHash(typedData, type)]]); + return (0, encode_js_1.encodeParameters)(types, values); +}; +//# sourceMappingURL=eip_712.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.js.map new file mode 100644 index 0000000..150738e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/eip_712.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eip_712.js","sourceRoot":"","sources":["../../src/eip_712.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAOF,2CAAkD;AAClD,kDAAsD;AAEtD,MAAM,UAAU,GAAG,MAAM,CAAC;AAC1B,MAAM,WAAW,GAAG,oBAAoB,CAAC;AAEzC;;;GAGG;AACH,MAAM,eAAe,GAAG,CACvB,SAA0B,EAC1B,IAAY,EACZ,eAAyB,EAAE,EAChB,EAAE;IACb,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAE,CAAC;IACtC,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5B,IAAI,YAAY,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QACtC,OAAO,YAAY,CAAC;KACpB;IAED,IAAI,CAAC,SAAS,CAAC,K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IAAA,sBAAS,EAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE;YAC/D,MAAM,IAAI,KAAK,CAAC,yCAAyC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC;SACxE;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,EAAE,YAAY,CAAC,GAAG,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAExE,OAAO;YACN,CAAC,GAAG,MAAM,EAAE,KAAK,CAAC;YAClB,CAAC,GAAG,OAAO,EAAE,YAAY,CAAC;SAC1B,CAAC;IACH,CAAC,EACD,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,WAAW,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAC7C,CAAC;IAEF,OAAO,IAAA,4BAAgB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AACxC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.d.ts new file mode 100644 index 0000000..c81c8ce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.d.ts @@ -0,0 +1,11 @@ +/** + * The web3.eth.abi functions let you encode and decode parameters to ABI (Application Binary Interface) for function calls to the EVM (Ethereum Virtual Machine). + */ +export * from './api/errors_api.js'; +export * from './api/events_api.js'; +export * from './api/functions_api.js'; +export * from './api/logs_api.js'; +export * from './api/parameters_api.js'; +export * from './utils.js'; +export * from './decode_contract_error_data.js'; +export { getMessage as getEncodedEip712Data } from './eip_712.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.js new file mode 100644 index 0000000..172ac3f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.js @@ -0,0 +1,46 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getEncodedEip712Data = void 0; +/** + * The web3.eth.abi functions let you encode and decode parameters to ABI (Application Binary Interface) for function calls to the EVM (Ethereum Virtual Machine). + */ +__exportStar(require("./api/errors_api.js"), exports); +__exportStar(require("./api/events_api.js"), exports); +__exportStar(require("./api/functions_api.js"), exports); +__exportStar(require("./api/logs_api.js"), exports); +__exportStar(require("./api/parameters_api.js"), exports); +__exportStar(require("./utils.js"), exports); +__exportStar(require("./decode_contract_error_data.js"), exports); +var eip_712_js_1 = require("./eip_712.js"); +Object.defineProperty(exports, "getEncodedEip712Data", { enumerable: true, get: function () { return eip_712_js_1.getMessage; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.js.map new file mode 100644 index 0000000..ca26ac8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;AAEF;;GAEG;AACH,sDAAoC;AACpC,sDAAoC;AACpC,yDAAuC;AACvC,oDAAkC;AAClC,0DAAwC;AACxC,6CAA2B;AAC3B,kEAAgD;AAChD,2CAAkE;AAAzD,kHAAA,UAAU,OAAwB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.d.ts new file mode 100644 index 0000000..758ff9b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.d.ts @@ -0,0 +1,43 @@ +import { AbiInput, AbiCoderStruct, AbiFragment, AbiParameter, AbiStruct, AbiEventFragment, AbiFunctionFragment, AbiConstructorFragment } from 'web3-types'; +export declare const isAbiFragment: (item: unknown) => item is AbiFragment; +export declare const isAbiErrorFragment: (item: unknown) => item is AbiEventFragment; +export declare const isAbiEventFragment: (item: unknown) => item is AbiEventFragment; +export declare const isAbiFunctionFragment: (item: unknown) => item is AbiFunctionFragment; +export declare const isAbiConstructorFragment: (item: unknown) => item is AbiConstructorFragment; +/** + * Check if type is simplified struct format + */ +export declare const isSimplifiedStructFormat: (type: string | Partial | Partial) => type is Omit; +/** + * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used + */ +export declare const mapStructNameAndType: (structName: string) => AbiStruct; +/** + * Maps the simplified format in to the expected format of the ABICoder + */ +export declare const mapStructToCoderFormat: (struct: AbiStruct) => Array; +/** + * Map types if simplified format is used + */ +export declare const mapTypes: (types: AbiInput[]) => Array>; +/** + * returns true if input is a hexstring and is odd-lengthed + */ +export declare const isOddHexstring: (param: unknown) => boolean; +/** + * format odd-length bytes to even-length + */ +export declare const formatOddHexstrings: (param: string) => string; +/** + * Handle some formatting of params for backwards compatibility with Ethers V4 + */ +export declare const formatParam: (type: string, _param: unknown) => unknown; +/** + * used to flatten json abi inputs/outputs into an array of type-representing-strings + */ +export declare const flattenTypes: (includeTuple: boolean, puts: ReadonlyArray) => string[]; +/** + * Should be used to create full function/event name from json abi + * returns a string + */ +export declare const jsonInterfaceMethodToString: (json: AbiFragment) => string; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.js new file mode 100644 index 0000000..2df2864 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.js @@ -0,0 +1,217 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jsonInterfaceMethodToString = exports.flattenTypes = exports.formatParam = exports.formatOddHexstrings = exports.isOddHexstring = exports.mapTypes = exports.mapStructToCoderFormat = exports.mapStructNameAndType = exports.isSimplifiedStructFormat = exports.isAbiConstructorFragment = exports.isAbiFunctionFragment = exports.isAbiEventFragment = exports.isAbiErrorFragment = exports.isAbiFragment = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const isAbiFragment = (item) => !(0, web3_utils_1.isNullish)(item) && + typeof item === 'object' && + !(0, web3_utils_1.isNullish)(item.type) && + ['function', 'event', 'constructor', 'error'].includes(item.type); +exports.isAbiFragment = isAbiFragment; +const isAbiErrorFragment = (item) => !(0, web3_utils_1.isNullish)(item) && + typeof item === 'object' && + !(0, web3_utils_1.isNullish)(item.type) && + item.type === 'error'; +exports.isAbiErrorFragment = isAbiErrorFragment; +const isAbiEventFragment = (item) => !(0, web3_utils_1.isNullish)(item) && + typeof item === 'object' && + !(0, web3_utils_1.isNullish)(item.type) && + item.type === 'event'; +exports.isAbiEventFragment = isAbiEventFragment; +const isAbiFunctionFragment = (item) => !(0, web3_utils_1.isNullish)(item) && + typeof item === 'object' && + !(0, web3_utils_1.isNullish)(item.type) && + item.type === 'function'; +exports.isAbiFunctionFragment = isAbiFunctionFragment; +const isAbiConstructorFragment = (item) => !(0, web3_utils_1.isNullish)(item) && + typeof item === 'object' && + !(0, web3_utils_1.isNullish)(item.type) && + item.type === 'constructor'; +exports.isAbiConstructorFragment = isAbiConstructorFragment; +/** + * Check if type is simplified struct format + */ +const isSimplifiedStructFormat = (type) => typeof type === 'object' && + typeof type.components === 'undefined' && + typeof type.name === 'undefined'; +exports.isSimplifiedStructFormat = isSimplifiedStructFormat; +/** + * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used + */ +const mapStructNameAndType = (structName) => structName.includes('[]') + ? { type: 'tuple[]', name: structName.slice(0, -2) } + : { type: 'tuple', name: structName }; +exports.mapStructNameAndType = mapStructNameAndType; +/** + * Maps the simplified format in to the expected format of the ABICoder + */ +const mapStructToCoderFormat = (struct) => { + const components = []; + for (const key of Object.keys(struct)) { + const item = struct[key]; + if (typeof item === 'object') { + components.push(Object.assign(Object.assign({}, (0, exports.mapStructNameAndType)(key)), { components: (0, exports.mapStructToCoderFormat)(item) })); + } + else { + components.push({ + name: key, + type: struct[key], + }); + } + } + return components; +}; +exports.mapStructToCoderFormat = mapStructToCoderFormat; +/** + * Map types if simplified format is used + */ +const mapTypes = (types) => { + const mappedTypes = []; + for (const type of types) { + let modifiedType = type; + // Clone object + if (typeof type === 'object') { + modifiedType = Object.assign({}, type); + } + // Remap `function` type params to bytes24 since Ethers does not + // recognize former type. Solidity docs say `Function` is a bytes24 + // encoding the contract address followed by the function selector hash. + if (typeof type === 'object' && type.type === 'function') { + modifiedType = Object.assign(Object.assign({}, type), { type: 'bytes24' }); + } + if ((0, exports.isSimplifiedStructFormat)(modifiedType)) { + const structName = Object.keys(modifiedType)[0]; + mappedTypes.push(Object.assign(Object.assign({}, (0, exports.mapStructNameAndType)(structName)), { components: (0, exports.mapStructToCoderFormat)(modifiedType[structName]) })); + } + else { + mappedTypes.push(modifiedType); + } + } + return mappedTypes; +}; +exports.mapTypes = mapTypes; +/** + * returns true if input is a hexstring and is odd-lengthed + */ +const isOddHexstring = (param) => typeof param === 'string' && /^(-)?0x[0-9a-f]*$/i.test(param) && param.length % 2 === 1; +exports.isOddHexstring = isOddHexstring; +/** + * format odd-length bytes to even-length + */ +const formatOddHexstrings = (param) => (0, exports.isOddHexstring)(param) ? `0x0${param.substring(2)}` : param; +exports.formatOddHexstrings = formatOddHexstrings; +/** + * Handle some formatting of params for backwards compatibility with Ethers V4 + */ +const formatParam = (type, _param) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + var _a; + // clone if _param is an object + const param = typeof _param === 'object' && !Array.isArray(_param) ? Object.assign({}, _param) : _param; + const paramTypeBytes = /^bytes([0-9]*)$/; + const paramTypeBytesArray = /^bytes([0-9]*)\[\]$/; + const paramTypeNumber = /^(u?int)([0-9]*)$/; + const paramTypeNumberArray = /^(u?int)([0-9]*)\[\]$/; + // Format BN to string + if (param instanceof BigInt) { + return param.toString(10); + } + if (paramTypeBytesArray.exec(type) || paramTypeNumberArray.exec(type)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const paramClone = [...param]; + return paramClone.map(p => (0, exports.formatParam)(type.replace('[]', ''), p)); + } + // Format correct width for u?int[0-9]* + let match = paramTypeNumber.exec(type); + if (match) { + const size = parseInt((_a = match[2]) !== null && _a !== void 0 ? _a : '256', 10); + if (size / 8 < param.length) { + // pad to correct bit width + return (0, web3_utils_1.leftPad)(param, size); + } + } + // Format correct length for bytes[0-9]+ + match = paramTypeBytes.exec(type); + if (match) { + const hexParam = param instanceof Uint8Array ? (0, web3_utils_1.toHex)(param) : param; + // format to correct length + const size = parseInt(match[1], 10); + if (size) { + let maxSize = size * 2; + if (param.startsWith('0x')) { + maxSize += 2; + } + // pad to correct length + const paddedParam = hexParam.length < maxSize + ? (0, web3_utils_1.rightPad)(param, size * 2) + : hexParam; + return (0, exports.formatOddHexstrings)(paddedParam); + } + return (0, exports.formatOddHexstrings)(hexParam); + } + return param; +}; +exports.formatParam = formatParam; +/** + * used to flatten json abi inputs/outputs into an array of type-representing-strings + */ +const flattenTypes = (includeTuple, puts) => { + const types = []; + puts.forEach(param => { + if (typeof param.components === 'object') { + if (!param.type.startsWith('tuple')) { + throw new web3_errors_1.AbiError(`Invalid value given "${param.type}". Error: components found but type is not tuple.`); + } + const arrayBracket = param.type.indexOf('['); + const suffix = arrayBracket >= 0 ? param.type.substring(arrayBracket) : ''; + const result = (0, exports.flattenTypes)(includeTuple, param.components); + if (Array.isArray(result) && includeTuple) { + types.push(`tuple(${result.join(',')})${suffix}`); + } + else if (!includeTuple) { + types.push(`(${result.join(',')})${suffix}`); + } + else { + types.push(`(${result.join()})`); + } + } + else { + types.push(param.type); + } + }); + return types; +}; +exports.flattenTypes = flattenTypes; +/** + * Should be used to create full function/event name from json abi + * returns a string + */ +const jsonInterfaceMethodToString = (json) => { + var _a, _b, _c, _d; + if ((0, exports.isAbiErrorFragment)(json) || (0, exports.isAbiEventFragment)(json) || (0, exports.isAbiFunctionFragment)(json)) { + if ((_a = json.name) === null || _a === void 0 ? void 0 : _a.includes('(')) { + return json.name; + } + return `${(_b = json.name) !== null && _b !== void 0 ? _b : ''}(${(0, exports.flattenTypes)(false, (_c = json.inputs) !== null && _c !== void 0 ? _c : []).join(',')})`; + } + // Constructor fragment + return `(${(0, exports.flattenTypes)(false, (_d = json.inputs) !== null && _d !== void 0 ? _d : []).join(',')})`; +}; +exports.jsonInterfaceMethodToString = jsonInterfaceMethodToString; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.js.map new file mode 100644 index 0000000..2a0c64b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/commonjs/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAAuC;AACvC,2CAAiE;AAY1D,MAAM,aAAa,GAAG,CAAC,IAAa,EAAuB,EAAE,CACnE,CAAC,IAAA,sBAAS,EAAC,IAAI,CAAC;IAChB,OAAO,IAAI,KAAK,QAAQ;IACxB,CAAC,IAAA,sBAAS,EAAE,IAAyB,CAAC,IAAI,CAAC;IAC3C,CAAC,UAAU,EAAE,OAAO,EAAE,aAAa,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAE,IAAyB,CAAC,IAAI,CAAC,CAAC;AAJ5E,QAAA,aAAa,iBAI+D;AAElF,MAAM,kBAAkB,GAAG,CAAC,IAAa,EAA4B,EAAE,CAC7E,CAAC,IAAA,sBAAS,EAAC,IAAI,CAAC;IAChB,OAAO,IAAI,KAAK,QAAQ;IACxB,CAAC,IAAA,sBAAS,EAAE,IAAyB,CAAC,IAAI,CAAC;IAC1C,IAAyB,CAAC,IAAI,KAAK,OAAO,CAAC;AAJhC,QAAA,kBAAkB,sBAIc;AAEtC,MAAM,kBAAkB,GAAG,CAAC,IAAa,EAA4B,EAAE,CAC7E,CAAC,IAAA,sBAAS,EAAC,IAAI,CA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AC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;aAC7C;iBAAM;gBACN,KAAK,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;aACjC;SACD;aAAM;YACN,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SACvB;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AA9BW,QAAA,YAAY,gBA8BvB;AAEF;;;GAGG;AACI,MAAM,2BAA2B,GAAG,CAAC,IAAiB,EAAU,EAAE;;IACxE,IAAI,IAAA,0BAAkB,EAAC,IAAI,CAAC,IAAI,IAAA,0BAAkB,EAAC,IAAI,CAAC,IAAI,IAAA,6BAAqB,EAAC,IAAI,CAAC,EAAE;QACxF,IAAI,MAAA,IAAI,CAAC,IAAI,0CAAE,QAAQ,CAAC,GAAG,CAAC,EAAE;YAC7B,OAAO,IAAI,CAAC,IAAI,CAAC;SACjB;QAED,OAAO,GAAG,MAAA,IAAI,CAAC,IAAI,mCAAI,EAAE,IAAI,IAAA,oBAAY,EAAC,KAAK,EAAE,MAAA,IAAI,CAAC,MAAM,mCAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;KACjF;IAED,uBAAuB;IACvB,OAAO,IAAI,IAAA,oBAAY,EAAC,KAAK,EAAE,MAAA,IAAI,CAAC,MAAM,mCAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;AAChE,CAAC,CAAC;AAXW,QAAA,2BAA2B,+BAWtC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/errors_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/errors_api.js new file mode 100644 index 0000000..d7380cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/errors_api.js @@ -0,0 +1,36 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { sha3Raw } from 'web3-utils'; +import { AbiError } from 'web3-errors'; +import { jsonInterfaceMethodToString, isAbiErrorFragment } from '../utils.js'; +/** + * Encodes the error name to its ABI signature, which are the sha3 hash of the error name including input types. + */ +export const encodeErrorSignature = (functionName) => { + if (typeof functionName !== 'string' && !isAbiErrorFragment(functionName)) { + throw new AbiError('Invalid parameter value in encodeErrorSignature'); + } + let name; + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = jsonInterfaceMethodToString(functionName); + } + else { + name = functionName; + } + return sha3Raw(name); +}; +//# sourceMappingURL=errors_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/errors_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/errors_api.js.map new file mode 100644 index 0000000..0a7aa53 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/errors_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors_api.js","sourceRoot":"","sources":["../../../src/api/errors_api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAE9E;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,YAAuC,EAAU,EAAE;IACvF,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,kBAAkB,CAAC,YAAY,CAAC,EAAE;QAC1E,MAAM,IAAI,QAAQ,CAAC,iDAAiD,CAAC,CAAC;KACtE;IAED,IAAI,IAAY,CAAC;IAEjB,IAAI,YAAY,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,IAAI,OAAO,YAAY,KAAK,QAAQ,CAAC,EAAE;QAC7F,IAAI,GAAG,2BAA2B,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACN,IAAI,GAAG,YAAY,CAAC;KACpB;IAED,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/events_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/events_api.js new file mode 100644 index 0000000..db98466 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/events_api.js @@ -0,0 +1,82 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { sha3Raw } from 'web3-utils'; +import { AbiError } from 'web3-errors'; +import { jsonInterfaceMethodToString, isAbiEventFragment } from '../utils.js'; +/** + * Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types. + * @param functionName - The event name to encode, or the {@link AbiEventFragment} object of the event. If string, it has to be in the form of `eventName(param1Type,param2Type,...)`. eg: myEvent(uint256,bytes32). + * @returns - The ABI signature of the event. + * + * @example + * ```ts + * const event = web3.eth.abi.encodeEventSignature({ + * name: "myEvent", + * type: "event", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "bytes32", + * name: "myBytes", + * }, + * ], + * }); + * console.log(event); + * > 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 + * + * const event = web3.eth.abi.encodeEventSignature({ + * inputs: [ + * { + * indexed: true, + * name: "from", + * type: "address", + * }, + * { + * indexed: true, + * name: "to", + * type: "address", + * }, + * { + * indexed: false, + * name: "value", + * type: "uint256", + * }, + * ], + * name: "Transfer", + * type: "event", + * }); + * console.log(event); + * > 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + * ``` + */ +export const encodeEventSignature = (functionName) => { + if (typeof functionName !== 'string' && !isAbiEventFragment(functionName)) { + throw new AbiError('Invalid parameter value in encodeEventSignature'); + } + let name; + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = jsonInterfaceMethodToString(functionName); + } + else { + name = functionName; + } + return sha3Raw(name); +}; +//# sourceMappingURL=events_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/events_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/events_api.js.map new file mode 100644 index 0000000..885e95e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/events_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events_api.js","sourceRoot":"","sources":["../../../src/api/events_api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,YAAuC,EAAU,EAAE;IACvF,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,kBAAkB,CAAC,YAAY,CAAC,EAAE;QAC1E,MAAM,IAAI,QAAQ,CAAC,iDAAiD,CAAC,CAAC;KACtE;IAED,IAAI,IAAY,CAAC;IAEjB,IAAI,YAAY,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,IAAI,OAAO,YAAY,KAAK,QAAQ,CAAC,EAAE;QAC7F,IAAI,GAAG,2BAA2B,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACN,IAAI,GAAG,YAAY,CAAC;KACpB;IAED,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/functions_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/functions_api.js new file mode 100644 index 0000000..3435dac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/functions_api.js @@ -0,0 +1,130 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { sha3Raw } from 'web3-utils'; +import { isAbiFunctionFragment, jsonInterfaceMethodToString } from '../utils.js'; +import { encodeParameters } from './parameters_api.js'; +// todo Add link to JSON interface documentation +/** + * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. + * @param functionName - The function name to encode or the `JSON interface` object of the function. + * If the passed parameter is a string, it has to be in the form of `functionName(param1Type,param2Type,...)`. eg: myFunction(uint256,uint32[],bytes10,bytes) + * @returns - The ABI signature of the function. + * @example + * ```ts + * const signature = web3.eth.abi.encodeFunctionSignature({ + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }); + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)') + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('safeTransferFrom(address,address,uint256,bytes)'); + * console.log(signature); + * > 0xb88d4fde + * ``` + */ +export const encodeFunctionSignature = (functionName) => { + if (typeof functionName !== 'string' && !isAbiFunctionFragment(functionName)) { + throw new AbiError('Invalid parameter value in encodeFunctionSignature'); + } + let name; + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = jsonInterfaceMethodToString(functionName); + } + else { + name = functionName; + } + return sha3Raw(name).slice(0, 10); +}; +// todo Add link to JSON interface documentation +/** + * Encodes a function call using its `JSON interface` object and given parameters. + * @param jsonInterface - The `JSON interface` object of the function. + * @param params - The parameters to encode + * @returns - The ABI encoded function call, which, means the function signature and the parameters passed. + * @example + * ```ts + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }, + * ["2345675643", "Hello!%"] + * ); + * console.log(sig); + * > 0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * + * + * + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * inputs: [ + * { + * name: "account", + * type: "address", + * }, + * ], + * name: "balanceOf", + * outputs: [ + * { + * name: "", + * type: "uint256", + * }, + * ], + * stateMutability: "view", + * type: "function", + * }, + * ["0x1234567890123456789012345678901234567890"] + * ); + * + * console.log(sig); + * > 0x70a082310000000000000000000000001234567890123456789012345678901234567890 + * ``` + */ +export const encodeFunctionCall = (jsonInterface, params) => { + var _a; + if (!isAbiFunctionFragment(jsonInterface)) { + throw new AbiError('Invalid parameter value in encodeFunctionCall'); + } + return `${encodeFunctionSignature(jsonInterface)}${encodeParameters((_a = jsonInterface.inputs) !== null && _a !== void 0 ? _a : [], params !== null && params !== void 0 ? params : []).replace('0x', '')}`; +}; +//# sourceMappingURL=functions_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/functions_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/functions_api.js.map new file mode 100644 index 0000000..3876194 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/functions_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"functions_api.js","sourceRoot":"","sources":["../../../src/api/functions_api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,gDAAgD;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,YAA0C,EAAU,EAAE;IAC7F,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAAC,EAAE;QAC7E,MAAM,IAAI,QAAQ,CAAC,oDAAoD,CAAC,CAAC;KACzE;IAED,IAAI,IAAY,CAAC;IAEjB,IAAI,YAAY,IAAI,CAAC,OAAO,YAAY,KAAK,UAAU,IAAI,OAAO,YAAY,KAAK,QAAQ,CAAC,EAAE;QAC7F,IAAI,GAAG,2BAA2B,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACN,IAAI,GAAG,YAAY,CAAC;KACpB;IAED,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC,CAAC;AAEF,gDAAgD;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CACjC,aAAkC,EAClC,MAAiB,EACR,EAAE;;IACX,IAAI,CAAC,qBAAqB,CAAC,aAAa,CAAC,EAAE;QAC1C,MAAM,IAAI,QAAQ,CAAC,+CAA+C,CAAC,CAAC;KACpE;IAED,OAAO,GAAG,uBAAuB,CAAC,aAAa,CAAC,GAAG,gBAAgB,CAClE,MAAA,aAAa,CAAC,MAAM,mCAAI,EAAE,EAC1B,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CACZ,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;AACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/logs_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/logs_api.js new file mode 100644 index 0000000..d9d1d87 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/logs_api.js @@ -0,0 +1,103 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { decodeParameter, decodeParametersWith } from './parameters_api.js'; +const STATIC_TYPES = ['bool', 'string', 'int', 'uint', 'address', 'fixed', 'ufixed']; +const _decodeParameter = (inputType, clonedTopic) => inputType === 'string' ? clonedTopic : decodeParameter(inputType, clonedTopic); +/** + * Decodes ABI-encoded log data and indexed topic data. + * @param inputs - A {@link AbiParameter} input array. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param data - The ABI byte code in the `data` field of a log. + * @param topics - An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0] + * @returns - The result object containing the decoded parameters. + * + * @example + * ```ts + * let res = web3.eth.abi.decodeLog( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * indexed: true, + * }, + * { + * type: "uint8", + * name: "mySmallNumber", + * indexed: true, + * }, + * ], + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000", + * [ + * "0x000000000000000000000000000000000000000000000000000000000000f310", + * "0x0000000000000000000000000000000000000000000000000000000000000010", + * ] + * ); + * > { + * '0': 'Hello%!', + * '1': 62224n, + * '2': 16n, + * __length__: 3, + * myString: 'Hello%!', + * myNumber: 62224n, + * mySmallNumber: 16n + * } + * ``` + */ +export const decodeLog = (inputs, data, topics) => { + const clonedTopics = Array.isArray(topics) ? topics : [topics]; + const indexedInputs = {}; + const nonIndexedInputs = {}; + for (const [i, input] of inputs.entries()) { + if (input.indexed) { + indexedInputs[i] = input; + } + else { + nonIndexedInputs[i] = input; + } + } + const decodedNonIndexedInputs = data + ? decodeParametersWith(Object.values(nonIndexedInputs), data, true) + : { __length__: 0 }; + // If topics are more than indexed inputs, that means first topic is the event signature + const offset = clonedTopics.length - Object.keys(indexedInputs).length; + const decodedIndexedInputs = Object.values(indexedInputs).map((input, index) => STATIC_TYPES.some(s => input.type.startsWith(s)) + ? _decodeParameter(input.type, clonedTopics[index + offset]) + : clonedTopics[index + offset]); + const returnValues = { __length__: 0 }; + let indexedCounter = 0; + let nonIndexedCounter = 0; + for (const [i, res] of inputs.entries()) { + returnValues[i] = res.type === 'string' ? '' : undefined; + if (indexedInputs[i]) { + returnValues[i] = decodedIndexedInputs[indexedCounter]; + indexedCounter += 1; + } + if (nonIndexedInputs[i]) { + returnValues[i] = decodedNonIndexedInputs[String(nonIndexedCounter)]; + nonIndexedCounter += 1; + } + if (res.name) { + returnValues[res.name] = returnValues[i]; + } + returnValues.__length__ += 1; + } + return returnValues; +}; +//# sourceMappingURL=logs_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/logs_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/logs_api.js.map new file mode 100644 index 0000000..48c27f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/logs_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logs_api.js","sourceRoot":"","sources":["../../../src/api/logs_api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAErF,MAAM,gBAAgB,GAAG,CAAC,SAAiB,EAAE,WAAmB,EAAE,EAAE,CACnE,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,eAAe,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CACxB,MAA2B,EAC3B,IAAe,EACf,MAAyB,EACxB,EAAE;IACH,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAE/D,MAAM,aAAa,GAAiC,E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AC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;QAEzD,IAAI,aAAa,CAAC,CAAC,CAAC,EAAE;YACrB,YAAY,CAAC,CAAC,CAAC,GAAG,oBAAoB,CAAC,cAAc,CAAC,CAAC;YACvD,cAAc,IAAI,CAAC,CAAC;SACpB;QAED,IAAI,gBAAgB,CAAC,CAAC,CAAC,EAAE;YACxB,YAAY,CAAC,CAAC,CAAC,GAAG,uBAAuB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC;YACrE,iBAAiB,IAAI,CAAC,CAAC;SACvB;QAED,IAAI,GAAG,CAAC,IAAI,EAAE;YACb,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;SACzC;QAED,YAAY,CAAC,UAAU,IAAI,CAAC,CAAC;KAC7B;IAED,OAAO,YAA0B,CAAC;AACnC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/parameters_api.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/parameters_api.js new file mode 100644 index 0000000..ed94148 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/parameters_api.js @@ -0,0 +1,283 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { decodeParameters as decodeParametersInternal } from '../coders/decode.js'; +import { encodeParameters as encodeParametersInternal } from '../coders/encode.js'; +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - An array of {@link AbiInput}. See [Solidity's documentation](https://solidity.readthedocs.io/en/v0.5.3/abi-spec.html#json) for more details. + * @param params - The actual parameters to encode. + * @returns - The ABI encoded parameters + * @example + * ```ts + * const res = web3.eth.abi.encodeParameters( + * ["uint256", "string"], + * ["2345675643", "Hello!%"] + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * ``` + */ +export const encodeParameters = (abi, params) => encodeParametersInternal(abi, params); +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param param - The actual parameter to encode. + * @returns - The ABI encoded parameter + * @example + * ```ts + * const res = web3.eth.abi.encodeParameter("uint256", "2345675643"); + * console.log(res); + * 0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("uint", "2345675643"); + * + * console.log(res); + * >0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("bytes32", "0xdf3234"); + * + * console.log(res); + * >0xdf32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes", "0xdf3234"); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes32[]", ["0xdf3234", "0xfdfd"]); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * { + * propertyOne: 42, + * propertyTwo: 56, + * childStruct: { + * propertyOne: 45, + * propertyTwo: 78, + * }, + * } + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e + * ``` + */ +export const encodeParameter = (abi, param) => encodeParameters([abi], [param]); +/** + * Should be used to decode list of params + */ +export const decodeParametersWith = (abis, bytes, loose) => { + try { + if (abis.length > 0 && (!bytes || bytes === '0x' || bytes === '0X')) { + throw new AbiError("Returned values aren't valid, did it run Out of Gas? " + + 'You might also see this error if you are not using the ' + + 'correct ABI for the contract you are retrieving data from, ' + + 'requesting data from a block number that does not exist, ' + + 'or querying a node which is not fully synced.'); + } + return decodeParametersInternal(abis, `0x${bytes.replace(/0x/i, '')}`, loose); + } + catch (err) { + throw new AbiError(`Parameter decoding error: ${err.message}`, { + internalErr: err, + }); + } +}; +/** + * Should be used to decode list of params + */ +/** + * Decodes ABI encoded parameters to its JavaScript types. + * @param abi - An array of {@link AbiInput}. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The result object containing the decoded parameters. + * @example + * ```ts + * let res = web3.eth.abi.decodeParameters( + * ["string", "uint256"], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { '0': 'Hello!%!', '1': 234n, __length__: 2 } + * + * let res = web3.eth.abi.decodeParameters( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * }, + * ], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { + * '0': 'Hello!%!', + * '1': 234n, + * __length__: 2, + * myString: 'Hello!%!', + * myNumber: 234n + * } + * + * const res = web3.eth.abi.decodeParameters( + * [ + * "uint8[]", + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * ], + * "0x00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000018" + * ); + * console.log(res); + * > + * '0': [ 42n, 24n ], + * '1': { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * }, + * __length__: 2, + * ParentStruct: { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * } + *} + * ``` + */ +export const decodeParameters = (abi, bytes) => decodeParametersWith(abi, bytes, false); +/** + * Should be used to decode bytes to plain param + */ +/** + * Decodes an ABI encoded parameter to its JavaScript type. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The decoded parameter + * @example + * ```ts + * const res = web3.eth.abi.decodeParameter( + * "uint256", + * "0x0000000000000000000000000000000000000000000000000000000000000010" + * ); + * console.log(res); + * > 16n + * + * const res = web3.eth.abi.decodeParameter( + * "string", + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * + * console.log(res); + * > Hello!%! + * + * const res = web3.eth.abi.decodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * "0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e" + * ); + * + * console.log(res); + * { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + *} + * ``` + */ +export const decodeParameter = (abi, bytes) => decodeParameters([abi], bytes)['0']; +//# sourceMappingURL=parameters_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/parameters_api.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/parameters_api.js.map new file mode 100644 index 0000000..1e94346 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/api/parameters_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parameters_api.js","sourceRoot":"","sources":["../../../src/api/parameters_api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,gBAAgB,IAAI,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAE,gBAAgB,IAA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gBAAgB,GAAG,CAC/B,GAAe,EACf,KAAgB,EACiC,EAAE,CAAC,oBAAoB,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AAE7F;;GAEG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAa,EAAE,KAAgB,EAAW,EAAE,CAC3E,gBAAgB,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/address.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/address.js new file mode 100644 index 0000000..990a427 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/address.js @@ -0,0 +1,70 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { toChecksumAddress } from 'web3-utils'; +import { isAddress, utils } from 'web3-validator'; +import { alloc, WORD_SIZE } from '../utils.js'; +const ADDRESS_BYTES_COUNT = 20; +const ADDRESS_OFFSET = WORD_SIZE - ADDRESS_BYTES_COUNT; +export function encodeAddress(param, input) { + if (typeof input !== 'string') { + throw new AbiError('address type expects string as input type', { + value: input, + name: param.name, + type: param.type, + }); + } + let address = input.toLowerCase(); + if (!address.startsWith('0x')) { + address = `0x${address}`; + } + if (!isAddress(address)) { + throw new AbiError('provided input is not valid address', { + value: input, + name: param.name, + type: param.type, + }); + } + // for better performance, we could convert hex to destination bytes directly (encoded var) + const addressBytes = utils.hexToUint8Array(address); + // expand address to WORD_SIZE + const encoded = alloc(WORD_SIZE); + encoded.set(addressBytes, ADDRESS_OFFSET); + return { + dynamic: false, + encoded, + }; +} +export function decodeAddress(_param, bytes) { + const addressBytes = bytes.subarray(ADDRESS_OFFSET, WORD_SIZE); + if (addressBytes.length !== ADDRESS_BYTES_COUNT) { + throw new AbiError('Invalid decoding input, not enough bytes to decode address', { bytes }); + } + const result = utils.uint8ArrayToHexString(addressBytes); + // should we check is decoded value is valid address? + // if(!isAddress(result)) { + // throw new AbiError("encoded data is not valid address", { + // address: result, + // }); + // } + return { + result: toChecksumAddress(result), + encoded: bytes.subarray(WORD_SIZE), + consumed: WORD_SIZE, + }; +} +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/address.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/address.js.map new file mode 100644 index 0000000..208856d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../../src/coders/base/address.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,cAAc,GAAG,SAAS,GAAG,mBAAmB,CAAC;AAEvD,MAAM,UAAU,aAAa,CAAC,KAAmB,EAAE,KAAc;IAChE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,MAA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AAO;QACN,MAAM,EAAE,iBAAiB,CAAC,MAAM,CAAC;QACjC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC;QAClC,QAAQ,EAAE,SAAS;KACnB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/array.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/array.js new file mode 100644 index 0000000..e5fa253 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/array.js @@ -0,0 +1,101 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { uint8ArrayConcat } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { decodeParamFromAbiParameter, encodeNumber, encodeParamFromAbiParameter } from './index.js'; +import { extractArrayType, isDynamic, WORD_SIZE } from '../utils.js'; +import { decodeNumber } from './number.js'; +import { encodeDynamicParams } from './utils.js'; +export function encodeArray(param, values) { + if (!Array.isArray(values)) { + throw new AbiError('Expected value to be array', { abi: param, values }); + } + const { size, param: arrayItemParam } = extractArrayType(param); + const encodedParams = values.map(v => encodeParamFromAbiParameter(arrayItemParam, v)); + const dynamic = size === -1; + const dynamicItems = encodedParams.length > 0 && encodedParams[0].dynamic; + if (!dynamic && values.length !== size) { + throw new AbiError("Given arguments count doesn't match array length", { + arrayLength: size, + argumentsLength: values.length, + }); + } + if (dynamic || dynamicItems) { + const encodingResult = encodeDynamicParams(encodedParams); + if (dynamic) { + const encodedLength = encodeNumber({ type: 'uint256', name: '' }, encodedParams.length).encoded; + return { + dynamic: true, + encoded: encodedParams.length > 0 + ? uint8ArrayConcat(encodedLength, encodingResult) + : encodedLength, + }; + } + return { + dynamic: true, + encoded: encodingResult, + }; + } + return { + dynamic: false, + encoded: uint8ArrayConcat(...encodedParams.map(p => p.encoded)), + }; +} +export function decodeArray(param, bytes) { + // eslint-disable-next-line prefer-const + let { size, param: arrayItemParam } = extractArrayType(param); + const dynamic = size === -1; + let consumed = 0; + const result = []; + let remaining = bytes; + // dynamic array, we need to decode length + if (dynamic) { + const lengthResult = decodeNumber({ type: 'uint32', name: '' }, bytes); + size = Number(lengthResult.result); + consumed = lengthResult.consumed; + remaining = lengthResult.encoded; + } + const hasDynamicChild = isDynamic(arrayItemParam); + if (hasDynamicChild) { + // known length but dynamic child, each child is actually head element with encoded offset + for (let i = 0; i < size; i += 1) { + const offsetResult = decodeNumber({ type: 'uint32', name: '' }, remaining.subarray(i * WORD_SIZE)); + consumed += offsetResult.consumed; + const decodedChildResult = decodeParamFromAbiParameter(arrayItemParam, remaining.subarray(Number(offsetResult.result))); + consumed += decodedChildResult.consumed; + result.push(decodedChildResult.result); + } + return { + result, + encoded: remaining.subarray(consumed), + consumed, + }; + } + for (let i = 0; i < size; i += 1) { + // decode static params + const decodedChildResult = decodeParamFromAbiParameter(arrayItemParam, bytes.subarray(consumed)); + consumed += decodedChildResult.consumed; + result.push(decodedChildResult.result); + } + return { + result, + encoded: bytes.subarray(consumed), + consumed, + }; +} +//# sourceMappingURL=array.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/array.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/array.js.map new file mode 100644 index 0000000..25eed71 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"array.js","sourceRoot":"","sources":["../../../../src/coders/base/array.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;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abi/lib/esm/coders/base/bool.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bool.js new file mode 100644 index 0000000..e949e6f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bool.js @@ -0,0 +1,51 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError, InvalidBooleanError } from 'web3-errors'; +import { toBool } from 'web3-utils'; +import { WORD_SIZE } from '../utils.js'; +import { decodeNumber, encodeNumber } from './number.js'; +export function encodeBoolean(param, input) { + let value; + try { + value = toBool(input); + } + catch (e) { + if (e instanceof InvalidBooleanError) { + throw new AbiError('provided input is not valid boolean value', { + type: param.type, + value: input, + name: param.name, + }); + } + } + return encodeNumber({ type: 'uint8', name: '' }, Number(value)); +} +export function decodeBool(_param, bytes) { + const numberResult = decodeNumber({ type: 'uint8', name: '' }, bytes); + if (numberResult.result > 1 || numberResult.result < 0) { + throw new AbiError('Invalid boolean value encoded', { + boolBytes: bytes.subarray(0, WORD_SIZE), + numberResult, + }); + } + return { + result: numberResult.result === BigInt(1), + encoded: numberResult.encoded, + consumed: WORD_SIZE, + }; +} +//# sourceMappingURL=bool.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bool.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bool.js.map new file mode 100644 index 0000000..6917d5a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bool.js","sourceRoot":"","sources":["../../../../src/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AAM,CAAC,CAAC,CAAC;QACzC,OAAO,EAAE,YAAY,CAAC,OAAO;QAC7B,QAAQ,EAAE,SAAS;KACnB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bytes.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bytes.js new file mode 100644 index 0000000..61364ed --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bytes.js @@ -0,0 +1,96 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { bytesToHex, bytesToUint8Array } from 'web3-utils'; +import { isBytes } from 'web3-validator'; +import { alloc, WORD_SIZE } from '../utils.js'; +import { decodeNumber, encodeNumber } from './number.js'; +const MAX_STATIC_BYTES_COUNT = 32; +export function encodeBytes(param, input) { + // hack for odd length hex strings + if (typeof input === 'string' && input.length % 2 !== 0) { + // eslint-disable-next-line no-param-reassign + input += '0'; + } + if (!isBytes(input)) { + throw new AbiError('provided input is not valid bytes value', { + type: param.type, + value: input, + name: param.name, + }); + } + const bytes = bytesToUint8Array(input); + const [, size] = param.type.split('bytes'); + // fixed size + if (size) { + if (Number(size) > MAX_STATIC_BYTES_COUNT || Number(size) < 1) { + throw new AbiError('invalid bytes type. Static byte type can have between 1 and 32 bytes', { + type: param.type, + }); + } + if (Number(size) < bytes.length) { + throw new AbiError('provided input size is different than type size', { + type: param.type, + value: input, + name: param.name, + }); + } + const encoded = alloc(WORD_SIZE); + encoded.set(bytes); + return { + dynamic: false, + encoded, + }; + } + const partsLength = Math.ceil(bytes.length / WORD_SIZE); + // one word for length of data + WORD for each part of actual data + const encoded = alloc(WORD_SIZE + partsLength * WORD_SIZE); + encoded.set(encodeNumber({ type: 'uint32', name: '' }, bytes.length).encoded); + encoded.set(bytes, WORD_SIZE); + return { + dynamic: true, + encoded, + }; +} +export function decodeBytes(param, bytes) { + const [, sizeString] = param.type.split('bytes'); + let size = Number(sizeString); + let remainingBytes = bytes; + let partsCount = 1; + let consumed = 0; + if (!size) { + // dynamic bytes + const result = decodeNumber({ type: 'uint32', name: '' }, remainingBytes); + size = Number(result.result); + consumed += result.consumed; + remainingBytes = result.encoded; + partsCount = Math.ceil(size / WORD_SIZE); + } + if (size > bytes.length) { + throw new AbiError('there is not enough data to decode', { + type: param.type, + encoded: bytes, + size, + }); + } + return { + result: bytesToHex(remainingBytes.subarray(0, size)), + encoded: remainingBytes.subarray(partsCount * WORD_SIZE), + consumed: consumed + partsCount * WORD_SIZE, + }; +} +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bytes.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bytes.js.map new file mode 100644 index 0000000..1c5c09f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../../src/coders/base/bytes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAmB,MAAM,gBAAgB,CAAC;AAE1D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC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MAAM,IAAI,QAAQ,CAAC,oCAAoC,EAAE;YACxD,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,OAAO,EAAE,KAAK;YACd,IAAI;SACJ,CAAC,CAAC;KACH;IAED,OAAO;QACN,MAAM,EAAE,UAAU,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACpD,OAAO,EAAE,cAAc,CAAC,QAAQ,CAAC,UAAU,GAAG,SAAS,CAAC;QACxD,QAAQ,EAAE,QAAQ,GAAG,UAAU,GAAG,SAAS;KAC3C,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/index.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/index.js new file mode 100644 index 0000000..0825aaa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/index.js @@ -0,0 +1,83 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { decodeAddress, encodeAddress } from './address.js'; +import { decodeBool, encodeBoolean } from './bool.js'; +import { decodeBytes, encodeBytes } from './bytes.js'; +import { decodeNumber, encodeNumber } from './number.js'; +import { decodeString, encodeString } from './string.js'; +// eslint-disable-next-line import/no-cycle +import { decodeTuple, encodeTuple } from './tuple.js'; +// eslint-disable-next-line import/no-cycle +import { decodeArray, encodeArray } from './array.js'; +export { encodeAddress, decodeAddress } from './address.js'; +export { encodeBoolean, decodeBool } from './bool.js'; +export { encodeBytes, decodeBytes } from './bytes.js'; +export { encodeNumber, decodeNumber } from './number.js'; +export { encodeString, decodeString } from './string.js'; +// eslint-disable-next-line import/no-cycle +export { encodeTuple, decodeTuple } from './tuple.js'; +// eslint-disable-next-line import/no-cycle +export { encodeArray, decodeArray } from './array.js'; +export function encodeParamFromAbiParameter(param, value) { + if (param.type === 'string') { + return encodeString(param, value); + } + if (param.type === 'bool') { + return encodeBoolean(param, value); + } + if (param.type === 'address') { + return encodeAddress(param, value); + } + if (param.type === 'tuple') { + return encodeTuple(param, value); + } + if (param.type.endsWith(']')) { + return encodeArray(param, value); + } + if (param.type.startsWith('bytes')) { + return encodeBytes(param, value); + } + if (param.type.startsWith('uint') || param.type.startsWith('int')) { + return encodeNumber(param, value); + } + throw new Error('Unsupported'); +} +export function decodeParamFromAbiParameter(param, bytes) { + if (param.type === 'string') { + return decodeString(param, bytes); + } + if (param.type === 'bool') { + return decodeBool(param, bytes); + } + if (param.type === 'address') { + return decodeAddress(param, bytes); + } + if (param.type === 'tuple') { + return decodeTuple(param, bytes); + } + if (param.type.endsWith(']')) { + return decodeArray(param, bytes); + } + if (param.type.startsWith('bytes')) { + return decodeBytes(param, bytes); + } + if (param.type.startsWith('uint') || param.type.startsWith('int')) { + return decodeNumber(param, bytes); + } + throw new Error('Unsupported'); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/index.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/index.js.map new file mode 100644 index 0000000..34fd1b5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/coders/base/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAIF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,WAAW,EA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AAC,CAAC;KACjC;IACD,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE;QAClE,OAAO,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;KAClC;IACD,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;AAChC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/number.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/number.js new file mode 100644 index 0000000..b118615 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/number.js @@ -0,0 +1,111 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { padLeft, toBigInt } from 'web3-utils'; +import { utils } from 'web3-validator'; +import { WORD_SIZE } from '../utils.js'; +import { numberLimits } from './numbersLimits.js'; +// eslint-disable-next-line no-bitwise +const mask = BigInt(1) << BigInt(256); +function bigIntToUint8Array(value, byteLength = WORD_SIZE) { + let hexValue; + if (value < 0) { + hexValue = (mask + value).toString(16); + } + else { + hexValue = value.toString(16); + } + hexValue = padLeft(hexValue, byteLength * 2); + return utils.hexToUint8Array(hexValue); +} +function uint8ArrayToBigInt(value, max) { + const hexValue = utils.uint8ArrayToHexString(value); + const result = BigInt(hexValue); + if (result <= max) + return result; + return result - mask; +} +export function encodeNumber(param, input) { + let value; + try { + value = toBigInt(input); + } + catch (e) { + throw new AbiError('provided input is not number value', { + type: param.type, + value: input, + name: param.name, + }); + } + const limit = numberLimits.get(param.type); + if (!limit) { + throw new AbiError('provided abi contains invalid number datatype', { type: param.type }); + } + if (value < limit.min) { + throw new AbiError('provided input is less then minimum for given type', { + type: param.type, + value: input, + name: param.name, + minimum: limit.min.toString(), + }); + } + if (value > limit.max) { + throw new AbiError('provided input is greater then maximum for given type', { + type: param.type, + value: input, + name: param.name, + maximum: limit.max.toString(), + }); + } + return { + dynamic: false, + encoded: bigIntToUint8Array(value), + }; +} +export function decodeNumber(param, bytes) { + if (bytes.length < WORD_SIZE) { + throw new AbiError('Not enough bytes left to decode', { param, bytesLeft: bytes.length }); + } + const boolBytes = bytes.subarray(0, WORD_SIZE); + const limit = numberLimits.get(param.type); + if (!limit) { + throw new AbiError('provided abi contains invalid number datatype', { type: param.type }); + } + const numberResult = uint8ArrayToBigInt(boolBytes, limit.max); + if (numberResult < limit.min) { + throw new AbiError('decoded value is less then minimum for given type', { + type: param.type, + value: numberResult, + name: param.name, + minimum: limit.min.toString(), + }); + } + if (numberResult > limit.max) { + throw new AbiError('decoded value is greater then maximum for given type', { + type: param.type, + value: numberResult, + name: param.name, + maximum: limit.max.toString(), + }); + } + return { + result: numberResult, + encoded: bytes.subarray(WORD_SIZE), + consumed: WORD_SIZE, + }; +} +//# sourceMappingURL=number.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/number.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/number.js.map new file mode 100644 index 0000000..66aa7fb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"number.js","sourceRoot":"","sources":["../../../../src/coders/base/number.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,YAA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AC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3C,IAAI,CAAC,KAAK,EAAE;QACX,MAAM,IAAI,QAAQ,CAAC,+CAA+C,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;KAC1F;IACD,MAAM,YAAY,GAAG,kBAAkB,CAAC,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAE9D,IAAI,YAAY,GAAG,KAAK,CAAC,GAAG,EAAE;QAC7B,MAAM,IAAI,QAAQ,CAAC,mDAAmD,EAAE;YACvE,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,KAAK,EAAE,YAAY;YACnB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,OAAO,EAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE;SAC7B,CAAC,CAAC;KACH;IACD,IAAI,YAAY,GAAG,KAAK,CAAC,GAAG,EAAE;QAC7B,MAAM,IAAI,QAAQ,CAAC,sDAAsD,EAAE;YAC1E,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,KAAK,EAAE,YAAY;YACnB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,OAAO,EAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE;SAC7B,CAAC,CAAC;KACH;IACD,OAAO;QACN,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC;QAClC,QAAQ,EAAE,SAAS;KACnB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/numbersLimits.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/numbersLimits.js new file mode 100644 index 0000000..28dd854 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/numbersLimits.js @@ -0,0 +1,37 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* + * this variable contains the precalculated limits for all the numbers for uint and int types +*/ +export const numberLimits = new Map(); +let base = BigInt(256); // 2 ^ 8 = 256 +for (let i = 8; i <= 256; i += 8) { + numberLimits.set(`uint${i}`, { + min: BigInt(0), + max: base - BigInt(1), + }); + numberLimits.set(`int${i}`, { + min: -base / BigInt(2), + max: base / BigInt(2) - BigInt(1), + }); + base *= BigInt(256); +} +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +numberLimits.set(`int`, numberLimits.get('int256')); +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +numberLimits.set(`uint`, numberLimits.get('uint256')); +//# sourceMappingURL=numbersLimits.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/numbersLimits.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/numbersLimits.js.map new file mode 100644 index 0000000..ca17fbf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/numbersLimits.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numbersLimits.js","sourceRoot":"","sources":["../../../../src/coders/base/numbersLimits.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;EAEE;AACF,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,GAAG,EAAwC,CAAC;AAE5E,IAAI,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc;AACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE;IACjC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE;QAC5B,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;QACd,GAAG,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC;KACrB,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE;QAC3B,GAAG,EAAE,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC;QACtB,GAAG,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;KACjC,CAAC,CAAC;IACH,IAAI,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;CACpB;AAED,oEAAoE;AACpE,YAAY,CAAC,GAAG,CAAC,KAAK,EAAE,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAE,CAAC,CAAC;AACrD,oEAAoE;AACpE,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,GAAG,CAAC,SAAS,CAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/string.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/string.js new file mode 100644 index 0000000..3acc7dd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/string.js @@ -0,0 +1,35 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { hexToUtf8, utf8ToBytes } from 'web3-utils'; +import { decodeBytes, encodeBytes } from './bytes.js'; +export function encodeString(_param, input) { + if (typeof input !== 'string') { + throw new AbiError('invalid input, should be string', { input }); + } + const bytes = utf8ToBytes(input); + return encodeBytes({ type: 'bytes', name: '' }, bytes); +} +export function decodeString(_param, bytes) { + const r = decodeBytes({ type: 'bytes', name: '' }, bytes); + return { + result: hexToUtf8(r.result), + encoded: r.encoded, + consumed: r.consumed, + }; +} +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/string.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/string.js.map new file mode 100644 index 0000000..e6590b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../../src/coders/base/string.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEtD,MAAM,UAAU,YAAY,CAAC,MAAoB,EAAE,KAAc;IAChE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,MAAM,IAAI,QAAQ,CAAC,iCAAiC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;KACjE;IACD,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IACjC,OAAO,WAAW,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,MAAoB,EAAE,KAAiB;IACnE,MAAM,CAAC,GAAG,WAAW,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC1D,OAAO;QACN,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;QAC3B,OAAO,EAAE,CAAC,CAAC,OAAO;QAClB,QAAQ,EAAE,CAAC,CAAC,QAAQ;KACpB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/tuple.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/tuple.js new file mode 100644 index 0000000..32ff0ef --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/tuple.js @@ -0,0 +1,118 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { uint8ArrayConcat } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { decodeParamFromAbiParameter, encodeParamFromAbiParameter } from './index.js'; +import { encodeDynamicParams } from './utils.js'; +import { isDynamic } from '../utils.js'; +import { decodeNumber } from './number.js'; +export function encodeTuple(param, input) { + var _a, _b, _c; + let dynamic = false; + if (!Array.isArray(input) && typeof input !== 'object') { + throw new AbiError('param must be either Array or Object', { + param, + input, + }); + } + const narrowedInput = input; + const encoded = []; + for (let i = 0; i < ((_b = (_a = param.components) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); i += 1) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const paramComponent = param.components[i]; + let result; + if (Array.isArray(narrowedInput)) { + if (i >= narrowedInput.length) { + throw new AbiError('input param length missmatch', { + param, + input, + }); + } + result = encodeParamFromAbiParameter(paramComponent, narrowedInput[i]); + } + else { + const paramInput = narrowedInput[(_c = paramComponent.name) !== null && _c !== void 0 ? _c : '']; + // eslint-disable-next-line no-null/no-null + if (paramInput === undefined || paramInput === null) { + throw new AbiError('missing input defined in abi', { + param, + input, + paramName: paramComponent.name, + }); + } + result = encodeParamFromAbiParameter(paramComponent, paramInput); + } + if (result.dynamic) { + dynamic = true; + } + encoded.push(result); + } + if (dynamic) { + return { + dynamic: true, + encoded: encodeDynamicParams(encoded), + }; + } + return { + dynamic: false, + encoded: uint8ArrayConcat(...encoded.map(e => e.encoded)), + }; +} +export function decodeTuple(param, bytes) { + const result = { + __length__: 0, + }; + // tracks how much static params consumed bytes + let consumed = 0; + if (!param.components) { + return { + result, + encoded: bytes, + consumed, + }; + } + // track how much dynamic params consumed bytes + let dynamicConsumed = 0; + for (const [index, childParam] of param.components.entries()) { + let decodedResult; + if (isDynamic(childParam)) { + // if dynamic, we will have offset encoded + const offsetResult = decodeNumber({ type: 'uint32', name: '' }, bytes.subarray(consumed)); + // offset counts from start of original byte sequence + decodedResult = decodeParamFromAbiParameter(childParam, bytes.subarray(Number(offsetResult.result))); + consumed += offsetResult.consumed; + dynamicConsumed += decodedResult.consumed; + } + else { + // static param, just decode + decodedResult = decodeParamFromAbiParameter(childParam, bytes.subarray(consumed)); + consumed += decodedResult.consumed; + } + result.__length__ += 1; + result[index] = decodedResult.result; + if (childParam.name && childParam.name !== '') { + result[childParam.name] = decodedResult.result; + } + } + return { + encoded: bytes.subarray(consumed + dynamicConsumed), + result, + consumed: consumed + dynamicConsumed, + }; +} +//# sourceMappingURL=tuple.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/tuple.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/tuple.js.map new file mode 100644 index 0000000..b5e4376 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/tuple.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.js","sourceRoot":"","sources":["../../../../src/coders/base/tuple.ts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AAE,EAAE;QAC7D,IAAI,aAA4B,CAAC;QACjC,IAAI,SAAS,CAAC,UAAU,CAAC,EAAE;YAC1B,0CAA0C;YAC1C,MAAM,YAAY,GAAG,YAAY,CAChC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE,EAC5B,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CACxB,CAAC;YACF,qDAAqD;YACrD,aAAa,GAAG,2BAA2B,CAC1C,UAAU,EACV,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAC3C,CAAC;YACF,QAAQ,IAAI,YAAY,CAAC,QAAQ,CAAC;YAClC,eAAe,IAAI,aAAa,CAAC,QAAQ,CAAC;SAC1C;aAAM;YACN,4BAA4B;YAC5B,aAAa,GAAG,2BAA2B,CAAC,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;YAClF,QAAQ,IAAI,aAAa,CAAC,QAAQ,CAAC;SACnC;QACD,MAAM,CAAC,UAAU,IAAI,CAAC,CAAC;QACvB,MAAM,CAAC,KAAK,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC;QACrC,IAAI,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,IAAI,KAAK,EAAE,EAAE;YAC9C,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC;SAC/C;KACD;IACD,OAAO;QACN,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,GAAG,eAAe,CAAC;QACnD,MAAM;QACN,QAAQ,EAAE,QAAQ,GAAG,eAAe;KACpC,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/utils.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/utils.js new file mode 100644 index 0000000..1ec49e4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/utils.js @@ -0,0 +1,46 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { uint8ArrayConcat } from 'web3-utils'; +import { WORD_SIZE } from '../utils.js'; +import { encodeNumber } from './number.js'; +export function encodeDynamicParams(encodedParams) { + let staticSize = 0; + let dynamicSize = 0; + const staticParams = []; + const dynamicParams = []; + // figure out static size + for (const encodedParam of encodedParams) { + if (encodedParam.dynamic) { + staticSize += WORD_SIZE; + } + else { + staticSize += encodedParam.encoded.length; + } + } + for (const encodedParam of encodedParams) { + if (encodedParam.dynamic) { + staticParams.push(encodeNumber({ type: 'uint256', name: '' }, staticSize + dynamicSize)); + dynamicParams.push(encodedParam); + dynamicSize += encodedParam.encoded.length; + } + else { + staticParams.push(encodedParam); + } + } + return uint8ArrayConcat(...staticParams.map(p => p.encoded), ...dynamicParams.map(p => p.encoded)); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/utils.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/utils.js.map new file mode 100644 index 0000000..c1e312d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/base/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/coders/base/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,UAAU,mBAAmB,CAAC,aAA2C;IAC9E,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,YAAY,GAAoB,EAAE,CAAC;IACzC,MAAM,aAAa,GAAoB,EAAE,CAAC;IAC1C,yBAAyB;IACzB,KAAK,MAAM,YAAY,IAAI,aAAa,EAAE;QACzC,IAAI,YAAY,CAAC,OAAO,EAAE;YACzB,UAAU,IAAI,SAAS,CAAC;SACxB;aAAM;YACN,UAAU,IAAI,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC;SAC1C;KACD;IAED,KAAK,MAAM,YAAY,IAAI,aAAa,EAAE;QACzC,IAAI,YAAY,CAAC,OAAO,EAAE;YACzB,YAAY,CAAC,IAAI,CAChB,YAAY,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,UAAU,GAAG,WAAW,CAAC,CACrE,CAAC;YACF,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YACjC,WAAW,IAAI,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC;SAC3C;aAAM;YACN,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;SAChC;KACD;IACD,OAAO,gBAAgB,CACtB,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EACnC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CACpC,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/decode.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/decode.js new file mode 100644 index 0000000..03a9727 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/decode.js @@ -0,0 +1,25 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { utils } from 'web3-validator'; +import { decodeTuple } from './base/tuple.js'; +import { toAbiParams } from './utils.js'; +export function decodeParameters(abis, bytes, _loose) { + const abiParams = toAbiParams(abis); + const bytesArray = utils.hexToUint8Array(bytes); + return decodeTuple({ type: 'tuple', name: '', components: abiParams }, bytesArray).result; +} +//# sourceMappingURL=decode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/decode.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/decode.js.map new file mode 100644 index 0000000..c9adfdd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/decode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode.js","sourceRoot":"","sources":["../../../src/coders/decode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,MAAM,UAAU,gBAAgB,CAC/B,IAAgB,EAChB,KAAgB,EAChB,MAAe;IAEf,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;IACpC,MAAM,UAAU,GAAG,KAAK,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAEhD,OAAO,WAAW,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC,MAAM,CAAC;AAC3F,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/encode.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/encode.js new file mode 100644 index 0000000..0c180f1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/encode.js @@ -0,0 +1,31 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { utils } from 'web3-validator'; +import { encodeTuple } from './base/index.js'; +import { toAbiParams } from './utils.js'; +export function encodeParameters(abi, params) { + if (abi.length !== params.length) { + throw new AbiError('Invalid number of values received for given ABI', { + expected: abi.length, + received: params.length, + }); + } + const abiParams = toAbiParams(abi); + return utils.uint8ArrayToHexString(encodeTuple({ type: 'tuple', name: '', components: abiParams }, params).encoded); +} +//# sourceMappingURL=encode.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/encode.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/encode.js.map new file mode 100644 index 0000000..a4fb687 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/encode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode.js","sourceRoot":"","sources":["../../../src/coders/encode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,MAAM,UAAU,gBAAgB,CAAC,GAA4B,EAAE,MAAiB;IAC/E,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE;QACjC,MAAM,IAAI,QAAQ,CAAC,iDAAiD,EAAE;YACrE,QAAQ,EAAE,GAAG,CAAC,MAAM;YACpB,QAAQ,EAAE,MAAM,CAAC,MAAM;SACvB,CAAC,CAAC;KACH;IACD,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,qBAAqB,CACjC,WAAW,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,OAAO,CAC/E,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/types.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/types.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/types.js.map new file mode 100644 index 0000000..4ade4ee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/coders/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/utils.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/utils.js new file mode 100644 index 0000000..da9f316 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/utils.js @@ -0,0 +1,105 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { parseAbiParameter } from 'abitype'; +import { AbiError } from 'web3-errors'; +import { isNullish } from 'web3-utils'; +import { isSimplifiedStructFormat, mapStructNameAndType, mapStructToCoderFormat, } from '../utils.js'; +export const WORD_SIZE = 32; +export function alloc(size = 0) { + var _a; + if (((_a = globalThis.Buffer) === null || _a === void 0 ? void 0 : _a.alloc) !== undefined) { + const buf = globalThis.Buffer.alloc(size); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + return new Uint8Array(size); +} +/** + * Where possible returns a Uint8Array of the requested size that references + * uninitialized memory. Only use if you are certain you will immediately + * overwrite every value in the returned `Uint8Array`. + */ +export function allocUnsafe(size = 0) { + var _a; + if (((_a = globalThis.Buffer) === null || _a === void 0 ? void 0 : _a.allocUnsafe) !== undefined) { + const buf = globalThis.Buffer.allocUnsafe(size); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + return new Uint8Array(size); +} +export function convertExternalAbiParameter(abiParam) { + var _a, _b; + return Object.assign(Object.assign({}, abiParam), { name: (_a = abiParam.name) !== null && _a !== void 0 ? _a : '', components: (_b = abiParam.components) === null || _b === void 0 ? void 0 : _b.map(c => convertExternalAbiParameter(c)) }); +} +export function isAbiParameter(param) { + return (!isNullish(param) && + typeof param === 'object' && + !isNullish(param.type) && + typeof param.type === 'string'); +} +export function toAbiParams(abi) { + return abi.map(input => { + var _a; + if (isAbiParameter(input)) { + return input; + } + if (typeof input === 'string') { + return convertExternalAbiParameter(parseAbiParameter(input.replace(/tuple/, ''))); + } + if (isSimplifiedStructFormat(input)) { + const structName = Object.keys(input)[0]; + const structInfo = mapStructNameAndType(structName); + structInfo.name = (_a = structInfo.name) !== null && _a !== void 0 ? _a : ''; + return Object.assign(Object.assign({}, structInfo), { components: mapStructToCoderFormat(input[structName]) }); + } + throw new AbiError('Invalid abi'); + }); +} +export function extractArrayType(param) { + const arrayParenthesisStart = param.type.lastIndexOf('['); + const arrayParamType = param.type.substring(0, arrayParenthesisStart); + const sizeString = param.type.substring(arrayParenthesisStart); + let size = -1; + if (sizeString !== '[]') { + size = Number(sizeString.slice(1, -1)); + // eslint-disable-next-line no-restricted-globals + if (isNaN(size)) { + throw new AbiError('Invalid fixed array size', { size: sizeString }); + } + } + return { + param: { type: arrayParamType, name: '', components: param.components }, + size, + }; +} +/** + * Param is dynamic if it's dynamic base type or if some of his children (components, array items) + * is of dynamic type + * @param param + */ +export function isDynamic(param) { + var _a, _b; + if (param.type === 'string' || param.type === 'bytes' || param.type.endsWith('[]')) + return true; + if (param.type === 'tuple') { + return (_b = (_a = param.components) === null || _a === void 0 ? void 0 : _a.some(isDynamic)) !== null && _b !== void 0 ? _b : false; + } + if (param.type.endsWith(']')) { + return isDynamic(extractArrayType(param).param); + } + return false; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/utils.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/utils.js.map new file mode 100644 index 0000000..3b116b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/coders/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/coders/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAwC,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EACN,wBAAwB,EACxB,oBAAoB,EACpB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AAErB,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAE5B,MAAM,UAAU,KAAK,CAAC,IAAI,GAAG,CAAC;;IAC7B,IAAI,CAAA,MAAA,UAAU,CAAC,MAAM,0CAAE,KAAK,MAAK,SAAS,EAAE;QAC3C,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;KAClE;IAED,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,IAAI,GAAG,CAAC;;IACnC,IAAI,CAAA,MAAA,UAAU,CAAC,MAAM,0CAAE,WAAW,MAAK,SAAS,EAAE;QACjD,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAChD,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;KAClE;IAED,OAAO,IAAI,UAAU,CAAC,I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EAAE;QAC7B,OAAO,SAAS,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;KAChD;IACD,OAAO,KAAK,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/decode_contract_error_data.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/decode_contract_error_data.js new file mode 100644 index 0000000..5feab5a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/decode_contract_error_data.js @@ -0,0 +1,43 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { encodeErrorSignature } from './api/errors_api.js'; +import { decodeParameters } from './api/parameters_api.js'; +import { jsonInterfaceMethodToString } from './utils.js'; +export const decodeContractErrorData = (errorsAbi, error) => { + if (error === null || error === void 0 ? void 0 : error.data) { + let errorName; + let errorSignature; + let errorArgs; + try { + const errorSha = error.data.slice(0, 10); + const errorAbi = errorsAbi.find(abi => encodeErrorSignature(abi).startsWith(errorSha)); + if (errorAbi === null || errorAbi === void 0 ? void 0 : errorAbi.inputs) { + errorName = errorAbi.name; + errorSignature = jsonInterfaceMethodToString(errorAbi); + // decode abi.inputs according to EIP-838 + errorArgs = decodeParameters([...errorAbi.inputs], error.data.substring(10)); + } + } + catch (err) { + console.error(err); + } + if (errorName) { + error.setDecodedProperties(errorName, errorSignature, errorArgs); + } + } +}; +//# sourceMappingURL=decode_contract_error_data.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/decode_contract_error_data.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/decode_contract_error_data.js.map new file mode 100644 index 0000000..b81b9cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/decode_contract_error_data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_contract_error_data.js","sourceRoot":"","sources":["../../src/decode_contract_error_data.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAKF,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAC;AAEzD,MAAM,CAAC,MAAM,uBAAuB,GAAG,CACtC,SAA6B,EAC7B,KAA2B,EAC1B,EAAE;IACH,IAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE;QAChB,IAAI,SAA6B,CAAC;QAClC,IAAI,cAAkC,CAAC;QACvC,IAAI,SAAiD,CAAC;QACtD,IAAI;YACH,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACzC,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC;YAEvF,IAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,EAAE;gBACrB,SAAS,GAAG,QAAQ,CAAC,IAAI,CAAC;gBAC1B,cAAc,GAAG,2BAA2B,CAAC,QAAQ,CAAC,CAAC;gBACvD,yCAAyC;gBACzC,SAAS,GAAG,gBAAgB,CAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;aAC7E;SACD;QAAC,OAAO,GAAG,EAAE;YACb,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SACnB;QACD,IAAI,SAAS,EAAE;YACd,KAAK,CAAC,oBAAoB,CAAC,SAAS,EAAE,cAAc,EAAE,SAAS,CAAC,CAAC;SACjE;KACD;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/eip_712.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/eip_712.js new file mode 100644 index 0000000..97ede97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/eip_712.js @@ -0,0 +1,132 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isNullish, keccak256 } from 'web3-utils'; +import { encodeParameters } from './coders/encode.js'; +const TYPE_REGEX = /^\w+/; +const ARRAY_REGEX = /^(.*)\[([0-9]*?)]$/; +/** + * Get the dependencies of a struct type. If a struct has the same dependency multiple times, it's only included once + * in the resulting array. + */ +const getDependencies = (typedData, type, dependencies = []) => { + const match = type.match(TYPE_REGEX); + const actualType = match[0]; + if (dependencies.includes(actualType)) { + return dependencies; + } + if (!typedData.types[actualType]) { + return dependencies; + } + return [ + actualType, + ...typedData.types[actualType].reduce((previous, _type) => [ + ...previous, + ...getDependencies(typedData, _type.type, previous).filter(dependency => !previous.includes(dependency)), + ], []), + ]; +}; +/** + * Encode a type to a string. All dependant types are alphabetically sorted. + * + * @param {TypedData} typedData + * @param {string} type + * @param {Options} [options] + * @return {string} + */ +const encodeType = (typedData, type) => { + const [primary, ...dependencies] = getDependencies(typedData, type); + // eslint-disable-next-line @typescript-eslint/require-array-sort-compare + const types = [primary, ...dependencies.sort()]; + return types + .map(dependency => + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${dependency}(${typedData.types[dependency].map(_type => `${_type.type} ${_type.name}`)})`) + .join(''); +}; +/** + * Get a type string as hash. + */ +const getTypeHash = (typedData, type) => keccak256(encodeType(typedData, type)); +/** + * Get encoded data as a hash. The data should be a key -> value object with all the required values. All dependant + * types are automatically encoded. + */ +const getStructHash = (typedData, type, data) => keccak256(encodeData(typedData, type, data)); +/** + * Get the EIP-191 encoded message to sign, from the typedData object. If `hash` is enabled, the message will be hashed + * with Keccak256. + */ +export const getMessage = (typedData, hash) => { + const EIP_191_PREFIX = '1901'; + const message = `0x${EIP_191_PREFIX}${getStructHash(typedData, 'EIP712Domain', typedData.domain).substring(2)}${getStructHash(typedData, typedData.primaryType, typedData.message).substring(2)}`; + if (hash) { + return keccak256(message); + } + return message; +}; +/** + * Encodes a single value to an ABI serialisable string, number or Buffer. Returns the data as tuple, which consists of + * an array of ABI compatible types, and an array of corresponding values. + */ +const encodeValue = (typedData, type, data) => { + const match = type.match(ARRAY_REGEX); + // Checks for array types + if (match) { + const arrayType = match[1]; + const length = Number(match[2]) || undefined; + if (!Array.isArray(data)) { + throw new Error('Cannot encode data: value is not of array type'); + } + if (length && data.length !== length) { + throw new Error(`Cannot encode data: expected length of ${length}, but got ${data.length}`); + } + const encodedData = data.map(item => encodeValue(typedData, arrayType, item)); + const types = encodedData.map(item => item[0]); + const values = encodedData.map(item => item[1]); + return ['bytes32', keccak256(encodeParameters(types, values))]; + } + if (typedData.types[type]) { + return ['bytes32', getStructHash(typedData, type, data)]; + } + // Strings and arbitrary byte arrays are hashed to bytes32 + if (type === 'string') { + return ['bytes32', keccak256(data)]; + } + if (type === 'bytes') { + return ['bytes32', keccak256(data)]; + } + return [type, data]; +}; +/** + * Encode the data to an ABI encoded Buffer. The data should be a key -> value object with all the required values. All + * dependant types are automatically encoded. + */ +const encodeData = (typedData, type, data) => { + const [types, values] = typedData.types[type].reduce(([_types, _values], field) => { + if (isNullish(data[field.name]) || isNullish(data[field.name])) { + throw new Error(`Cannot encode data: missing data for '${field.name}'`); + } + const value = data[field.name]; + const [_type, encodedValue] = encodeValue(typedData, field.type, value); + return [ + [..._types, _type], + [..._values, encodedValue], + ]; + }, [['bytes32'], [getTypeHash(typedData, type)]]); + return encodeParameters(types, values); +}; +//# sourceMappingURL=eip_712.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/eip_712.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/eip_712.js.map new file mode 100644 index 0000000..97f6bce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/eip_712.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eip_712.js","sourceRoot":"","sources":["../../src/eip_712.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAOF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,UAAU,GAAG,MAAM,CAAC;AAC1B,MAAM,WAAW,GAAG,oBAAoB,CAAC;AAEzC;;;GAGG;AACH,MAAM,eAAe,GAAG,CACvB,SAA0B,EAC1B,IAAY,EACZ,eAAyB,EAAE,EAChB,EAAE;IACb,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAE,CAAC;IACtC,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5B,IAAI,YAAY,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QACtC,OAAO,YAAY,CAAC;KACpB;IAED,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE;QACjC,OAAO,YAAY,CAAC;KACpB;IAED,OAAO;QACN,UAAU;QACV,GAAG,SAAS,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,MAAM,CACpC,CAAC,QAAQ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KAAK,EAAE,YAAY,CAAC,GAAG,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAExE,OAAO;YACN,CAAC,GAAG,MAAM,EAAE,KAAK,CAAC;YAClB,CAAC,GAAG,OAAO,EAAE,YAAY,CAAC;SAC1B,CAAC;IACH,CAAC,EACD,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,WAAW,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAC7C,CAAC;IAEF,OAAO,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AACxC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/index.js new file mode 100644 index 0000000..bea83fb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/index.js @@ -0,0 +1,28 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The web3.eth.abi functions let you encode and decode parameters to ABI (Application Binary Interface) for function calls to the EVM (Ethereum Virtual Machine). + */ +export * from './api/errors_api.js'; +export * from './api/events_api.js'; +export * from './api/functions_api.js'; +export * from './api/logs_api.js'; +export * from './api/parameters_api.js'; +export * from './utils.js'; +export * from './decode_contract_error_data.js'; +export { getMessage as getEncodedEip712Data } from './eip_712.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/index.js.map new file mode 100644 index 0000000..ebf3eeb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;GAEG;AACH,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,YAAY,CAAC;AAC3B,cAAc,iCAAiC,CAAC;AAChD,OAAO,EAAE,UAAU,IAAI,oBAAoB,EAAE,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/utils.js b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/utils.js new file mode 100644 index 0000000..d033787 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/utils.js @@ -0,0 +1,200 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { isNullish, leftPad, rightPad, toHex } from 'web3-utils'; +export const isAbiFragment = (item) => !isNullish(item) && + typeof item === 'object' && + !isNullish(item.type) && + ['function', 'event', 'constructor', 'error'].includes(item.type); +export const isAbiErrorFragment = (item) => !isNullish(item) && + typeof item === 'object' && + !isNullish(item.type) && + item.type === 'error'; +export const isAbiEventFragment = (item) => !isNullish(item) && + typeof item === 'object' && + !isNullish(item.type) && + item.type === 'event'; +export const isAbiFunctionFragment = (item) => !isNullish(item) && + typeof item === 'object' && + !isNullish(item.type) && + item.type === 'function'; +export const isAbiConstructorFragment = (item) => !isNullish(item) && + typeof item === 'object' && + !isNullish(item.type) && + item.type === 'constructor'; +/** + * Check if type is simplified struct format + */ +export const isSimplifiedStructFormat = (type) => typeof type === 'object' && + typeof type.components === 'undefined' && + typeof type.name === 'undefined'; +/** + * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used + */ +export const mapStructNameAndType = (structName) => structName.includes('[]') + ? { type: 'tuple[]', name: structName.slice(0, -2) } + : { type: 'tuple', name: structName }; +/** + * Maps the simplified format in to the expected format of the ABICoder + */ +export const mapStructToCoderFormat = (struct) => { + const components = []; + for (const key of Object.keys(struct)) { + const item = struct[key]; + if (typeof item === 'object') { + components.push(Object.assign(Object.assign({}, mapStructNameAndType(key)), { components: mapStructToCoderFormat(item) })); + } + else { + components.push({ + name: key, + type: struct[key], + }); + } + } + return components; +}; +/** + * Map types if simplified format is used + */ +export const mapTypes = (types) => { + const mappedTypes = []; + for (const type of types) { + let modifiedType = type; + // Clone object + if (typeof type === 'object') { + modifiedType = Object.assign({}, type); + } + // Remap `function` type params to bytes24 since Ethers does not + // recognize former type. Solidity docs say `Function` is a bytes24 + // encoding the contract address followed by the function selector hash. + if (typeof type === 'object' && type.type === 'function') { + modifiedType = Object.assign(Object.assign({}, type), { type: 'bytes24' }); + } + if (isSimplifiedStructFormat(modifiedType)) { + const structName = Object.keys(modifiedType)[0]; + mappedTypes.push(Object.assign(Object.assign({}, mapStructNameAndType(structName)), { components: mapStructToCoderFormat(modifiedType[structName]) })); + } + else { + mappedTypes.push(modifiedType); + } + } + return mappedTypes; +}; +/** + * returns true if input is a hexstring and is odd-lengthed + */ +export const isOddHexstring = (param) => typeof param === 'string' && /^(-)?0x[0-9a-f]*$/i.test(param) && param.length % 2 === 1; +/** + * format odd-length bytes to even-length + */ +export const formatOddHexstrings = (param) => isOddHexstring(param) ? `0x0${param.substring(2)}` : param; +/** + * Handle some formatting of params for backwards compatibility with Ethers V4 + */ +export const formatParam = (type, _param) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + var _a; + // clone if _param is an object + const param = typeof _param === 'object' && !Array.isArray(_param) ? Object.assign({}, _param) : _param; + const paramTypeBytes = /^bytes([0-9]*)$/; + const paramTypeBytesArray = /^bytes([0-9]*)\[\]$/; + const paramTypeNumber = /^(u?int)([0-9]*)$/; + const paramTypeNumberArray = /^(u?int)([0-9]*)\[\]$/; + // Format BN to string + if (param instanceof BigInt) { + return param.toString(10); + } + if (paramTypeBytesArray.exec(type) || paramTypeNumberArray.exec(type)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const paramClone = [...param]; + return paramClone.map(p => formatParam(type.replace('[]', ''), p)); + } + // Format correct width for u?int[0-9]* + let match = paramTypeNumber.exec(type); + if (match) { + const size = parseInt((_a = match[2]) !== null && _a !== void 0 ? _a : '256', 10); + if (size / 8 < param.length) { + // pad to correct bit width + return leftPad(param, size); + } + } + // Format correct length for bytes[0-9]+ + match = paramTypeBytes.exec(type); + if (match) { + const hexParam = param instanceof Uint8Array ? toHex(param) : param; + // format to correct length + const size = parseInt(match[1], 10); + if (size) { + let maxSize = size * 2; + if (param.startsWith('0x')) { + maxSize += 2; + } + // pad to correct length + const paddedParam = hexParam.length < maxSize + ? rightPad(param, size * 2) + : hexParam; + return formatOddHexstrings(paddedParam); + } + return formatOddHexstrings(hexParam); + } + return param; +}; +/** + * used to flatten json abi inputs/outputs into an array of type-representing-strings + */ +export const flattenTypes = (includeTuple, puts) => { + const types = []; + puts.forEach(param => { + if (typeof param.components === 'object') { + if (!param.type.startsWith('tuple')) { + throw new AbiError(`Invalid value given "${param.type}". Error: components found but type is not tuple.`); + } + const arrayBracket = param.type.indexOf('['); + const suffix = arrayBracket >= 0 ? param.type.substring(arrayBracket) : ''; + const result = flattenTypes(includeTuple, param.components); + if (Array.isArray(result) && includeTuple) { + types.push(`tuple(${result.join(',')})${suffix}`); + } + else if (!includeTuple) { + types.push(`(${result.join(',')})${suffix}`); + } + else { + types.push(`(${result.join()})`); + } + } + else { + types.push(param.type); + } + }); + return types; +}; +/** + * Should be used to create full function/event name from json abi + * returns a string + */ +export const jsonInterfaceMethodToString = (json) => { + var _a, _b, _c, _d; + if (isAbiErrorFragment(json) || isAbiEventFragment(json) || isAbiFunctionFragment(json)) { + if ((_a = json.name) === null || _a === void 0 ? void 0 : _a.includes('(')) { + return json.name; + } + return `${(_b = json.name) !== null && _b !== void 0 ? _b : ''}(${flattenTypes(false, (_c = json.inputs) !== null && _c !== void 0 ? _c : []).join(',')})`; + } + // Constructor fragment + return `(${flattenTypes(false, (_d = json.inputs) !== null && _d !== void 0 ? _d : []).join(',')})`; +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/utils.js.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/utils.js.map new file mode 100644 index 0000000..ee2165f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAYjE,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,IAAa,EAAuB,EAAE,CACnE,CAAC,SAAS,CAAC,IAAI,CAAC;IAChB,OAAO,IAAI,KAAK,QAAQ;IACxB,CAAC,SAAS,CAAE,IAAyB,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AAE;gBAC1C,KAAK,CAAC,IAAI,CAAC,SAAS,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;aAClD;iBAAM,IAAI,CAAC,YAAY,EAAE;gBACzB,KAAK,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC;aAC7C;iBAAM;gBACN,KAAK,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;aACjC;SACD;aAAM;YACN,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SACvB;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,IAAiB,EAAU,EAAE;;IACxE,IAAI,kBAAkB,CAAC,IAAI,CAAC,IAAI,kBAAkB,CAAC,IAAI,CAAC,IAAI,qBAAqB,CAAC,IAAI,CAAC,EAAE;QACxF,IAAI,MAAA,IAAI,CAAC,IAAI,0CAAE,QAAQ,CAAC,GAAG,CAAC,EAAE;YAC7B,OAAO,IAAI,CAAC,IAAI,CAAC;SACjB;QAED,OAAO,GAAG,MAAA,IAAI,CAAC,IAAI,mCAAI,EAAE,IAAI,YAAY,CAAC,KAAK,EAAE,MAAA,IAAI,CAAC,MAAM,mCAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;KACjF;IAED,uBAAuB;IACvB,OAAO,IAAI,YAAY,CAAC,KAAK,EAAE,MAAA,IAAI,CAAC,MAAM,mCAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;AAChE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/errors_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/errors_api.d.ts new file mode 100644 index 0000000..16064ff --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/errors_api.d.ts @@ -0,0 +1,6 @@ +import { AbiErrorFragment } from 'web3-types'; +/** + * Encodes the error name to its ABI signature, which are the sha3 hash of the error name including input types. + */ +export declare const encodeErrorSignature: (functionName: string | AbiErrorFragment) => string; +//# sourceMappingURL=errors_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/errors_api.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/errors_api.d.ts.map new file mode 100644 index 0000000..ec71aae --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/errors_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors_api.d.ts","sourceRoot":"","sources":["../../../src/api/errors_api.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAG9C;;GAEG;AACH,eAAO,MAAM,oBAAoB,iBAAkB,MAAM,GAAG,gBAAgB,KAAG,MAc9E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/events_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/events_api.d.ts new file mode 100644 index 0000000..a0b199f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/events_api.d.ts @@ -0,0 +1,52 @@ +import { AbiEventFragment } from 'web3-types'; +/** + * Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types. + * @param functionName - The event name to encode, or the {@link AbiEventFragment} object of the event. If string, it has to be in the form of `eventName(param1Type,param2Type,...)`. eg: myEvent(uint256,bytes32). + * @returns - The ABI signature of the event. + * + * @example + * ```ts + * const event = web3.eth.abi.encodeEventSignature({ + * name: "myEvent", + * type: "event", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "bytes32", + * name: "myBytes", + * }, + * ], + * }); + * console.log(event); + * > 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 + * + * const event = web3.eth.abi.encodeEventSignature({ + * inputs: [ + * { + * indexed: true, + * name: "from", + * type: "address", + * }, + * { + * indexed: true, + * name: "to", + * type: "address", + * }, + * { + * indexed: false, + * name: "value", + * type: "uint256", + * }, + * ], + * name: "Transfer", + * type: "event", + * }); + * console.log(event); + * > 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + * ``` + */ +export declare const encodeEventSignature: (functionName: string | AbiEventFragment) => string; +//# sourceMappingURL=events_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/events_api.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/events_api.d.ts.map new file mode 100644 index 0000000..8802105 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/events_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"events_api.d.ts","sourceRoot":"","sources":["../../../src/api/events_api.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAG9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,eAAO,MAAM,oBAAoB,iBAAkB,MAAM,GAAG,gBAAgB,KAAG,MAc9E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/functions_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/functions_api.d.ts new file mode 100644 index 0000000..050fa8c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/functions_api.d.ts @@ -0,0 +1,91 @@ +import { AbiFunctionFragment } from 'web3-types'; +/** + * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. + * @param functionName - The function name to encode or the `JSON interface` object of the function. + * If the passed parameter is a string, it has to be in the form of `functionName(param1Type,param2Type,...)`. eg: myFunction(uint256,uint32[],bytes10,bytes) + * @returns - The ABI signature of the function. + * @example + * ```ts + * const signature = web3.eth.abi.encodeFunctionSignature({ + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }); + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)') + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('safeTransferFrom(address,address,uint256,bytes)'); + * console.log(signature); + * > 0xb88d4fde + * ``` + */ +export declare const encodeFunctionSignature: (functionName: string | AbiFunctionFragment) => string; +/** + * Encodes a function call using its `JSON interface` object and given parameters. + * @param jsonInterface - The `JSON interface` object of the function. + * @param params - The parameters to encode + * @returns - The ABI encoded function call, which, means the function signature and the parameters passed. + * @example + * ```ts + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }, + * ["2345675643", "Hello!%"] + * ); + * console.log(sig); + * > 0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * + * + * + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * inputs: [ + * { + * name: "account", + * type: "address", + * }, + * ], + * name: "balanceOf", + * outputs: [ + * { + * name: "", + * type: "uint256", + * }, + * ], + * stateMutability: "view", + * type: "function", + * }, + * ["0x1234567890123456789012345678901234567890"] + * ); + * + * console.log(sig); + * > 0x70a082310000000000000000000000001234567890123456789012345678901234567890 + * ``` + */ +export declare const encodeFunctionCall: (jsonInterface: AbiFunctionFragment, params: unknown[]) => string; +//# sourceMappingURL=functions_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/functions_api.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/functions_api.d.ts.map new file mode 100644 index 0000000..a0487a4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/functions_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"functions_api.d.ts","sourceRoot":"","sources":["../../../src/api/functions_api.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAKjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,uBAAuB,iBAAkB,MAAM,GAAG,mBAAmB,KAAG,MAcpF,CAAC;AAGF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,eAAO,MAAM,kBAAkB,kBACf,mBAAmB,UAC1B,OAAO,EAAE,KACf,MASF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/logs_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/logs_api.d.ts new file mode 100644 index 0000000..6108fb1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/logs_api.d.ts @@ -0,0 +1,46 @@ +import { HexString, AbiParameter, DecodedParams } from 'web3-types'; +/** + * Decodes ABI-encoded log data and indexed topic data. + * @param inputs - A {@link AbiParameter} input array. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param data - The ABI byte code in the `data` field of a log. + * @param topics - An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0] + * @returns - The result object containing the decoded parameters. + * + * @example + * ```ts + * let res = web3.eth.abi.decodeLog( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * indexed: true, + * }, + * { + * type: "uint8", + * name: "mySmallNumber", + * indexed: true, + * }, + * ], + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000", + * [ + * "0x000000000000000000000000000000000000000000000000000000000000f310", + * "0x0000000000000000000000000000000000000000000000000000000000000010", + * ] + * ); + * > { + * '0': 'Hello%!', + * '1': 62224n, + * '2': 16n, + * __length__: 3, + * myString: 'Hello%!', + * myNumber: 62224n, + * mySmallNumber: 16n + * } + * ``` + */ +export declare const decodeLog: (inputs: Array, data: HexString, topics: string | string[]) => ReturnType_1; +//# sourceMappingURL=logs_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/logs_api.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/logs_api.d.ts.map new file mode 100644 index 0000000..c415054 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/logs_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logs_api.d.ts","sourceRoot":"","sources":["../../../src/api/logs_api.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAQpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,SAAS,+CACb,MAAM,YAAY,CAAC,QACrB,SAAS,UACP,MAAM,GAAG,MAAM,EAAE,iBAsDzB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/parameters_api.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/parameters_api.d.ts new file mode 100644 index 0000000..008ed9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/parameters_api.d.ts @@ -0,0 +1,255 @@ +import { AbiInput, HexString } from 'web3-types'; +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - An array of {@link AbiInput}. See [Solidity's documentation](https://solidity.readthedocs.io/en/v0.5.3/abi-spec.html#json) for more details. + * @param params - The actual parameters to encode. + * @returns - The ABI encoded parameters + * @example + * ```ts + * const res = web3.eth.abi.encodeParameters( + * ["uint256", "string"], + * ["2345675643", "Hello!%"] + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * ``` + */ +export declare const encodeParameters: (abi: ReadonlyArray, params: unknown[]) => string; +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param param - The actual parameter to encode. + * @returns - The ABI encoded parameter + * @example + * ```ts + * const res = web3.eth.abi.encodeParameter("uint256", "2345675643"); + * console.log(res); + * 0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("uint", "2345675643"); + * + * console.log(res); + * >0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("bytes32", "0xdf3234"); + * + * console.log(res); + * >0xdf32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes", "0xdf3234"); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes32[]", ["0xdf3234", "0xfdfd"]); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * { + * propertyOne: 42, + * propertyTwo: 56, + * childStruct: { + * propertyOne: 45, + * propertyTwo: 78, + * }, + * } + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e + * ``` + */ +export declare const encodeParameter: (abi: AbiInput, param: unknown) => string; +/** + * Should be used to decode list of params + */ +export declare const decodeParametersWith: (abis: AbiInput[], bytes: HexString, loose: boolean) => { + [key: string]: unknown; + __length__: number; +}; +/** + * Should be used to decode list of params + */ +/** + * Decodes ABI encoded parameters to its JavaScript types. + * @param abi - An array of {@link AbiInput}. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The result object containing the decoded parameters. + * @example + * ```ts + * let res = web3.eth.abi.decodeParameters( + * ["string", "uint256"], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { '0': 'Hello!%!', '1': 234n, __length__: 2 } + * + * let res = web3.eth.abi.decodeParameters( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * }, + * ], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { + * '0': 'Hello!%!', + * '1': 234n, + * __length__: 2, + * myString: 'Hello!%!', + * myNumber: 234n + * } + * + * const res = web3.eth.abi.decodeParameters( + * [ + * "uint8[]", + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * ], + * "0x00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000018" + * ); + * console.log(res); + * > + * '0': [ 42n, 24n ], + * '1': { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * }, + * __length__: 2, + * ParentStruct: { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * } + *} + * ``` + */ +export declare const decodeParameters: (abi: AbiInput[], bytes: HexString) => { + [key: string]: unknown; + __length__: number; +}; +/** + * Should be used to decode bytes to plain param + */ +/** + * Decodes an ABI encoded parameter to its JavaScript type. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The decoded parameter + * @example + * ```ts + * const res = web3.eth.abi.decodeParameter( + * "uint256", + * "0x0000000000000000000000000000000000000000000000000000000000000010" + * ); + * console.log(res); + * > 16n + * + * const res = web3.eth.abi.decodeParameter( + * "string", + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * + * console.log(res); + * > Hello!%! + * + * const res = web3.eth.abi.decodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * "0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e" + * ); + * + * console.log(res); + * { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + *} + * ``` + */ +export declare const decodeParameter: (abi: AbiInput, bytes: HexString) => unknown; +//# sourceMappingURL=parameters_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/parameters_api.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/parameters_api.d.ts.map new file mode 100644 index 0000000..c0f067e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/api/parameters_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parameters_api.d.ts","sourceRoot":"","sources":["../../../src/api/parameters_api.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIjD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,gBAAgB,QAAS,cAAc,QAAQ,CAAC,UAAU,OAAO,EAAE,KAAG,MAC7C,CAAC;AAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AACH,eAAO,MAAM,eAAe,QAAS,QAAQ,SAAS,OAAO,KAAG,MAC/B,CAAC;AAClC;;GAEG;AACH,eAAO,MAAM,oBAAoB,SAC1B,QAAQ,EAAE,SACT,SAAS,SACT,OAAO;;gBAC0B,MAAM;CAiB9C,CAAC;AAEF;;GAEG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoGG;AACH,eAAO,MAAM,gBAAgB,QACvB,QAAQ,EAAE,SACR,SAAS;;gBACwB,MAAM;CAA6C,CAAC;AAE7F;;GAEG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,eAAO,MAAM,eAAe,QAAS,QAAQ,SAAS,SAAS,KAAG,OAC9B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/address.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/address.d.ts new file mode 100644 index 0000000..9c2b1b4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/address.d.ts @@ -0,0 +1,5 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeAddress(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeAddress(_param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=address.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/address.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/address.d.ts.map new file mode 100644 index 0000000..1bb60b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/address.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAM3D,wBAAgB,aAAa,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CA4BhF;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,CAkB5F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/array.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/array.d.ts new file mode 100644 index 0000000..1e70d4b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/array.d.ts @@ -0,0 +1,5 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeArray(param: AbiParameter, values: unknown): EncoderResult; +export declare function decodeArray(param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=array.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/array.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/array.d.ts.map new file mode 100644 index 0000000..602b8ff --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/array.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAI1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAK3D,wBAAgB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,GAAG,aAAa,CAuC/E;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAAC,OAAO,EAAE,CAAC,CAoD5F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bool.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bool.d.ts new file mode 100644 index 0000000..74fdec3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bool.d.ts @@ -0,0 +1,5 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeBoolean(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeBool(_param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=bool.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bool.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bool.d.ts.map new file mode 100644 index 0000000..0dbbfb1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bool.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bool.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/bool.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAI3D,wBAAgB,aAAa,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CAehF;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAAC,OAAO,CAAC,CAa1F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bytes.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bytes.d.ts new file mode 100644 index 0000000..3826d68 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bytes.d.ts @@ -0,0 +1,5 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeBytes(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeBytes(param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=bytes.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bytes.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bytes.d.ts.map new file mode 100644 index 0000000..657bd59 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/bytes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/bytes.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAS,MAAM,YAAY,CAAC;AAGjD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAM3D,wBAAgB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CAkD9E;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,CA2BzF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/index.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/index.d.ts new file mode 100644 index 0000000..8c34059 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/index.d.ts @@ -0,0 +1,12 @@ +import { AbiParameter } from 'web3-types'; +import { EncoderResult, DecoderResult } from '../types.js'; +export { encodeAddress, decodeAddress } from './address.js'; +export { encodeBoolean, decodeBool } from './bool.js'; +export { encodeBytes, decodeBytes } from './bytes.js'; +export { encodeNumber, decodeNumber } from './number.js'; +export { encodeString, decodeString } from './string.js'; +export { encodeTuple, decodeTuple } from './tuple.js'; +export { encodeArray, decodeArray } from './array.js'; +export declare function encodeParamFromAbiParameter(param: AbiParameter, value: unknown): EncoderResult; +export declare function decodeParamFromAbiParameter(param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/index.d.ts.map new file mode 100644 index 0000000..9d0a327 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/index.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAW3D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEtD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CAuB9F;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAuBjG"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/number.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/number.d.ts new file mode 100644 index 0000000..e8007f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/number.d.ts @@ -0,0 +1,5 @@ +import type { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeNumber(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeNumber(param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=number.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/number.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/number.d.ts.map new file mode 100644 index 0000000..f087245 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/number.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG/C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAyB3D,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CAmC/E;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,CAgC1F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/numbersLimits.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/numbersLimits.d.ts new file mode 100644 index 0000000..1e99683 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/numbersLimits.d.ts @@ -0,0 +1,5 @@ +export declare const numberLimits: Map; +//# sourceMappingURL=numbersLimits.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/numbersLimits.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/numbersLimits.d.ts.map new file mode 100644 index 0000000..557b461 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/numbersLimits.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"numbersLimits.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/numbersLimits.ts"],"names":[],"mappings":"AAoBA,eAAO,MAAM,YAAY;SAA0B,MAAM;SAAO,MAAM;EAAK,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/string.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/string.d.ts new file mode 100644 index 0000000..faa9c86 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/string.d.ts @@ -0,0 +1,5 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeString(_param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeString(_param: AbiParameter, bytes: Uint8Array): DecoderResult; +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/string.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/string.d.ts.map new file mode 100644 index 0000000..0529e11 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/string.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG3D,wBAAgB,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CAMhF;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,CAO3F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/tuple.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/tuple.d.ts new file mode 100644 index 0000000..c37f1c3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/tuple.d.ts @@ -0,0 +1,8 @@ +import { AbiParameter } from 'web3-types'; +import { DecoderResult, EncoderResult } from '../types.js'; +export declare function encodeTuple(param: AbiParameter, input: unknown): EncoderResult; +export declare function decodeTuple(param: AbiParameter, bytes: Uint8Array): DecoderResult<{ + [key: string]: unknown; + __length__: number; +}>; +//# sourceMappingURL=tuple.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/tuple.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/tuple.d.ts.map new file mode 100644 index 0000000..01d53f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/tuple.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/tuple.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAO3D,wBAAgB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,aAAa,CAkD9E;AAED,wBAAgB,WAAW,CAC1B,KAAK,EAAE,YAAY,EACnB,KAAK,EAAE,UAAU,GACf,aAAa,CAAC;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAgD/D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/utils.d.ts new file mode 100644 index 0000000..928e462 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/utils.d.ts @@ -0,0 +1,3 @@ +import { EncoderResult } from '../types.js'; +export declare function encodeDynamicParams(encodedParams: ReadonlyArray): Uint8Array; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/utils.d.ts.map new file mode 100644 index 0000000..ea59938 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/base/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../src/coders/base/utils.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAI5C,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,aAAa,CAAC,aAAa,CAAC,GAAG,UAAU,CA6B3F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/decode.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/decode.d.ts new file mode 100644 index 0000000..e2b4a33 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/decode.d.ts @@ -0,0 +1,6 @@ +import { AbiInput, HexString } from 'web3-types'; +export declare function decodeParameters(abis: AbiInput[], bytes: HexString, _loose: boolean): { + [key: string]: unknown; + __length__: number; +}; +//# sourceMappingURL=decode.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/decode.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/decode.d.ts.map new file mode 100644 index 0000000..29d7c9f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/decode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode.d.ts","sourceRoot":"","sources":["../../../src/coders/decode.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAKjD,wBAAgB,gBAAgB,CAC/B,IAAI,EAAE,QAAQ,EAAE,EAChB,KAAK,EAAE,SAAS,EAChB,MAAM,EAAE,OAAO,GACb;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAKhD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/encode.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/encode.d.ts new file mode 100644 index 0000000..21c3430 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/encode.d.ts @@ -0,0 +1,3 @@ +import { AbiInput } from 'web3-types'; +export declare function encodeParameters(abi: ReadonlyArray, params: unknown[]): string; +//# sourceMappingURL=encode.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/encode.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/encode.d.ts.map new file mode 100644 index 0000000..231e5c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/encode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../../../src/coders/encode.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAKtC,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAWxF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/types.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/types.d.ts new file mode 100644 index 0000000..4226ae0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/types.d.ts @@ -0,0 +1,17 @@ +export declare type EncoderResult = { + dynamic: boolean; + encoded: Uint8Array; +}; +export declare type DecoderResult = { + result: T; + encoded: Uint8Array; + consumed: number; +}; +export declare type NumberType = { + signed: boolean; + byteLength: number; +}; +export declare type BytesType = { + size?: number; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/types.d.ts.map new file mode 100644 index 0000000..5b2696d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/coders/types.ts"],"names":[],"mappings":"AAiBA,oBAAY,aAAa,GAAG;IAC3B,OAAO,EAAE,OAAO,CAAC;IAEjB,OAAO,EAAE,UAAU,CAAC;CACpB,CAAC;AACF,oBAAY,aAAa,CAAC,CAAC,GAAG,OAAO,IAAI;IACxC,MAAM,EAAE,CAAC,CAAC;IAGV,OAAO,EAAE,UAAU,CAAC;IAGpB,QAAQ,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,oBAAY,UAAU,GAAG;IACxB,MAAM,EAAE,OAAO,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACnB,CAAC;AACF,oBAAY,SAAS,GAAG;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/utils.d.ts new file mode 100644 index 0000000..a4b9691 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/utils.d.ts @@ -0,0 +1,24 @@ +import { AbiParameter as ExternalAbiParameter } from 'abitype'; +import { AbiInput, AbiParameter } from 'web3-types'; +export declare const WORD_SIZE = 32; +export declare function alloc(size?: number): Uint8Array; +/** + * Where possible returns a Uint8Array of the requested size that references + * uninitialized memory. Only use if you are certain you will immediately + * overwrite every value in the returned `Uint8Array`. + */ +export declare function allocUnsafe(size?: number): Uint8Array; +export declare function convertExternalAbiParameter(abiParam: ExternalAbiParameter): AbiParameter; +export declare function isAbiParameter(param: unknown): param is AbiParameter; +export declare function toAbiParams(abi: ReadonlyArray): ReadonlyArray; +export declare function extractArrayType(param: AbiParameter): { + size: number; + param: AbiParameter; +}; +/** + * Param is dynamic if it's dynamic base type or if some of his children (components, array items) + * is of dynamic type + * @param param + */ +export declare function isDynamic(param: AbiParameter): boolean; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/utils.d.ts.map new file mode 100644 index 0000000..8b17e0b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/coders/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/coders/utils.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,IAAI,oBAAoB,EAAqB,MAAM,SAAS,CAAC;AAElF,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAa,MAAM,YAAY,CAAC;AAQ/D,eAAO,MAAM,SAAS,KAAK,CAAC;AAE5B,wBAAgB,KAAK,CAAC,IAAI,SAAI,GAAG,UAAU,CAO1C;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,IAAI,SAAI,GAAG,UAAU,CAOhD;AAED,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,oBAAoB,GAAG,YAAY,CAQxF;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAOpE;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,aAAa,CAAC,QAAQ,CAAC,GAAG,aAAa,CAAC,YAAY,CAAC,CAsBrF;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,YAAY,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,YAAY,CAAA;CAAE,CAgB3F;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAStD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/decode_contract_error_data.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/decode_contract_error_data.d.ts new file mode 100644 index 0000000..1b58db5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/decode_contract_error_data.d.ts @@ -0,0 +1,4 @@ +import { Eip838ExecutionError } from 'web3-errors'; +import { AbiErrorFragment } from 'web3-types'; +export declare const decodeContractErrorData: (errorsAbi: AbiErrorFragment[], error: Eip838ExecutionError) => void; +//# sourceMappingURL=decode_contract_error_data.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/decode_contract_error_data.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/decode_contract_error_data.d.ts.map new file mode 100644 index 0000000..3304ad6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/decode_contract_error_data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_contract_error_data.d.ts","sourceRoot":"","sources":["../../src/decode_contract_error_data.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAM9C,eAAO,MAAM,uBAAuB,cACxB,gBAAgB,EAAE,SACtB,oBAAoB,SAuB3B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/eip_712.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/eip_712.d.ts new file mode 100644 index 0000000..acd2a44 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/eip_712.d.ts @@ -0,0 +1,10 @@ +/** + * @note This code was taken from: https://github.com/Mrtenz/eip-712/tree/master + */ +import { Eip712TypedData } from 'web3-types'; +/** + * Get the EIP-191 encoded message to sign, from the typedData object. If `hash` is enabled, the message will be hashed + * with Keccak256. + */ +export declare const getMessage: (typedData: Eip712TypedData, hash?: boolean) => string; +//# sourceMappingURL=eip_712.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/eip_712.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/eip_712.d.ts.map new file mode 100644 index 0000000..62bb04b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/eip_712.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eip_712.d.ts","sourceRoot":"","sources":["../../src/eip_712.ts"],"names":[],"mappings":"AAiBA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAiF7C;;;GAGG;AACH,eAAO,MAAM,UAAU,cAAe,eAAe,SAAS,OAAO,KAAG,MAevE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/index.d.ts new file mode 100644 index 0000000..701daa6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/index.d.ts @@ -0,0 +1,12 @@ +/** + * The web3.eth.abi functions let you encode and decode parameters to ABI (Application Binary Interface) for function calls to the EVM (Ethereum Virtual Machine). + */ +export * from './api/errors_api.js'; +export * from './api/events_api.js'; +export * from './api/functions_api.js'; +export * from './api/logs_api.js'; +export * from './api/parameters_api.js'; +export * from './utils.js'; +export * from './decode_contract_error_data.js'; +export { getMessage as getEncodedEip712Data } from './eip_712.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/index.d.ts.map new file mode 100644 index 0000000..dc64270 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;GAEG;AACH,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,YAAY,CAAC;AAC3B,cAAc,iCAAiC,CAAC;AAChD,OAAO,EAAE,UAAU,IAAI,oBAAoB,EAAE,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/utils.d.ts new file mode 100644 index 0000000..071bb3a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/utils.d.ts @@ -0,0 +1,44 @@ +import { AbiInput, AbiCoderStruct, AbiFragment, AbiParameter, AbiStruct, AbiEventFragment, AbiFunctionFragment, AbiConstructorFragment } from 'web3-types'; +export declare const isAbiFragment: (item: unknown) => item is AbiFragment; +export declare const isAbiErrorFragment: (item: unknown) => item is AbiEventFragment; +export declare const isAbiEventFragment: (item: unknown) => item is AbiEventFragment; +export declare const isAbiFunctionFragment: (item: unknown) => item is AbiFunctionFragment; +export declare const isAbiConstructorFragment: (item: unknown) => item is AbiConstructorFragment; +/** + * Check if type is simplified struct format + */ +export declare const isSimplifiedStructFormat: (type: string | Partial | Partial) => type is Omit; +/** + * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used + */ +export declare const mapStructNameAndType: (structName: string) => AbiStruct; +/** + * Maps the simplified format in to the expected format of the ABICoder + */ +export declare const mapStructToCoderFormat: (struct: AbiStruct) => Array; +/** + * Map types if simplified format is used + */ +export declare const mapTypes: (types: AbiInput[]) => Array>; +/** + * returns true if input is a hexstring and is odd-lengthed + */ +export declare const isOddHexstring: (param: unknown) => boolean; +/** + * format odd-length bytes to even-length + */ +export declare const formatOddHexstrings: (param: string) => string; +/** + * Handle some formatting of params for backwards compatibility with Ethers V4 + */ +export declare const formatParam: (type: string, _param: unknown) => unknown; +/** + * used to flatten json abi inputs/outputs into an array of type-representing-strings + */ +export declare const flattenTypes: (includeTuple: boolean, puts: ReadonlyArray) => string[]; +/** + * Should be used to create full function/event name from json abi + * returns a string + */ +export declare const jsonInterfaceMethodToString: (json: AbiFragment) => string; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/lib/types/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/utils.d.ts.map new file mode 100644 index 0000000..c25ea3f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/lib/types/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAmBA,OAAO,EACN,QAAQ,EACR,cAAc,EACd,WAAW,EACX,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,mBAAmB,EACnB,sBAAsB,EACtB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,aAAa,SAAU,OAAO,wBAI6C,CAAC;AAEzF,eAAO,MAAM,kBAAkB,SAAU,OAAO,6BAIJ,CAAC;AAE7C,eAAO,MAAM,kBAAkB,SAAU,OAAO,6BAIJ,CAAC;AAE7C,eAAO,MAAM,qBAAqB,SAAU,OAAO,gCAIJ,CAAC;AAEhD,eAAO,MAAM,wBAAwB,SAAU,OAAO,mCAIJ,CAAC;AAEnD;;GAEG;AACH,eAAO,MAAM,wBAAwB,SAC9B,MAAM,GAAG,QAAQ,YAAY,CAAC,GAAG,QAAQ,QAAQ,CAAC,sDAID,CAAC;AAEzD;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAAgB,MAAM,KAAG,SAGnB,CAAC;AAExC;;GAEG;AACH,eAAO,MAAM,sBAAsB,WAAY,SAAS,KAAG,MAAM,cAAc,CAmB9E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ,UACb,QAAQ,EAAE,KACf,MAAM,MAAM,GAAG,YAAY,GAAG,OAAO,MAAM,EAAE,OAAO,CAAC,CAiCvD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,UAAW,OAAO,KAAG,OACwC,CAAC;AAEzF;;GAEG;AACH,eAAO,MAAM,mBAAmB,UAAW,MAAM,KAAG,MACO,CAAC;AAE5D;;GAEG;AACH,eAAO,MAAM,WAAW,SAAU,MAAM,UAAU,OAAO,KAAG,OAuD3D,CAAC;AAEF;;GAEG;AAEH,eAAO,MAAM,YAAY,iBACV,OAAO,QACf,cAAc,YAAY,CAAC,KAC/B,MAAM,EA2BR,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,2BAA2B,SAAU,WAAW,KAAG,MAW/D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-abi/package.json b/test/merkletreejs/node_modules/web3-eth-abi/package.json new file mode 100644 index 0000000..063f956 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/package.json @@ -0,0 +1,69 @@ +{ + "name": "web3-eth-abi", + "version": "4.1.4", + "description": "Web3 module encode and decode EVM in/output.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ethereum/web3.js/tree/4.x/packages/web3-eth-abi", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "dependencies": { + "abitype": "0.7.1", + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "web3-validator": "^2.0.3" + }, + "devDependencies": { + "@humeris/espresso-shot": "^4.0.0", + "@types/jest": "^28.1.6", + "@types/jest-when": "^3.5.2", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "jest-when": "^3.5.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "gitHead": "41824d669db6aae87d7917122a28d5f057f5aa74" +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/api/errors_api.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/api/errors_api.ts new file mode 100644 index 0000000..7a6a2bc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/api/errors_api.ts @@ -0,0 +1,40 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { sha3Raw } from 'web3-utils'; +import { AbiError } from 'web3-errors'; +import { AbiErrorFragment } from 'web3-types'; +import { jsonInterfaceMethodToString, isAbiErrorFragment } from '../utils.js'; + +/** + * Encodes the error name to its ABI signature, which are the sha3 hash of the error name including input types. + */ +export const encodeErrorSignature = (functionName: string | AbiErrorFragment): string => { + if (typeof functionName !== 'string' && !isAbiErrorFragment(functionName)) { + throw new AbiError('Invalid parameter value in encodeErrorSignature'); + } + + let name: string; + + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = jsonInterfaceMethodToString(functionName); + } else { + name = functionName; + } + + return sha3Raw(name); +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/api/events_api.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/api/events_api.ts new file mode 100644 index 0000000..92b38b4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/api/events_api.ts @@ -0,0 +1,86 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { sha3Raw } from 'web3-utils'; +import { AbiError } from 'web3-errors'; +import { AbiEventFragment } from 'web3-types'; +import { jsonInterfaceMethodToString, isAbiEventFragment } from '../utils.js'; + +/** + * Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types. + * @param functionName - The event name to encode, or the {@link AbiEventFragment} object of the event. If string, it has to be in the form of `eventName(param1Type,param2Type,...)`. eg: myEvent(uint256,bytes32). + * @returns - The ABI signature of the event. + * + * @example + * ```ts + * const event = web3.eth.abi.encodeEventSignature({ + * name: "myEvent", + * type: "event", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "bytes32", + * name: "myBytes", + * }, + * ], + * }); + * console.log(event); + * > 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 + * + * const event = web3.eth.abi.encodeEventSignature({ + * inputs: [ + * { + * indexed: true, + * name: "from", + * type: "address", + * }, + * { + * indexed: true, + * name: "to", + * type: "address", + * }, + * { + * indexed: false, + * name: "value", + * type: "uint256", + * }, + * ], + * name: "Transfer", + * type: "event", + * }); + * console.log(event); + * > 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + * ``` + */ +export const encodeEventSignature = (functionName: string | AbiEventFragment): string => { + if (typeof functionName !== 'string' && !isAbiEventFragment(functionName)) { + throw new AbiError('Invalid parameter value in encodeEventSignature'); + } + + let name: string; + + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = jsonInterfaceMethodToString(functionName); + } else { + name = functionName; + } + + return sha3Raw(name); +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/api/functions_api.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/api/functions_api.ts new file mode 100644 index 0000000..0c78c4f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/api/functions_api.ts @@ -0,0 +1,141 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiError } from 'web3-errors'; +import { sha3Raw } from 'web3-utils'; +import { AbiFunctionFragment } from 'web3-types'; +import { isAbiFunctionFragment, jsonInterfaceMethodToString } from '../utils.js'; +import { encodeParameters } from './parameters_api.js'; + +// todo Add link to JSON interface documentation +/** + * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. + * @param functionName - The function name to encode or the `JSON interface` object of the function. + * If the passed parameter is a string, it has to be in the form of `functionName(param1Type,param2Type,...)`. eg: myFunction(uint256,uint32[],bytes10,bytes) + * @returns - The ABI signature of the function. + * @example + * ```ts + * const signature = web3.eth.abi.encodeFunctionSignature({ + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }); + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)') + * console.log(signature); + * > 0x24ee0097 + * + * const signature = web3.eth.abi.encodeFunctionSignature('safeTransferFrom(address,address,uint256,bytes)'); + * console.log(signature); + * > 0xb88d4fde + * ``` + */ +export const encodeFunctionSignature = (functionName: string | AbiFunctionFragment): string => { + if (typeof functionName !== 'string' && !isAbiFunctionFragment(functionName)) { + throw new AbiError('Invalid parameter value in encodeFunctionSignature'); + } + + let name: string; + + if (functionName && (typeof functionName === 'function' || typeof functionName === 'object')) { + name = jsonInterfaceMethodToString(functionName); + } else { + name = functionName; + } + + return sha3Raw(name).slice(0, 10); +}; + +// todo Add link to JSON interface documentation +/** + * Encodes a function call using its `JSON interface` object and given parameters. + * @param jsonInterface - The `JSON interface` object of the function. + * @param params - The parameters to encode + * @returns - The ABI encoded function call, which, means the function signature and the parameters passed. + * @example + * ```ts + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * name: "myMethod", + * type: "function", + * inputs: [ + * { + * type: "uint256", + * name: "myNumber", + * }, + * { + * type: "string", + * name: "myString", + * }, + * ], + * }, + * ["2345675643", "Hello!%"] + * ); + * console.log(sig); + * > 0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * + * + * + * const sig = web3.eth.abi.encodeFunctionCall( + * { + * inputs: [ + * { + * name: "account", + * type: "address", + * }, + * ], + * name: "balanceOf", + * outputs: [ + * { + * name: "", + * type: "uint256", + * }, + * ], + * stateMutability: "view", + * type: "function", + * }, + * ["0x1234567890123456789012345678901234567890"] + * ); + * + * console.log(sig); + * > 0x70a082310000000000000000000000001234567890123456789012345678901234567890 + * ``` + */ +export const encodeFunctionCall = ( + jsonInterface: AbiFunctionFragment, + params: unknown[], +): string => { + if (!isAbiFunctionFragment(jsonInterface)) { + throw new AbiError('Invalid parameter value in encodeFunctionCall'); + } + + return `${encodeFunctionSignature(jsonInterface)}${encodeParameters( + jsonInterface.inputs ?? [], + params ?? [], + ).replace('0x', '')}`; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/api/logs_api.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/api/logs_api.ts new file mode 100644 index 0000000..677a4c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/api/logs_api.ts @@ -0,0 +1,126 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { HexString, AbiParameter, DecodedParams } from 'web3-types'; +import { decodeParameter, decodeParametersWith } from './parameters_api.js'; + +const STATIC_TYPES = ['bool', 'string', 'int', 'uint', 'address', 'fixed', 'ufixed']; + +const _decodeParameter = (inputType: string, clonedTopic: string) => + inputType === 'string' ? clonedTopic : decodeParameter(inputType, clonedTopic); + +/** + * Decodes ABI-encoded log data and indexed topic data. + * @param inputs - A {@link AbiParameter} input array. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param data - The ABI byte code in the `data` field of a log. + * @param topics - An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0] + * @returns - The result object containing the decoded parameters. + * + * @example + * ```ts + * let res = web3.eth.abi.decodeLog( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * indexed: true, + * }, + * { + * type: "uint8", + * name: "mySmallNumber", + * indexed: true, + * }, + * ], + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000", + * [ + * "0x000000000000000000000000000000000000000000000000000000000000f310", + * "0x0000000000000000000000000000000000000000000000000000000000000010", + * ] + * ); + * > { + * '0': 'Hello%!', + * '1': 62224n, + * '2': 16n, + * __length__: 3, + * myString: 'Hello%!', + * myNumber: 62224n, + * mySmallNumber: 16n + * } + * ``` + */ +export const decodeLog = ( + inputs: Array, + data: HexString, + topics: string | string[], +) => { + const clonedTopics = Array.isArray(topics) ? topics : [topics]; + + const indexedInputs: Record = {}; + const nonIndexedInputs: Record = {}; + + for (const [i, input] of inputs.entries()) { + if (input.indexed) { + indexedInputs[i] = input; + } else { + nonIndexedInputs[i] = input; + } + } + + const decodedNonIndexedInputs: DecodedParams = data + ? decodeParametersWith(Object.values(nonIndexedInputs), data, true) + : { __length__: 0 }; + + // If topics are more than indexed inputs, that means first topic is the event signature + const offset = clonedTopics.length - Object.keys(indexedInputs).length; + + const decodedIndexedInputs = Object.values(indexedInputs).map((input, index) => + STATIC_TYPES.some(s => input.type.startsWith(s)) + ? _decodeParameter(input.type, clonedTopics[index + offset]) + : clonedTopics[index + offset], + ); + + const returnValues: DecodedParams = { __length__: 0 }; + + let indexedCounter = 0; + let nonIndexedCounter = 0; + + for (const [i, res] of inputs.entries()) { + returnValues[i] = res.type === 'string' ? '' : undefined; + + if (indexedInputs[i]) { + returnValues[i] = decodedIndexedInputs[indexedCounter]; + indexedCounter += 1; + } + + if (nonIndexedInputs[i]) { + returnValues[i] = decodedNonIndexedInputs[String(nonIndexedCounter)]; + nonIndexedCounter += 1; + } + + if (res.name) { + returnValues[res.name] = returnValues[i]; + } + + returnValues.__length__ += 1; + } + + return returnValues as ReturnType; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/api/parameters_api.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/api/parameters_api.ts new file mode 100644 index 0000000..98624b2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/api/parameters_api.ts @@ -0,0 +1,298 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiInput, HexString } from 'web3-types'; +import { decodeParameters as decodeParametersInternal } from '../coders/decode.js'; +import { encodeParameters as encodeParametersInternal } from '../coders/encode.js'; + +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - An array of {@link AbiInput}. See [Solidity's documentation](https://solidity.readthedocs.io/en/v0.5.3/abi-spec.html#json) for more details. + * @param params - The actual parameters to encode. + * @returns - The ABI encoded parameters + * @example + * ```ts + * const res = web3.eth.abi.encodeParameters( + * ["uint256", "string"], + * ["2345675643", "Hello!%"] + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000 + * ``` + */ +export const encodeParameters = (abi: ReadonlyArray, params: unknown[]): string => + encodeParametersInternal(abi, params); + +/** + * Encodes a parameter based on its type to its ABI representation. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param param - The actual parameter to encode. + * @returns - The ABI encoded parameter + * @example + * ```ts + * const res = web3.eth.abi.encodeParameter("uint256", "2345675643"); + * console.log(res); + * 0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("uint", "2345675643"); + * + * console.log(res); + * >0x000000000000000000000000000000000000000000000000000000008bd02b7b + * + * const res = web3.eth.abi.encodeParameter("bytes32", "0xdf3234"); + * + * console.log(res); + * >0xdf32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes", "0xdf3234"); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter("bytes32[]", ["0xdf3234", "0xfdfd"]); + * + * console.log(res); + * > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000 + * + * const res = web3.eth.abi.encodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * { + * propertyOne: 42, + * propertyTwo: 56, + * childStruct: { + * propertyOne: 45, + * propertyTwo: 78, + * }, + * } + * ); + * + * console.log(res); + * > 0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e + * ``` + */ +export const encodeParameter = (abi: AbiInput, param: unknown): string => + encodeParameters([abi], [param]); +/** + * Should be used to decode list of params + */ +export const decodeParametersWith = ( + abis: AbiInput[], + bytes: HexString, + loose: boolean, +): { [key: string]: unknown; __length__: number } => { + try { + if (abis.length > 0 && (!bytes || bytes === '0x' || bytes === '0X')) { + throw new AbiError( + "Returned values aren't valid, did it run Out of Gas? " + + 'You might also see this error if you are not using the ' + + 'correct ABI for the contract you are retrieving data from, ' + + 'requesting data from a block number that does not exist, ' + + 'or querying a node which is not fully synced.', + ); + } + return decodeParametersInternal(abis, `0x${bytes.replace(/0x/i, '')}`, loose); + } catch (err) { + throw new AbiError(`Parameter decoding error: ${(err as Error).message}`, { + internalErr: err, + }); + } +}; + +/** + * Should be used to decode list of params + */ +/** + * Decodes ABI encoded parameters to its JavaScript types. + * @param abi - An array of {@link AbiInput}. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The result object containing the decoded parameters. + * @example + * ```ts + * let res = web3.eth.abi.decodeParameters( + * ["string", "uint256"], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { '0': 'Hello!%!', '1': 234n, __length__: 2 } + * + * let res = web3.eth.abi.decodeParameters( + * [ + * { + * type: "string", + * name: "myString", + * }, + * { + * type: "uint256", + * name: "myNumber", + * }, + * ], + * "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * console.log(res); + * > { + * '0': 'Hello!%!', + * '1': 234n, + * __length__: 2, + * myString: 'Hello!%!', + * myNumber: 234n + * } + * + * const res = web3.eth.abi.decodeParameters( + * [ + * "uint8[]", + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * ], + * "0x00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000018" + * ); + * console.log(res); + * > + * '0': [ 42n, 24n ], + * '1': { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * }, + * __length__: 2, + * ParentStruct: { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + * } + *} + * ``` + */ +export const decodeParameters = ( + abi: AbiInput[], + bytes: HexString, +): { [key: string]: unknown; __length__: number } => decodeParametersWith(abi, bytes, false); + +/** + * Should be used to decode bytes to plain param + */ +/** + * Decodes an ABI encoded parameter to its JavaScript type. + * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. + * @param bytes - The ABI byte code to decode + * @returns - The decoded parameter + * @example + * ```ts + * const res = web3.eth.abi.decodeParameter( + * "uint256", + * "0x0000000000000000000000000000000000000000000000000000000000000010" + * ); + * console.log(res); + * > 16n + * + * const res = web3.eth.abi.decodeParameter( + * "string", + * "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000" + * ); + * + * console.log(res); + * > Hello!%! + * + * const res = web3.eth.abi.decodeParameter( + * { + * ParentStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * childStruct: { + * propertyOne: "uint256", + * propertyTwo: "uint256", + * }, + * }, + * }, + * "0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e" + * ); + * + * console.log(res); + * { + * '0': 42n, + * '1': 56n, + * '2': { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * }, + * __length__: 3, + * propertyOne: 42n, + * propertyTwo: 56n, + * childStruct: { + * '0': 45n, + * '1': 78n, + * __length__: 2, + * propertyOne: 45n, + * propertyTwo: 78n + * } + *} + * ``` + */ +export const decodeParameter = (abi: AbiInput, bytes: HexString): unknown => + decodeParameters([abi], bytes)['0']; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/address.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/address.ts new file mode 100644 index 0000000..ae63744 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/address.ts @@ -0,0 +1,75 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiParameter } from 'web3-types'; +import { toChecksumAddress } from 'web3-utils'; +import { isAddress, utils } from 'web3-validator'; +import { DecoderResult, EncoderResult } from '../types.js'; +import { alloc, WORD_SIZE } from '../utils.js'; + +const ADDRESS_BYTES_COUNT = 20; +const ADDRESS_OFFSET = WORD_SIZE - ADDRESS_BYTES_COUNT; + +export function encodeAddress(param: AbiParameter, input: unknown): EncoderResult { + if (typeof input !== 'string') { + throw new AbiError('address type expects string as input type', { + value: input, + name: param.name, + type: param.type, + }); + } + let address = input.toLowerCase(); + if (!address.startsWith('0x')) { + address = `0x${address}`; + } + if (!isAddress(address)) { + throw new AbiError('provided input is not valid address', { + value: input, + name: param.name, + type: param.type, + }); + } + // for better performance, we could convert hex to destination bytes directly (encoded var) + const addressBytes = utils.hexToUint8Array(address); + // expand address to WORD_SIZE + const encoded = alloc(WORD_SIZE); + encoded.set(addressBytes, ADDRESS_OFFSET); + return { + dynamic: false, + encoded, + }; +} + +export function decodeAddress(_param: AbiParameter, bytes: Uint8Array): DecoderResult { + const addressBytes = bytes.subarray(ADDRESS_OFFSET, WORD_SIZE); + if (addressBytes.length !== ADDRESS_BYTES_COUNT) { + throw new AbiError('Invalid decoding input, not enough bytes to decode address', { bytes }); + } + const result = utils.uint8ArrayToHexString(addressBytes); + + // should we check is decoded value is valid address? + // if(!isAddress(result)) { + // throw new AbiError("encoded data is not valid address", { + // address: result, + // }); + // } + return { + result: toChecksumAddress(result), + encoded: bytes.subarray(WORD_SIZE), + consumed: WORD_SIZE, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/array.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/array.ts new file mode 100644 index 0000000..0c23ac4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/array.ts @@ -0,0 +1,120 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiParameter } from 'web3-types'; +import { uint8ArrayConcat } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { decodeParamFromAbiParameter, encodeNumber, encodeParamFromAbiParameter } from './index.js'; +import { DecoderResult, EncoderResult } from '../types.js'; +import { extractArrayType, isDynamic, WORD_SIZE } from '../utils.js'; +import { decodeNumber } from './number.js'; +import { encodeDynamicParams } from './utils.js'; + +export function encodeArray(param: AbiParameter, values: unknown): EncoderResult { + if (!Array.isArray(values)) { + throw new AbiError('Expected value to be array', { abi: param, values }); + } + const { size, param: arrayItemParam } = extractArrayType(param); + const encodedParams = values.map(v => encodeParamFromAbiParameter(arrayItemParam, v)); + const dynamic = size === -1; + const dynamicItems = encodedParams.length > 0 && encodedParams[0].dynamic; + if (!dynamic && values.length !== size) { + throw new AbiError("Given arguments count doesn't match array length", { + arrayLength: size, + argumentsLength: values.length, + }); + } + if (dynamic || dynamicItems) { + const encodingResult = encodeDynamicParams(encodedParams); + if (dynamic) { + const encodedLength = encodeNumber( + { type: 'uint256', name: '' }, + encodedParams.length, + ).encoded; + return { + dynamic: true, + encoded: + encodedParams.length > 0 + ? uint8ArrayConcat(encodedLength, encodingResult) + : encodedLength, + }; + } + return { + dynamic: true, + encoded: encodingResult, + }; + } + + return { + dynamic: false, + encoded: uint8ArrayConcat(...encodedParams.map(p => p.encoded)), + }; +} + +export function decodeArray(param: AbiParameter, bytes: Uint8Array): DecoderResult { + // eslint-disable-next-line prefer-const + let { size, param: arrayItemParam } = extractArrayType(param); + const dynamic = size === -1; + + let consumed = 0; + const result: unknown[] = []; + let remaining = bytes; + // dynamic array, we need to decode length + if (dynamic) { + const lengthResult = decodeNumber({ type: 'uint32', name: '' }, bytes); + size = Number(lengthResult.result); + consumed = lengthResult.consumed; + remaining = lengthResult.encoded; + } + const hasDynamicChild = isDynamic(arrayItemParam); + if (hasDynamicChild) { + // known length but dynamic child, each child is actually head element with encoded offset + for (let i = 0; i < size; i += 1) { + const offsetResult = decodeNumber( + { type: 'uint32', name: '' }, + remaining.subarray(i * WORD_SIZE), + ); + consumed += offsetResult.consumed; + const decodedChildResult = decodeParamFromAbiParameter( + arrayItemParam, + remaining.subarray(Number(offsetResult.result)), + ); + consumed += decodedChildResult.consumed; + result.push(decodedChildResult.result); + } + return { + result, + encoded: remaining.subarray(consumed), + consumed, + }; + } + + for (let i = 0; i < size; i += 1) { + // decode static params + const decodedChildResult = decodeParamFromAbiParameter( + arrayItemParam, + bytes.subarray(consumed), + ); + consumed += decodedChildResult.consumed; + result.push(decodedChildResult.result); + } + return { + result, + encoded: bytes.subarray(consumed), + consumed, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/bool.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/bool.ts new file mode 100644 index 0000000..af0b95d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/bool.ts @@ -0,0 +1,54 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError, InvalidBooleanError } from 'web3-errors'; +import { AbiParameter } from 'web3-types'; +import { toBool } from 'web3-utils'; +import { DecoderResult, EncoderResult } from '../types.js'; +import { WORD_SIZE } from '../utils.js'; +import { decodeNumber, encodeNumber } from './number.js'; + +export function encodeBoolean(param: AbiParameter, input: unknown): EncoderResult { + let value; + try { + value = toBool(input); + } catch (e) { + if (e instanceof InvalidBooleanError) { + throw new AbiError('provided input is not valid boolean value', { + type: param.type, + value: input, + name: param.name, + }); + } + } + + return encodeNumber({ type: 'uint8', name: '' }, Number(value)); +} + +export function decodeBool(_param: AbiParameter, bytes: Uint8Array): DecoderResult { + const numberResult = decodeNumber({ type: 'uint8', name: '' }, bytes); + if (numberResult.result > 1 || numberResult.result < 0) { + throw new AbiError('Invalid boolean value encoded', { + boolBytes: bytes.subarray(0, WORD_SIZE), + numberResult, + }); + } + return { + result: numberResult.result === BigInt(1), + encoded: numberResult.encoded, + consumed: WORD_SIZE, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/bytes.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/bytes.ts new file mode 100644 index 0000000..714abbf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/bytes.ts @@ -0,0 +1,106 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiParameter, Bytes } from 'web3-types'; +import { bytesToHex, bytesToUint8Array } from 'web3-utils'; +import { isBytes, ValidInputTypes } from 'web3-validator'; +import { DecoderResult, EncoderResult } from '../types.js'; +import { alloc, WORD_SIZE } from '../utils.js'; +import { decodeNumber, encodeNumber } from './number.js'; + +const MAX_STATIC_BYTES_COUNT = 32; + +export function encodeBytes(param: AbiParameter, input: unknown): EncoderResult { + // hack for odd length hex strings + if (typeof input === 'string' && input.length % 2 !== 0) { + // eslint-disable-next-line no-param-reassign + input += '0'; + } + if (!isBytes(input as ValidInputTypes)) { + throw new AbiError('provided input is not valid bytes value', { + type: param.type, + value: input, + name: param.name, + }); + } + const bytes = bytesToUint8Array(input as Bytes); + const [, size] = param.type.split('bytes'); + // fixed size + if (size) { + if (Number(size) > MAX_STATIC_BYTES_COUNT || Number(size) < 1) { + throw new AbiError( + 'invalid bytes type. Static byte type can have between 1 and 32 bytes', + { + type: param.type, + }, + ); + } + if (Number(size) < bytes.length) { + throw new AbiError('provided input size is different than type size', { + type: param.type, + value: input, + name: param.name, + }); + } + const encoded = alloc(WORD_SIZE); + encoded.set(bytes); + return { + dynamic: false, + encoded, + }; + } + + const partsLength = Math.ceil(bytes.length / WORD_SIZE); + // one word for length of data + WORD for each part of actual data + const encoded = alloc(WORD_SIZE + partsLength * WORD_SIZE); + + encoded.set(encodeNumber({ type: 'uint32', name: '' }, bytes.length).encoded); + encoded.set(bytes, WORD_SIZE); + return { + dynamic: true, + encoded, + }; +} + +export function decodeBytes(param: AbiParameter, bytes: Uint8Array): DecoderResult { + const [, sizeString] = param.type.split('bytes'); + let size = Number(sizeString); + let remainingBytes = bytes; + let partsCount = 1; + let consumed = 0; + if (!size) { + // dynamic bytes + const result = decodeNumber({ type: 'uint32', name: '' }, remainingBytes); + size = Number(result.result); + consumed += result.consumed; + remainingBytes = result.encoded; + partsCount = Math.ceil(size / WORD_SIZE); + } + if (size > bytes.length) { + throw new AbiError('there is not enough data to decode', { + type: param.type, + encoded: bytes, + size, + }); + } + + return { + result: bytesToHex(remainingBytes.subarray(0, size)), + encoded: remainingBytes.subarray(partsCount * WORD_SIZE), + consumed: consumed + partsCount * WORD_SIZE, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/index.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/index.ts new file mode 100644 index 0000000..007d31e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/index.ts @@ -0,0 +1,88 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiParameter } from 'web3-types'; +import { EncoderResult, DecoderResult } from '../types.js'; +import { decodeAddress, encodeAddress } from './address.js'; +import { decodeBool, encodeBoolean } from './bool.js'; +import { decodeBytes, encodeBytes } from './bytes.js'; +import { decodeNumber, encodeNumber } from './number.js'; +import { decodeString, encodeString } from './string.js'; +// eslint-disable-next-line import/no-cycle +import { decodeTuple, encodeTuple } from './tuple.js'; +// eslint-disable-next-line import/no-cycle +import { decodeArray, encodeArray } from './array.js'; + +export { encodeAddress, decodeAddress } from './address.js'; +export { encodeBoolean, decodeBool } from './bool.js'; +export { encodeBytes, decodeBytes } from './bytes.js'; +export { encodeNumber, decodeNumber } from './number.js'; +export { encodeString, decodeString } from './string.js'; +// eslint-disable-next-line import/no-cycle +export { encodeTuple, decodeTuple } from './tuple.js'; +// eslint-disable-next-line import/no-cycle +export { encodeArray, decodeArray } from './array.js'; + +export function encodeParamFromAbiParameter(param: AbiParameter, value: unknown): EncoderResult { + if (param.type === 'string') { + return encodeString(param, value); + } + if (param.type === 'bool') { + return encodeBoolean(param, value); + } + if (param.type === 'address') { + return encodeAddress(param, value); + } + if (param.type === 'tuple') { + return encodeTuple(param, value); + } + if (param.type.endsWith(']')) { + return encodeArray(param, value); + } + if (param.type.startsWith('bytes')) { + return encodeBytes(param, value); + } + if (param.type.startsWith('uint') || param.type.startsWith('int')) { + return encodeNumber(param, value); + } + throw new Error('Unsupported'); +} + +export function decodeParamFromAbiParameter(param: AbiParameter, bytes: Uint8Array): DecoderResult { + if (param.type === 'string') { + return decodeString(param, bytes); + } + if (param.type === 'bool') { + return decodeBool(param, bytes); + } + if (param.type === 'address') { + return decodeAddress(param, bytes); + } + if (param.type === 'tuple') { + return decodeTuple(param, bytes); + } + if (param.type.endsWith(']')) { + return decodeArray(param, bytes); + } + if (param.type.startsWith('bytes')) { + return decodeBytes(param, bytes); + } + if (param.type.startsWith('uint') || param.type.startsWith('int')) { + return decodeNumber(param, bytes); + } + throw new Error('Unsupported'); +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/number.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/number.ts new file mode 100644 index 0000000..a86ee4f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/number.ts @@ -0,0 +1,116 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiError } from 'web3-errors'; +import type { AbiParameter } from 'web3-types'; +import { padLeft, toBigInt } from 'web3-utils'; +import { utils } from 'web3-validator'; +import { DecoderResult, EncoderResult } from '../types.js'; +import { WORD_SIZE } from '../utils.js'; +import { numberLimits } from './numbersLimits.js'; + +// eslint-disable-next-line no-bitwise +const mask = BigInt(1) << BigInt(256); + +function bigIntToUint8Array(value: bigint, byteLength = WORD_SIZE): Uint8Array { + let hexValue; + if (value < 0) { + hexValue = (mask + value).toString(16); + } else { + hexValue = value.toString(16); + } + hexValue = padLeft(hexValue, byteLength * 2); + return utils.hexToUint8Array(hexValue); +} + +function uint8ArrayToBigInt(value: Uint8Array, max: bigint): bigint { + const hexValue = utils.uint8ArrayToHexString(value); + const result = BigInt(hexValue); + if (result <= max) return result; + return result - mask; +} + +export function encodeNumber(param: AbiParameter, input: unknown): EncoderResult { + let value; + try { + value = toBigInt(input); + } catch (e) { + throw new AbiError('provided input is not number value', { + type: param.type, + value: input, + name: param.name, + }); + } + const limit = numberLimits.get(param.type); + if (!limit) { + throw new AbiError('provided abi contains invalid number datatype', { type: param.type }); + } + if (value < limit.min) { + throw new AbiError('provided input is less then minimum for given type', { + type: param.type, + value: input, + name: param.name, + minimum: limit.min.toString(), + }); + } + if (value > limit.max) { + throw new AbiError('provided input is greater then maximum for given type', { + type: param.type, + value: input, + name: param.name, + maximum: limit.max.toString(), + }); + } + return { + dynamic: false, + encoded: bigIntToUint8Array(value), + }; +} + +export function decodeNumber(param: AbiParameter, bytes: Uint8Array): DecoderResult { + if (bytes.length < WORD_SIZE) { + throw new AbiError('Not enough bytes left to decode', { param, bytesLeft: bytes.length }); + } + const boolBytes = bytes.subarray(0, WORD_SIZE); + const limit = numberLimits.get(param.type); + if (!limit) { + throw new AbiError('provided abi contains invalid number datatype', { type: param.type }); + } + const numberResult = uint8ArrayToBigInt(boolBytes, limit.max); + + if (numberResult < limit.min) { + throw new AbiError('decoded value is less then minimum for given type', { + type: param.type, + value: numberResult, + name: param.name, + minimum: limit.min.toString(), + }); + } + if (numberResult > limit.max) { + throw new AbiError('decoded value is greater then maximum for given type', { + type: param.type, + value: numberResult, + name: param.name, + maximum: limit.max.toString(), + }); + } + return { + result: numberResult, + encoded: bytes.subarray(WORD_SIZE), + consumed: WORD_SIZE, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/numbersLimits.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/numbersLimits.ts new file mode 100644 index 0000000..29f1146 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/numbersLimits.ts @@ -0,0 +1,39 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/* + * this variable contains the precalculated limits for all the numbers for uint and int types +*/ +export const numberLimits = new Map(); + +let base = BigInt(256); // 2 ^ 8 = 256 +for (let i = 8; i <= 256; i += 8) { + numberLimits.set(`uint${i}`, { + min: BigInt(0), + max: base - BigInt(1), + }); + numberLimits.set(`int${i}`, { + min: -base / BigInt(2), + max: base / BigInt(2) - BigInt(1), + }); + base *= BigInt(256); +} + +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +numberLimits.set(`int`, numberLimits.get('int256')!); +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +numberLimits.set(`uint`, numberLimits.get('uint256')!); diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/string.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/string.ts new file mode 100644 index 0000000..6ad69e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/string.ts @@ -0,0 +1,38 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiParameter } from 'web3-types'; +import { hexToUtf8, utf8ToBytes } from 'web3-utils'; +import { DecoderResult, EncoderResult } from '../types.js'; +import { decodeBytes, encodeBytes } from './bytes.js'; + +export function encodeString(_param: AbiParameter, input: unknown): EncoderResult { + if (typeof input !== 'string') { + throw new AbiError('invalid input, should be string', { input }); + } + const bytes = utf8ToBytes(input); + return encodeBytes({ type: 'bytes', name: '' }, bytes); +} + +export function decodeString(_param: AbiParameter, bytes: Uint8Array): DecoderResult { + const r = decodeBytes({ type: 'bytes', name: '' }, bytes); + return { + result: hexToUtf8(r.result), + encoded: r.encoded, + consumed: r.consumed, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/tuple.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/tuple.ts new file mode 100644 index 0000000..89ccff4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/tuple.ts @@ -0,0 +1,130 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiParameter } from 'web3-types'; +import { uint8ArrayConcat } from 'web3-utils'; +import { DecoderResult, EncoderResult } from '../types.js'; +// eslint-disable-next-line import/no-cycle +import { decodeParamFromAbiParameter, encodeParamFromAbiParameter } from './index.js'; +import { encodeDynamicParams } from './utils.js'; +import { isDynamic } from '../utils.js'; +import { decodeNumber } from './number.js'; + +export function encodeTuple(param: AbiParameter, input: unknown): EncoderResult { + let dynamic = false; + if (!Array.isArray(input) && typeof input !== 'object') { + throw new AbiError('param must be either Array or Object', { + param, + input, + }); + } + const narrowedInput = input as Array | Record; + const encoded: Array = []; + for (let i = 0; i < (param.components?.length ?? 0); i += 1) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const paramComponent = param.components![i]; + let result: EncoderResult; + if (Array.isArray(narrowedInput)) { + if (i >= narrowedInput.length) { + throw new AbiError('input param length missmatch', { + param, + input, + }); + } + result = encodeParamFromAbiParameter(paramComponent, narrowedInput[i]); + } else { + const paramInput = narrowedInput[paramComponent.name ?? '']; + // eslint-disable-next-line no-null/no-null + if (paramInput === undefined || paramInput === null) { + throw new AbiError('missing input defined in abi', { + param, + input, + paramName: paramComponent.name, + }); + } + result = encodeParamFromAbiParameter(paramComponent, paramInput); + } + if (result.dynamic) { + dynamic = true; + } + encoded.push(result); + } + + if (dynamic) { + return { + dynamic: true, + encoded: encodeDynamicParams(encoded), + }; + } + return { + dynamic: false, + encoded: uint8ArrayConcat(...encoded.map(e => e.encoded)), + }; +} + +export function decodeTuple( + param: AbiParameter, + bytes: Uint8Array, +): DecoderResult<{ [key: string]: unknown; __length__: number }> { + const result: { [key: string]: unknown; __length__: number } = { + __length__: 0, + }; + + // tracks how much static params consumed bytes + let consumed = 0; + + if (!param.components) { + return { + result, + encoded: bytes, + consumed, + }; + } + // track how much dynamic params consumed bytes + let dynamicConsumed = 0; + for (const [index, childParam] of param.components.entries()) { + let decodedResult: DecoderResult; + if (isDynamic(childParam)) { + // if dynamic, we will have offset encoded + const offsetResult = decodeNumber( + { type: 'uint32', name: '' }, + bytes.subarray(consumed), + ); + // offset counts from start of original byte sequence + decodedResult = decodeParamFromAbiParameter( + childParam, + bytes.subarray(Number(offsetResult.result)), + ); + consumed += offsetResult.consumed; + dynamicConsumed += decodedResult.consumed; + } else { + // static param, just decode + decodedResult = decodeParamFromAbiParameter(childParam, bytes.subarray(consumed)); + consumed += decodedResult.consumed; + } + result.__length__ += 1; + result[index] = decodedResult.result; + if (childParam.name && childParam.name !== '') { + result[childParam.name] = decodedResult.result; + } + } + return { + encoded: bytes.subarray(consumed + dynamicConsumed), + result, + consumed: consumed + dynamicConsumed, + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/utils.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/utils.ts new file mode 100644 index 0000000..65a7f46 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/base/utils.ts @@ -0,0 +1,51 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { uint8ArrayConcat } from 'web3-utils'; +import { EncoderResult } from '../types.js'; +import { WORD_SIZE } from '../utils.js'; +import { encodeNumber } from './number.js'; + +export function encodeDynamicParams(encodedParams: ReadonlyArray): Uint8Array { + let staticSize = 0; + let dynamicSize = 0; + const staticParams: EncoderResult[] = []; + const dynamicParams: EncoderResult[] = []; + // figure out static size + for (const encodedParam of encodedParams) { + if (encodedParam.dynamic) { + staticSize += WORD_SIZE; + } else { + staticSize += encodedParam.encoded.length; + } + } + + for (const encodedParam of encodedParams) { + if (encodedParam.dynamic) { + staticParams.push( + encodeNumber({ type: 'uint256', name: '' }, staticSize + dynamicSize), + ); + dynamicParams.push(encodedParam); + dynamicSize += encodedParam.encoded.length; + } else { + staticParams.push(encodedParam); + } + } + return uint8ArrayConcat( + ...staticParams.map(p => p.encoded), + ...dynamicParams.map(p => p.encoded), + ); +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/decode.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/decode.ts new file mode 100644 index 0000000..adc84ad --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/decode.ts @@ -0,0 +1,32 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiInput, HexString } from 'web3-types'; +import { utils } from 'web3-validator'; +import { decodeTuple } from './base/tuple.js'; +import { toAbiParams } from './utils.js'; + +export function decodeParameters( + abis: AbiInput[], + bytes: HexString, + _loose: boolean, +): { [key: string]: unknown; __length__: number } { + const abiParams = toAbiParams(abis); + const bytesArray = utils.hexToUint8Array(bytes); + + return decodeTuple({ type: 'tuple', name: '', components: abiParams }, bytesArray).result; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/encode.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/encode.ts new file mode 100644 index 0000000..d0d8260 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/encode.ts @@ -0,0 +1,34 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiError } from 'web3-errors'; +import { AbiInput } from 'web3-types'; +import { utils } from 'web3-validator'; +import { encodeTuple } from './base/index.js'; +import { toAbiParams } from './utils.js'; + +export function encodeParameters(abi: ReadonlyArray, params: unknown[]): string { + if (abi.length !== params.length) { + throw new AbiError('Invalid number of values received for given ABI', { + expected: abi.length, + received: params.length, + }); + } + const abiParams = toAbiParams(abi); + return utils.uint8ArrayToHexString( + encodeTuple({ type: 'tuple', name: '', components: abiParams }, params).encoded, + ); +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/types.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/types.ts new file mode 100644 index 0000000..b99d856 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/types.ts @@ -0,0 +1,39 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export type EncoderResult = { + dynamic: boolean; + + encoded: Uint8Array; +}; +export type DecoderResult = { + result: T; + + // remaining bytes not yet decoded + encoded: Uint8Array; + + // number of bytes consumed + consumed: number; +}; + +export type NumberType = { + signed: boolean; + byteLength: number; +}; +export type BytesType = { + size?: number; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/coders/utils.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/utils.ts new file mode 100644 index 0000000..82b5572 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/coders/utils.ts @@ -0,0 +1,128 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiParameter as ExternalAbiParameter, parseAbiParameter } from 'abitype'; +import { AbiError } from 'web3-errors'; +import { AbiInput, AbiParameter, AbiStruct } from 'web3-types'; +import { isNullish } from 'web3-utils'; +import { + isSimplifiedStructFormat, + mapStructNameAndType, + mapStructToCoderFormat, +} from '../utils.js'; + +export const WORD_SIZE = 32; + +export function alloc(size = 0): Uint8Array { + if (globalThis.Buffer?.alloc !== undefined) { + const buf = globalThis.Buffer.alloc(size); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + + return new Uint8Array(size); +} + +/** + * Where possible returns a Uint8Array of the requested size that references + * uninitialized memory. Only use if you are certain you will immediately + * overwrite every value in the returned `Uint8Array`. + */ +export function allocUnsafe(size = 0): Uint8Array { + if (globalThis.Buffer?.allocUnsafe !== undefined) { + const buf = globalThis.Buffer.allocUnsafe(size); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + + return new Uint8Array(size); +} + +export function convertExternalAbiParameter(abiParam: ExternalAbiParameter): AbiParameter { + return { + ...abiParam, + name: abiParam.name ?? '', + components: (abiParam as { components: readonly AbiParameter[] }).components?.map(c => + convertExternalAbiParameter(c), + ), + }; +} + +export function isAbiParameter(param: unknown): param is AbiParameter { + return ( + !isNullish(param) && + typeof param === 'object' && + !isNullish((param as { type: unknown }).type) && + typeof (param as { type: unknown }).type === 'string' + ); +} + +export function toAbiParams(abi: ReadonlyArray): ReadonlyArray { + return abi.map(input => { + if (isAbiParameter(input)) { + return input; + } + if (typeof input === 'string') { + return convertExternalAbiParameter(parseAbiParameter(input.replace(/tuple/, ''))); + } + + if (isSimplifiedStructFormat(input)) { + const structName = Object.keys(input)[0]; + const structInfo = mapStructNameAndType(structName); + structInfo.name = structInfo.name ?? ''; + return { + ...structInfo, + components: mapStructToCoderFormat( + input[structName as keyof typeof input] as unknown as AbiStruct, + ), + }; + } + throw new AbiError('Invalid abi'); + }); +} + +export function extractArrayType(param: AbiParameter): { size: number; param: AbiParameter } { + const arrayParenthesisStart = param.type.lastIndexOf('['); + const arrayParamType = param.type.substring(0, arrayParenthesisStart); + const sizeString = param.type.substring(arrayParenthesisStart); + let size = -1; + if (sizeString !== '[]') { + size = Number(sizeString.slice(1, -1)); + // eslint-disable-next-line no-restricted-globals + if (isNaN(size)) { + throw new AbiError('Invalid fixed array size', { size: sizeString }); + } + } + return { + param: { type: arrayParamType, name: '', components: param.components }, + size, + }; +} + +/** + * Param is dynamic if it's dynamic base type or if some of his children (components, array items) + * is of dynamic type + * @param param + */ +export function isDynamic(param: AbiParameter): boolean { + if (param.type === 'string' || param.type === 'bytes' || param.type.endsWith('[]')) return true; + if (param.type === 'tuple') { + return param.components?.some(isDynamic) ?? false; + } + if (param.type.endsWith(']')) { + return isDynamic(extractArrayType(param).param); + } + return false; +} diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/decode_contract_error_data.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/decode_contract_error_data.ts new file mode 100644 index 0000000..98eb02d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/decode_contract_error_data.ts @@ -0,0 +1,50 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Eip838ExecutionError } from 'web3-errors'; +import { AbiErrorFragment } from 'web3-types'; + +import { encodeErrorSignature } from './api/errors_api.js'; +import { decodeParameters } from './api/parameters_api.js'; +import { jsonInterfaceMethodToString } from './utils.js'; + +export const decodeContractErrorData = ( + errorsAbi: AbiErrorFragment[], + error: Eip838ExecutionError, +) => { + if (error?.data) { + let errorName: string | undefined; + let errorSignature: string | undefined; + let errorArgs: { [K in string]: unknown } | undefined; + try { + const errorSha = error.data.slice(0, 10); + const errorAbi = errorsAbi.find(abi => encodeErrorSignature(abi).startsWith(errorSha)); + + if (errorAbi?.inputs) { + errorName = errorAbi.name; + errorSignature = jsonInterfaceMethodToString(errorAbi); + // decode abi.inputs according to EIP-838 + errorArgs = decodeParameters([...errorAbi.inputs], error.data.substring(10)); + } + } catch (err) { + console.error(err); + } + if (errorName) { + error.setDecodedProperties(errorName, errorSignature, errorArgs); + } + } +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/eip_712.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/eip_712.ts new file mode 100644 index 0000000..f08609b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/eip_712.ts @@ -0,0 +1,200 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * @note This code was taken from: https://github.com/Mrtenz/eip-712/tree/master + */ + +import { Eip712TypedData } from 'web3-types'; +import { isNullish, keccak256 } from 'web3-utils'; +import { encodeParameters } from './coders/encode.js'; + +const TYPE_REGEX = /^\w+/; +const ARRAY_REGEX = /^(.*)\[([0-9]*?)]$/; + +/** + * Get the dependencies of a struct type. If a struct has the same dependency multiple times, it's only included once + * in the resulting array. + */ +const getDependencies = ( + typedData: Eip712TypedData, + type: string, + dependencies: string[] = [], +): string[] => { + const match = type.match(TYPE_REGEX)!; + const actualType = match[0]; + if (dependencies.includes(actualType)) { + return dependencies; + } + + if (!typedData.types[actualType]) { + return dependencies; + } + + return [ + actualType, + ...typedData.types[actualType].reduce( + (previous, _type) => [ + ...previous, + ...getDependencies(typedData, _type.type, previous).filter( + dependency => !previous.includes(dependency), + ), + ], + [], + ), + ]; +}; + +/** + * Encode a type to a string. All dependant types are alphabetically sorted. + * + * @param {TypedData} typedData + * @param {string} type + * @param {Options} [options] + * @return {string} + */ +const encodeType = (typedData: Eip712TypedData, type: string): string => { + const [primary, ...dependencies] = getDependencies(typedData, type); + // eslint-disable-next-line @typescript-eslint/require-array-sort-compare + const types = [primary, ...dependencies.sort()]; + + return types + .map( + dependency => + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${dependency}(${typedData.types[dependency].map( + _type => `${_type.type} ${_type.name}`, + )})`, + ) + .join(''); +}; + +/** + * Get a type string as hash. + */ +const getTypeHash = (typedData: Eip712TypedData, type: string) => + keccak256(encodeType(typedData, type)); + +/** + * Get encoded data as a hash. The data should be a key -> value object with all the required values. All dependant + * types are automatically encoded. + */ +const getStructHash = ( + typedData: Eip712TypedData, + type: string, + data: Record, + // eslint-disable-next-line no-use-before-define +): string => keccak256(encodeData(typedData, type, data)); + +/** + * Get the EIP-191 encoded message to sign, from the typedData object. If `hash` is enabled, the message will be hashed + * with Keccak256. + */ +export const getMessage = (typedData: Eip712TypedData, hash?: boolean): string => { + const EIP_191_PREFIX = '1901'; + const message = `0x${EIP_191_PREFIX}${getStructHash( + typedData, + 'EIP712Domain', + typedData.domain as Record, + ).substring(2)}${getStructHash(typedData, typedData.primaryType, typedData.message).substring( + 2, + )}`; + + if (hash) { + return keccak256(message); + } + + return message; +}; + +/** + * Encodes a single value to an ABI serialisable string, number or Buffer. Returns the data as tuple, which consists of + * an array of ABI compatible types, and an array of corresponding values. + */ +const encodeValue = ( + typedData: Eip712TypedData, + type: string, + data: unknown, +): [string, string | Uint8Array | number] => { + const match = type.match(ARRAY_REGEX); + + // Checks for array types + if (match) { + const arrayType = match[1]; + const length = Number(match[2]) || undefined; + + if (!Array.isArray(data)) { + throw new Error('Cannot encode data: value is not of array type'); + } + + if (length && data.length !== length) { + throw new Error( + `Cannot encode data: expected length of ${length}, but got ${data.length}`, + ); + } + + const encodedData = data.map(item => encodeValue(typedData, arrayType, item)); + const types = encodedData.map(item => item[0]); + const values = encodedData.map(item => item[1]); + + return ['bytes32', keccak256(encodeParameters(types, values))]; + } + + if (typedData.types[type]) { + return ['bytes32', getStructHash(typedData, type, data as Record)]; + } + + // Strings and arbitrary byte arrays are hashed to bytes32 + if (type === 'string') { + return ['bytes32', keccak256(data as string)]; + } + + if (type === 'bytes') { + return ['bytes32', keccak256(data as string)]; + } + + return [type, data as string]; +}; + +/** + * Encode the data to an ABI encoded Buffer. The data should be a key -> value object with all the required values. All + * dependant types are automatically encoded. + */ +const encodeData = ( + typedData: Eip712TypedData, + type: string, + data: Record, +): string => { + const [types, values] = typedData.types[type].reduce<[string[], unknown[]]>( + ([_types, _values], field) => { + if (isNullish(data[field.name]) || isNullish(data[field.name])) { + throw new Error(`Cannot encode data: missing data for '${field.name}'`); + } + + const value = data[field.name]; + const [_type, encodedValue] = encodeValue(typedData, field.type, value); + + return [ + [..._types, _type], + [..._values, encodedValue], + ]; + }, + [['bytes32'], [getTypeHash(typedData, type)]], + ); + + return encodeParameters(types, values); +}; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/index.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/index.ts new file mode 100644 index 0000000..baa5794 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/index.ts @@ -0,0 +1,28 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The web3.eth.abi functions let you encode and decode parameters to ABI (Application Binary Interface) for function calls to the EVM (Ethereum Virtual Machine). + */ +export * from './api/errors_api.js'; +export * from './api/events_api.js'; +export * from './api/functions_api.js'; +export * from './api/logs_api.js'; +export * from './api/parameters_api.js'; +export * from './utils.js'; +export * from './decode_contract_error_data.js'; +export { getMessage as getEncodedEip712Data } from './eip_712.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-abi/src/utils.ts b/test/merkletreejs/node_modules/web3-eth-abi/src/utils.ts new file mode 100644 index 0000000..e8212c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-abi/src/utils.ts @@ -0,0 +1,266 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiError } from 'web3-errors'; +import { isNullish, leftPad, rightPad, toHex } from 'web3-utils'; +import { + AbiInput, + AbiCoderStruct, + AbiFragment, + AbiParameter, + AbiStruct, + AbiEventFragment, + AbiFunctionFragment, + AbiConstructorFragment, +} from 'web3-types'; + +export const isAbiFragment = (item: unknown): item is AbiFragment => + !isNullish(item) && + typeof item === 'object' && + !isNullish((item as { type: string }).type) && + ['function', 'event', 'constructor', 'error'].includes((item as { type: string }).type); + +export const isAbiErrorFragment = (item: unknown): item is AbiEventFragment => + !isNullish(item) && + typeof item === 'object' && + !isNullish((item as { type: string }).type) && + (item as { type: string }).type === 'error'; + +export const isAbiEventFragment = (item: unknown): item is AbiEventFragment => + !isNullish(item) && + typeof item === 'object' && + !isNullish((item as { type: string }).type) && + (item as { type: string }).type === 'event'; + +export const isAbiFunctionFragment = (item: unknown): item is AbiFunctionFragment => + !isNullish(item) && + typeof item === 'object' && + !isNullish((item as { type: string }).type) && + (item as { type: string }).type === 'function'; + +export const isAbiConstructorFragment = (item: unknown): item is AbiConstructorFragment => + !isNullish(item) && + typeof item === 'object' && + !isNullish((item as { type: string }).type) && + (item as { type: string }).type === 'constructor'; + +/** + * Check if type is simplified struct format + */ +export const isSimplifiedStructFormat = ( + type: string | Partial | Partial, +): type is Omit => + typeof type === 'object' && + typeof (type as { components: unknown }).components === 'undefined' && + typeof (type as { name: unknown }).name === 'undefined'; + +/** + * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used + */ +export const mapStructNameAndType = (structName: string): AbiStruct => + structName.includes('[]') + ? { type: 'tuple[]', name: structName.slice(0, -2) } + : { type: 'tuple', name: structName }; + +/** + * Maps the simplified format in to the expected format of the ABICoder + */ +export const mapStructToCoderFormat = (struct: AbiStruct): Array => { + const components: Array = []; + + for (const key of Object.keys(struct)) { + const item = struct[key]; + + if (typeof item === 'object') { + components.push({ + ...mapStructNameAndType(key), + components: mapStructToCoderFormat(item as unknown as AbiStruct), + }); + } else { + components.push({ + name: key, + type: struct[key] as string, + }); + } + } + return components; +}; + +/** + * Map types if simplified format is used + */ +export const mapTypes = ( + types: AbiInput[], +): Array> => { + const mappedTypes: Array> = []; + + for (const type of types) { + let modifiedType = type; + + // Clone object + if (typeof type === 'object') { + modifiedType = { ...type }; + } + + // Remap `function` type params to bytes24 since Ethers does not + // recognize former type. Solidity docs say `Function` is a bytes24 + // encoding the contract address followed by the function selector hash. + if (typeof type === 'object' && type.type === 'function') { + modifiedType = { ...type, type: 'bytes24' }; + } + + if (isSimplifiedStructFormat(modifiedType)) { + const structName = Object.keys(modifiedType)[0] as unknown as keyof typeof modifiedType; + + mappedTypes.push({ + ...mapStructNameAndType(structName), + components: mapStructToCoderFormat( + modifiedType[structName] as unknown as AbiStruct, + ) as unknown as AbiParameter[], + }); + } else { + mappedTypes.push(modifiedType); + } + } + + return mappedTypes; +}; + +/** + * returns true if input is a hexstring and is odd-lengthed + */ +export const isOddHexstring = (param: unknown): boolean => + typeof param === 'string' && /^(-)?0x[0-9a-f]*$/i.test(param) && param.length % 2 === 1; + +/** + * format odd-length bytes to even-length + */ +export const formatOddHexstrings = (param: string): string => + isOddHexstring(param) ? `0x0${param.substring(2)}` : param; + +/** + * Handle some formatting of params for backwards compatibility with Ethers V4 + */ +export const formatParam = (type: string, _param: unknown): unknown => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + + // clone if _param is an object + const param = typeof _param === 'object' && !Array.isArray(_param) ? { ..._param } : _param; + const paramTypeBytes = /^bytes([0-9]*)$/; + const paramTypeBytesArray = /^bytes([0-9]*)\[\]$/; + const paramTypeNumber = /^(u?int)([0-9]*)$/; + const paramTypeNumberArray = /^(u?int)([0-9]*)\[\]$/; + + // Format BN to string + if (param instanceof BigInt) { + return param.toString(10); + } + + if (paramTypeBytesArray.exec(type) || paramTypeNumberArray.exec(type)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const paramClone = [...(param as Array)]; + return paramClone.map(p => formatParam(type.replace('[]', ''), p)); + } + + // Format correct width for u?int[0-9]* + let match = paramTypeNumber.exec(type); + if (match) { + const size = parseInt(match[2] ?? '256', 10); + if (size / 8 < (param as { length: number }).length) { + // pad to correct bit width + return leftPad(param as string, size); + } + } + + // Format correct length for bytes[0-9]+ + match = paramTypeBytes.exec(type); + if (match) { + const hexParam = param instanceof Uint8Array ? toHex(param) : param; + + // format to correct length + const size = parseInt(match[1], 10); + if (size) { + let maxSize = size * 2; + + if ((param as string).startsWith('0x')) { + maxSize += 2; + } + // pad to correct length + const paddedParam = + (hexParam as string).length < maxSize + ? rightPad(param as string, size * 2) + : hexParam; + return formatOddHexstrings(paddedParam as string); + } + + return formatOddHexstrings(hexParam as string); + } + return param; +}; + +/** + * used to flatten json abi inputs/outputs into an array of type-representing-strings + */ + +export const flattenTypes = ( + includeTuple: boolean, + puts: ReadonlyArray, +): string[] => { + const types: string[] = []; + + puts.forEach(param => { + if (typeof param.components === 'object') { + if (!param.type.startsWith('tuple')) { + throw new AbiError( + `Invalid value given "${param.type}". Error: components found but type is not tuple.`, + ); + } + const arrayBracket = param.type.indexOf('['); + const suffix = arrayBracket >= 0 ? param.type.substring(arrayBracket) : ''; + const result = flattenTypes(includeTuple, param.components); + + if (Array.isArray(result) && includeTuple) { + types.push(`tuple(${result.join(',')})${suffix}`); + } else if (!includeTuple) { + types.push(`(${result.join(',')})${suffix}`); + } else { + types.push(`(${result.join()})`); + } + } else { + types.push(param.type); + } + }); + + return types; +}; + +/** + * Should be used to create full function/event name from json abi + * returns a string + */ +export const jsonInterfaceMethodToString = (json: AbiFragment): string => { + if (isAbiErrorFragment(json) || isAbiEventFragment(json) || isAbiFunctionFragment(json)) { + if (json.name?.includes('(')) { + return json.name; + } + + return `${json.name ?? ''}(${flattenTypes(false, json.inputs ?? []).join(',')})`; + } + + // Constructor fragment + return `(${flattenTypes(false, json.inputs ?? []).join(',')})`; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/LICENSE b/test/merkletreejs/node_modules/web3-eth-accounts/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/README.md b/test/merkletreejs/node_modules/web3-eth-accounts/README.md new file mode 100644 index 0000000..3ca18c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Web3 Eth Accounts + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth-accounts` contains functionality for managing Ethereum accounts and signing. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth-accounts) or using [Yarn](https://yarnpkg.com/package/web3-eth-accounts) + +### Using NPM + +```bash +npm install web3-eth-accounts +``` + +### Using Yarn + +```bash +yarn add web3-eth-accounts +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth-accounts +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-accounts%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth-accounts +[downloads-image]: https://img.shields.io/npm/dm/web3-eth-accounts?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.d.ts new file mode 100644 index 0000000..0ebd4d8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.d.ts @@ -0,0 +1,341 @@ +import { Address, Bytes, CipherOptions, HexString, KeyStore } from 'web3-types'; +import type { SignatureObject, SignTransactionResult, TypedTransaction, Web3Account, SignResult } from './types.js'; +/** + * Get the private key Uint8Array after the validation + */ +export declare const parseAndValidatePrivateKey: (data: Bytes, ignoreLength?: boolean) => Uint8Array; +/** + * + * Hashes the given message. The data will be UTF-8 HEX decoded and enveloped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message and hashed using keccak256. + * + * @param message - A message to hash, if its HEX it will be UTF8 decoded. + * @returns The hashed message + * + * ```ts + * hashMessage("Hello world") + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * hashMessage(utf8ToHex("Hello world")) // Will be hex decoded in hashMessage + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * ``` + */ +export declare const hashMessage: (message: string) => string; +/** + * Signs arbitrary data with a given private key. + * **_NOTE:_** The value passed as the data parameter will be UTF-8 HEX decoded and wrapped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message + * + * @param data - The data to sign + * @param privateKey - The 32 byte private key to sign with + * @returns The signature Object containing the message, messageHash, signature r, s, v + * + * ```ts + * web3.eth.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318') + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1c', + * r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', + * s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029', + * signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c' + * } + * ``` + */ +export declare const sign: (data: string, privateKey: Bytes) => SignResult; +/** + * Signs an Ethereum transaction with a given private key. + * + * @param transaction - The transaction, must be a legacy, EIP2930 or EIP 1559 transaction type + * @param privateKey - The private key to import. This is 32 bytes of random data. + * @returns A signTransactionResult object that contains message hash, r, s, v, transaction hash and raw transaction. + * + * This function is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * This function will rely on user to provide the full transaction to be signed. If you want to sign a partial transaction object + * Use {@link Web3.eth.accounts.sign} instead. + * + * Signing a legacy transaction + * ```ts + * signTransaction({ + * to: '0x118C2E5F57FD62C2B5b46a5ae9216F4FF4011a07', + * value: '0x186A0', + * gasLimit: '0x520812', + * gasPrice: '0x09184e72a000', + * data: '', + * chainId: 1, + * nonce: 0, + * }, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')) + * } + * > { + * messageHash: '0x28b7b75f7ba48d588a902c1ff4d5d13cc0ca9ac0aaa39562368146923fb853bf', + * v: '0x25', + * r: '0x601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5', + * s: '0x690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * rawTransaction: '0xf869808609184e72a0008352081294118c2e5f57fd62c2b5b46a5ae9216f4ff4011a07830186a08025a00601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5a0690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * ``` + * Signing an eip 1559 transaction + * ```ts + * signTransaction({ + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * maxPriorityFeePerGas: '0x3B9ACA00', + * maxFeePerGas: '0xB2D05E00', + * gasLimit: '0x6A4012', + * value: '0x186A0', + * data: '', + * chainId: 1, + * nonce: 0, + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0x5744f24d5f0aff6c70487c8e85adf07d8564e50b08558788f00479611d7bae5f', + * v: '0x25', + * r: '0x78a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347', + * s: '0x9cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * rawTransaction: '0xf8638080836a401294f0109fc8df283027b6285cc889f5aa624eac1f55830186a08025a078a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347a009cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + * Signing an eip 2930 transaction + * ```ts + * signTransaction({ + * chainId: 1, + * nonce: 0, + * gasPrice: '0x09184e72a000', + * gasLimit: '0x2710321', + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * value: '0x186A0', + * data: '', + * accessList: [ + * { + * address: '0x0000000000000000000000000000000000000101', + * storageKeys: [ + * '0x0000000000000000000000000000000000000000000000000000000000000000', + * '0x00000000000000000000000000000000000000000000000000000000000060a7', + * ], + * }, + * ], + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0xc55ea24bdb4c379550a7c9a6818ac39ca33e75bc78ddb862bd82c31cc1c7a073', + * v: '0x26', + * r: '0x27344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098e', + * s: '0x519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * rawTransaction: '0xf86a808609184e72a000840271032194f0109fc8df283027b6285cc889f5aa624eac1f55830186a08026a027344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098ea0519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + */ +export declare const signTransaction: (transaction: TypedTransaction, privateKey: HexString) => Promise; +/** + * Recovers the Ethereum address which was used to sign the given RLP encoded transaction. + * + * @param rawTransaction - The hex string having RLP encoded transaction + * @returns The Ethereum address used to sign this transaction + * ```ts + * recoverTransaction('0xf869808504e3b29200831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a0c9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895a0727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68'); + * > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23" + * ``` + */ +export declare const recoverTransaction: (rawTransaction: HexString) => Address; +/** + * Recovers the Ethereum address which was used to sign the given data + * + * @param data - Either a signed message, hash, or the {@link signatureObject} + * @param signature - The raw RLP encoded signature + * @param signatureOrV - signatureOrV + * @param prefixedOrR - prefixedOrR + * @param s - s + * @param prefixed - (default: false) If the last parameter is true, the given message will NOT automatically be prefixed with "\\x19Ethereum Signed Message:\\n" + message.length + message, and assumed to be already prefixed. + * @returns The Ethereum address used to sign this data + * ```ts + * sign('Some data', '0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728'); + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1b', + * r: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f9', + * s: '0x53e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb150', + * signature: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b' + * } + * recover('0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b'); + * > '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0' + * ``` + */ +export declare const recover: (data: string | SignatureObject, signatureOrV?: string, prefixedOrR?: boolean | string, s?: string, prefixed?: boolean) => Address; +/** + * Get the ethereum Address from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns The Ethereum address + * @example + * ```ts + * privateKeyToAddress("0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728") + * > "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0" + * ``` + */ +export declare const privateKeyToAddress: (privateKey: Bytes) => string; +/** + * Get the public key from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param isCompressed - if true, will generate a 33 byte compressed public key instead of a 65 byte public key + * @returns The public key + * @example + * ```ts + * privateKeyToAddress("0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", true) + * > "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a" // uncompressed public key + * ``` + */ +export declare const privateKeyToPublicKey: (privateKey: Bytes, isCompressed: boolean) => string; +/** + * encrypt a private key with a password, returns a V3 JSON Keystore + * + * Read more: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + * + * @param privateKey - The private key to encrypt, 32 bytes. + * @param password - The password used for encryption. + * @param options - Options to configure to encrypt the keystore either scrypt or pbkdf2 + * @returns Returns a V3 JSON Keystore + * + * + * Encrypt using scrypt options + * ```ts + * encrypt('0x67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * '123', + * { + * n: 8192, + * iv: web3.utils.hexToBytes('0xbfb43120ae00e9de110f8325143a2709'), + * salt: web3.utils.hexToBytes('0x210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'), + * ), + * }).then(console.log) + * > { + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + *} + *``` + * Encrypting using pbkdf2 options + * ```ts + * encrypt('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + *'123', + *{ + * iv: 'bfb43120ae00e9de110f8325143a2709', + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * kdf: 'pbkdf2', + *}).then(console.log) + * > + * { + * version: 3, + * id: '77381417-0973-4e4b-b590-8eb3ace0fe2d', + * address: 'b8ce9ab6943e0eced004cde8e3bbed6568b2fa01', + * crypto: { + * ciphertext: '76512156a34105fa6473ad040c666ae7b917d14c06543accc0d2dc28e6073b12', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'pbkdf2', + * kdfparams: { + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * prf: 'hmac-sha256' + * }, + * mac: '46eb4884e82dc43b5aa415faba53cc653b7038e9d61cc32fd643cf8c396189b7' + * } + * } + *``` + */ +export declare const encrypt: (privateKey: Bytes, password: string | Uint8Array, options?: CipherOptions) => Promise; +/** + * Get an Account object from the privateKey + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns A Web3Account object + * + * The `Web3Account.signTransaction` is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * Use {@link Web3.eth.accounts.signTransaction} instead. + * + * ```ts + * privateKeyToAccount("0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709"); + * > { + * address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01', + * privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + * sign, + * signTransaction, + * encrypt, + * } + * ``` + */ +export declare const privateKeyToAccount: (privateKey: Bytes, ignoreLength?: boolean) => Web3Account; +/** + * + * Generates and returns a Web3Account object that includes the private and public key + * For creation of private key, it uses an audited package ethereum-cryptography/secp256k1 + * that is cryptographically secure random number with certain characteristics. + * Read more: https://www.npmjs.com/package/ethereum-cryptography#secp256k1-curve + * + * @returns A Web3Account object + * ```ts + * web3.eth.accounts.create(); + * { + * address: '0xbD504f977021b5E5DdccD8741A368b147B3B38bB', + * privateKey: '0x964ced1c69ad27a311c432fdc0d8211e987595f7eb34ab405a5f16bdc9563ec5', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export declare const create: () => Web3Account; +/** + * Decrypts a v3 keystore JSON, and creates the account. + * + * @param keystore - the encrypted Keystore object or string to decrypt + * @param password - The password that was used for encryption + * @param nonStrict - if true and given a json string, the keystore will be parsed as lowercase. + * @returns Returns the decrypted Web3Account object + * Decrypting scrypt + * + * ```ts + * decrypt({ + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + * }, '123').then(console.log) + * > { + * address: '0xcdA9A91875fc35c8Ac1320E098e584495d66e47c', + * privateKey: '67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export declare const decrypt: (keystore: KeyStore | string, password: string | Uint8Array, nonStrict?: boolean) => Promise; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.js new file mode 100644 index 0000000..ed02380 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.js @@ -0,0 +1,610 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decrypt = exports.create = exports.privateKeyToAccount = exports.encrypt = exports.privateKeyToPublicKey = exports.privateKeyToAddress = exports.recover = exports.recoverTransaction = exports.signTransaction = exports.sign = exports.hashMessage = exports.parseAndValidatePrivateKey = void 0; +const aes_js_1 = require("ethereum-cryptography/aes.js"); +const pbkdf2_js_1 = require("ethereum-cryptography/pbkdf2.js"); +const scrypt_js_1 = require("ethereum-cryptography/scrypt.js"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const constants_js_1 = require("./tx/constants.js"); +const schemas_js_1 = require("./schemas.js"); +const transactionFactory_js_1 = require("./tx/transactionFactory.js"); +/** + * Get the private key Uint8Array after the validation + */ +const parseAndValidatePrivateKey = (data, ignoreLength) => { + let privateKeyUint8Array; + // To avoid the case of 1 character less in a hex string which is prefixed with '0' by using 'bytesToUint8Array' + if (!ignoreLength && typeof data === 'string' && (0, web3_validator_1.isHexStrict)(data) && data.length !== 66) { + throw new web3_errors_1.PrivateKeyLengthError(); + } + try { + privateKeyUint8Array = data instanceof Uint8Array ? data : (0, web3_utils_1.bytesToUint8Array)(data); + } + catch (_a) { + throw new web3_errors_1.InvalidPrivateKeyError(); + } + if (!ignoreLength && privateKeyUint8Array.byteLength !== 32) { + throw new web3_errors_1.PrivateKeyLengthError(); + } + return privateKeyUint8Array; +}; +exports.parseAndValidatePrivateKey = parseAndValidatePrivateKey; +/** + * + * Hashes the given message. The data will be UTF-8 HEX decoded and enveloped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message and hashed using keccak256. + * + * @param message - A message to hash, if its HEX it will be UTF8 decoded. + * @returns The hashed message + * + * ```ts + * hashMessage("Hello world") + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * hashMessage(utf8ToHex("Hello world")) // Will be hex decoded in hashMessage + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * ``` + */ +const hashMessage = (message) => { + const messageHex = (0, web3_validator_1.isHexStrict)(message) ? message : (0, web3_utils_1.utf8ToHex)(message); + const messageBytes = (0, web3_utils_1.hexToBytes)(messageHex); + const preamble = (0, web3_utils_1.hexToBytes)((0, web3_utils_1.fromUtf8)(`\x19Ethereum Signed Message:\n${messageBytes.byteLength}`)); + const ethMessage = (0, web3_utils_1.uint8ArrayConcat)(preamble, messageBytes); + return (0, web3_utils_1.sha3Raw)(ethMessage); // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different +}; +exports.hashMessage = hashMessage; +/** + * Signs arbitrary data with a given private key. + * **_NOTE:_** The value passed as the data parameter will be UTF-8 HEX decoded and wrapped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message + * + * @param data - The data to sign + * @param privateKey - The 32 byte private key to sign with + * @returns The signature Object containing the message, messageHash, signature r, s, v + * + * ```ts + * web3.eth.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318') + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1c', + * r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', + * s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029', + * signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c' + * } + * ``` + */ +const sign = (data, privateKey) => { + const privateKeyUint8Array = (0, exports.parseAndValidatePrivateKey)(privateKey); + const hash = (0, exports.hashMessage)(data); + const signature = constants_js_1.secp256k1.sign(hash.substring(2), privateKeyUint8Array); + const signatureBytes = signature.toCompactRawBytes(); + const r = signature.r.toString(16).padStart(64, '0'); + const s = signature.s.toString(16).padStart(64, '0'); + const v = signature.recovery + 27; + return { + message: data, + messageHash: hash, + v: (0, web3_utils_1.numberToHex)(v), + r: `0x${r}`, + s: `0x${s}`, + signature: `${(0, web3_utils_1.bytesToHex)(signatureBytes)}${v.toString(16)}`, + }; +}; +exports.sign = sign; +/** + * Signs an Ethereum transaction with a given private key. + * + * @param transaction - The transaction, must be a legacy, EIP2930 or EIP 1559 transaction type + * @param privateKey - The private key to import. This is 32 bytes of random data. + * @returns A signTransactionResult object that contains message hash, r, s, v, transaction hash and raw transaction. + * + * This function is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * This function will rely on user to provide the full transaction to be signed. If you want to sign a partial transaction object + * Use {@link Web3.eth.accounts.sign} instead. + * + * Signing a legacy transaction + * ```ts + * signTransaction({ + * to: '0x118C2E5F57FD62C2B5b46a5ae9216F4FF4011a07', + * value: '0x186A0', + * gasLimit: '0x520812', + * gasPrice: '0x09184e72a000', + * data: '', + * chainId: 1, + * nonce: 0, + * }, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')) + * } + * > { + * messageHash: '0x28b7b75f7ba48d588a902c1ff4d5d13cc0ca9ac0aaa39562368146923fb853bf', + * v: '0x25', + * r: '0x601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5', + * s: '0x690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * rawTransaction: '0xf869808609184e72a0008352081294118c2e5f57fd62c2b5b46a5ae9216f4ff4011a07830186a08025a00601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5a0690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * ``` + * Signing an eip 1559 transaction + * ```ts + * signTransaction({ + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * maxPriorityFeePerGas: '0x3B9ACA00', + * maxFeePerGas: '0xB2D05E00', + * gasLimit: '0x6A4012', + * value: '0x186A0', + * data: '', + * chainId: 1, + * nonce: 0, + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0x5744f24d5f0aff6c70487c8e85adf07d8564e50b08558788f00479611d7bae5f', + * v: '0x25', + * r: '0x78a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347', + * s: '0x9cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * rawTransaction: '0xf8638080836a401294f0109fc8df283027b6285cc889f5aa624eac1f55830186a08025a078a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347a009cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + * Signing an eip 2930 transaction + * ```ts + * signTransaction({ + * chainId: 1, + * nonce: 0, + * gasPrice: '0x09184e72a000', + * gasLimit: '0x2710321', + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * value: '0x186A0', + * data: '', + * accessList: [ + * { + * address: '0x0000000000000000000000000000000000000101', + * storageKeys: [ + * '0x0000000000000000000000000000000000000000000000000000000000000000', + * '0x00000000000000000000000000000000000000000000000000000000000060a7', + * ], + * }, + * ], + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0xc55ea24bdb4c379550a7c9a6818ac39ca33e75bc78ddb862bd82c31cc1c7a073', + * v: '0x26', + * r: '0x27344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098e', + * s: '0x519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * rawTransaction: '0xf86a808609184e72a000840271032194f0109fc8df283027b6285cc889f5aa624eac1f55830186a08026a027344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098ea0519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + */ +const signTransaction = (transaction, privateKey) => __awaiter(void 0, void 0, void 0, function* () { + const signedTx = transaction.sign((0, web3_utils_1.hexToBytes)(privateKey)); + if ((0, web3_validator_1.isNullish)(signedTx.v) || (0, web3_validator_1.isNullish)(signedTx.r) || (0, web3_validator_1.isNullish)(signedTx.s)) + throw new web3_errors_1.TransactionSigningError('Signer Error'); + const validationErrors = signedTx.validate(true); + if (validationErrors.length > 0) { + let errorString = 'Signer Error '; + for (const validationError of validationErrors) { + errorString += `${errorString} ${validationError}.`; + } + throw new web3_errors_1.TransactionSigningError(errorString); + } + const rawTx = (0, web3_utils_1.bytesToHex)(signedTx.serialize()); + const txHash = (0, web3_utils_1.sha3Raw)(rawTx); // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different + return { + messageHash: (0, web3_utils_1.bytesToHex)(signedTx.getMessageToSign(true)), + v: `0x${signedTx.v.toString(16)}`, + r: `0x${signedTx.r.toString(16).padStart(64, '0')}`, + s: `0x${signedTx.s.toString(16).padStart(64, '0')}`, + rawTransaction: rawTx, + transactionHash: (0, web3_utils_1.bytesToHex)(txHash), + }; +}); +exports.signTransaction = signTransaction; +/** + * Recovers the Ethereum address which was used to sign the given RLP encoded transaction. + * + * @param rawTransaction - The hex string having RLP encoded transaction + * @returns The Ethereum address used to sign this transaction + * ```ts + * recoverTransaction('0xf869808504e3b29200831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a0c9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895a0727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68'); + * > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23" + * ``` + */ +const recoverTransaction = (rawTransaction) => { + if ((0, web3_validator_1.isNullish)(rawTransaction)) + throw new web3_errors_1.UndefinedRawTransactionError(); + const tx = transactionFactory_js_1.TransactionFactory.fromSerializedData((0, web3_utils_1.hexToBytes)(rawTransaction)); + return (0, web3_utils_1.toChecksumAddress)(tx.getSenderAddress().toString()); +}; +exports.recoverTransaction = recoverTransaction; +/** + * Recovers the Ethereum address which was used to sign the given data + * + * @param data - Either a signed message, hash, or the {@link signatureObject} + * @param signature - The raw RLP encoded signature + * @param signatureOrV - signatureOrV + * @param prefixedOrR - prefixedOrR + * @param s - s + * @param prefixed - (default: false) If the last parameter is true, the given message will NOT automatically be prefixed with "\\x19Ethereum Signed Message:\\n" + message.length + message, and assumed to be already prefixed. + * @returns The Ethereum address used to sign this data + * ```ts + * sign('Some data', '0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728'); + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1b', + * r: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f9', + * s: '0x53e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb150', + * signature: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b' + * } + * recover('0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b'); + * > '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0' + * ``` + */ +const recover = (data, signatureOrV, prefixedOrR, s, prefixed) => { + if (typeof data === 'object') { + const signatureStr = `${data.r}${data.s.slice(2)}${data.v.slice(2)}`; + return (0, exports.recover)(data.messageHash, signatureStr, prefixedOrR); + } + if (typeof signatureOrV === 'string' && typeof prefixedOrR === 'string' && !(0, web3_validator_1.isNullish)(s)) { + const signatureStr = `${prefixedOrR}${s.slice(2)}${signatureOrV.slice(2)}`; + return (0, exports.recover)(data, signatureStr, prefixed); + } + if ((0, web3_validator_1.isNullish)(signatureOrV)) + throw new web3_errors_1.InvalidSignatureError('signature string undefined'); + const V_INDEX = 130; // r = first 32 bytes, s = second 32 bytes, v = last byte of signature + const hashedMessage = prefixedOrR ? data : (0, exports.hashMessage)(data); + let v = parseInt(signatureOrV.substring(V_INDEX), 16); // 0x + r + s + v + if (v > 26) { + v -= 27; + } + const ecPublicKey = constants_js_1.secp256k1.Signature.fromCompact(signatureOrV.slice(2, V_INDEX)) + .addRecoveryBit(v) + .recoverPublicKey(hashedMessage.replace('0x', '')) + .toRawBytes(false); + const publicHash = (0, web3_utils_1.sha3Raw)(ecPublicKey.subarray(1)); + const address = (0, web3_utils_1.toChecksumAddress)(`0x${publicHash.slice(-40)}`); + return address; +}; +exports.recover = recover; +/** + * Get the ethereum Address from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns The Ethereum address + * @example + * ```ts + * privateKeyToAddress("0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728") + * > "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0" + * ``` + */ +const privateKeyToAddress = (privateKey) => { + const privateKeyUint8Array = (0, exports.parseAndValidatePrivateKey)(privateKey); + // Get public key from private key in compressed format + const publicKey = constants_js_1.secp256k1.getPublicKey(privateKeyUint8Array, false); + // Uncompressed ECDSA public key contains the prefix `0x04` which is not used in the Ethereum public key + const publicKeyHash = (0, web3_utils_1.sha3Raw)(publicKey.slice(1)); + // The hash is returned as 256 bits (32 bytes) or 64 hex characters + // To get the address, take the last 20 bytes of the public hash + const address = publicKeyHash.slice(-40); + return (0, web3_utils_1.toChecksumAddress)(`0x${address}`); +}; +exports.privateKeyToAddress = privateKeyToAddress; +/** + * Get the public key from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param isCompressed - if true, will generate a 33 byte compressed public key instead of a 65 byte public key + * @returns The public key + * @example + * ```ts + * privateKeyToAddress("0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", true) + * > "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a" // uncompressed public key + * ``` + */ +const privateKeyToPublicKey = (privateKey, isCompressed) => { + const privateKeyUint8Array = (0, exports.parseAndValidatePrivateKey)(privateKey); + // Get public key from private key in compressed format + return `0x${(0, web3_utils_1.bytesToHex)(constants_js_1.secp256k1.getPublicKey(privateKeyUint8Array, isCompressed)).slice(4)}`; // 0x and removing compression byte +}; +exports.privateKeyToPublicKey = privateKeyToPublicKey; +/** + * encrypt a private key with a password, returns a V3 JSON Keystore + * + * Read more: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + * + * @param privateKey - The private key to encrypt, 32 bytes. + * @param password - The password used for encryption. + * @param options - Options to configure to encrypt the keystore either scrypt or pbkdf2 + * @returns Returns a V3 JSON Keystore + * + * + * Encrypt using scrypt options + * ```ts + * encrypt('0x67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * '123', + * { + * n: 8192, + * iv: web3.utils.hexToBytes('0xbfb43120ae00e9de110f8325143a2709'), + * salt: web3.utils.hexToBytes('0x210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'), + * ), + * }).then(console.log) + * > { + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + *} + *``` + * Encrypting using pbkdf2 options + * ```ts + * encrypt('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + *'123', + *{ + * iv: 'bfb43120ae00e9de110f8325143a2709', + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * kdf: 'pbkdf2', + *}).then(console.log) + * > + * { + * version: 3, + * id: '77381417-0973-4e4b-b590-8eb3ace0fe2d', + * address: 'b8ce9ab6943e0eced004cde8e3bbed6568b2fa01', + * crypto: { + * ciphertext: '76512156a34105fa6473ad040c666ae7b917d14c06543accc0d2dc28e6073b12', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'pbkdf2', + * kdfparams: { + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * prf: 'hmac-sha256' + * }, + * mac: '46eb4884e82dc43b5aa415faba53cc653b7038e9d61cc32fd643cf8c396189b7' + * } + * } + *``` + */ +const encrypt = (privateKey, password, options) => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d, _e, _f, _g; + const privateKeyUint8Array = (0, exports.parseAndValidatePrivateKey)(privateKey); + // if given salt or iv is a string, convert it to a Uint8Array + let salt; + if (options === null || options === void 0 ? void 0 : options.salt) { + salt = typeof options.salt === 'string' ? (0, web3_utils_1.hexToBytes)(options.salt) : options.salt; + } + else { + salt = (0, web3_utils_1.randomBytes)(32); + } + if (!((0, web3_validator_1.isString)(password) || password instanceof Uint8Array)) { + throw new web3_errors_1.InvalidPasswordError(); + } + const uint8ArrayPassword = typeof password === 'string' ? (0, web3_utils_1.hexToBytes)((0, web3_utils_1.utf8ToHex)(password)) : password; + let initializationVector; + if (options === null || options === void 0 ? void 0 : options.iv) { + initializationVector = typeof options.iv === 'string' ? (0, web3_utils_1.hexToBytes)(options.iv) : options.iv; + if (initializationVector.length !== 16) { + throw new web3_errors_1.IVLengthError(); + } + } + else { + initializationVector = (0, web3_utils_1.randomBytes)(16); + } + const kdf = (_a = options === null || options === void 0 ? void 0 : options.kdf) !== null && _a !== void 0 ? _a : 'scrypt'; + let derivedKey; + let kdfparams; + // derive key from key derivation function + if (kdf === 'pbkdf2') { + kdfparams = { + dklen: (_b = options === null || options === void 0 ? void 0 : options.dklen) !== null && _b !== void 0 ? _b : 32, + salt: (0, web3_utils_1.bytesToHex)(salt).replace('0x', ''), + c: (_c = options === null || options === void 0 ? void 0 : options.c) !== null && _c !== void 0 ? _c : 262144, + prf: 'hmac-sha256', + }; + if (kdfparams.c < 1000) { + // error when c < 1000, pbkdf2 is less secure with less iterations + throw new web3_errors_1.PBKDF2IterationsError(); + } + derivedKey = (0, pbkdf2_js_1.pbkdf2Sync)(uint8ArrayPassword, salt, kdfparams.c, kdfparams.dklen, 'sha256'); + } + else if (kdf === 'scrypt') { + kdfparams = { + n: (_d = options === null || options === void 0 ? void 0 : options.n) !== null && _d !== void 0 ? _d : 8192, + r: (_e = options === null || options === void 0 ? void 0 : options.r) !== null && _e !== void 0 ? _e : 8, + p: (_f = options === null || options === void 0 ? void 0 : options.p) !== null && _f !== void 0 ? _f : 1, + dklen: (_g = options === null || options === void 0 ? void 0 : options.dklen) !== null && _g !== void 0 ? _g : 32, + salt: (0, web3_utils_1.bytesToHex)(salt).replace('0x', ''), + }; + derivedKey = (0, scrypt_js_1.scryptSync)(uint8ArrayPassword, salt, kdfparams.n, kdfparams.p, kdfparams.r, kdfparams.dklen); + } + else { + throw new web3_errors_1.InvalidKdfError(); + } + const cipher = yield (0, aes_js_1.encrypt)(privateKeyUint8Array, derivedKey.slice(0, 16), initializationVector, 'aes-128-ctr'); + const ciphertext = (0, web3_utils_1.bytesToHex)(cipher).slice(2); + const mac = (0, web3_utils_1.sha3Raw)((0, web3_utils_1.uint8ArrayConcat)(derivedKey.slice(16, 32), cipher)).replace('0x', ''); + return { + version: 3, + id: (0, web3_utils_1.uuidV4)(), + address: (0, exports.privateKeyToAddress)(privateKeyUint8Array).toLowerCase().replace('0x', ''), + crypto: { + ciphertext, + cipherparams: { + iv: (0, web3_utils_1.bytesToHex)(initializationVector).replace('0x', ''), + }, + cipher: 'aes-128-ctr', + kdf, + kdfparams, + mac, + }, + }; +}); +exports.encrypt = encrypt; +/** + * Get an Account object from the privateKey + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns A Web3Account object + * + * The `Web3Account.signTransaction` is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * Use {@link Web3.eth.accounts.signTransaction} instead. + * + * ```ts + * privateKeyToAccount("0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709"); + * > { + * address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01', + * privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + * sign, + * signTransaction, + * encrypt, + * } + * ``` + */ +const privateKeyToAccount = (privateKey, ignoreLength) => { + const privateKeyUint8Array = (0, exports.parseAndValidatePrivateKey)(privateKey, ignoreLength); + return { + address: (0, exports.privateKeyToAddress)(privateKeyUint8Array), + privateKey: (0, web3_utils_1.bytesToHex)(privateKeyUint8Array), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + signTransaction: (_tx) => { + throw new web3_errors_1.TransactionSigningError('Do not have network access to sign the transaction'); + }, + sign: (data) => (0, exports.sign)(typeof data === 'string' ? data : JSON.stringify(data), privateKeyUint8Array), + encrypt: (password, options) => __awaiter(void 0, void 0, void 0, function* () { return (0, exports.encrypt)(privateKeyUint8Array, password, options); }), + }; +}; +exports.privateKeyToAccount = privateKeyToAccount; +/** + * + * Generates and returns a Web3Account object that includes the private and public key + * For creation of private key, it uses an audited package ethereum-cryptography/secp256k1 + * that is cryptographically secure random number with certain characteristics. + * Read more: https://www.npmjs.com/package/ethereum-cryptography#secp256k1-curve + * + * @returns A Web3Account object + * ```ts + * web3.eth.accounts.create(); + * { + * address: '0xbD504f977021b5E5DdccD8741A368b147B3B38bB', + * privateKey: '0x964ced1c69ad27a311c432fdc0d8211e987595f7eb34ab405a5f16bdc9563ec5', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +const create = () => { + const privateKey = constants_js_1.secp256k1.utils.randomPrivateKey(); + return (0, exports.privateKeyToAccount)(`${(0, web3_utils_1.bytesToHex)(privateKey)}`); +}; +exports.create = create; +/** + * Decrypts a v3 keystore JSON, and creates the account. + * + * @param keystore - the encrypted Keystore object or string to decrypt + * @param password - The password that was used for encryption + * @param nonStrict - if true and given a json string, the keystore will be parsed as lowercase. + * @returns Returns the decrypted Web3Account object + * Decrypting scrypt + * + * ```ts + * decrypt({ + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + * }, '123').then(console.log) + * > { + * address: '0xcdA9A91875fc35c8Ac1320E098e584495d66e47c', + * privateKey: '67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +const decrypt = (keystore, password, nonStrict) => __awaiter(void 0, void 0, void 0, function* () { + const json = typeof keystore === 'object' + ? keystore + : JSON.parse(nonStrict ? keystore.toLowerCase() : keystore); + web3_validator_1.validator.validateJSONSchema(schemas_js_1.keyStoreSchema, json); + if (json.version !== 3) + throw new web3_errors_1.KeyStoreVersionError(); + const uint8ArrayPassword = typeof password === 'string' ? (0, web3_utils_1.hexToBytes)((0, web3_utils_1.utf8ToHex)(password)) : password; + web3_validator_1.validator.validate(['bytes'], [uint8ArrayPassword]); + let derivedKey; + if (json.crypto.kdf === 'scrypt') { + const kdfparams = json.crypto.kdfparams; + const uint8ArraySalt = typeof kdfparams.salt === 'string' ? (0, web3_utils_1.hexToBytes)(kdfparams.salt) : kdfparams.salt; + derivedKey = (0, scrypt_js_1.scryptSync)(uint8ArrayPassword, uint8ArraySalt, kdfparams.n, kdfparams.p, kdfparams.r, kdfparams.dklen); + } + else if (json.crypto.kdf === 'pbkdf2') { + const kdfparams = json.crypto.kdfparams; + const uint8ArraySalt = typeof kdfparams.salt === 'string' ? (0, web3_utils_1.hexToBytes)(kdfparams.salt) : kdfparams.salt; + derivedKey = (0, pbkdf2_js_1.pbkdf2Sync)(uint8ArrayPassword, uint8ArraySalt, kdfparams.c, kdfparams.dklen, 'sha256'); + } + else { + throw new web3_errors_1.InvalidKdfError(); + } + const ciphertext = (0, web3_utils_1.hexToBytes)(json.crypto.ciphertext); + const mac = (0, web3_utils_1.sha3Raw)((0, web3_utils_1.uint8ArrayConcat)(derivedKey.slice(16, 32), ciphertext)).replace('0x', ''); + if (mac !== json.crypto.mac) { + throw new web3_errors_1.KeyDerivationError(); + } + const seed = yield (0, aes_js_1.decrypt)((0, web3_utils_1.hexToBytes)(json.crypto.ciphertext), derivedKey.slice(0, 16), (0, web3_utils_1.hexToBytes)(json.crypto.cipherparams.iv)); + return (0, exports.privateKeyToAccount)(seed); +}); +exports.decrypt = decrypt; +//# sourceMappingURL=account.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.js.map new file mode 100644 index 0000000..53f1a7c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/account.js.map @@ -0,0 +1 @@ +{"version":3,"file":"account.js","sourceRoot":"","sources":["../../src/account.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,yDAGsC;AACtC,+DAA6D;AAC7D,+DAA6D;AAC7D,6CAYqB;AAWrB,2CAYoB;AAEpB,mDAA6E;AAC7E,oDAA8C;AAC9C,6CAA8C;AAC9C,sEAAgE;AAShE;;GAEG;AACI,MAAM,0BAA0B,GAAG,CAAC,IAAW,EAAE,YAAsB,EAAc,EAAE;IAC7F,IAAI,oBAAgC,CAAC;IAErC,gHAAgH;IAChH,IAAI,CAAC,YAAY,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAA,4BAAW,EAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,EAAE,EAAE;QACzF,MAAM,IAAI,mCAAqB,EAAE,CAAC;KAClC;IAED,IAAI;QACH,oBAAoB,GAAG,IAA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AI,CAAC,CAAC;AAClC,CAAC,CAAA,CAAC;AA/DW,QAAA,OAAO,WA+DlB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.d.ts new file mode 100644 index 0000000..590e380 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.d.ts @@ -0,0 +1,45 @@ +declare const _default: { + name: string; + chainId: number; + networkId: number; + defaultHardfork: string; + consensus: { + type: string; + algorithm: string; + clique: { + period: number; + epoch: number; + }; + }; + comment: string; + url: string; + genesis: { + timestamp: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + }; + hardforks: ({ + name: string; + block: number; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + } | { + "//_comment": string; + name: string; + ttd: string; + block: number; + forkHash: string; + } | { + name: string; + block: null; + forkHash: null; + "//_comment"?: undefined; + ttd?: undefined; + })[]; + bootstrapNodes: never[]; + dnsNetworks: string[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.js new file mode 100644 index 0000000..bbc5950 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.js @@ -0,0 +1,99 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "goerli", + "chainId": 5, + "networkId": 5, + "defaultHardfork": "merge", + "consensus": { + "type": "poa", + "algorithm": "clique", + "clique": { + "period": 15, + "epoch": 30000 + } + }, + "comment": "Cross-client PoA test network", + "url": "https://github.com/goerli/testnet", + "genesis": { + "timestamp": "0x5c51a607", + "gasLimit": 10485760, + "difficulty": 1, + "nonce": "0x0000000000000000", + "extraData": "0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "homestead", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "tangerineWhistle", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "spuriousDragon", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "byzantium", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "constantinople", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "petersburg", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "istanbul", + "block": 1561651, + "forkHash": "0xc25efa5c" + }, + { + "name": "berlin", + "block": 4460644, + "forkHash": "0x757a1c47" + }, + { + "name": "london", + "block": 5062605, + "forkHash": "0xb8c6299d" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://goerli.etherscan.io/block/7382818", + "name": "merge", + "ttd": "10790000", + "block": 7382819, + "forkHash": "0xb8c6299d" + }, + { + "name": "mergeForkIdTransition", + "block": null, + "forkHash": null + }, + { + "name": "shanghai", + "block": null, + "forkHash": null + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.goerli.ethdisco.net" + ] +}; +//# sourceMappingURL=goerli.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.js.map new file mode 100644 index 0000000..8d4b219 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/goerli.js.map @@ -0,0 +1 @@ +{"version":3,"file":"goerli.js","sourceRoot":"","sources":["../../../../src/common/chains/goerli.ts"],"names":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ACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,YAAY,EAAE,iIAAiI;YAC/I,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,UAAU;YACjB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,uBAAuB;YAC/B,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;SAChB;KACD;IACD,gBAAgB,EAAE,EAAE;IACpB,aAAa,EAAE;QACd,yFAAyF;KACzF;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.d.ts new file mode 100644 index 0000000..ac9aed7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.d.ts @@ -0,0 +1,41 @@ +declare const _default: { + name: string; + chainId: number; + networkId: number; + defaultHardfork: string; + consensus: { + type: string; + algorithm: string; + ethash: {}; + }; + comment: string; + url: string; + genesis: { + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + }; + hardforks: ({ + name: string; + block: number; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + } | { + "//_comment": string; + name: string; + ttd: string; + block: number; + forkHash: string; + } | { + name: string; + block: null; + forkHash: null; + "//_comment"?: undefined; + ttd?: undefined; + })[]; + bootstrapNodes: never[]; + dnsNetworks: string[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.js new file mode 100644 index 0000000..d0c8fcc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.js @@ -0,0 +1,115 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "mainnet", + "chainId": 1, + "networkId": 1, + "defaultHardfork": "merge", + "consensus": { + "type": "pow", + "algorithm": "ethash", + "ethash": {} + }, + "comment": "The Ethereum main chain", + "url": "https://ethstats.net/", + "genesis": { + "gasLimit": 5000, + "difficulty": 17179869184, + "nonce": "0x0000000000000042", + "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xfc64ec04" + }, + { + "name": "homestead", + "block": 1150000, + "forkHash": "0x97c2c34c" + }, + { + "name": "dao", + "block": 1920000, + "forkHash": "0x91d1f948" + }, + { + "name": "tangerineWhistle", + "block": 2463000, + "forkHash": "0x7a64da13" + }, + { + "name": "spuriousDragon", + "block": 2675000, + "forkHash": "0x3edd5b10" + }, + { + "name": "byzantium", + "block": 4370000, + "forkHash": "0xa00bc324" + }, + { + "name": "constantinople", + "block": 7280000, + "forkHash": "0x668db0af" + }, + { + "name": "petersburg", + "block": 7280000, + "forkHash": "0x668db0af" + }, + { + "name": "istanbul", + "block": 9069000, + "forkHash": "0x879d6e30" + }, + { + "name": "muirGlacier", + "block": 9200000, + "forkHash": "0xe029e991" + }, + { + "name": "berlin", + "block": 12244000, + "forkHash": "0x0eb440f6" + }, + { + "name": "london", + "block": 12965000, + "forkHash": "0xb715077d" + }, + { + "name": "arrowGlacier", + "block": 13773000, + "forkHash": "0x20c327fc" + }, + { + "name": "grayGlacier", + "block": 15050000, + "forkHash": "0xf0afd0e3" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://etherscan.io/block/15537393", + "name": "merge", + "ttd": "58750000000000000000000", + "block": 15537394, + "forkHash": "0xf0afd0e3" + }, + { + "name": "mergeForkIdTransition", + "block": null, + "forkHash": null + }, + { + "name": "shanghai", + "block": null, + "forkHash": null + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.mainnet.ethdisco.net" + ] +}; +//# sourceMappingURL=mainnet.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.js.map new file mode 100644 index 0000000..bee3104 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/mainnet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mainnet.js","sourceRoot":"","sources":["../../../../src/common/chains/mainnet.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,SAAS;IACjB,SAAS,EAAE,CAAC;IACZ,WAAW,EAAE,CAAC;IACd,iBAAiB,EAAE,OAAO;IAC1B,WAAW,EAAE;QACZ,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,EAAE;KACZ;IACD,SAAS,EAAE,yBAAyB;IACpC,KAAK,EAAE,uBAAuB;IAC9B,SAAS,EAAE;QACV,UAAU,EAAE,IAAI;QAChB,YAAY,EAAE,WAAW;QACzB,OAAO,EAAE,oBAAoB;QAC7B,WAAW,EAAE,oEAAoE;KACjF;IACD,WAAW,EAAE;QACZ;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,KAAK;YACb,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,kBAAkB;YAC1B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YAC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_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.d.ts new file mode 100644 index 0000000..3ce78d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.d.ts @@ -0,0 +1,45 @@ +declare const _default: { + name: string; + chainId: number; + networkId: number; + defaultHardfork: string; + consensus: { + type: string; + algorithm: string; + ethash: {}; + }; + comment: string; + url: string; + genesis: { + timestamp: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + }; + hardforks: ({ + name: string; + block: number; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + timestamp?: undefined; + } | { + "//_comment": string; + name: string; + ttd: string; + block: number; + forkHash: string; + timestamp?: undefined; + } | { + name: string; + block: null; + timestamp: string; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + })[]; + bootstrapNodes: never[]; + dnsNetworks: string[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.js new file mode 100644 index 0000000..3f5051c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.js @@ -0,0 +1,102 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "sepolia", + "chainId": 11155111, + "networkId": 11155111, + "defaultHardfork": "merge", + "consensus": { + "type": "pow", + "algorithm": "ethash", + "ethash": {} + }, + "comment": "PoW test network to replace Ropsten", + "url": "https://github.com/ethereum/go-ethereum/pull/23730", + "genesis": { + "timestamp": "0x6159af19", + "gasLimit": 30000000, + "difficulty": 131072, + "nonce": "0x0000000000000000", + "extraData": "0x5365706f6c69612c20417468656e732c204174746963612c2047726565636521" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "homestead", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "tangerineWhistle", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "spuriousDragon", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "byzantium", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "constantinople", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "petersburg", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "istanbul", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "muirGlacier", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "berlin", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "london", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://sepolia.etherscan.io/block/1450408", + "name": "merge", + "ttd": "17000000000000000", + "block": 1450409, + "forkHash": "0xfe3366e7" + }, + { + "name": "mergeForkIdTransition", + "block": 1735371, + "forkHash": "0xb96cbd13" + }, + { + "name": "shanghai", + "block": null, + "timestamp": "1677557088", + "forkHash": "0xf7f9bc08" + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.sepolia.ethdisco.net" + ] +}; +//# sourceMappingURL=sepolia.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.js.map new file mode 100644 index 0000000..ab56dd0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/chains/sepolia.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sepolia.js","sourceRoot":"","sources":["../../../../src/common/chains/sepolia.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,SAAS;IACjB,S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;YAChB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,YAAY,EAAE,kIAAkI;YAChJ,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,mBAAmB;YAC1B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,uBAAuB;YAC/B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,IAAI;YACb,WAAW,EAAE,YAAY;YACzB,UAAU,EAAE,YAAY;SACxB;KACD;IACD,gBAAgB,EAAE,EAAE;IACpB,aAAa,EAAE;QACd,0FAA0F;KAC1F;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.d.ts new file mode 100644 index 0000000..150b3c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.d.ts @@ -0,0 +1,343 @@ +import { EventEmitter } from 'web3-utils'; +import type { Numbers } from 'web3-types'; +import type { ConsensusAlgorithm, ConsensusType } from './enums.js'; +import { Chain, CustomChain, Hardfork } from './enums.js'; +import type { BootstrapNodeConfig, CasperConfig, ChainConfig, ChainsConfig, CliqueConfig, CommonOpts, CustomCommonOpts, EthashConfig, GenesisBlockConfig, GethConfigOpts, HardforkConfig } from './types.js'; +/** + * Common class to access chain and hardfork parameters and to provide + * a unified and shared view on the network and hardfork state. + * + * Use the {@link Common.custom} static constructor for creating simple + * custom chain {@link Common} objects (more complete custom chain setups + * can be created via the main constructor and the {@link CommonOpts.customChains} parameter). + */ +export declare class Common extends EventEmitter { + readonly DEFAULT_HARDFORK: string | Hardfork; + private _chainParams; + private _hardfork; + private _eips; + private readonly _customChains; + private readonly HARDFORK_CHANGES; + /** + * Creates a {@link Common} object for a custom chain, based on a standard one. + * + * It uses all the {@link Chain} parameters from the {@link baseChain} option except the ones overridden + * in a provided {@link chainParamsOrName} dictionary. Some usage example: + * + * ```javascript + * Common.custom({chainId: 123}) + * ``` + * + * There are also selected supported custom chains which can be initialized by using one of the + * {@link CustomChains} for {@link chainParamsOrName}, e.g.: + * + * ```javascript + * Common.custom(CustomChains.MaticMumbai) + * ``` + * + * Note that these supported custom chains only provide some base parameters (usually the chain and + * network ID and a name) and can only be used for selected use cases (e.g. sending a tx with + * the `web3-utils/tx` library to a Layer-2 chain). + * + * @param chainParamsOrName Custom parameter dict (`name` will default to `custom-chain`) or string with name of a supported custom chain + * @param opts Custom chain options to set the {@link CustomCommonOpts.baseChain}, selected {@link CustomCommonOpts.hardfork} and others + */ + static custom(chainParamsOrName: Partial | CustomChain, opts?: CustomCommonOpts): Common; + /** + * Static method to load and set common from a geth genesis json + * @param genesisJson json of geth configuration + * @param { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge } to further configure the common instance + * @returns Common + */ + static fromGethGenesis(genesisJson: any, { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge }: GethConfigOpts): Common; + /** + * Static method to determine if a {@link chainId} is supported as a standard chain + * @param chainId bigint id (`1`) of a standard chain + * @returns boolean + */ + static isSupportedChainId(chainId: bigint): boolean; + private static _getChainParams; + constructor(opts: CommonOpts); + /** + * Sets the chain + * @param chain String ('mainnet') or Number (1) chain representation. + * Or, a Dictionary of chain parameters for a private network. + * @returns The dictionary with parameters set as chain + */ + setChain(chain: string | number | Chain | bigint | object): ChainConfig; + /** + * Sets the hardfork to get params for + * @param hardfork String identifier (e.g. 'byzantium') or {@link Hardfork} enum + */ + setHardfork(hardfork: string | Hardfork): void; + /** + * Returns the hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td : total difficulty of the parent block (for block hf) OR of the chain latest (for chain hf) + * @param timestamp: timestamp in seconds at which block was/is to be minted + * @returns The name of the HF + */ + getHardforkByBlockNumber(_blockNumber: Numbers, _td?: Numbers, _timestamp?: Numbers): string; + /** + * Sets a new hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td + * @param timestamp + * @returns The name of the HF set + */ + setHardforkByBlockNumber(blockNumber: Numbers, td?: Numbers, timestamp?: Numbers): string; + /** + * Internal helper function, returns the params for the given hardfork for the chain set + * @param hardfork Hardfork name + * @returns Dictionary with hardfork params or null if hardfork not on chain + */ + _getHardfork(hardfork: string | Hardfork): HardforkConfig | null; + /** + * Sets the active EIPs + * @param eips + */ + setEIPs(eips?: number[]): void; + /** + * Returns a parameter for the current chain setup + * + * If the parameter is present in an EIP, the EIP always takes precedence. + * Otherwise the parameter if taken from the latest applied HF with + * a change on the respective parameter. + * + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @returns The value requested or `BigInt(0)` if not found + */ + param(topic: string, name: string): bigint; + /** + * Returns the parameter corresponding to a hardfork + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param hardfork Hardfork name + * @returns The value requested or `BigInt(0)` if not found + */ + paramByHardfork(topic: string, name: string, hardfork: string | Hardfork): bigint; + /** + * Returns a parameter corresponding to an EIP + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param eip Number of the EIP + * @returns The value requested or `undefined` if not found + */ + paramByEIP(topic: string, name: string, eip: number): bigint | undefined; + /** + * Returns a parameter for the hardfork active on block number or + * optional provided total difficulty (Merge HF) + * @param topic Parameter topic + * @param name Parameter name + * @param blockNumber Block number + * @param td Total difficulty + * * @returns The value requested or `BigInt(0)` if not found + */ + paramByBlock(topic: string, name: string, blockNumber: Numbers, td?: Numbers, timestamp?: Numbers): bigint; + /** + * Checks if an EIP is activated by either being included in the EIPs + * manually passed in with the {@link CommonOpts.eips} or in a + * hardfork currently being active + * + * Note: this method only works for EIPs being supported + * by the {@link CommonOpts.eips} constructor option + * @param eip + */ + isActivatedEIP(eip: number): boolean; + /** + * Checks if set or provided hardfork is active on block number + * @param hardfork Hardfork name or null (for HF set) + * @param blockNumber + * @returns True if HF is active on block number + */ + hardforkIsActiveOnBlock(_hardfork: string | Hardfork | null, _blockNumber: Numbers): boolean; + /** + * Alias to hardforkIsActiveOnBlock when hardfork is set + * @param blockNumber + * @returns True if HF is active on block number + */ + activeOnBlock(blockNumber: Numbers): boolean; + /** + * Sequence based check if given or set HF1 is greater than or equal HF2 + * @param hardfork1 Hardfork name or null (if set) + * @param hardfork2 Hardfork name + * @param opts Hardfork options + * @returns True if HF1 gte HF2 + */ + hardforkGteHardfork(_hardfork1: string | Hardfork | null, hardfork2: string | Hardfork): boolean; + /** + * Alias to hardforkGteHardfork when hardfork is set + * @param hardfork Hardfork name + * @returns True if hardfork set is greater than hardfork provided + */ + gteHardfork(hardfork: string | Hardfork): boolean; + /** + * Returns the hardfork change block for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if unscheduled + */ + hardforkBlock(_hardfork?: string | Hardfork): bigint | null; + hardforkTimestamp(_hardfork?: string | Hardfork): bigint | null; + /** + * Returns the hardfork change block for eip + * @param eip EIP number + * @returns Block number or null if unscheduled + */ + eipBlock(eip: number): bigint | null; + /** + * Returns the hardfork change total difficulty (Merge HF) for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Total difficulty or null if no set + */ + hardforkTTD(_hardfork?: string | Hardfork): bigint | null; + /** + * True if block number provided is the hardfork (given or set) change block + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isHardforkBlock(_blockNumber: Numbers, _hardfork?: string | Hardfork): boolean; + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block timestamp, number or null if not available + */ + nextHardforkBlockOrTimestamp(_hardfork?: string | Hardfork): bigint | null; + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if not available + * @deprecated + */ + nextHardforkBlock(_hardfork?: string | Hardfork): bigint | null; + /** + * True if block number provided is the hardfork change block following the hardfork given or set + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isNextHardforkBlock(_blockNumber: Numbers, _hardfork?: string | Hardfork): boolean; + /** + * Internal helper function to calculate a fork hash + * @param hardfork Hardfork name + * @param genesisHash Genesis block hash of the chain + * @returns Fork hash as hex string + */ + _calcForkHash(hardfork: string | Hardfork, genesisHash: Uint8Array): string; + /** + * Returns an eth/64 compliant fork hash (EIP-2124) + * @param hardfork Hardfork name, optional if HF set + * @param genesisHash Genesis block hash of the chain, optional if already defined and not needed to be calculated + */ + forkHash(_hardfork?: string | Hardfork, genesisHash?: Uint8Array): string; + /** + * + * @param forkHash Fork hash as a hex string + * @returns Array with hardfork data (name, block, forkHash) + */ + hardforkForForkHash(forkHash: string): HardforkConfig | null; + /** + * Sets any missing forkHashes on the passed-in {@link Common} instance + * @param common The {@link Common} to set the forkHashes for + * @param genesisHash The genesis block hash + */ + setForkHashes(genesisHash: Uint8Array): void; + /** + * Returns the Genesis parameters of the current chain + * @returns Genesis dictionary + */ + genesis(): GenesisBlockConfig; + /** + * Returns the hardforks for current chain + * @returns {Array} Array with arrays of hardforks + */ + hardforks(): HardforkConfig[]; + /** + * Returns bootstrap nodes for the current chain + * @returns {Dictionary} Dict with bootstrap nodes + */ + bootstrapNodes(): BootstrapNodeConfig[] | undefined; + /** + * Returns DNS networks for the current chain + * @returns {String[]} Array of DNS ENR urls + */ + dnsNetworks(): string[]; + /** + * Returns the hardfork set + * @returns Hardfork name + */ + hardfork(): string | Hardfork; + /** + * Returns the Id of current chain + * @returns chain Id + */ + chainId(): bigint; + /** + * Returns the name of current chain + * @returns chain name (lower case) + */ + chainName(): string; + /** + * Returns the Id of current network + * @returns network Id + */ + networkId(): bigint; + /** + * Returns the active EIPs + * @returns List of EIPs + */ + eips(): number[]; + /** + * Returns the consensus type of the network + * Possible values: "pow"|"poa"|"pos" + * + * Note: This value can update along a Hardfork. + */ + consensusType(): string | ConsensusType; + /** + * Returns the concrete consensus implementation + * algorithm or protocol for the network + * e.g. "ethash" for "pow" consensus type, + * "clique" for "poa" consensus type or + * "casper" for "pos" consensus type. + * + * Note: This value can update along a Hardfork. + */ + consensusAlgorithm(): string | ConsensusAlgorithm; + /** + * Returns a dictionary with consensus configuration + * parameters based on the consensus algorithm + * + * Expected returns (parameters must be present in + * the respective chain json files): + * + * ethash: empty object + * clique: period, epoch + * casper: empty object + * + * Note: This value can update along a Hardfork. + */ + consensusConfig(): { + [key: string]: CliqueConfig | EthashConfig | CasperConfig; + }; + /** + * Returns a deep copy of this {@link Common} instance. + */ + copy(): Common; + static _getInitializedChains(customChains?: ChainConfig[]): ChainsConfig; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.js new file mode 100644 index 0000000..eba28a0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.js @@ -0,0 +1,1050 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Common = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const crc_32_1 = __importDefault(require("crc-32")); +const web3_utils_1 = require("web3-utils"); +const types_js_1 = require("./types.js"); +const utils_js_1 = require("./utils.js"); +const goerli_js_1 = __importDefault(require("./chains/goerli.js")); +const mainnet_js_1 = __importDefault(require("./chains/mainnet.js")); +const sepolia_js_1 = __importDefault(require("./chains/sepolia.js")); +const index_js_1 = require("./eips/index.js"); +const enums_js_1 = require("./enums.js"); +const index_js_2 = require("./hardforks/index.js"); +const { buf: crc32Uint8Array } = crc_32_1.default; +/** + * Common class to access chain and hardfork parameters and to provide + * a unified and shared view on the network and hardfork state. + * + * Use the {@link Common.custom} static constructor for creating simple + * custom chain {@link Common} objects (more complete custom chain setups + * can be created via the main constructor and the {@link CommonOpts.customChains} parameter). + */ +class Common extends web3_utils_1.EventEmitter { + constructor(opts) { + var _a, _b; + super(); + this._eips = []; + this._customChains = (_a = opts.customChains) !== null && _a !== void 0 ? _a : []; + this._chainParams = this.setChain(opts.chain); + this.DEFAULT_HARDFORK = (_b = this._chainParams.defaultHardfork) !== null && _b !== void 0 ? _b : enums_js_1.Hardfork.Merge; + // Assign hardfork changes in the sequence of the applied hardforks + this.HARDFORK_CHANGES = this.hardforks().map(hf => [ + hf.name, + index_js_2.hardforks[hf.name], + ]); + this._hardfork = this.DEFAULT_HARDFORK; + if (opts.hardfork !== undefined) { + this.setHardfork(opts.hardfork); + } + if (opts.eips) { + this.setEIPs(opts.eips); + } + } + /** + * Creates a {@link Common} object for a custom chain, based on a standard one. + * + * It uses all the {@link Chain} parameters from the {@link baseChain} option except the ones overridden + * in a provided {@link chainParamsOrName} dictionary. Some usage example: + * + * ```javascript + * Common.custom({chainId: 123}) + * ``` + * + * There are also selected supported custom chains which can be initialized by using one of the + * {@link CustomChains} for {@link chainParamsOrName}, e.g.: + * + * ```javascript + * Common.custom(CustomChains.MaticMumbai) + * ``` + * + * Note that these supported custom chains only provide some base parameters (usually the chain and + * network ID and a name) and can only be used for selected use cases (e.g. sending a tx with + * the `web3-utils/tx` library to a Layer-2 chain). + * + * @param chainParamsOrName Custom parameter dict (`name` will default to `custom-chain`) or string with name of a supported custom chain + * @param opts Custom chain options to set the {@link CustomCommonOpts.baseChain}, selected {@link CustomCommonOpts.hardfork} and others + */ + static custom(chainParamsOrName, opts = {}) { + var _a; + const baseChain = (_a = opts.baseChain) !== null && _a !== void 0 ? _a : 'mainnet'; + const standardChainParams = Object.assign({}, Common._getChainParams(baseChain)); + standardChainParams.name = 'custom-chain'; + if (typeof chainParamsOrName !== 'string') { + return new Common(Object.assign({ chain: Object.assign(Object.assign({}, standardChainParams), chainParamsOrName) }, opts)); + } + if (chainParamsOrName === enums_js_1.CustomChain.PolygonMainnet) { + return Common.custom({ + name: enums_js_1.CustomChain.PolygonMainnet, + chainId: 137, + networkId: 137, + }, opts); + } + if (chainParamsOrName === enums_js_1.CustomChain.PolygonMumbai) { + return Common.custom({ + name: enums_js_1.CustomChain.PolygonMumbai, + chainId: 80001, + networkId: 80001, + }, opts); + } + if (chainParamsOrName === enums_js_1.CustomChain.ArbitrumRinkebyTestnet) { + return Common.custom({ + name: enums_js_1.CustomChain.ArbitrumRinkebyTestnet, + chainId: 421611, + networkId: 421611, + }, opts); + } + if (chainParamsOrName === enums_js_1.CustomChain.ArbitrumOne) { + return Common.custom({ + name: enums_js_1.CustomChain.ArbitrumOne, + chainId: 42161, + networkId: 42161, + }, opts); + } + if (chainParamsOrName === enums_js_1.CustomChain.xDaiChain) { + return Common.custom({ + name: enums_js_1.CustomChain.xDaiChain, + chainId: 100, + networkId: 100, + }, opts); + } + if (chainParamsOrName === enums_js_1.CustomChain.OptimisticKovan) { + return Common.custom({ + name: enums_js_1.CustomChain.OptimisticKovan, + chainId: 69, + networkId: 69, + }, Object.assign({ hardfork: enums_js_1.Hardfork.Berlin }, opts)); + } + if (chainParamsOrName === enums_js_1.CustomChain.OptimisticEthereum) { + return Common.custom({ + name: enums_js_1.CustomChain.OptimisticEthereum, + chainId: 10, + networkId: 10, + }, Object.assign({ hardfork: enums_js_1.Hardfork.Berlin }, opts)); + } + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + throw new Error(`Custom chain ${chainParamsOrName} not supported`); + } + /** + * Static method to load and set common from a geth genesis json + * @param genesisJson json of geth configuration + * @param { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge } to further configure the common instance + * @returns Common + */ + static fromGethGenesis(genesisJson, { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge }) { + var _a; + const genesisParams = (0, utils_js_1.parseGethGenesis)(genesisJson, chain, mergeForkIdPostMerge); + const common = new Common({ + chain: (_a = genesisParams.name) !== null && _a !== void 0 ? _a : 'custom', + customChains: [genesisParams], + eips, + hardfork: hardfork !== null && hardfork !== void 0 ? hardfork : genesisParams.hardfork, + }); + if (genesisHash !== undefined) { + common.setForkHashes(genesisHash); + } + return common; + } + /** + * Static method to determine if a {@link chainId} is supported as a standard chain + * @param chainId bigint id (`1`) of a standard chain + * @returns boolean + */ + static isSupportedChainId(chainId) { + const initializedChains = this._getInitializedChains(); + return Boolean(initializedChains.names[chainId.toString()]); + } + static _getChainParams(_chain, customChains) { + let chain = _chain; + const initializedChains = this._getInitializedChains(customChains); + if (typeof chain === 'number' || typeof chain === 'bigint') { + chain = chain.toString(); + if (initializedChains.names[chain]) { + const name = initializedChains.names[chain]; + return initializedChains[name]; + } + throw new Error(`Chain with ID ${chain} not supported`); + } + if (initializedChains[chain] !== undefined) { + return initializedChains[chain]; + } + throw new Error(`Chain with name ${chain} not supported`); + } + /** + * Sets the chain + * @param chain String ('mainnet') or Number (1) chain representation. + * Or, a Dictionary of chain parameters for a private network. + * @returns The dictionary with parameters set as chain + */ + setChain(chain) { + if (typeof chain === 'number' || typeof chain === 'bigint' || typeof chain === 'string') { + this._chainParams = Common._getChainParams(chain, this._customChains); + } + else if (typeof chain === 'object') { + if (this._customChains.length > 0) { + throw new Error('Chain must be a string, number, or bigint when initialized with customChains passed in'); + } + const required = ['networkId', 'genesis', 'hardforks', 'bootstrapNodes']; + for (const param of required) { + if (!(param in chain)) { + throw new Error(`Missing required chain parameter: ${param}`); + } + } + this._chainParams = chain; + } + else { + throw new Error('Wrong input format'); + } + for (const hf of this.hardforks()) { + if (hf.block === undefined) { + throw new Error(`Hardfork cannot have undefined block number`); + } + } + return this._chainParams; + } + /** + * Sets the hardfork to get params for + * @param hardfork String identifier (e.g. 'byzantium') or {@link Hardfork} enum + */ + setHardfork(hardfork) { + let existing = false; + for (const hfChanges of this.HARDFORK_CHANGES) { + if (hfChanges[0] === hardfork) { + if (this._hardfork !== hardfork) { + this._hardfork = hardfork; + this.emit('hardforkChanged', hardfork); + } + existing = true; + } + } + if (!existing) { + throw new Error(`Hardfork with name ${hardfork} not supported`); + } + } + /** + * Returns the hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td : total difficulty of the parent block (for block hf) OR of the chain latest (for chain hf) + * @param timestamp: timestamp in seconds at which block was/is to be minted + * @returns The name of the HF + */ + getHardforkByBlockNumber(_blockNumber, _td, _timestamp) { + const blockNumber = (0, utils_js_1.toType)(_blockNumber, types_js_1.TypeOutput.BigInt); + const td = (0, utils_js_1.toType)(_td, types_js_1.TypeOutput.BigInt); + const timestamp = (0, utils_js_1.toType)(_timestamp, types_js_1.TypeOutput.Number); + // Filter out hardforks with no block number, no ttd or no timestamp (i.e. unapplied hardforks) + const hfs = this.hardforks().filter(hf => + // eslint-disable-next-line no-null/no-null + hf.block !== null || + // eslint-disable-next-line no-null/no-null + (hf.ttd !== null && hf.ttd !== undefined) || + hf.timestamp !== undefined); + // eslint-disable-next-line no-null/no-null + const mergeIndex = hfs.findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + const doubleTTDHF = hfs + .slice(mergeIndex + 1) + // eslint-disable-next-line no-null/no-null + .findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + if (doubleTTDHF >= 0) { + throw Error(`More than one merge hardforks found with ttd specified`); + } + // Find the first hardfork that has a block number greater than `blockNumber` + // (skips the merge hardfork since it cannot have a block number specified). + // If timestamp is not provided, it also skips timestamps hardforks to continue + // discovering/checking number hardforks. + let hfIndex = hfs.findIndex(hf => + // eslint-disable-next-line no-null/no-null + (hf.block !== null && hf.block > blockNumber) || + (timestamp !== undefined && Number(hf.timestamp) > timestamp)); + if (hfIndex === -1) { + // all hardforks apply, set hfIndex to the last one as that's the candidate + hfIndex = hfs.length; + } + else if (hfIndex === 0) { + // cannot have a case where a block number is before all applied hardforks + // since the chain has to start with a hardfork + throw Error('Must have at least one hardfork at block 0'); + } + // If timestamp is not provided, we need to rollback to the last hf with block or ttd + if (timestamp === undefined) { + const stepBack = hfs + .slice(0, hfIndex) + .reverse() + // eslint-disable-next-line no-null/no-null + .findIndex(hf => hf.block !== null || hf.ttd !== undefined); + hfIndex -= stepBack; + } + // Move hfIndex one back to arrive at candidate hardfork + hfIndex -= 1; + // If the timestamp was not provided, we could have skipped timestamp hardforks to look for number + // hardforks. so it will now be needed to rollback + // eslint-disable-next-line no-null/no-null + if (hfs[hfIndex].block === null && hfs[hfIndex].timestamp === undefined) { + // We're on the merge hardfork. Let's check the TTD + // eslint-disable-next-line no-null/no-null + if (td === undefined || td === null || BigInt(hfs[hfIndex].ttd) > td) { + // Merge ttd greater than current td so we're on hardfork before merge + hfIndex -= 1; + } + // eslint-disable-next-line no-null/no-null + } + else if (mergeIndex >= 0 && td !== undefined && td !== null) { + if (hfIndex >= mergeIndex && BigInt(hfs[mergeIndex].ttd) > td) { + throw Error('Maximum HF determined by total difficulty is lower than the block number HF'); + } + else if (hfIndex < mergeIndex && BigInt(hfs[mergeIndex].ttd) <= td) { + throw Error('HF determined by block number is lower than the minimum total difficulty HF'); + } + } + const hfStartIndex = hfIndex; + // Move the hfIndex to the end of the hardforks that might be scheduled on the same block/timestamp + // This won't anyway be the case with Merge hfs + for (; hfIndex < hfs.length - 1; hfIndex += 1) { + // break out if hfIndex + 1 is not scheduled at hfIndex + if (hfs[hfIndex].block !== hfs[hfIndex + 1].block || + hfs[hfIndex].timestamp !== hfs[hfIndex + 1].timestamp) { + break; + } + } + if (timestamp) { + const minTimeStamp = hfs + .slice(0, hfStartIndex) + .reduce((acc, hf) => { var _a; return Math.max(Number((_a = hf.timestamp) !== null && _a !== void 0 ? _a : '0'), acc); }, 0); + if (minTimeStamp > timestamp) { + throw Error(`Maximum HF determined by timestamp is lower than the block number/ttd HF`); + } + const maxTimeStamp = hfs + .slice(hfIndex + 1) + .reduce((acc, hf) => { var _a; return Math.min(Number((_a = hf.timestamp) !== null && _a !== void 0 ? _a : timestamp), acc); }, timestamp); + if (maxTimeStamp < timestamp) { + throw Error(`Maximum HF determined by block number/ttd is lower than timestamp HF`); + } + } + const hardfork = hfs[hfIndex]; + return hardfork.name; + } + /** + * Sets a new hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td + * @param timestamp + * @returns The name of the HF set + */ + setHardforkByBlockNumber(blockNumber, td, timestamp) { + const hardfork = this.getHardforkByBlockNumber(blockNumber, td, timestamp); + this.setHardfork(hardfork); + return hardfork; + } + /** + * Internal helper function, returns the params for the given hardfork for the chain set + * @param hardfork Hardfork name + * @returns Dictionary with hardfork params or null if hardfork not on chain + */ + // eslint-disable-next-line @typescript-eslint/ban-types + _getHardfork(hardfork) { + const hfs = this.hardforks(); + for (const hf of hfs) { + if (hf.name === hardfork) + return hf; + } + // eslint-disable-next-line no-null/no-null + return null; + } + /** + * Sets the active EIPs + * @param eips + */ + setEIPs(eips = []) { + for (const eip of eips) { + if (!(eip in index_js_1.EIPs)) { + throw new Error(`${eip} not supported`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument + const minHF = this.gteHardfork(index_js_1.EIPs[eip].minimumHardfork); + if (!minHF) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${eip} cannot be activated on hardfork ${this.hardfork()}, minimumHardfork: ${minHF}`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (index_js_1.EIPs[eip].requiredEIPs !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + for (const elem of index_js_1.EIPs[eip].requiredEIPs) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + if (!(eips.includes(elem) || this.isActivatedEIP(elem))) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${eip} requires EIP ${elem}, but is not included in the EIP list`); + } + } + } + } + this._eips = eips; + } + /** + * Returns a parameter for the current chain setup + * + * If the parameter is present in an EIP, the EIP always takes precedence. + * Otherwise the parameter if taken from the latest applied HF with + * a change on the respective parameter. + * + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @returns The value requested or `BigInt(0)` if not found + */ + param(topic, name) { + // TODO: consider the case that different active EIPs + // can change the same parameter + let value; + for (const eip of this._eips) { + value = this.paramByEIP(topic, name, eip); + if (value !== undefined) + return value; + } + return this.paramByHardfork(topic, name, this._hardfork); + } + /** + * Returns the parameter corresponding to a hardfork + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param hardfork Hardfork name + * @returns The value requested or `BigInt(0)` if not found + */ + paramByHardfork(topic, name, hardfork) { + // eslint-disable-next-line no-null/no-null + let value = null; + for (const hfChanges of this.HARDFORK_CHANGES) { + // EIP-referencing HF file (e.g. berlin.json) + if ('eips' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + const hfEIPs = hfChanges[1].eips; + for (const eip of hfEIPs) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const valueEIP = this.paramByEIP(topic, name, eip); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + value = typeof valueEIP === 'bigint' ? valueEIP : value; + } + // Parameter-inlining HF file (e.g. istanbul.json) + } + else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hfChanges[1][topic] === undefined) { + throw new Error(`Topic ${topic} not defined`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hfChanges[1][topic][name] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1][topic][name].v; + } + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return BigInt(value !== null && value !== void 0 ? value : 0); + } + /** + * Returns a parameter corresponding to an EIP + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param eip Number of the EIP + * @returns The value requested or `undefined` if not found + */ + // eslint-disable-next-line class-methods-use-this + paramByEIP(topic, name, eip) { + if (!(eip in index_js_1.EIPs)) { + throw new Error(`${eip} not supported`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const eipParams = index_js_1.EIPs[eip]; + if (!(topic in eipParams)) { + throw new Error(`Topic ${topic} not defined`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (eipParams[topic][name] === undefined) { + return undefined; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + const value = eipParams[topic][name].v; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return BigInt(value); + } + /** + * Returns a parameter for the hardfork active on block number or + * optional provided total difficulty (Merge HF) + * @param topic Parameter topic + * @param name Parameter name + * @param blockNumber Block number + * @param td Total difficulty + * * @returns The value requested or `BigInt(0)` if not found + */ + paramByBlock(topic, name, blockNumber, td, timestamp) { + const hardfork = this.getHardforkByBlockNumber(blockNumber, td, timestamp); + return this.paramByHardfork(topic, name, hardfork); + } + /** + * Checks if an EIP is activated by either being included in the EIPs + * manually passed in with the {@link CommonOpts.eips} or in a + * hardfork currently being active + * + * Note: this method only works for EIPs being supported + * by the {@link CommonOpts.eips} constructor option + * @param eip + */ + isActivatedEIP(eip) { + if (this.eips().includes(eip)) { + return true; + } + for (const hfChanges of this.HARDFORK_CHANGES) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const hf = hfChanges[1]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument + if (this.gteHardfork(hf.name) && 'eips' in hf) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hf.eips.includes(eip)) { + return true; + } + } + } + return false; + } + /** + * Checks if set or provided hardfork is active on block number + * @param hardfork Hardfork name or null (for HF set) + * @param blockNumber + * @returns True if HF is active on block number + */ + hardforkIsActiveOnBlock( + // eslint-disable-next-line @typescript-eslint/ban-types + _hardfork, _blockNumber) { + const blockNumber = (0, utils_js_1.toType)(_blockNumber, types_js_1.TypeOutput.BigInt); + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const hfBlock = this.hardforkBlock(hardfork); + if (typeof hfBlock === 'bigint' && hfBlock !== BigInt(0) && blockNumber >= hfBlock) { + return true; + } + return false; + } + /** + * Alias to hardforkIsActiveOnBlock when hardfork is set + * @param blockNumber + * @returns True if HF is active on block number + */ + activeOnBlock(blockNumber) { + // eslint-disable-next-line no-null/no-null + return this.hardforkIsActiveOnBlock(null, blockNumber); + } + /** + * Sequence based check if given or set HF1 is greater than or equal HF2 + * @param hardfork1 Hardfork name or null (if set) + * @param hardfork2 Hardfork name + * @param opts Hardfork options + * @returns True if HF1 gte HF2 + */ + hardforkGteHardfork( + // eslint-disable-next-line @typescript-eslint/ban-types + _hardfork1, hardfork2) { + const hardfork1 = _hardfork1 !== null && _hardfork1 !== void 0 ? _hardfork1 : this._hardfork; + const hardforks = this.hardforks(); + let posHf1 = -1; + let posHf2 = -1; + let index = 0; + for (const hf of hardforks) { + if (hf.name === hardfork1) + posHf1 = index; + if (hf.name === hardfork2) + posHf2 = index; + index += 1; + } + return posHf1 >= posHf2 && posHf2 !== -1; + } + /** + * Alias to hardforkGteHardfork when hardfork is set + * @param hardfork Hardfork name + * @returns True if hardfork set is greater than hardfork provided + */ + gteHardfork(hardfork) { + // eslint-disable-next-line no-null/no-null + return this.hardforkGteHardfork(null, hardfork); + } + /** + * Returns the hardfork change block for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if unscheduled + */ + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkBlock(_hardfork) { + var _a; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const block = (_a = this._getHardfork(hardfork)) === null || _a === void 0 ? void 0 : _a.block; + // eslint-disable-next-line no-null/no-null + if (block === undefined || block === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(block); + } + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkTimestamp(_hardfork) { + var _a; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const timestamp = (_a = this._getHardfork(hardfork)) === null || _a === void 0 ? void 0 : _a.timestamp; + // eslint-disable-next-line no-null/no-null + if (timestamp === undefined || timestamp === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(timestamp); + } + /** + * Returns the hardfork change block for eip + * @param eip EIP number + * @returns Block number or null if unscheduled + */ + // eslint-disable-next-line @typescript-eslint/ban-types + eipBlock(eip) { + for (const hfChanges of this.HARDFORK_CHANGES) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const hf = hfChanges[1]; + if ('eips' in hf) { + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + if (hf.eips.includes(eip)) { + return this.hardforkBlock(typeof hfChanges[0] === 'number' ? String(hfChanges[0]) : hfChanges[0]); + } + } + } + // eslint-disable-next-line no-null/no-null + return null; + } + /** + * Returns the hardfork change total difficulty (Merge HF) for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Total difficulty or null if no set + */ + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkTTD(_hardfork) { + var _a; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const ttd = (_a = this._getHardfork(hardfork)) === null || _a === void 0 ? void 0 : _a.ttd; + // eslint-disable-next-line no-null/no-null + if (ttd === undefined || ttd === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(ttd); + } + /** + * True if block number provided is the hardfork (given or set) change block + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isHardforkBlock(_blockNumber, _hardfork) { + const blockNumber = (0, utils_js_1.toType)(_blockNumber, types_js_1.TypeOutput.BigInt); + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const block = this.hardforkBlock(hardfork); + return typeof block === 'bigint' && block !== BigInt(0) ? block === blockNumber : false; + } + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block timestamp, number or null if not available + */ + // eslint-disable-next-line @typescript-eslint/ban-types + nextHardforkBlockOrTimestamp(_hardfork) { + var _a, _b; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const hfs = this.hardforks(); + let hfIndex = hfs.findIndex(hf => hf.name === hardfork); + // If the current hardfork is merge, go one behind as merge hf is not part of these + // calcs even if the merge hf block is set + if (hardfork === enums_js_1.Hardfork.Merge) { + hfIndex -= 1; + } + // Hardfork not found + if (hfIndex < 0) { + // eslint-disable-next-line no-null/no-null + return null; + } + let currHfTimeOrBlock = (_a = hfs[hfIndex].timestamp) !== null && _a !== void 0 ? _a : hfs[hfIndex].block; + currHfTimeOrBlock = + // eslint-disable-next-line no-null/no-null + currHfTimeOrBlock !== null && currHfTimeOrBlock !== undefined + ? Number(currHfTimeOrBlock) + : // eslint-disable-next-line no-null/no-null + null; + const nextHf = hfs.slice(hfIndex + 1).find(hf => { + var _a; + let hfTimeOrBlock = (_a = hf.timestamp) !== null && _a !== void 0 ? _a : hf.block; + hfTimeOrBlock = + // eslint-disable-next-line no-null/no-null + hfTimeOrBlock !== null && hfTimeOrBlock !== undefined + ? Number(hfTimeOrBlock) + : // eslint-disable-next-line no-null/no-null + null; + return (hf.name !== enums_js_1.Hardfork.Merge && + // eslint-disable-next-line no-null/no-null + hfTimeOrBlock !== null && + hfTimeOrBlock !== undefined && + hfTimeOrBlock !== currHfTimeOrBlock); + }); + // If no next hf found with valid block or timestamp return null + if (nextHf === undefined) { + // eslint-disable-next-line no-null/no-null + return null; + } + const nextHfBlock = (_b = nextHf.timestamp) !== null && _b !== void 0 ? _b : nextHf.block; + // eslint-disable-next-line no-null/no-null + if (nextHfBlock === null || nextHfBlock === undefined) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(nextHfBlock); + } + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if not available + * @deprecated + */ + // eslint-disable-next-line @typescript-eslint/ban-types + nextHardforkBlock(_hardfork) { + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + let hfBlock = this.hardforkBlock(hardfork); + // If this is a merge hardfork with block not set, then we fallback to previous hardfork + // to find the nextHardforkBlock + // eslint-disable-next-line no-null/no-null + if (hfBlock === null && hardfork === enums_js_1.Hardfork.Merge) { + const hfs = this.hardforks(); + // eslint-disable-next-line no-null/no-null + const mergeIndex = hfs.findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + if (mergeIndex < 0) { + throw Error(`Merge hardfork should have been found`); + } + hfBlock = this.hardforkBlock(hfs[mergeIndex - 1].name); + } + // eslint-disable-next-line no-null/no-null + if (hfBlock === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + // Next fork block number or null if none available + // Logic: if accumulator is still null and on the first occurrence of + // a block greater than the current hfBlock set the accumulator, + // pass on the accumulator as the final result from this time on + // eslint-disable-next-line no-null/no-null, @typescript-eslint/ban-types + const nextHfBlock = this.hardforks().reduce((acc, hf) => { + // We need to ignore the merge block in our next hardfork calc + const block = BigInt( + // eslint-disable-next-line no-null/no-null + hf.block === null || (hf.ttd !== undefined && hf.ttd !== null) ? 0 : hf.block); + // Typescript can't seem to follow that the hfBlock is not null at this point + // eslint-disable-next-line no-null/no-null + return block > hfBlock && acc === null ? block : acc; + // eslint-disable-next-line no-null/no-null + }, null); + return nextHfBlock; + } + /** + * True if block number provided is the hardfork change block following the hardfork given or set + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isNextHardforkBlock(_blockNumber, _hardfork) { + const blockNumber = (0, utils_js_1.toType)(_blockNumber, types_js_1.TypeOutput.BigInt); + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + // eslint-disable-next-line deprecation/deprecation + const nextHardforkBlock = this.nextHardforkBlock(hardfork); + // eslint-disable-next-line no-null/no-null + return nextHardforkBlock === null ? false : nextHardforkBlock === blockNumber; + } + /** + * Internal helper function to calculate a fork hash + * @param hardfork Hardfork name + * @param genesisHash Genesis block hash of the chain + * @returns Fork hash as hex string + */ + _calcForkHash(hardfork, genesisHash) { + let hfUint8Array = new Uint8Array(); + let prevBlockOrTime = 0; + for (const hf of this.hardforks()) { + const { block, timestamp, name } = hf; + // Timestamp to be used for timestamp based hfs even if we may bundle + // block number with them retrospectively + let blockOrTime = timestamp !== null && timestamp !== void 0 ? timestamp : block; + // eslint-disable-next-line no-null/no-null + blockOrTime = blockOrTime !== null ? Number(blockOrTime) : null; + // Skip for chainstart (0), not applied HFs (null) and + // when already applied on same blockOrTime HFs + // and on the merge since forkhash doesn't change on merge hf + if (typeof blockOrTime === 'number' && + blockOrTime !== 0 && + blockOrTime !== prevBlockOrTime && + name !== enums_js_1.Hardfork.Merge) { + const hfBlockUint8Array = (0, web3_utils_1.hexToBytes)(blockOrTime.toString(16).padStart(16, '0')); + hfUint8Array = (0, web3_utils_1.uint8ArrayConcat)(hfUint8Array, hfBlockUint8Array); + prevBlockOrTime = blockOrTime; + } + if (hf.name === hardfork) + break; + } + const inputUint8Array = (0, web3_utils_1.uint8ArrayConcat)(genesisHash, hfUint8Array); + // CRC32 delivers result as signed (negative) 32-bit integer, + // convert to hex string + // eslint-disable-next-line no-bitwise + const forkhash = (0, web3_utils_1.bytesToHex)((0, utils_js_1.intToUint8Array)(crc32Uint8Array(inputUint8Array) >>> 0)); + return forkhash; + } + /** + * Returns an eth/64 compliant fork hash (EIP-2124) + * @param hardfork Hardfork name, optional if HF set + * @param genesisHash Genesis block hash of the chain, optional if already defined and not needed to be calculated + */ + forkHash(_hardfork, genesisHash) { + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const data = this._getHardfork(hardfork); + if ( + // eslint-disable-next-line no-null/no-null + data === null || + // eslint-disable-next-line no-null/no-null + ((data === null || data === void 0 ? void 0 : data.block) === null && (data === null || data === void 0 ? void 0 : data.timestamp) === undefined && (data === null || data === void 0 ? void 0 : data.ttd) === undefined)) { + const msg = 'No fork hash calculation possible for future hardfork'; + throw new Error(msg); + } + // eslint-disable-next-line no-null/no-null + if ((data === null || data === void 0 ? void 0 : data.forkHash) !== null && (data === null || data === void 0 ? void 0 : data.forkHash) !== undefined) { + return data.forkHash; + } + if (!genesisHash) + throw new Error('genesisHash required for forkHash calculation'); + return this._calcForkHash(hardfork, genesisHash); + } + /** + * + * @param forkHash Fork hash as a hex string + * @returns Array with hardfork data (name, block, forkHash) + */ + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkForForkHash(forkHash) { + const resArray = this.hardforks().filter((hf) => hf.forkHash === forkHash); + // eslint-disable-next-line no-null/no-null + return resArray.length >= 1 ? resArray[resArray.length - 1] : null; + } + /** + * Sets any missing forkHashes on the passed-in {@link Common} instance + * @param common The {@link Common} to set the forkHashes for + * @param genesisHash The genesis block hash + */ + setForkHashes(genesisHash) { + var _a; + for (const hf of this.hardforks()) { + const blockOrTime = (_a = hf.timestamp) !== null && _a !== void 0 ? _a : hf.block; + if ( + // eslint-disable-next-line no-null/no-null + (hf.forkHash === null || hf.forkHash === undefined) && + // eslint-disable-next-line no-null/no-null + ((blockOrTime !== null && blockOrTime !== undefined) || + typeof hf.ttd !== 'undefined')) { + hf.forkHash = this.forkHash(hf.name, genesisHash); + } + } + } + /** + * Returns the Genesis parameters of the current chain + * @returns Genesis dictionary + */ + genesis() { + return this._chainParams.genesis; + } + /** + * Returns the hardforks for current chain + * @returns {Array} Array with arrays of hardforks + */ + hardforks() { + return this._chainParams.hardforks; + } + /** + * Returns bootstrap nodes for the current chain + * @returns {Dictionary} Dict with bootstrap nodes + */ + bootstrapNodes() { + return this._chainParams.bootstrapNodes; + } + /** + * Returns DNS networks for the current chain + * @returns {String[]} Array of DNS ENR urls + */ + dnsNetworks() { + return this._chainParams.dnsNetworks; + } + /** + * Returns the hardfork set + * @returns Hardfork name + */ + hardfork() { + return this._hardfork; + } + /** + * Returns the Id of current chain + * @returns chain Id + */ + chainId() { + return BigInt(this._chainParams.chainId); + } + /** + * Returns the name of current chain + * @returns chain name (lower case) + */ + chainName() { + return this._chainParams.name; + } + /** + * Returns the Id of current network + * @returns network Id + */ + networkId() { + return BigInt(this._chainParams.networkId); + } + /** + * Returns the active EIPs + * @returns List of EIPs + */ + eips() { + return this._eips; + } + /** + * Returns the consensus type of the network + * Possible values: "pow"|"poa"|"pos" + * + * Note: This value can update along a Hardfork. + */ + consensusType() { + const hardfork = this.hardfork(); + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus.type; + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value !== null && value !== void 0 ? value : this._chainParams.consensus.type; + } + /** + * Returns the concrete consensus implementation + * algorithm or protocol for the network + * e.g. "ethash" for "pow" consensus type, + * "clique" for "poa" consensus type or + * "casper" for "pos" consensus type. + * + * Note: This value can update along a Hardfork. + */ + consensusAlgorithm() { + const hardfork = this.hardfork(); + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus.algorithm; + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value !== null && value !== void 0 ? value : this._chainParams.consensus.algorithm; + } + /** + * Returns a dictionary with consensus configuration + * parameters based on the consensus algorithm + * + * Expected returns (parameters must be present in + * the respective chain json files): + * + * ethash: empty object + * clique: period, epoch + * casper: empty object + * + * Note: This value can update along a Hardfork. + */ + consensusConfig() { + var _a; + const hardfork = this.hardfork(); + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // The config parameter is named after the respective consensus algorithm + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus[hfChanges[1].consensus.algorithm]; + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return ((_a = value !== null && value !== void 0 ? value : this._chainParams.consensus[this.consensusAlgorithm()]) !== null && _a !== void 0 ? _a : {}); + } + /** + * Returns a deep copy of this {@link Common} instance. + */ + copy() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment + const copy = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + copy.removeAllListeners(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return copy; + } + static _getInitializedChains(customChains) { + const names = {}; + for (const [name, id] of Object.entries(enums_js_1.Chain)) { + names[id] = name.toLowerCase(); + } + const chains = { mainnet: mainnet_js_1.default, goerli: goerli_js_1.default, sepolia: sepolia_js_1.default }; + if (customChains) { + for (const chain of customChains) { + const { name } = chain; + names[chain.chainId.toString()] = name; + chains[name] = chain; + } + } + chains.names = names; + return chains; + } +} +exports.Common = Common; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.js.map new file mode 100644 index 0000000..a83b720 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/common/common.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,oDAAyB;AACzB,2CAAoF;AAEpF,yCAAwC;AACxC,yCAAuE;AACvE,mEAAwC;AACxC,qEAA0C;AAC1C,qEAA0C;AAC1C,8CAAuC;AAEvC,yCAA0D;AAC1D,mDAAmE;AAiBnE,MAAM,EAAE,GAAG,EAAE,eAAe,EAAE,GAAG,gBAAG,CAAC;AAIrC;;;;;;;GAOG;AACH,MAAa,MAAO,SAAQ,yBAAY;IA0LvC,YAAmB,IAAgB;;QAClC,KAAK,EAAE,CAAC;QAtLD,UAAK,GAAa,EAAE,CAAC;QAuL5B,IAAI,CAAC,aAAa,GAAG,MAAA,IAAI,CAAC,YAAY,mCAAI,EAAE,CAAC;QAC7C,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,CAAC,gBAAgB,GAAG,MAAA,IAAI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S,CAAC,IAAI,CAAC,kBAAkB,EAAwB,CAAC,mCAC5E,EAAE,CACF,CAAC;IACH,CAAC;IAED;;OAEG;IACI,IAAI;QACV,0GAA0G;QAC1G,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QAC7E,yGAAyG;QACzG,IAAI,CAAC,kBAAkB,EAAE,CAAC;QAC1B,+DAA+D;QAC/D,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,MAAM,CAAC,qBAAqB,CAAC,YAA4B;QAC/D,MAAM,KAAK,GAAc,EAAE,CAAC;QAC5B,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,gBAAK,CAAC,EAAE;YAC/C,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;SAC/B;QACD,MAAM,MAAM,GAAG,EAAE,OAAO,EAAP,oBAAO,EAAE,MAAM,EAAN,mBAAM,EAAE,OAAO,EAAP,oBAAO,EAAkB,CAAC;QAC5D,IAAI,YAAY,EAAE;YACjB,KAAK,MAAM,KAAK,IAAI,YAAY,EAAE;gBACjC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;gBACvB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC;gBACvC,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;aACrB;SACD;QACD,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;QACrB,OAAO,MAAM,CAAC;IACf,CAAC;CACD;AA9nCD,wBA8nCC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.d.ts new file mode 100644 index 0000000..ab3b26a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.d.ts @@ -0,0 +1,23 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: { + tstore: { + v: number; + d: string; + }; + tload: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.js new file mode 100644 index 0000000..11380a9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-1153", + "number": 1153, + "comment": "Transient Storage", + "url": "https://eips.ethereum.org/EIPS/eip-1153", + "status": "Review", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "tstore": { + "v": 100, + "d": "Base fee of the TSTORE opcode" + }, + "tload": { + "v": 100, + "d": "Base fee of the TLOAD opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=1153.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.js.map new file mode 100644 index 0000000..79f2a16 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1153.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1153.js","sourceRoot":"","sources":["../../../../src/common/eips/1153.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,mBAAmB;IAC9B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,YAAY;IAC/B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,QAAQ,EAAE;YACT,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,+BAA+B;SACpC;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,8BAA8B;SACnC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.d.ts new file mode 100644 index 0000000..4c3aa4e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.d.ts @@ -0,0 +1,27 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: { + baseFeeMaxChangeDenominator: { + v: number; + d: string; + }; + elasticityMultiplier: { + v: number; + d: string; + }; + initialBaseFee: { + v: number; + d: string; + }; + }; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.js new file mode 100644 index 0000000..c0fc3f0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-1559", + "number": 1559, + "comment": "Fee market change for ETH 1.0 chain", + "url": "https://eips.ethereum.org/EIPS/eip-1559", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [2930], + "gasConfig": { + "baseFeeMaxChangeDenominator": { + "v": 8, + "d": "Maximum base fee change denominator" + }, + "elasticityMultiplier": { + "v": 2, + "d": "Maximum block gas target elasticity" + }, + "initialBaseFee": { + "v": 1000000000, + "d": "Initial base fee on first EIP1559 block" + } + }, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=1559.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.js.map new file mode 100644 index 0000000..f858293 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/1559.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1559.js","sourceRoot":"","sources":["../../../../src/common/eips/1559.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,qCAAqC;IAChD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE;QACZ,6BAA6B,EAAE;YAC9B,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,UAAU;YACf,GAAG,EAAE,yCAAyC;SAC9C;KACD;IACD,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.d.ts new file mode 100644 index 0000000..164334f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.d.ts @@ -0,0 +1,26 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + beginsub: { + v: number; + d: string; + }; + returnsub: { + v: number; + d: string; + }; + jumpsub: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.js new file mode 100644 index 0000000..a456d9f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-2315", + "number": 2315, + "comment": "Simple subroutines for the EVM", + "url": "https://eips.ethereum.org/EIPS/eip-2315", + "status": "Draft", + "minimumHardfork": "istanbul", + "gasConfig": {}, + "gasPrices": { + "beginsub": { + "v": 2, + "d": "Base fee of the BEGINSUB opcode" + }, + "returnsub": { + "v": 5, + "d": "Base fee of the RETURNSUB opcode" + }, + "jumpsub": { + "v": 10, + "d": "Base fee of the JUMPSUB opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2315.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.js.map new file mode 100644 index 0000000..b2472cd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2315.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2315.js","sourceRoot":"","sources":["../../../../src/common/eips/2315.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,gCAAgC;IAC3C,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,UAAU;IAC7B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;QACD,WAAW,EAAE;YACZ,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,kCAAkC;SACvC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,gCAAgC;SACrC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.d.ts new file mode 100644 index 0000000..dbd1935 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.d.ts @@ -0,0 +1,50 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + Bls12381G1AddGas: { + v: number; + d: string; + }; + Bls12381G1MulGas: { + v: number; + d: string; + }; + Bls12381G2AddGas: { + v: number; + d: string; + }; + Bls12381G2MulGas: { + v: number; + d: string; + }; + Bls12381PairingBaseGas: { + v: number; + d: string; + }; + Bls12381PairingPerPairGas: { + v: number; + d: string; + }; + Bls12381MapG1Gas: { + v: number; + d: string; + }; + Bls12381MapG2Gas: { + v: number; + d: string; + }; + Bls12381MultiExpGasDiscount: { + v: number[][]; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.js new file mode 100644 index 0000000..aede581 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.js @@ -0,0 +1,181 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-2537", + "number": 2537, + "comment": "BLS12-381 precompiles", + "url": "https://eips.ethereum.org/EIPS/eip-2537", + "status": "Draft", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": { + "Bls12381G1AddGas": { + "v": 600, + "d": "Gas cost of a single BLS12-381 G1 addition precompile-call" + }, + "Bls12381G1MulGas": { + "v": 12000, + "d": "Gas cost of a single BLS12-381 G1 multiplication precompile-call" + }, + "Bls12381G2AddGas": { + "v": 4500, + "d": "Gas cost of a single BLS12-381 G2 addition precompile-call" + }, + "Bls12381G2MulGas": { + "v": 55000, + "d": "Gas cost of a single BLS12-381 G2 multiplication precompile-call" + }, + "Bls12381PairingBaseGas": { + "v": 115000, + "d": "Base gas cost of BLS12-381 pairing check" + }, + "Bls12381PairingPerPairGas": { + "v": 23000, + "d": "Per-pair gas cost of BLS12-381 pairing check" + }, + "Bls12381MapG1Gas": { + "v": 5500, + "d": "Gas cost of BLS12-381 map field element to G1" + }, + "Bls12381MapG2Gas": { + "v": 110000, + "d": "Gas cost of BLS12-381 map field element to G2" + }, + "Bls12381MultiExpGasDiscount": { + "v": [ + [1, 1200], + [2, 888], + [3, 764], + [4, 641], + [5, 594], + [6, 547], + [7, 500], + [8, 453], + [9, 438], + [10, 423], + [11, 408], + [12, 394], + [13, 379], + [14, 364], + [15, 349], + [16, 334], + [17, 330], + [18, 326], + [19, 322], + [20, 318], + [21, 314], + [22, 310], + [23, 306], + [24, 302], + [25, 298], + [26, 294], + [27, 289], + [28, 285], + [29, 281], + [30, 277], + [31, 273], + [32, 269], + [33, 268], + [34, 266], + [35, 265], + [36, 263], + [37, 262], + [38, 260], + [39, 259], + [40, 257], + [41, 256], + [42, 254], + [43, 253], + [44, 251], + [45, 250], + [46, 248], + [47, 247], + [48, 245], + [49, 244], + [50, 242], + [51, 241], + [52, 239], + [53, 238], + [54, 236], + [55, 235], + [56, 233], + [57, 232], + [58, 231], + [59, 229], + [60, 228], + [61, 226], + [62, 225], + [63, 223], + [64, 222], + [65, 221], + [66, 220], + [67, 219], + [68, 219], + [69, 218], + [70, 217], + [71, 216], + [72, 216], + [73, 215], + [74, 214], + [75, 213], + [76, 213], + [77, 212], + [78, 211], + [79, 211], + [80, 210], + [81, 209], + [82, 208], + [83, 208], + [84, 207], + [85, 206], + [86, 205], + [87, 205], + [88, 204], + [89, 203], + [90, 202], + [91, 202], + [92, 201], + [93, 200], + [94, 199], + [95, 199], + [96, 198], + [97, 197], + [98, 196], + [99, 196], + [100, 195], + [101, 194], + [102, 193], + [103, 193], + [104, 192], + [105, 191], + [106, 191], + [107, 190], + [108, 189], + [109, 188], + [110, 188], + [111, 187], + [112, 186], + [113, 185], + [114, 185], + [115, 184], + [116, 183], + [117, 182], + [118, 182], + [119, 181], + [120, 180], + [121, 179], + [122, 179], + [123, 178], + [124, 177], + [125, 176], + [126, 176], + [127, 175], + [128, 174] + ], + "d": "Discount gas costs of calls to the MultiExp precompiles with `k` (point, scalar) pair" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2537.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.js.map new file mode 100644 index 0000000..d55817e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2537.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2537.js","sourceRoot":"","sources":["../../../../src/common/eips/2537.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,uBAAuB;IAClC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,4DAA4D;SACjE;QACD,kBAAkB,EAAE;Y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,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;aACV;YACD,GAAG,EAAE,uFAAuF;SAC5F;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.d.ts new file mode 100644 index 0000000..c06af95 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.d.ts @@ -0,0 +1,18 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + modexpGquaddivisor: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.js new file mode 100644 index 0000000..2c1318e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-2565", + "number": 2565, + "comment": "ModExp gas cost", + "url": "https://eips.ethereum.org/EIPS/eip-2565", + "status": "Final", + "minimumHardfork": "byzantium", + "gasConfig": {}, + "gasPrices": { + "modexpGquaddivisor": { + "v": 3, + "d": "Gquaddivisor from modexp precompile for gas calculation" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2565.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.js.map new file mode 100644 index 0000000..1e6ec90 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2565.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2565.js","sourceRoot":"","sources":["../../../../src/common/eips/2565.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,iBAAiB;IAC5B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,WAAW;IAC9B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,oBAAoB,EAAE;YACrB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,yDAAyD;SAC9D;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.d.ts new file mode 100644 index 0000000..779fc1d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.d.ts @@ -0,0 +1,12 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.js new file mode 100644 index 0000000..8ea4c30 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-2718", + "comment": "Typed Transaction Envelope", + "url": "https://eips.ethereum.org/EIPS/eip-2718", + "status": "Final", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2718.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.js.map new file mode 100644 index 0000000..d41ec6e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2718.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2718.js","sourceRoot":"","sources":["../../../../src/common/eips/2718.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,4BAA4B;IACvC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.d.ts new file mode 100644 index 0000000..f33679c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.d.ts @@ -0,0 +1,85 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + coldsload: { + v: number; + d: string; + }; + coldaccountaccess: { + v: number; + d: string; + }; + warmstorageread: { + v: number; + d: string; + }; + sstoreCleanGasEIP2200: { + v: number; + d: string; + }; + sstoreNoopGasEIP2200: { + v: number; + d: string; + }; + sstoreDirtyGasEIP2200: { + v: number; + d: string; + }; + sstoreInitRefundEIP2200: { + v: number; + d: string; + }; + sstoreCleanRefundEIP2200: { + v: number; + d: string; + }; + call: { + v: number; + d: string; + }; + callcode: { + v: number; + d: string; + }; + delegatecall: { + v: number; + d: string; + }; + staticcall: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + extcodesize: { + v: number; + d: string; + }; + extcodecopy: { + v: number; + d: string; + }; + extcodehash: { + v: number; + d: string; + }; + sload: { + v: number; + d: string; + }; + sstore: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.js new file mode 100644 index 0000000..3c816e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.js @@ -0,0 +1,87 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-2929", + "comment": "Gas cost increases for state access opcodes", + "url": "https://eips.ethereum.org/EIPS/eip-2929", + "status": "Final", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": { + "coldsload": { + "v": 2100, + "d": "Gas cost of the first read of storage from a given location (per transaction)" + }, + "coldaccountaccess": { + "v": 2600, + "d": "Gas cost of the first read of a given address (per transaction)" + }, + "warmstorageread": { + "v": 100, + "d": "Gas cost of reading storage locations which have already loaded 'cold'" + }, + "sstoreCleanGasEIP2200": { + "v": 2900, + "d": "Once per SSTORE operation from clean non-zero to something else" + }, + "sstoreNoopGasEIP2200": { + "v": 100, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "sstoreDirtyGasEIP2200": { + "v": 100, + "d": "Once per SSTORE operation if a dirty value is changed" + }, + "sstoreInitRefundEIP2200": { + "v": 19900, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "sstoreCleanRefundEIP2200": { + "v": 4900, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "call": { + "v": 0, + "d": "Base fee of the CALL opcode" + }, + "callcode": { + "v": 0, + "d": "Base fee of the CALLCODE opcode" + }, + "delegatecall": { + "v": 0, + "d": "Base fee of the DELEGATECALL opcode" + }, + "staticcall": { + "v": 0, + "d": "Base fee of the STATICCALL opcode" + }, + "balance": { + "v": 0, + "d": "Base fee of the BALANCE opcode" + }, + "extcodesize": { + "v": 0, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 0, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "extcodehash": { + "v": 0, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "sload": { + "v": 0, + "d": "Base fee of the SLOAD opcode" + }, + "sstore": { + "v": 0, + "d": "Base fee of the SSTORE opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2929.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.js.map new file mode 100644 index 0000000..75e218c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2929.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2929.js","sourceRoot":"","sources":["../../../../src/common/eips/2929.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,6CAA6C;IACxD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,WAAW,EAAE;YACZ,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+EAA+E;SACpF;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,iBAAiB,EAAE;YAClB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,wEAAwE;SAC7E;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,yBAAyB,EAAE;YAC1B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,oEAAoE;SACzE;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wEAAwE;SAC7E;QACD,MAAM,EAAE;YACP,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,6BAA6B;SAClC;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;QACD,cAAc,EAAE;YACf,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;QACD,YAAY,EAAE;YACb,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,mCAAmC;SACxC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gCAAgC;SACrC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,OAAO,EAAE;YACR,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,8BAA8B;SACnC;QACD,QAAQ,EAAE;YACT,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,+BAA+B;SACpC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.d.ts new file mode 100644 index 0000000..8e1fd43 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.d.ts @@ -0,0 +1,22 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: { + accessListStorageKeyCost: { + v: number; + d: string; + }; + accessListAddressCost: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.js new file mode 100644 index 0000000..2b0d3a0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-2930", + "comment": "Optional access lists", + "url": "https://eips.ethereum.org/EIPS/eip-2930", + "status": "Final", + "minimumHardfork": "istanbul", + "requiredEIPs": [2718, 2929], + "gasConfig": {}, + "gasPrices": { + "accessListStorageKeyCost": { + "v": 1900, + "d": "Gas cost per storage key in an Access List transaction" + }, + "accessListAddressCost": { + "v": 2400, + "d": "Gas cost per storage key in an Access List transaction" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2930.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.js.map new file mode 100644 index 0000000..9730adb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/2930.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2930.js","sourceRoot":"","sources":["../../../../src/common/eips/2930.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,uBAAuB;IAClC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,UAAU;IAC7B,cAAc,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IAC5B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wDAAwD;SAC7D;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wDAAwD;SAC7D;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.d.ts new file mode 100644 index 0000000..442b1db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.d.ts @@ -0,0 +1,26 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + auth: { + v: number; + d: string; + }; + authcall: { + v: number; + d: string; + }; + authcallValueTransfer: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.js new file mode 100644 index 0000000..241b104 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3074", + "number": 3074, + "comment": "AUTH and AUTHCALL opcodes", + "url": "https://eips.ethereum.org/EIPS/eip-3074", + "status": "Review", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": { + "auth": { + "v": 3100, + "d": "Gas cost of the AUTH opcode" + }, + "authcall": { + "v": 0, + "d": "Gas cost of the AUTHCALL opcode" + }, + "authcallValueTransfer": { + "v": 6700, + "d": "Paid for CALL when the value transfer is non-zero" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3074.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.js.map new file mode 100644 index 0000000..999199e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3074.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3074.js","sourceRoot":"","sources":["../../../../src/common/eips/3074.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,2BAA2B;IACtC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,MAAM,EAAE;YACP,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,6BAA6B;SAClC;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,mDAAmD;SACxD;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.d.ts new file mode 100644 index 0000000..8d462ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.d.ts @@ -0,0 +1,18 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + basefee: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.js new file mode 100644 index 0000000..f9f43ec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3198", + "number": 3198, + "comment": "BASEFEE opcode", + "url": "https://eips.ethereum.org/EIPS/eip-3198", + "status": "Final", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": { + "basefee": { + "v": 2, + "d": "Gas cost of the BASEFEE opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3198.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.js.map new file mode 100644 index 0000000..be3cbf0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3198.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3198.js","sourceRoot":"","sources":["../../../../src/common/eips/3198.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,gBAAgB;IAC3B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,SAAS,EAAE;YACV,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gCAAgC;SACrC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.d.ts new file mode 100644 index 0000000..fcd659a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.d.ts @@ -0,0 +1,27 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: { + maxRefundQuotient: { + v: number; + d: string; + }; + }; + gasPrices: { + selfdestructRefund: { + v: number; + d: string; + }; + sstoreClearRefundEIP2200: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.js new file mode 100644 index 0000000..9d881a2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3529", + "comment": "Reduction in refunds", + "url": "https://eips.ethereum.org/EIPS/eip-3529", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [2929], + "gasConfig": { + "maxRefundQuotient": { + "v": 5, + "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" + } + }, + "gasPrices": { + "selfdestructRefund": { + "v": 0, + "d": "Refunded following a selfdestruct operation" + }, + "sstoreClearRefundEIP2200": { + "v": 4800, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3529.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.js.map new file mode 100644 index 0000000..e1f7960 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3529.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3529.js","sourceRoot":"","sources":["../../../../src/common/eips/3529.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,sBAAsB;IACjC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE;QACZ,mBAAmB,EAAE;YACpB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,2FAA2F;SAChG;KACD;IACD,WAAW,EAAE;QACZ,oBAAoB,EAAE;YACrB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,6CAA6C;SAClD;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,4EAA4E;SACjF;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.d.ts new file mode 100644 index 0000000..052b261 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.js new file mode 100644 index 0000000..14c1fd2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3540", + "number": 3540, + "comment": "EVM Object Format (EOF) v1", + "url": "https://eips.ethereum.org/EIPS/eip-3540", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [3541], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3540.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.js.map new file mode 100644 index 0000000..4baa191 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3540.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3540.js","sourceRoot":"","sources":["../../../../src/common/eips/3540.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,4BAA4B;IACvC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.d.ts new file mode 100644 index 0000000..028cbd9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.js new file mode 100644 index 0000000..295aae3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3541", + "comment": "Reject new contracts starting with the 0xEF byte", + "url": "https://eips.ethereum.org/EIPS/eip-3541", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3541.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.js.map new file mode 100644 index 0000000..de9ed79 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3541.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3541.js","sourceRoot":"","sources":["../../../../src/common/eips/3541.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,kDAAkD;IAC7D,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.d.ts new file mode 100644 index 0000000..12cca65 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.d.ts @@ -0,0 +1,18 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.js new file mode 100644 index 0000000..c4724cd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3554", + "comment": "Reduction in refunds", + "url": "Difficulty Bomb Delay to December 1st 2021", + "status": "Final", + "minimumHardfork": "muirGlacier", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 9500000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=3554.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.js.map new file mode 100644 index 0000000..104c78f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3554.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3554.js","sourceRoot":"","sources":["../../../../src/common/eips/3554.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,sBAAsB;IACjC,KAAK,EAAE,4CAA4C;IACnD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,aAAa;IAChC,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.d.ts new file mode 100644 index 0000000..966b01a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.js new file mode 100644 index 0000000..25e841b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3607", + "number": 3607, + "comment": "Reject transactions from senders with deployed code", + "url": "https://eips.ethereum.org/EIPS/eip-3607", + "status": "Final", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3607.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.js.map new file mode 100644 index 0000000..c1ae10d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3607.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3607.js","sourceRoot":"","sources":["../../../../src/common/eips/3607.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,qDAAqD;IAChE,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.d.ts new file mode 100644 index 0000000..052b261 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.js new file mode 100644 index 0000000..b773278 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3651", + "number": 3198, + "comment": "Warm COINBASE", + "url": "https://eips.ethereum.org/EIPS/eip-3651", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [2929], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3651.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.js.map new file mode 100644 index 0000000..ebd4925 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3651.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3651.js","sourceRoot":"","sources":["../../../../src/common/eips/3651.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,eAAe;IAC1B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.d.ts new file mode 100644 index 0000000..052b261 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.js new file mode 100644 index 0000000..dc2fb09 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3670", + "number": 3670, + "comment": "EOF - Code Validation", + "url": "https://eips.ethereum.org/EIPS/eip-3670", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [3540], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3670.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.js.map new file mode 100644 index 0000000..a972865 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3670.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3670.js","sourceRoot":"","sources":["../../../../src/common/eips/3670.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,uBAAuB;IAClC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.d.ts new file mode 100644 index 0000000..966b01a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.js new file mode 100644 index 0000000..e21be29 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3675", + "number": 3675, + "comment": "Upgrade consensus to Proof-of-Stake", + "url": "https://eips.ethereum.org/EIPS/eip-3675", + "status": "Final", + "minimumHardfork": "london", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3675.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.js.map new file mode 100644 index 0000000..20ee3be --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3675.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3675.js","sourceRoot":"","sources":["../../../../src/common/eips/3675.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,qCAAqC;IAChD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.d.ts new file mode 100644 index 0000000..f499fd5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: { + push0: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.js new file mode 100644 index 0000000..fc10042 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3855", + "number": 3855, + "comment": "PUSH0 instruction", + "url": "https://eips.ethereum.org/EIPS/eip-3855", + "status": "Review", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "push0": { + "v": 2, + "d": "Base fee of the PUSH0 opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3855.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.js.map new file mode 100644 index 0000000..7409a34 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3855.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3855.js","sourceRoot":"","sources":["../../../../src/common/eips/3855.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,mBAAmB;IAC9B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,YAAY;IAC/B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,OAAO,EAAE;YACR,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,8BAA8B;SACnC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.d.ts new file mode 100644 index 0000000..ae55f5c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.d.ts @@ -0,0 +1,24 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: { + initCodeWordCost: { + v: number; + d: string; + }; + }; + vm: { + maxInitCodeSize: { + v: number; + d: string; + }; + }; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.js new file mode 100644 index 0000000..df54df6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-3860", + "number": 3860, + "comment": "Limit and meter initcode", + "url": "https://eips.ethereum.org/EIPS/eip-3860", + "status": "Review", + "minimumHardfork": "spuriousDragon", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "initCodeWordCost": { + "v": 2, + "d": "Gas to pay for each word (32 bytes) of initcode when creating a contract" + } + }, + "vm": { + "maxInitCodeSize": { + "v": 49152, + "d": "Maximum length of initialization code when creating a contract" + } + }, + "pow": {} +}; +//# sourceMappingURL=3860.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.js.map new file mode 100644 index 0000000..7c768db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/3860.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3860.js","sourceRoot":"","sources":["../../../../src/common/eips/3860.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,0BAA0B;IACrC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,gBAAgB;IACnC,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,0EAA0E;SAC/E;KACD;IACD,IAAI,EAAE;QACL,iBAAiB,EAAE;YAClB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,gEAAgE;SACrE;KACD;IACD,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.d.ts new file mode 100644 index 0000000..8e7d251 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.d.ts @@ -0,0 +1,18 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.js new file mode 100644 index 0000000..a5d525a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-4345", + "number": 4345, + "comment": "Difficulty Bomb Delay to June 2022", + "url": "https://eips.ethereum.org/EIPS/eip-4345", + "status": "Final", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 10700000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=4345.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.js.map new file mode 100644 index 0000000..3b80e87 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4345.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4345.js","sourceRoot":"","sources":["../../../../src/common/eips/4345.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,oCAAoC;IAC/C,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,QAAQ;YACb,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.d.ts new file mode 100644 index 0000000..966b01a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.js new file mode 100644 index 0000000..b015784 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-4399", + "number": 4399, + "comment": "Supplant DIFFICULTY opcode with PREVRANDAO", + "url": "https://eips.ethereum.org/EIPS/eip-4399", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=4399.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.js.map new file mode 100644 index 0000000..a0875e6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4399.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4399.js","sourceRoot":"","sources":["../../../../src/common/eips/4399.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,4CAA4C;IACvD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.d.ts new file mode 100644 index 0000000..8722632 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.d.ts @@ -0,0 +1,58 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: { + dataGasPerBlob: { + v: number; + d: string; + }; + targetDataGasPerBlock: { + v: number; + d: string; + }; + maxDataGasPerBlock: { + v: number; + d: string; + }; + dataGasPriceUpdateFraction: { + v: number; + d: string; + }; + }; + gasPrices: { + simpleGasPerBlob: { + v: number; + d: string; + }; + minDataGasPrice: { + v: number; + d: string; + }; + kzgPointEvaluationGasPrecompilePrice: { + v: number; + d: string; + }; + datahash: { + v: number; + d: string; + }; + }; + sharding: { + blobCommitmentVersionKzg: { + v: number; + d: string; + }; + fieldElementsPerBlob: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.js new file mode 100644 index 0000000..4fb265f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-4844", + "number": 4844, + "comment": "Shard Blob Transactions", + "url": "https://eips.ethereum.org/EIPS/eip-4844", + "status": "Draft", + "minimumHardfork": "merge", + "requiredEIPs": [1559, 2718, 2930, 4895], + "gasConfig": { + "dataGasPerBlob": { + "v": 131072, + "d": "The base fee for data gas per blob" + }, + "targetDataGasPerBlock": { + "v": 262144, + "d": "The target data gas consumed per block" + }, + "maxDataGasPerBlock": { + "v": 524288, + "d": "The max data gas allowable per block" + }, + "dataGasPriceUpdateFraction": { + "v": 2225652, + "d": "The denominator used in the exponential when calculating a data gas price" + } + }, + "gasPrices": { + "simpleGasPerBlob": { + "v": 12000, + "d": "The basic gas fee for each blob" + }, + "minDataGasPrice": { + "v": 1, + "d": "The minimum fee per data gas" + }, + "kzgPointEvaluationGasPrecompilePrice": { + "v": 50000, + "d": "The fee associated with the point evaluation precompile" + }, + "datahash": { + "v": 3, + "d": "Base fee of the DATAHASH opcode" + } + }, + "sharding": { + "blobCommitmentVersionKzg": { + "v": 1, + "d": "The number indicated a versioned hash is a KZG commitment" + }, + "fieldElementsPerBlob": { + "v": 4096, + "d": "The number of field elements allowed per blob" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=4844.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.js.map new file mode 100644 index 0000000..2b373b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4844.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4844.js","sourceRoot":"","sources":["../../../../src/common/eips/4844.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,yBAAyB;IACpC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,OAAO;IAC1B,cAAc,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IACxC,WAAW,EAAE;QACZ,gBAAgB,EAAE;YACjB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,oCAAoC;SACzC;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,wCAAwC;SAC7C;QACD,oBAAoB,EAAE;YACrB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,sCAAsC;SAC3C;QACD,4BAA4B,EAAE;YAC7B,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,2EAA2E;SAChF;KACD;IACD,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,iCAAiC;SACtC;QACD,iBAAiB,EAAE;YAClB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,8BAA8B;SACnC;QACD,sCAAsC,EAAE;YACvC,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,yDAAyD;SAC9D;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;KACD;IACD,UAAU,EAAE;QACX,0BAA0B,EAAE;YAC3B,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,2DAA2D;SAChE;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+CAA+C;SACpD;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.d.ts new file mode 100644 index 0000000..966b01a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.js new file mode 100644 index 0000000..ad9a396 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-4895", + "number": 4895, + "comment": "Beacon chain push withdrawals as operations", + "url": "https://eips.ethereum.org/EIPS/eip-4895", + "status": "Review", + "minimumHardfork": "merge", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=4895.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.js.map new file mode 100644 index 0000000..e569eb0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/4895.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4895.js","sourceRoot":"","sources":["../../../../src/common/eips/4895.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,6CAA6C;IACxD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,OAAO;IAC1B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.d.ts new file mode 100644 index 0000000..8e7d251 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.d.ts @@ -0,0 +1,18 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.js new file mode 100644 index 0000000..059d3f5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "EIP-5133", + "number": 5133, + "comment": "Delaying Difficulty Bomb to mid-September 2022", + "url": "https://eips.ethereum.org/EIPS/eip-5133", + "status": "Draft", + "minimumHardfork": "grayGlacier", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 11400000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=5133.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.js.map new file mode 100644 index 0000000..074b2a3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/5133.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5133.js","sourceRoot":"","sources":["../../../../src/common/eips/5133.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,gDAAgD;IAC3D,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,aAAa;IAChC,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,QAAQ;YACb,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.d.ts new file mode 100644 index 0000000..537323e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.d.ts @@ -0,0 +1,3 @@ +export declare const EIPs: { + [key: number]: any; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.js new file mode 100644 index 0000000..7475c6c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.js @@ -0,0 +1,69 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EIPs = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const _1153_js_1 = __importDefault(require("./1153.js")); +const _1559_js_1 = __importDefault(require("./1559.js")); +const _2315_js_1 = __importDefault(require("./2315.js")); +const _2537_js_1 = __importDefault(require("./2537.js")); +const _2565_js_1 = __importDefault(require("./2565.js")); +const _2718_js_1 = __importDefault(require("./2718.js")); +const _2929_js_1 = __importDefault(require("./2929.js")); +const _2930_js_1 = __importDefault(require("./2930.js")); +const _3198_js_1 = __importDefault(require("./3198.js")); +const _3529_js_1 = __importDefault(require("./3529.js")); +const _3540_js_1 = __importDefault(require("./3540.js")); +const _3541_js_1 = __importDefault(require("./3541.js")); +const _3554_js_1 = __importDefault(require("./3554.js")); +const _3607_js_1 = __importDefault(require("./3607.js")); +const _3651_js_1 = __importDefault(require("./3651.js")); +const _3670_js_1 = __importDefault(require("./3670.js")); +const _3675_js_1 = __importDefault(require("./3675.js")); +const _3855_js_1 = __importDefault(require("./3855.js")); +const _3860_js_1 = __importDefault(require("./3860.js")); +const _4345_js_1 = __importDefault(require("./4345.js")); +const _4399_js_1 = __importDefault(require("./4399.js")); +const _5133_js_1 = __importDefault(require("./5133.js")); +exports.EIPs = { + 1153: _1153_js_1.default, + 1559: _1559_js_1.default, + 2315: _2315_js_1.default, + 2537: _2537_js_1.default, + 2565: _2565_js_1.default, + 2718: _2718_js_1.default, + 2929: _2929_js_1.default, + 2930: _2930_js_1.default, + 3198: _3198_js_1.default, + 3529: _3529_js_1.default, + 3540: _3540_js_1.default, + 3541: _3541_js_1.default, + 3554: _3554_js_1.default, + 3607: _3607_js_1.default, + 3651: _3651_js_1.default, + 3670: _3670_js_1.default, + 3675: _3675_js_1.default, + 3855: _3855_js_1.default, + 3860: _3860_js_1.default, + 4345: _4345_js_1.default, + 4399: _4399_js_1.default, + 5133: _5133_js_1.default, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.js.map new file mode 100644 index 0000000..321788c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/eips/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/eips/index.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAC9B,yDAA8B;AAEjB,QAAA,IAAI,GAA2B;IAC3C,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;IACX,IAAI,EAAE,kBAAK;CACX,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.d.ts new file mode 100644 index 0000000..a752ae9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.d.ts @@ -0,0 +1,79 @@ +export declare enum Chain { + Mainnet = 1, + Goerli = 5, + Sepolia = 11155111 +} +export declare enum Hardfork { + Chainstart = "chainstart", + Homestead = "homestead", + Dao = "dao", + TangerineWhistle = "tangerineWhistle", + SpuriousDragon = "spuriousDragon", + Byzantium = "byzantium", + Constantinople = "constantinople", + Petersburg = "petersburg", + Istanbul = "istanbul", + MuirGlacier = "muirGlacier", + Berlin = "berlin", + London = "london", + ArrowGlacier = "arrowGlacier", + GrayGlacier = "grayGlacier", + MergeForkIdTransition = "mergeForkIdTransition", + Merge = "merge", + Shanghai = "shanghai", + ShardingForkDev = "shardingFork" +} +export declare enum ConsensusType { + ProofOfStake = "pos", + ProofOfWork = "pow", + ProofOfAuthority = "poa" +} +export declare enum ConsensusAlgorithm { + Ethash = "ethash", + Clique = "clique", + Casper = "casper" +} +export declare enum CustomChain { + /** + * Polygon (Matic) Mainnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + PolygonMainnet = "polygon-mainnet", + /** + * Polygon (Matic) Mumbai Testnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + PolygonMumbai = "polygon-mumbai", + /** + * Arbitrum Rinkeby Testnet + * + * - [Documentation](https://developer.offchainlabs.com/docs/public_testnet) + */ + ArbitrumRinkebyTestnet = "arbitrum-rinkeby-testnet", + /** + * Arbitrum One - mainnet for Arbitrum roll-up + * + * - [Documentation](https://developer.offchainlabs.com/public-chains) + */ + ArbitrumOne = "arbitrum-one", + /** + * xDai EVM sidechain with a native stable token + * + * - [Documentation](https://www.xdaichain.com/) + */ + xDaiChain = "x-dai-chain", + /** + * Optimistic Kovan - testnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + OptimisticKovan = "optimistic-kovan", + /** + * Optimistic Ethereum - mainnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + OptimisticEthereum = "optimistic-ethereum" +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.js new file mode 100644 index 0000000..46a96cb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CustomChain = exports.ConsensusAlgorithm = exports.ConsensusType = exports.Hardfork = exports.Chain = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var Chain; +(function (Chain) { + Chain[Chain["Mainnet"] = 1] = "Mainnet"; + Chain[Chain["Goerli"] = 5] = "Goerli"; + Chain[Chain["Sepolia"] = 11155111] = "Sepolia"; +})(Chain = exports.Chain || (exports.Chain = {})); +var Hardfork; +(function (Hardfork) { + Hardfork["Chainstart"] = "chainstart"; + Hardfork["Homestead"] = "homestead"; + Hardfork["Dao"] = "dao"; + Hardfork["TangerineWhistle"] = "tangerineWhistle"; + Hardfork["SpuriousDragon"] = "spuriousDragon"; + Hardfork["Byzantium"] = "byzantium"; + Hardfork["Constantinople"] = "constantinople"; + Hardfork["Petersburg"] = "petersburg"; + Hardfork["Istanbul"] = "istanbul"; + Hardfork["MuirGlacier"] = "muirGlacier"; + Hardfork["Berlin"] = "berlin"; + Hardfork["London"] = "london"; + Hardfork["ArrowGlacier"] = "arrowGlacier"; + Hardfork["GrayGlacier"] = "grayGlacier"; + Hardfork["MergeForkIdTransition"] = "mergeForkIdTransition"; + Hardfork["Merge"] = "merge"; + Hardfork["Shanghai"] = "shanghai"; + Hardfork["ShardingForkDev"] = "shardingFork"; +})(Hardfork = exports.Hardfork || (exports.Hardfork = {})); +var ConsensusType; +(function (ConsensusType) { + ConsensusType["ProofOfStake"] = "pos"; + ConsensusType["ProofOfWork"] = "pow"; + ConsensusType["ProofOfAuthority"] = "poa"; +})(ConsensusType = exports.ConsensusType || (exports.ConsensusType = {})); +var ConsensusAlgorithm; +(function (ConsensusAlgorithm) { + ConsensusAlgorithm["Ethash"] = "ethash"; + ConsensusAlgorithm["Clique"] = "clique"; + ConsensusAlgorithm["Casper"] = "casper"; +})(ConsensusAlgorithm = exports.ConsensusAlgorithm || (exports.ConsensusAlgorithm = {})); +var CustomChain; +(function (CustomChain) { + /** + * Polygon (Matic) Mainnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + CustomChain["PolygonMainnet"] = "polygon-mainnet"; + /** + * Polygon (Matic) Mumbai Testnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + CustomChain["PolygonMumbai"] = "polygon-mumbai"; + /** + * Arbitrum Rinkeby Testnet + * + * - [Documentation](https://developer.offchainlabs.com/docs/public_testnet) + */ + CustomChain["ArbitrumRinkebyTestnet"] = "arbitrum-rinkeby-testnet"; + /** + * Arbitrum One - mainnet for Arbitrum roll-up + * + * - [Documentation](https://developer.offchainlabs.com/public-chains) + */ + CustomChain["ArbitrumOne"] = "arbitrum-one"; + /** + * xDai EVM sidechain with a native stable token + * + * - [Documentation](https://www.xdaichain.com/) + */ + CustomChain["xDaiChain"] = "x-dai-chain"; + /** + * Optimistic Kovan - testnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + CustomChain["OptimisticKovan"] = "optimistic-kovan"; + /** + * Optimistic Ethereum - mainnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + CustomChain["OptimisticEthereum"] = "optimistic-ethereum"; +})(CustomChain = exports.CustomChain || (exports.CustomChain = {})); +//# sourceMappingURL=enums.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.js.map new file mode 100644 index 0000000..f122699 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/enums.js.map @@ -0,0 +1 @@ +{"version":3,"file":"enums.js","sourceRoot":"","sources":["../../../src/common/enums.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,IAAY,KAIX;AAJD,WAAY,KAAK;IAChB,uCAAW,CAAA;IACX,qCAAU,CAAA;IACV,8CAAkB,CAAA;AACnB,CAAC,EAJW,KAAK,GAAL,aAAK,KAAL,aAAK,QAIhB;AAED,IAAY,QAmBX;AAnBD,WAAY,QAAQ;IACnB,qCAAyB,CAAA;IACzB,mCAAuB,CAAA;IACvB,uBAAW,CAAA;IACX,iDAAqC,CAAA;IACrC,6CAAiC,CAAA;IACjC,mCAAuB,CAAA;IACvB,6CAAiC,CAAA;IACjC,qCAAyB,CAAA;IACzB,iCAAqB,CAAA;IACrB,uCAA2B,CAAA;IAC3B,6BAAiB,CAAA;IACjB,6BAAiB,CAAA;IACjB,yCAA6B,CAAA;IAC7B,uCAA2B,CAAA;IAC3B,2DAA+C,CAAA;IAC/C,2BAAe,CAAA;IACf,iCAAqB,CAAA;IACrB,4CAAgC,CAAA;AACjC,CAAC,EAnBW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAmBnB;AAED,IAAY,aAIX;AAJD,WAAY,aAAa;IACxB,qCAAoB,CAAA;IACpB,oCAAmB,CAAA;IACnB,yCAAwB,CAAA;AACzB,CAAC,EAJW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAIxB;AAED,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC7B,uCAAiB,CAAA;IACjB,uCAAiB,CAAA;IACjB,uCAAiB,CAAA;AAClB,CAAC,EAJW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAI7B;AAED,IAAY,WAiDX;AAjDD,WAAY,WAAW;IACtB;;;;OAIG;IACH,iDAAkC,CAAA;IAElC;;;;OAIG;IACH,+CAAgC,CAAA;IAEhC;;;;OAIG;IACH,kEAAmD,CAAA;IAEnD;;;;OAIG;IACH,2CAA4B,CAAA;IAE5B;;;;OAIG;IACH,wCAAyB,CAAA;IAEzB;;;;OAIG;IACH,mDAAoC,CAAA;IAEpC;;;;OAIG;IACH,yDAA0C,CAAA;AAC3C,CAAC,EAjDW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAiDtB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.d.ts new file mode 100644 index 0000000..3c83d0c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.d.ts @@ -0,0 +1,12 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.js new file mode 100644 index 0000000..b76e1b8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "arrowGlacier", + "comment": "HF to delay the difficulty bomb", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/arrow-glacier.md", + "status": "Final", + "eips": [4345], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=arrowGlacier.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.js.map new file mode 100644 index 0000000..88b6dfa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/arrowGlacier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arrowGlacier.js","sourceRoot":"","sources":["../../../../src/common/hardforks/arrowGlacier.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,cAAc;IACtB,SAAS,EAAE,iCAAiC;IAC5C,KAAK,EAAE,4GAA4G;IACnH,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,CAAC;IACd,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.d.ts new file mode 100644 index 0000000..fb32424 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.d.ts @@ -0,0 +1,8 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.js new file mode 100644 index 0000000..aa2c677 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "berlin", + "comment": "HF targeted for July 2020 following the Muir Glacier HF", + "url": "https://eips.ethereum.org/EIPS/eip-2070", + "status": "Final", + "eips": [2565, 2929, 2718, 2930] +}; +//# sourceMappingURL=berlin.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.js.map new file mode 100644 index 0000000..4a700e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/berlin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"berlin.js","sourceRoot":"","sources":["../../../../src/common/hardforks/berlin.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,QAAQ;IAChB,SAAS,EAAE,yDAAyD;IACpE,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;CAChC,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.d.ts new file mode 100644 index 0000000..8b568bc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.d.ts @@ -0,0 +1,57 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + modexpGquaddivisor: { + v: number; + d: string; + }; + ecAdd: { + v: number; + d: string; + }; + ecMul: { + v: number; + d: string; + }; + ecPairing: { + v: number; + d: string; + }; + ecPairingWord: { + v: number; + d: string; + }; + revert: { + v: number; + d: string; + }; + staticcall: { + v: number; + d: string; + }; + returndatasize: { + v: number; + d: string; + }; + returndatacopy: { + v: number; + d: string; + }; + }; + vm: {}; + pow: { + minerReward: { + v: string; + d: string; + }; + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.js new file mode 100644 index 0000000..eae7c65 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "byzantium", + "comment": "Hardfork with new precompiles, instructions and other protocol changes", + "url": "https://eips.ethereum.org/EIPS/eip-609", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "modexpGquaddivisor": { + "v": 20, + "d": "Gquaddivisor from modexp precompile for gas calculation" + }, + "ecAdd": { + "v": 500, + "d": "Gas costs for curve addition precompile" + }, + "ecMul": { + "v": 40000, + "d": "Gas costs for curve multiplication precompile" + }, + "ecPairing": { + "v": 100000, + "d": "Base gas costs for curve pairing precompile" + }, + "ecPairingWord": { + "v": 80000, + "d": "Gas costs regarding curve pairing precompile input length" + }, + "revert": { + "v": 0, + "d": "Base fee of the REVERT opcode" + }, + "staticcall": { + "v": 700, + "d": "Base fee of the STATICCALL opcode" + }, + "returndatasize": { + "v": 2, + "d": "Base fee of the RETURNDATASIZE opcode" + }, + "returndatacopy": { + "v": 3, + "d": "Base fee of the RETURNDATACOPY opcode" + } + }, + "vm": {}, + "pow": { + "minerReward": { + "v": "3000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 3000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=byzantium.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.js.map new file mode 100644 index 0000000..84fc22e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/byzantium.js.map @@ -0,0 +1 @@ +{"version":3,"file":"byzantium.js","sourceRoot":"","sources":["../../../../src/common/hardforks/byzantium.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,WAAW;IACnB,SAAS,EAAE,wEAAwE;IACnF,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,oBAAoB,EAAE;YACrB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,yDAAyD;SAC9D;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,yCAAyC;SAC9C;QACD,OAAO,EAAE;YACR,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,+CAA+C;SACpD;QACD,WAAW,EAAE;YACZ,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,6CAA6C;SAClD;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,2DAA2D;SAChE;QACD,QAAQ,EAAE;YACT,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,+BAA+B;SACpC;QACD,YAAY,EAAE;YACb,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,mCAAmC;SACxC;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,uCAAuC;SAC5C;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,uCAAuC;SAC5C;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,aAAa,EAAE;YACd,GAAG,EAAE,qBAAqB;YAC1B,GAAG,EAAE,oDAAoD;SACzD;QACD,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.d.ts new file mode 100644 index 0000000..0c226da --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.d.ts @@ -0,0 +1,439 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: { + minGasLimit: { + v: number; + d: string; + }; + gasLimitBoundDivisor: { + v: number; + d: string; + }; + maxRefundQuotient: { + v: number; + d: string; + }; + }; + gasPrices: { + base: { + v: number; + d: string; + }; + tierStep: { + v: number[]; + d: string; + }; + exp: { + v: number; + d: string; + }; + expByte: { + v: number; + d: string; + }; + sha3: { + v: number; + d: string; + }; + sha3Word: { + v: number; + d: string; + }; + sload: { + v: number; + d: string; + }; + sstoreSet: { + v: number; + d: string; + }; + sstoreReset: { + v: number; + d: string; + }; + sstoreRefund: { + v: number; + d: string; + }; + jumpdest: { + v: number; + d: string; + }; + log: { + v: number; + d: string; + }; + logData: { + v: number; + d: string; + }; + logTopic: { + v: number; + d: string; + }; + create: { + v: number; + d: string; + }; + call: { + v: number; + d: string; + }; + callStipend: { + v: number; + d: string; + }; + callValueTransfer: { + v: number; + d: string; + }; + callNewAccount: { + v: number; + d: string; + }; + selfdestructRefund: { + v: number; + d: string; + }; + memory: { + v: number; + d: string; + }; + quadCoeffDiv: { + v: number; + d: string; + }; + createData: { + v: number; + d: string; + }; + tx: { + v: number; + d: string; + }; + txCreation: { + v: number; + d: string; + }; + txDataZero: { + v: number; + d: string; + }; + txDataNonZero: { + v: number; + d: string; + }; + copy: { + v: number; + d: string; + }; + ecRecover: { + v: number; + d: string; + }; + sha256: { + v: number; + d: string; + }; + sha256Word: { + v: number; + d: string; + }; + ripemd160: { + v: number; + d: string; + }; + ripemd160Word: { + v: number; + d: string; + }; + identity: { + v: number; + d: string; + }; + identityWord: { + v: number; + d: string; + }; + stop: { + v: number; + d: string; + }; + add: { + v: number; + d: string; + }; + mul: { + v: number; + d: string; + }; + sub: { + v: number; + d: string; + }; + div: { + v: number; + d: string; + }; + sdiv: { + v: number; + d: string; + }; + mod: { + v: number; + d: string; + }; + smod: { + v: number; + d: string; + }; + addmod: { + v: number; + d: string; + }; + mulmod: { + v: number; + d: string; + }; + signextend: { + v: number; + d: string; + }; + lt: { + v: number; + d: string; + }; + gt: { + v: number; + d: string; + }; + slt: { + v: number; + d: string; + }; + sgt: { + v: number; + d: string; + }; + eq: { + v: number; + d: string; + }; + iszero: { + v: number; + d: string; + }; + and: { + v: number; + d: string; + }; + or: { + v: number; + d: string; + }; + xor: { + v: number; + d: string; + }; + not: { + v: number; + d: string; + }; + byte: { + v: number; + d: string; + }; + address: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + origin: { + v: number; + d: string; + }; + caller: { + v: number; + d: string; + }; + callvalue: { + v: number; + d: string; + }; + calldataload: { + v: number; + d: string; + }; + calldatasize: { + v: number; + d: string; + }; + calldatacopy: { + v: number; + d: string; + }; + codesize: { + v: number; + d: string; + }; + codecopy: { + v: number; + d: string; + }; + gasprice: { + v: number; + d: string; + }; + extcodesize: { + v: number; + d: string; + }; + extcodecopy: { + v: number; + d: string; + }; + blockhash: { + v: number; + d: string; + }; + coinbase: { + v: number; + d: string; + }; + timestamp: { + v: number; + d: string; + }; + number: { + v: number; + d: string; + }; + difficulty: { + v: number; + d: string; + }; + gaslimit: { + v: number; + d: string; + }; + pop: { + v: number; + d: string; + }; + mload: { + v: number; + d: string; + }; + mstore: { + v: number; + d: string; + }; + mstore8: { + v: number; + d: string; + }; + sstore: { + v: number; + d: string; + }; + jump: { + v: number; + d: string; + }; + jumpi: { + v: number; + d: string; + }; + pc: { + v: number; + d: string; + }; + msize: { + v: number; + d: string; + }; + gas: { + v: number; + d: string; + }; + push: { + v: number; + d: string; + }; + dup: { + v: number; + d: string; + }; + swap: { + v: number; + d: string; + }; + callcode: { + v: number; + d: string; + }; + return: { + v: number; + d: string; + }; + invalid: { + v: number; + d: string; + }; + selfdestruct: { + v: number; + d: string; + }; + }; + vm: { + stackLimit: { + v: number; + d: string; + }; + callCreateDepth: { + v: number; + d: string; + }; + maxExtraDataSize: { + v: number; + d: string; + }; + }; + pow: { + minimumDifficulty: { + v: number; + d: string; + }; + difficultyBoundDivisor: { + v: number; + d: string; + }; + durationLimit: { + v: number; + d: string; + }; + epochDuration: { + v: number; + d: string; + }; + timebombPeriod: { + v: number; + d: string; + }; + minerReward: { + v: string; + d: string; + }; + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.js new file mode 100644 index 0000000..0d0b35b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.js @@ -0,0 +1,441 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "chainstart", + "comment": "Start of the Ethereum main chain", + "url": "", + "status": "", + "gasConfig": { + "minGasLimit": { + "v": 5000, + "d": "Minimum the gas limit may ever be" + }, + "gasLimitBoundDivisor": { + "v": 1024, + "d": "The bound divisor of the gas limit, used in update calculations" + }, + "maxRefundQuotient": { + "v": 2, + "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" + } + }, + "gasPrices": { + "base": { + "v": 2, + "d": "Gas base cost, used e.g. for ChainID opcode (Istanbul)" + }, + "tierStep": { + "v": [0, 2, 3, 5, 8, 10, 20], + "d": "Once per operation, for a selection of them" + }, + "exp": { + "v": 10, + "d": "Base fee of the EXP opcode" + }, + "expByte": { + "v": 10, + "d": "Times ceil(log256(exponent)) for the EXP instruction" + }, + "sha3": { + "v": 30, + "d": "Base fee of the SHA3 opcode" + }, + "sha3Word": { + "v": 6, + "d": "Once per word of the SHA3 operation's data" + }, + "sload": { + "v": 50, + "d": "Base fee of the SLOAD opcode" + }, + "sstoreSet": { + "v": 20000, + "d": "Once per SSTORE operation if the zeroness changes from zero" + }, + "sstoreReset": { + "v": 5000, + "d": "Once per SSTORE operation if the zeroness does not change from zero" + }, + "sstoreRefund": { + "v": 15000, + "d": "Once per SSTORE operation if the zeroness changes to zero" + }, + "jumpdest": { + "v": 1, + "d": "Base fee of the JUMPDEST opcode" + }, + "log": { + "v": 375, + "d": "Base fee of the LOG opcode" + }, + "logData": { + "v": 8, + "d": "Per byte in a LOG* operation's data" + }, + "logTopic": { + "v": 375, + "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas" + }, + "create": { + "v": 32000, + "d": "Base fee of the CREATE opcode" + }, + "call": { + "v": 40, + "d": "Base fee of the CALL opcode" + }, + "callStipend": { + "v": 2300, + "d": "Free gas given at beginning of call" + }, + "callValueTransfer": { + "v": 9000, + "d": "Paid for CALL when the value transfor is non-zero" + }, + "callNewAccount": { + "v": 25000, + "d": "Paid for CALL when the destination address didn't exist prior" + }, + "selfdestructRefund": { + "v": 24000, + "d": "Refunded following a selfdestruct operation" + }, + "memory": { + "v": 3, + "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL" + }, + "quadCoeffDiv": { + "v": 512, + "d": "Divisor for the quadratic particle of the memory cost equation" + }, + "createData": { + "v": 200, + "d": "" + }, + "tx": { + "v": 21000, + "d": "Per transaction. NOTE: Not payable on data of calls between transactions" + }, + "txCreation": { + "v": 32000, + "d": "The cost of creating a contract via tx" + }, + "txDataZero": { + "v": 4, + "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions" + }, + "txDataNonZero": { + "v": 68, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + }, + "copy": { + "v": 3, + "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added" + }, + "ecRecover": { + "v": 3000, + "d": "" + }, + "sha256": { + "v": 60, + "d": "" + }, + "sha256Word": { + "v": 12, + "d": "" + }, + "ripemd160": { + "v": 600, + "d": "" + }, + "ripemd160Word": { + "v": 120, + "d": "" + }, + "identity": { + "v": 15, + "d": "" + }, + "identityWord": { + "v": 3, + "d": "" + }, + "stop": { + "v": 0, + "d": "Base fee of the STOP opcode" + }, + "add": { + "v": 3, + "d": "Base fee of the ADD opcode" + }, + "mul": { + "v": 5, + "d": "Base fee of the MUL opcode" + }, + "sub": { + "v": 3, + "d": "Base fee of the SUB opcode" + }, + "div": { + "v": 5, + "d": "Base fee of the DIV opcode" + }, + "sdiv": { + "v": 5, + "d": "Base fee of the SDIV opcode" + }, + "mod": { + "v": 5, + "d": "Base fee of the MOD opcode" + }, + "smod": { + "v": 5, + "d": "Base fee of the SMOD opcode" + }, + "addmod": { + "v": 8, + "d": "Base fee of the ADDMOD opcode" + }, + "mulmod": { + "v": 8, + "d": "Base fee of the MULMOD opcode" + }, + "signextend": { + "v": 5, + "d": "Base fee of the SIGNEXTEND opcode" + }, + "lt": { + "v": 3, + "d": "Base fee of the LT opcode" + }, + "gt": { + "v": 3, + "d": "Base fee of the GT opcode" + }, + "slt": { + "v": 3, + "d": "Base fee of the SLT opcode" + }, + "sgt": { + "v": 3, + "d": "Base fee of the SGT opcode" + }, + "eq": { + "v": 3, + "d": "Base fee of the EQ opcode" + }, + "iszero": { + "v": 3, + "d": "Base fee of the ISZERO opcode" + }, + "and": { + "v": 3, + "d": "Base fee of the AND opcode" + }, + "or": { + "v": 3, + "d": "Base fee of the OR opcode" + }, + "xor": { + "v": 3, + "d": "Base fee of the XOR opcode" + }, + "not": { + "v": 3, + "d": "Base fee of the NOT opcode" + }, + "byte": { + "v": 3, + "d": "Base fee of the BYTE opcode" + }, + "address": { + "v": 2, + "d": "Base fee of the ADDRESS opcode" + }, + "balance": { + "v": 20, + "d": "Base fee of the BALANCE opcode" + }, + "origin": { + "v": 2, + "d": "Base fee of the ORIGIN opcode" + }, + "caller": { + "v": 2, + "d": "Base fee of the CALLER opcode" + }, + "callvalue": { + "v": 2, + "d": "Base fee of the CALLVALUE opcode" + }, + "calldataload": { + "v": 3, + "d": "Base fee of the CALLDATALOAD opcode" + }, + "calldatasize": { + "v": 2, + "d": "Base fee of the CALLDATASIZE opcode" + }, + "calldatacopy": { + "v": 3, + "d": "Base fee of the CALLDATACOPY opcode" + }, + "codesize": { + "v": 2, + "d": "Base fee of the CODESIZE opcode" + }, + "codecopy": { + "v": 3, + "d": "Base fee of the CODECOPY opcode" + }, + "gasprice": { + "v": 2, + "d": "Base fee of the GASPRICE opcode" + }, + "extcodesize": { + "v": 20, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 20, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "blockhash": { + "v": 20, + "d": "Base fee of the BLOCKHASH opcode" + }, + "coinbase": { + "v": 2, + "d": "Base fee of the COINBASE opcode" + }, + "timestamp": { + "v": 2, + "d": "Base fee of the TIMESTAMP opcode" + }, + "number": { + "v": 2, + "d": "Base fee of the NUMBER opcode" + }, + "difficulty": { + "v": 2, + "d": "Base fee of the DIFFICULTY opcode" + }, + "gaslimit": { + "v": 2, + "d": "Base fee of the GASLIMIT opcode" + }, + "pop": { + "v": 2, + "d": "Base fee of the POP opcode" + }, + "mload": { + "v": 3, + "d": "Base fee of the MLOAD opcode" + }, + "mstore": { + "v": 3, + "d": "Base fee of the MSTORE opcode" + }, + "mstore8": { + "v": 3, + "d": "Base fee of the MSTORE8 opcode" + }, + "sstore": { + "v": 0, + "d": "Base fee of the SSTORE opcode" + }, + "jump": { + "v": 8, + "d": "Base fee of the JUMP opcode" + }, + "jumpi": { + "v": 10, + "d": "Base fee of the JUMPI opcode" + }, + "pc": { + "v": 2, + "d": "Base fee of the PC opcode" + }, + "msize": { + "v": 2, + "d": "Base fee of the MSIZE opcode" + }, + "gas": { + "v": 2, + "d": "Base fee of the GAS opcode" + }, + "push": { + "v": 3, + "d": "Base fee of the PUSH opcode" + }, + "dup": { + "v": 3, + "d": "Base fee of the DUP opcode" + }, + "swap": { + "v": 3, + "d": "Base fee of the SWAP opcode" + }, + "callcode": { + "v": 40, + "d": "Base fee of the CALLCODE opcode" + }, + "return": { + "v": 0, + "d": "Base fee of the RETURN opcode" + }, + "invalid": { + "v": 0, + "d": "Base fee of the INVALID opcode" + }, + "selfdestruct": { + "v": 0, + "d": "Base fee of the SELFDESTRUCT opcode" + } + }, + "vm": { + "stackLimit": { + "v": 1024, + "d": "Maximum size of VM stack allowed" + }, + "callCreateDepth": { + "v": 1024, + "d": "Maximum depth of call/create stack" + }, + "maxExtraDataSize": { + "v": 32, + "d": "Maximum size extra data may be after Genesis" + } + }, + "pow": { + "minimumDifficulty": { + "v": 131072, + "d": "The minimum that the difficulty may ever be" + }, + "difficultyBoundDivisor": { + "v": 2048, + "d": "The bound divisor of the difficulty, used in the update calculations" + }, + "durationLimit": { + "v": 13, + "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not" + }, + "epochDuration": { + "v": 30000, + "d": "Duration between proof-of-work epochs" + }, + "timebombPeriod": { + "v": 100000, + "d": "Exponential difficulty timebomb period" + }, + "minerReward": { + "v": "5000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 0, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=chainstart.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.js.map new file mode 100644 index 0000000..90109fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/chainstart.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chainstart.js","sourceRoot":"","sources":["../../../../src/common/hardforks/chainstart.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,YAAY;IACpB,SAAS,EAAE,kCAAkC;IAC7C,KAAK,EAAE,EAAE;IACT,QAAQ,EAAE,EAAE;IACZ,WAAW,EAAE;QACZ,aAAa,EAAE;YACd,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,mCAAmC;SACxC;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,2FAA2F;SAChG;KACD;IACD,WAAW,EAAE;QACZ,MAAM,EAAE;YACP,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,wDAAwD;SAC7D;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC;YAC5B,GAAG,EAAE,6CAA6C;SAClD;QACD,KAAK,EAAE;YACN,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,4BAA4B;SACjC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,sDAAsD;SAC3D;QACD,MAAM,EAAE;YACP,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,6BAA6B;SAClC;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAA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ACD,cAAc,EAAE;YACf,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;KACD;IACD,IAAI,EAAE;QACL,YAAY,EAAE;YACb,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,kCAAkC;SACvC;QACD,iBAAiB,EAAE;YAClB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,oCAAoC;SACzC;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,8CAA8C;SACnD;KACD;IACD,KAAK,EAAE;QACN,mBAAmB,EAAE;YACpB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,6CAA6C;SAClD;QACD,wBAAwB,EAAE;YACzB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,sEAAsE;SAC3E;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,0GAA0G;SAC/G;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,uCAAuC;SAC5C;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,wCAAwC;SAC7C;QACD,aAAa,EAAE;YACd,GAAG,EAAE,qBAAqB;YAC1B,GAAG,EAAE,oDAAoD;SACzD;QACD,qBAAqB,EAAE;YACtB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.d.ts new file mode 100644 index 0000000..3bd57b1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.d.ts @@ -0,0 +1,69 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + netSstoreNoopGas: { + v: number; + d: string; + }; + netSstoreInitGas: { + v: number; + d: string; + }; + netSstoreCleanGas: { + v: number; + d: string; + }; + netSstoreDirtyGas: { + v: number; + d: string; + }; + netSstoreClearRefund: { + v: number; + d: string; + }; + netSstoreResetRefund: { + v: number; + d: string; + }; + netSstoreResetClearRefund: { + v: number; + d: string; + }; + shl: { + v: number; + d: string; + }; + shr: { + v: number; + d: string; + }; + sar: { + v: number; + d: string; + }; + extcodehash: { + v: number; + d: string; + }; + create2: { + v: number; + d: string; + }; + }; + vm: {}; + pow: { + minerReward: { + v: string; + d: string; + }; + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.js new file mode 100644 index 0000000..352edfa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "constantinople", + "comment": "Postponed hardfork including EIP-1283 (SSTORE gas metering changes)", + "url": "https://eips.ethereum.org/EIPS/eip-1013", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "netSstoreNoopGas": { + "v": 200, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "netSstoreInitGas": { + "v": 20000, + "d": "Once per SSTORE operation from clean zero" + }, + "netSstoreCleanGas": { + "v": 5000, + "d": "Once per SSTORE operation from clean non-zero" + }, + "netSstoreDirtyGas": { + "v": 200, + "d": "Once per SSTORE operation from dirty" + }, + "netSstoreClearRefund": { + "v": 15000, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + }, + "netSstoreResetRefund": { + "v": 4800, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "netSstoreResetClearRefund": { + "v": 19800, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "shl": { + "v": 3, + "d": "Base fee of the SHL opcode" + }, + "shr": { + "v": 3, + "d": "Base fee of the SHR opcode" + }, + "sar": { + "v": 3, + "d": "Base fee of the SAR opcode" + }, + "extcodehash": { + "v": 400, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "create2": { + "v": 32000, + "d": "Base fee of the CREATE2 opcode" + } + }, + "vm": {}, + "pow": { + "minerReward": { + "v": "2000000000000000000", + "d": "The amount a miner gets rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 5000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=constantinople.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.js.map new file mode 100644 index 0000000..752f1f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/constantinople.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constantinople.js","sourceRoot":"","sources":["../../../../src/common/hardforks/constantinople.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,gBAAgB;IACxB,SAAS,EAAE,qEAAqE;IAChF,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,2CAA2C;SAChD;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+CAA+C;SACpD;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,sCAAsC;SAC3C;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,4EAA4E;SACjF;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wEAAwE;SAC7E;QACD,2BAA2B,EAAE;YAC5B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,oEAAoE;SACzE;QACD,KAAK,EAAE;YACN,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4BAA4B;SACjC;QACD,KAAK,EAAE;YACN,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4BAA4B;SACjC;QACD,KAAK,EAAE;YACN,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4BAA4B;SACjC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,gCAAgC;SACrC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,aAAa,EAAE;YACd,GAAG,EAAE,qBAAqB;YAC1B,GAAG,EAAE,qDAAqD;SAC1D;QACD,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.d.ts new file mode 100644 index 0000000..27845b8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.d.ts @@ -0,0 +1,11 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.js new file mode 100644 index 0000000..8497bf1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "dao", + "comment": "DAO rescue hardfork", + "url": "https://eips.ethereum.org/EIPS/eip-779", + "status": "Final", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=dao.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.js.map new file mode 100644 index 0000000..9160633 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/dao.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dao.js","sourceRoot":"","sources":["../../../../src/common/hardforks/dao.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,qBAAqB;IAChC,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.d.ts new file mode 100644 index 0000000..3c83d0c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.d.ts @@ -0,0 +1,12 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.js new file mode 100644 index 0000000..52fca8c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "grayGlacier", + "comment": "Delaying the difficulty bomb to Mid September 2022", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md", + "status": "Draft", + "eips": [5133], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=grayGlacier.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.js.map new file mode 100644 index 0000000..04d878f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/grayGlacier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"grayGlacier.js","sourceRoot":"","sources":["../../../../src/common/hardforks/grayGlacier.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,aAAa;IACrB,SAAS,EAAE,oDAAoD;IAC/D,KAAK,EAAE,2GAA2G;IAClH,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,CAAC;IACd,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.d.ts new file mode 100644 index 0000000..6bfa243 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.d.ts @@ -0,0 +1,16 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + delegatecall: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.js new file mode 100644 index 0000000..cf66201 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "homestead", + "comment": "Homestead hardfork with protocol and network changes", + "url": "https://eips.ethereum.org/EIPS/eip-606", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "delegatecall": { + "v": 40, + "d": "Base fee of the DELEGATECALL opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=homestead.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.js.map new file mode 100644 index 0000000..a24244d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/homestead.js.map @@ -0,0 +1 @@ +{"version":3,"file":"homestead.js","sourceRoot":"","sources":["../../../../src/common/hardforks/homestead.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,WAAW;IACnB,SAAS,EAAE,sDAAsD;IACjE,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,cAAc,EAAE;YACf,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,qCAAqC;SAC1C;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.d.ts new file mode 100644 index 0000000..7658ee5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.d.ts @@ -0,0 +1,3 @@ +export declare const hardforks: { + [key: string]: any; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.js new file mode 100644 index 0000000..ed7c4bf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.js @@ -0,0 +1,59 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hardforks = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const chainstart_js_1 = __importDefault(require("./chainstart.js")); +const dao_js_1 = __importDefault(require("./dao.js")); +const homestead_js_1 = __importDefault(require("./homestead.js")); +const tangerineWhistle_js_1 = __importDefault(require("./tangerineWhistle.js")); +const spuriousDragon_js_1 = __importDefault(require("./spuriousDragon.js")); +const byzantium_js_1 = __importDefault(require("./byzantium.js")); +const constantinople_js_1 = __importDefault(require("./constantinople.js")); +const petersburg_js_1 = __importDefault(require("./petersburg.js")); +const istanbul_js_1 = __importDefault(require("./istanbul.js")); +const muirGlacier_js_1 = __importDefault(require("./muirGlacier.js")); +const berlin_js_1 = __importDefault(require("./berlin.js")); +const london_js_1 = __importDefault(require("./london.js")); +const shanghai_js_1 = __importDefault(require("./shanghai.js")); +const arrowGlacier_js_1 = __importDefault(require("./arrowGlacier.js")); +const grayGlacier_js_1 = __importDefault(require("./grayGlacier.js")); +const mergeForkIdTransition_js_1 = __importDefault(require("./mergeForkIdTransition.js")); +const merge_js_1 = __importDefault(require("./merge.js")); +exports.hardforks = { + chainstart: chainstart_js_1.default, + homestead: homestead_js_1.default, + dao: dao_js_1.default, + tangerineWhistle: tangerineWhistle_js_1.default, + spuriousDragon: spuriousDragon_js_1.default, + byzantium: byzantium_js_1.default, + constantinople: constantinople_js_1.default, + petersburg: petersburg_js_1.default, + istanbul: istanbul_js_1.default, + muirGlacier: muirGlacier_js_1.default, + berlin: berlin_js_1.default, + london: london_js_1.default, + shanghai: shanghai_js_1.default, + arrowGlacier: arrowGlacier_js_1.default, + grayGlacier: grayGlacier_js_1.default, + mergeForkIdTransition: mergeForkIdTransition_js_1.default, + merge: merge_js_1.default, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.js.map new file mode 100644 index 0000000..2d23b2d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/hardforks/index.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,oEAAyC;AACzC,sDAA2B;AAC3B,kEAAuC;AACvC,gFAAqD;AACrD,4EAAiD;AACjD,kEAAuC;AACvC,4EAAiD;AACjD,oEAAyC;AACzC,gEAAqC;AACrC,sEAA2C;AAC3C,4DAAiC;AACjC,4DAAiC;AACjC,gEAAqC;AACrC,wEAA6C;AAC7C,sEAA2C;AAC3C,0FAA+D;AAC/D,0DAA+B;AAElB,QAAA,SAAS,GAA2B;IAChD,UAAU,EAAV,uBAAU;IACV,SAAS,EAAT,sBAAS;IACT,GAAG,EAAH,gBAAG;IACH,gBAAgB,EAAhB,6BAAgB;IAChB,cAAc,EAAd,2BAAc;IACd,SAAS,EAAT,sBAAS;IACT,cAAc,EAAd,2BAAc;IACd,UAAU,EAAV,uBAAU;IACV,QAAQ,EAAR,qBAAQ;IACR,WAAW,EAAX,wBAAW;IACX,MAAM,EAAN,mBAAM;IACN,MAAM,EAAN,mBAAM;IACN,QAAQ,EAAR,qBAAQ;IACR,YAAY,EAAZ,yBAAY;IACZ,WAAW,EAAX,wBAAW;IACX,qBAAqB,EAArB,kCAAqB;IACrB,KAAK,EAAL,kBAAK;CACL,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.d.ts new file mode 100644 index 0000000..8226710 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.d.ts @@ -0,0 +1,88 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + blake2Round: { + v: number; + d: string; + }; + ecAdd: { + v: number; + d: string; + }; + ecMul: { + v: number; + d: string; + }; + ecPairing: { + v: number; + d: string; + }; + ecPairingWord: { + v: number; + d: string; + }; + txDataNonZero: { + v: number; + d: string; + }; + sstoreSentryGasEIP2200: { + v: number; + d: string; + }; + sstoreNoopGasEIP2200: { + v: number; + d: string; + }; + sstoreDirtyGasEIP2200: { + v: number; + d: string; + }; + sstoreInitGasEIP2200: { + v: number; + d: string; + }; + sstoreInitRefundEIP2200: { + v: number; + d: string; + }; + sstoreCleanGasEIP2200: { + v: number; + d: string; + }; + sstoreCleanRefundEIP2200: { + v: number; + d: string; + }; + sstoreClearRefundEIP2200: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + extcodehash: { + v: number; + d: string; + }; + chainid: { + v: number; + d: string; + }; + selfbalance: { + v: number; + d: string; + }; + sload: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.js new file mode 100644 index 0000000..d7ea5c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "istanbul", + "comment": "HF targeted for December 2019 following the Constantinople/Petersburg HF", + "url": "https://eips.ethereum.org/EIPS/eip-1679", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "blake2Round": { + "v": 1, + "d": "Gas cost per round for the Blake2 F precompile" + }, + "ecAdd": { + "v": 150, + "d": "Gas costs for curve addition precompile" + }, + "ecMul": { + "v": 6000, + "d": "Gas costs for curve multiplication precompile" + }, + "ecPairing": { + "v": 45000, + "d": "Base gas costs for curve pairing precompile" + }, + "ecPairingWord": { + "v": 34000, + "d": "Gas costs regarding curve pairing precompile input length" + }, + "txDataNonZero": { + "v": 16, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + }, + "sstoreSentryGasEIP2200": { + "v": 2300, + "d": "Minimum gas required to be present for an SSTORE call, not consumed" + }, + "sstoreNoopGasEIP2200": { + "v": 800, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "sstoreDirtyGasEIP2200": { + "v": 800, + "d": "Once per SSTORE operation if a dirty value is changed" + }, + "sstoreInitGasEIP2200": { + "v": 20000, + "d": "Once per SSTORE operation from clean zero to non-zero" + }, + "sstoreInitRefundEIP2200": { + "v": 19200, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "sstoreCleanGasEIP2200": { + "v": 5000, + "d": "Once per SSTORE operation from clean non-zero to something else" + }, + "sstoreCleanRefundEIP2200": { + "v": 4200, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "sstoreClearRefundEIP2200": { + "v": 15000, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + }, + "balance": { + "v": 700, + "d": "Base fee of the BALANCE opcode" + }, + "extcodehash": { + "v": 700, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "chainid": { + "v": 2, + "d": "Base fee of the CHAINID opcode" + }, + "selfbalance": { + "v": 5, + "d": "Base fee of the SELFBALANCE opcode" + }, + "sload": { + "v": 800, + "d": "Base fee of the SLOAD opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=istanbul.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.js.map new file mode 100644 index 0000000..0f4e476 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/istanbul.js.map @@ -0,0 +1 @@ +{"version":3,"file":"istanbul.js","sourceRoot":"","sources":["../../../../src/common/hardforks/istanbul.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,0EAA0E;IACrF,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gDAAgD;SACrD;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,yCAAyC;SAC9C;QACD,OAAO,EAAE;YACR,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+CAA+C;SACpD;QACD,WAAW,EAAE;YACZ,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,6CAA6C;SAClD;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,2DAA2D;SAChE;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,+HAA+H;SACpI;QACD,wBAAwB,EAAE;YACzB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,qEAAqE;SAC1E;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,uDAAuD;SAC5D;QACD,yBAAyB,EAAE;YAC1B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,oEAAoE;SACzE;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wEAAwE;SAC7E;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,4EAA4E;SACjF;QACD,SAAS,EAAE;YACV,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,gCAAgC;SACrC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gCAAgC;SACrC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,8BAA8B;SACnC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.d.ts new file mode 100644 index 0000000..fb32424 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.d.ts @@ -0,0 +1,8 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.js new file mode 100644 index 0000000..72d0f97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "london", + "comment": "HF targeted for July 2021 following the Berlin fork", + "url": "https://github.com/ethereum/eth1.0-specs/blob/master/network-upgrades/mainnet-upgrades/london.md", + "status": "Final", + "eips": [1559, 3198, 3529, 3541] +}; +//# sourceMappingURL=london.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.js.map new file mode 100644 index 0000000..7e7cd7a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/london.js.map @@ -0,0 +1 @@ +{"version":3,"file":"london.js","sourceRoot":"","sources":["../../../../src/common/hardforks/london.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,QAAQ;IAChB,SAAS,EAAE,qDAAqD;IAChE,KAAK,EAAE,kGAAkG;IACzG,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;CAChC,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.d.ts new file mode 100644 index 0000000..f54d7fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + consensus: { + type: string; + algorithm: string; + casper: {}; + }; + eips: number[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.js new file mode 100644 index 0000000..729a208 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "merge", + "comment": "Hardfork to upgrade the consensus mechanism to Proof-of-Stake", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/merge.md", + "status": "Final", + "consensus": { + "type": "pos", + "algorithm": "casper", + "casper": {} + }, + "eips": [3675, 4399] +}; +//# sourceMappingURL=merge.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.js.map new file mode 100644 index 0000000..6a5369c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/merge.js.map @@ -0,0 +1 @@ +{"version":3,"file":"merge.js","sourceRoot":"","sources":["../../../../src/common/hardforks/merge.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,OAAO;IACf,SAAS,EAAE,+DAA+D;IAC1E,KAAK,EAAE,oGAAoG;IAC3G,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE;QACZ,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,EAAE;KACZ;IACD,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;CACpB,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.d.ts new file mode 100644 index 0000000..05f1fd7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.d.ts @@ -0,0 +1,8 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: never[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.js new file mode 100644 index 0000000..ef9a9fe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "mergeForkIdTransition", + "comment": "Pre-merge hardfork to fork off non-upgraded clients", + "url": "https://eips.ethereum.org/EIPS/eip-3675", + "status": "Draft", + "eips": [] +}; +//# sourceMappingURL=mergeForkIdTransition.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.js.map new file mode 100644 index 0000000..2a693f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/mergeForkIdTransition.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mergeForkIdTransition.js","sourceRoot":"","sources":["../../../../src/common/hardforks/mergeForkIdTransition.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,uBAAuB;IAC/B,SAAS,EAAE,qDAAqD;IAChE,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,EAAE;CACV,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.d.ts new file mode 100644 index 0000000..f751cd1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.d.ts @@ -0,0 +1,16 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.js new file mode 100644 index 0000000..dbde8e8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "muirGlacier", + "comment": "HF to delay the difficulty bomb", + "url": "https://eips.ethereum.org/EIPS/eip-2384", + "status": "Final", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 9000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=muirGlacier.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.js.map new file mode 100644 index 0000000..0a0c57e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/muirGlacier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"muirGlacier.js","sourceRoot":"","sources":["../../../../src/common/hardforks/muirGlacier.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,aAAa;IACrB,SAAS,EAAE,iCAAiC;IAC5C,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.d.ts new file mode 100644 index 0000000..6880311 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.d.ts @@ -0,0 +1,40 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + netSstoreNoopGas: { + v: null; + d: string; + }; + netSstoreInitGas: { + v: null; + d: string; + }; + netSstoreCleanGas: { + v: null; + d: string; + }; + netSstoreDirtyGas: { + v: null; + d: string; + }; + netSstoreClearRefund: { + v: null; + d: string; + }; + netSstoreResetRefund: { + v: null; + d: string; + }; + netSstoreResetClearRefund: { + v: null; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.js new file mode 100644 index 0000000..fa20f54 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "petersburg", + "comment": "Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople", + "url": "https://eips.ethereum.org/EIPS/eip-1716", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "netSstoreNoopGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreInitGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreCleanGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreDirtyGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreClearRefund": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreResetRefund": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreResetClearRefund": { + "v": null, + "d": "Removed along EIP-1283" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=petersburg.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.js.map new file mode 100644 index 0000000..8c3c7c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/petersburg.js.map @@ -0,0 +1 @@ +{"version":3,"file":"petersburg.js","sourceRoot":"","sources":["../../../../src/common/hardforks/petersburg.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,YAAY;IACpB,SAAS,EAAE,yFAAyF;IACpG,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,2BAA2B,EAAE;YAC5B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.d.ts new file mode 100644 index 0000000..fb32424 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.d.ts @@ -0,0 +1,8 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.js new file mode 100644 index 0000000..b16a294 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "shanghai", + "comment": "Next feature hardfork after the merge hardfork having withdrawals, warm coinbase, push0, limit/meter initcode", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md", + "status": "Final", + "eips": [3651, 3855, 3860, 4895] +}; +//# sourceMappingURL=shanghai.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.js.map new file mode 100644 index 0000000..22b3de9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/shanghai.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shanghai.js","sourceRoot":"","sources":["../../../../src/common/hardforks/shanghai.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,+GAA+G;IAC1H,KAAK,EAAE,uGAAuG;IAC9G,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;CAChC,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.d.ts new file mode 100644 index 0000000..fb32424 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.d.ts @@ -0,0 +1,8 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.js new file mode 100644 index 0000000..38cf797 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "shardingFork", + "comment": "Internal hardfork to test proto-danksharding (do not use in production)", + "url": "https://eips.ethereum.org/EIPS/eip-4844", + "status": "Experimental", + "eips": [4844] +}; +//# sourceMappingURL=sharding.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.js.map new file mode 100644 index 0000000..470a32b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/sharding.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sharding.js","sourceRoot":"","sources":["../../../../src/common/hardforks/sharding.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,cAAc;IACtB,SAAS,EAAE,yEAAyE;IACpF,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,cAAc;IACxB,MAAM,EAAE,CAAC,IAAI,CAAC;CACd,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.d.ts new file mode 100644 index 0000000..615e6ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.d.ts @@ -0,0 +1,21 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + expByte: { + v: number; + d: string; + }; + }; + vm: { + maxCodeSize: { + v: number; + d: string; + }; + }; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.js new file mode 100644 index 0000000..060b22d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "spuriousDragon", + "comment": "HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit", + "url": "https://eips.ethereum.org/EIPS/eip-607", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "expByte": { + "v": 50, + "d": "Times ceil(log256(exponent)) for the EXP instruction" + } + }, + "vm": { + "maxCodeSize": { + "v": 24576, + "d": "Maximum length of contract code" + } + }, + "pow": {} +}; +//# sourceMappingURL=spuriousDragon.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.js.map new file mode 100644 index 0000000..30e9ee3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/spuriousDragon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spuriousDragon.js","sourceRoot":"","sources":["../../../../src/common/hardforks/spuriousDragon.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,gBAAgB;IACxB,SAAS,EAAE,oHAAoH;IAC/H,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,SAAS,EAAE;YACV,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,sDAAsD;SAC3D;KACD;IACD,IAAI,EAAE;QACL,aAAa,EAAE;YACd,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,iCAAiC;SACtC;KACD;IACD,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.d.ts new file mode 100644 index 0000000..5c41789 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.d.ts @@ -0,0 +1,44 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + sload: { + v: number; + d: string; + }; + call: { + v: number; + d: string; + }; + extcodesize: { + v: number; + d: string; + }; + extcodecopy: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + delegatecall: { + v: number; + d: string; + }; + callcode: { + v: number; + d: string; + }; + selfdestruct: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.js new file mode 100644 index 0000000..326084a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = { + "name": "tangerineWhistle", + "comment": "Hardfork with gas cost changes for IO-heavy operations", + "url": "https://eips.ethereum.org/EIPS/eip-608", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "sload": { + "v": 200, + "d": "Once per SLOAD operation" + }, + "call": { + "v": 700, + "d": "Once per CALL operation & message call transaction" + }, + "extcodesize": { + "v": 700, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 700, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "balance": { + "v": 400, + "d": "Base fee of the BALANCE opcode" + }, + "delegatecall": { + "v": 700, + "d": "Base fee of the DELEGATECALL opcode" + }, + "callcode": { + "v": 700, + "d": "Base fee of the CALLCODE opcode" + }, + "selfdestruct": { + "v": 5000, + "d": "Base fee of the SELFDESTRUCT opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=tangerineWhistle.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.js.map new file mode 100644 index 0000000..d2d6079 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/hardforks/tangerineWhistle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tangerineWhistle.js","sourceRoot":"","sources":["../../../../src/common/hardforks/tangerineWhistle.ts"],"names":[],"mappings":";;AAAA,kBAAe;IACd,MAAM,EAAE,kBAAkB;IAC1B,SAAS,EAAE,wDAAwD;IACnE,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,0BAA0B;SAC/B;QACD,MAAM,EAAE;YACP,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oDAAoD;SACzD;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,gCAAgC;SACrC;QACD,cAAc,EAAE;YACf,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,qCAAqC;SAC1C;QACD,UAAU,EAAE;YACX,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,iCAAiC;SACtC;QACD,cAAc,EAAE;YACf,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,qCAAqC;SAC1C;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.d.ts new file mode 100644 index 0000000..ca2d274 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.d.ts @@ -0,0 +1,4 @@ +export * from './common.js'; +export * from './enums.js'; +export * from './types.js'; +export * from './utils.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.js new file mode 100644 index 0000000..0876fec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.js @@ -0,0 +1,38 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// @ethereumjs/common version 3.1.1 +__exportStar(require("./common.js"), exports); +__exportStar(require("./enums.js"), exports); +__exportStar(require("./types.js"), exports); +__exportStar(require("./utils.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.js.map new file mode 100644 index 0000000..e71a26c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,mCAAmC;AACnC,8CAA4B;AAC5B,6CAA2B;AAC3B,6CAA2B;AAC3B,6CAA2B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.d.ts new file mode 100644 index 0000000..4aa7d71 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.d.ts @@ -0,0 +1,135 @@ +import type { Chain, ConsensusAlgorithm, ConsensusType, Hardfork } from './enums.js'; +export interface ChainName { + [chainId: string]: string; +} +export declare type CliqueConfig = { + period: number; + epoch: number; +}; +export declare type EthashConfig = Record; +export declare type CasperConfig = Record; +export interface GenesisBlockConfig { + timestamp?: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + baseFeePerGas?: string; +} +export interface HardforkConfig { + name: Hardfork | string; + block: number | null; + ttd?: bigint | string; + timestamp?: number | string; + forkHash?: string | null; +} +export interface BootstrapNodeConfig { + ip: string; + port: number | string; + network?: string; + chainId?: number; + id: string; + location: string; + comment: string; +} +export interface ChainConfig { + name: string; + chainId: number | bigint; + networkId: number | bigint; + defaultHardfork?: string; + comment?: string; + url?: string; + genesis: GenesisBlockConfig; + hardforks: HardforkConfig[]; + bootstrapNodes?: BootstrapNodeConfig[]; + dnsNetworks?: string[]; + consensus: { + type: ConsensusType | string; + algorithm: ConsensusAlgorithm | string; + clique?: CliqueConfig; + ethash?: EthashConfig; + casper?: CasperConfig; + }; +} +export interface ChainsConfig { + [key: string]: ChainConfig | ChainName; +} +interface BaseOpts { + /** + * String identifier ('byzantium') for hardfork or {@link Hardfork} enum. + * + * Default: Hardfork.London + */ + hardfork?: string | Hardfork; + /** + * Selected EIPs which can be activated, please use an array for instantiation + * (e.g. `eips: [ 2537, ]`) + * + * Currently supported: + * + * - [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537) - BLS12-381 precompiles + */ + eips?: number[]; +} +/** + * Options for instantiating a {@link Common} instance. + */ +export interface CommonOpts extends BaseOpts { + /** + * Chain name ('mainnet'), id (1), or {@link Chain} enum, + * either from a chain directly supported or a custom chain + * passed in via {@link CommonOpts.customChains}. + */ + chain: string | number | Chain | bigint | object; + /** + * Initialize (in addition to the supported chains) with the selected + * custom chains. Custom genesis state should be passed to the Blockchain class if used. + * + * Usage (directly with the respective chain initialization via the {@link CommonOpts.chain} option): + * + * ```javascript + * import myCustomChain1 from '[PATH_TO_MY_CHAINS]/myCustomChain1.json' + * const common = new Common({ chain: 'myCustomChain1', customChains: [ myCustomChain1 ]}) + * ``` + */ + customChains?: ChainConfig[]; +} +/** + * Options to be used with the {@link Common.custom} static constructor. + */ +export interface CustomCommonOpts extends BaseOpts { + /** + * The name (`mainnet`), id (`1`), or {@link Chain} enum of + * a standard chain used to base the custom chain params on. + */ + baseChain?: string | number | Chain | bigint; +} +export interface GethConfigOpts extends BaseOpts { + chain?: string; + genesisHash?: Uint8Array; + mergeForkIdPostMerge?: boolean; +} +export declare type PrefixedHexString = string; +export declare type Uint8ArrayLike = Uint8Array | number[] | number | bigint | PrefixedHexString; +export declare type BigIntLike = bigint | PrefixedHexString | number | Uint8Array; +export interface TransformableToArray { + toArray(): Uint8Array; +} +export declare type NestedUint8Array = Array; +/** + * Type output options + */ +export declare enum TypeOutput { + Number = 0, + BigInt = 1, + Uint8Array = 2, + PrefixedHexString = 3 +} +export declare type TypeOutputReturnType = { + [TypeOutput.Number]: number; + [TypeOutput.BigInt]: bigint; + [TypeOutput.Uint8Array]: Uint8Array; + [TypeOutput.PrefixedHexString]: PrefixedHexString; +}; +export declare type ToBytesInputTypes = PrefixedHexString | number | bigint | Uint8Array | number[] | TransformableToArray | null | undefined; +export {}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.js new file mode 100644 index 0000000..67cf197 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeOutput = void 0; +/** + * Type output options + */ +var TypeOutput; +(function (TypeOutput) { + TypeOutput[TypeOutput["Number"] = 0] = "Number"; + TypeOutput[TypeOutput["BigInt"] = 1] = "BigInt"; + TypeOutput[TypeOutput["Uint8Array"] = 2] = "Uint8Array"; + TypeOutput[TypeOutput["PrefixedHexString"] = 3] = "PrefixedHexString"; +})(TypeOutput = exports.TypeOutput || (exports.TypeOutput = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.js.map new file mode 100644 index 0000000..d9c25d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/common/types.ts"],"names":[],"mappings":";;;AAqKA;;GAEG;AACH,IAAY,UAKX;AALD,WAAY,UAAU;IACrB,+CAAM,CAAA;IACN,+CAAM,CAAA;IACN,uDAAU,CAAA;IACV,qEAAiB,CAAA;AAClB,CAAC,EALW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAKrB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.d.ts new file mode 100644 index 0000000..4020800 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.d.ts @@ -0,0 +1,137 @@ +import { ToBytesInputTypes, TypeOutput, TypeOutputReturnType } from './types.js'; +declare type ConfigHardfork = { + name: string; + block: null; + timestamp: number; +} | { + name: string; + block: number; + timestamp?: number; +}; +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +export declare const stripHexPrefix: (str: string) => string; +/** + * Parses a genesis.json exported from Geth into parameters for Common instance + * @param json representing the Geth genesis file + * @param name optional chain name + * @returns parsed params + */ +export declare function parseGethGenesis(json: any, name?: string, mergeForkIdPostMerge?: boolean): { + name: string; + chainId: number; + networkId: number; + genesis: { + timestamp: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + mixHash: string; + coinbase: string; + baseFeePerGas: string; + }; + hardfork: string | undefined; + hardforks: ConfigHardfork[]; + bootstrapNodes: never[]; + consensus: { + type: string; + algorithm: string; + clique: { + period: any; + epoch: any; + }; + ethash?: undefined; + } | { + type: string; + algorithm: string; + ethash: {}; + clique?: undefined; + }; +}; +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +export declare function padToEven(value: string): string; +/** + * Converts an `Number` to a `Uint8Array` + * @param {Number} i + * @return {Uint8Array} + */ +export declare const intToUint8Array: (i: number) => Uint8Array; +/** + * Attempts to turn a value into a `Uint8Array`. + * Inputs supported: `Uint8Array` `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toUint8Array()` method. + * @param v the value + */ +export declare const toUint8Array: (v: ToBytesInputTypes) => Uint8Array; +/** + * Converts a {@link Uint8Array} to a {@link bigint} + */ +export declare function uint8ArrayToBigInt(buf: Uint8Array): bigint; +/** + * Converts a {@link bigint} to a {@link Uint8Array} + */ +export declare function bigIntToUint8Array(num: bigint): Uint8Array; +/** + * Returns a Uint8Array filled with 0s. + * @param bytes the number of bytes the Uint8Array should be + */ +export declare const zeros: (bytes: number) => Uint8Array; +/** + * Throws if input is not a Uint8Array + * @param {Uint8Array} input value to check + */ +export declare function assertIsUint8Array(input: unknown): asserts input is Uint8Array; +/** + * Left Pads a `Uint8Array` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @return (Uint8Array) + */ +export declare const setLengthLeft: (msg: Uint8Array, length: number) => Uint8Array; +/** + * Trims leading zeros from a `Uint8Array`, `String` or `Number[]`. + * @param a (Uint8Array|Array|String) + * @return (Uint8Array|Array|String) + */ +export declare function stripZeros(a: T): T; +/** + * Trims leading zeros from a `Uint8Array`. + * @param a (Uint8Array) + * @return (Uint8Array) + */ +export declare const unpadUint8Array: (a: Uint8Array) => Uint8Array; +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +export declare const bigIntToHex: (num: bigint) => string; +/** + * Convert value from bigint to an unpadded Uint8Array + * (useful for RLP transport) + * @param value value to convert + */ +export declare function bigIntToUnpaddedUint8Array(value: bigint): Uint8Array; +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +export declare const ecrecover: (msgHash: Uint8Array, v: bigint, r: Uint8Array, s: Uint8Array, chainId?: bigint) => Uint8Array; +/** + * Convert an input to a specified type. + * Input of null/undefined returns null/undefined regardless of the output type. + * @param input value to convert + * @param outputType type to output + */ +export declare function toType(input: null, outputType: T): null; +export declare function toType(input: undefined, outputType: T): undefined; +export declare function toType(input: ToBytesInputTypes, outputType: T): TypeOutputReturnType[T]; +export {}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.js new file mode 100644 index 0000000..5e5e8eb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.js @@ -0,0 +1,496 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toType = exports.ecrecover = exports.bigIntToUnpaddedUint8Array = exports.bigIntToHex = exports.unpadUint8Array = exports.stripZeros = exports.setLengthLeft = exports.assertIsUint8Array = exports.zeros = exports.bigIntToUint8Array = exports.uint8ArrayToBigInt = exports.toUint8Array = exports.intToUint8Array = exports.padToEven = exports.parseGethGenesis = exports.stripHexPrefix = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_validator_1 = require("web3-validator"); +const web3_utils_1 = require("web3-utils"); +const constants_js_1 = require("../tx/constants.js"); +const enums_js_1 = require("./enums.js"); +const types_js_1 = require("./types.js"); +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +const stripHexPrefix = (str) => { + if (typeof str !== 'string') + throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`); + return (0, web3_validator_1.isHexPrefixed)(str) ? str.slice(2) : str; +}; +exports.stripHexPrefix = stripHexPrefix; +/** + * Transforms Geth formatted nonce (i.e. hex string) to 8 byte 0x-prefixed string used internally + * @param nonce string parsed from the Geth genesis file + * @returns nonce as a 0x-prefixed 8 byte string + */ +function formatNonce(nonce) { + if (!nonce || nonce === '0x0') { + return '0x0000000000000000'; + } + if ((0, web3_validator_1.isHexPrefixed)(nonce)) { + return `0x${(0, exports.stripHexPrefix)(nonce).padStart(16, '0')}`; + } + return `0x${nonce.padStart(16, '0')}`; +} +/** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ +const intToHex = function (i) { + if (!Number.isSafeInteger(i) || i < 0) { + throw new Error(`Received an invalid integer type: ${i}`); + } + return `0x${i.toString(16)}`; +}; +/** + * Converts Geth genesis parameters to an EthereumJS compatible `CommonOpts` object + * @param json object representing the Geth genesis file + * @param optional mergeForkIdPostMerge which clarifies the placement of MergeForkIdTransition + * hardfork, which by default is post merge as with the merged eth networks but could also come + * before merge like in kiln genesis + * @returns genesis parameters in a `CommonOpts` compliant object + */ +function parseGethParams(json, mergeForkIdPostMerge = true) { + var _a, _b; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { name, config, difficulty, mixHash, gasLimit, coinbase, baseFeePerGas, } = json; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + let { extraData, timestamp, nonce } = json; + const genesisTimestamp = Number(timestamp); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { chainId } = config; + // geth is not strictly putting empty fields with a 0x prefix + if (extraData === '') { + extraData = '0x'; + } + // geth may use number for timestamp + if (!(0, web3_validator_1.isHexPrefixed)(timestamp)) { + // eslint-disable-next-line radix + timestamp = intToHex(parseInt(timestamp)); + } + // geth may not give us a nonce strictly formatted to an 8 byte hex string + if (nonce.length !== 18) { + nonce = formatNonce(nonce); + } + // EIP155 and EIP158 are both part of Spurious Dragon hardfork and must occur at the same time + // but have different configuration parameters in geth genesis parameters + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (config.eip155Block !== config.eip158Block) { + throw new Error('EIP155 block number must equal EIP 158 block number since both are part of SpuriousDragon hardfork and the client only supports activating the full hardfork'); + } + const params = { + name, + chainId, + networkId: chainId, + genesis: { + timestamp, + // eslint-disable-next-line radix + gasLimit: parseInt(gasLimit), + // eslint-disable-next-line radix + difficulty: parseInt(difficulty), + nonce, + extraData, + mixHash, + coinbase, + baseFeePerGas, + }, + hardfork: undefined, + hardforks: [], + bootstrapNodes: [], + consensus: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config.clique !== undefined + ? { + type: 'poa', + algorithm: 'clique', + clique: { + // The recent geth genesis seems to be using blockperiodseconds + // and epochlength for clique specification + // see: https://hackmd.io/PqZgMpnkSWCWv5joJoFymQ + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + period: (_a = config.clique.period) !== null && _a !== void 0 ? _a : config.clique.blockperiodseconds, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + epoch: (_b = config.clique.epoch) !== null && _b !== void 0 ? _b : config.clique.epochlength, + }, + } + : { + type: 'pow', + algorithm: 'ethash', + ethash: {}, + }, + }; + const forkMap = { + [enums_js_1.Hardfork.Homestead]: { name: 'homesteadBlock' }, + [enums_js_1.Hardfork.Dao]: { name: 'daoForkBlock' }, + [enums_js_1.Hardfork.TangerineWhistle]: { name: 'eip150Block' }, + [enums_js_1.Hardfork.SpuriousDragon]: { name: 'eip155Block' }, + [enums_js_1.Hardfork.Byzantium]: { name: 'byzantiumBlock' }, + [enums_js_1.Hardfork.Constantinople]: { name: 'constantinopleBlock' }, + [enums_js_1.Hardfork.Petersburg]: { name: 'petersburgBlock' }, + [enums_js_1.Hardfork.Istanbul]: { name: 'istanbulBlock' }, + [enums_js_1.Hardfork.MuirGlacier]: { name: 'muirGlacierBlock' }, + [enums_js_1.Hardfork.Berlin]: { name: 'berlinBlock' }, + [enums_js_1.Hardfork.London]: { name: 'londonBlock' }, + [enums_js_1.Hardfork.MergeForkIdTransition]: { + name: 'mergeForkBlock', + postMerge: mergeForkIdPostMerge, + }, + [enums_js_1.Hardfork.Shanghai]: { name: 'shanghaiTime', postMerge: true, isTimestamp: true }, + [enums_js_1.Hardfork.ShardingForkDev]: { + name: 'shardingForkTime', + postMerge: true, + isTimestamp: true, + }, + }; + // forkMapRev is the map from config field name to Hardfork + const forkMapRev = Object.keys(forkMap).reduce((acc, elem) => { + acc[forkMap[elem].name] = elem; + return acc; + }, {}); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const configHardforkNames = Object.keys(config).filter( + // eslint-disable-next-line no-null/no-null, @typescript-eslint/no-unsafe-member-access + key => forkMapRev[key] !== undefined && config[key] !== undefined && config[key] !== null); + params.hardforks = configHardforkNames + .map(nameBlock => ({ + name: forkMapRev[nameBlock], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + block: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + forkMap[forkMapRev[nameBlock]].isTimestamp === true || + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof config[nameBlock] !== 'number' + ? // eslint-disable-next-line no-null/no-null + null + : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config[nameBlock], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + timestamp: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + forkMap[forkMapRev[nameBlock]].isTimestamp === true && + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof config[nameBlock] === 'number' + ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config[nameBlock] + : undefined, + })) + // eslint-disable-next-line no-null/no-null + .filter(fork => fork.block !== null || fork.timestamp !== undefined); + params.hardforks.sort((a, b) => { var _a, _b; return ((_a = a.block) !== null && _a !== void 0 ? _a : Infinity) - ((_b = b.block) !== null && _b !== void 0 ? _b : Infinity); }); + params.hardforks.sort((a, b) => { var _a, _b; return ((_a = a.timestamp) !== null && _a !== void 0 ? _a : genesisTimestamp) - ((_b = b.timestamp) !== null && _b !== void 0 ? _b : genesisTimestamp); }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (config.terminalTotalDifficulty !== undefined) { + // Following points need to be considered for placement of merge hf + // - Merge hardfork can't be placed at genesis + // - Place merge hf before any hardforks that require CL participation for e.g. withdrawals + // - Merge hardfork has to be placed just after genesis if any of the genesis hardforks make CL + // necessary for e.g. withdrawals + const mergeConfig = { + name: enums_js_1.Hardfork.Merge, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + ttd: config.terminalTotalDifficulty, + // eslint-disable-next-line no-null/no-null + block: null, + }; + // Merge hardfork has to be placed before first hardfork that is dependent on merge + const postMergeIndex = params.hardforks.findIndex( + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (hf) => { var _a; return ((_a = forkMap[hf.name]) === null || _a === void 0 ? void 0 : _a.postMerge) === true; }); + if (postMergeIndex !== -1) { + params.hardforks.splice(postMergeIndex, 0, mergeConfig); + } + else { + params.hardforks.push(mergeConfig); + } + } + const latestHardfork = params.hardforks.length > 0 ? params.hardforks.slice(-1)[0] : undefined; + params.hardfork = latestHardfork === null || latestHardfork === void 0 ? void 0 : latestHardfork.name; + params.hardforks.unshift({ name: enums_js_1.Hardfork.Chainstart, block: 0 }); + return params; +} +/** + * Parses a genesis.json exported from Geth into parameters for Common instance + * @param json representing the Geth genesis file + * @param name optional chain name + * @returns parsed params + */ +function parseGethGenesis(json, name, mergeForkIdPostMerge) { + try { + if (['config', 'difficulty', 'gasLimit', 'alloc'].some(field => !(field in json))) { + throw new Error('Invalid format, expected geth genesis fields missing'); + } + if (name !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-param-reassign + json.name = name; + } + return parseGethParams(json, mergeForkIdPostMerge); + } + catch (e) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-template-expressions + throw new Error(`Error parsing parameters file: ${e.message}`); + } +} +exports.parseGethGenesis = parseGethGenesis; +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +function padToEven(value) { + let a = value; + if (typeof a !== 'string') { + throw new Error(`[padToEven] value must be type 'string', received ${typeof a}`); + } + if (a.length % 2) + a = `0${a}`; + return a; +} +exports.padToEven = padToEven; +/** + * Converts an `Number` to a `Uint8Array` + * @param {Number} i + * @return {Uint8Array} + */ +const intToUint8Array = function (i) { + const hex = intToHex(i); + return (0, web3_utils_1.hexToBytes)(`0x${padToEven(hex.slice(2))}`); +}; +exports.intToUint8Array = intToUint8Array; +/** + * Attempts to turn a value into a `Uint8Array`. + * Inputs supported: `Uint8Array` `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toUint8Array()` method. + * @param v the value + */ +const toUint8Array = function (v) { + // eslint-disable-next-line no-null/no-null + if (v === null || v === undefined) { + return new Uint8Array(); + } + if (v instanceof Uint8Array) { + return v; + } + if (Array.isArray(v)) { + return Uint8Array.from(v); + } + if (typeof v === 'string') { + if (!(0, web3_validator_1.isHexString)(v)) { + throw new Error(`Cannot convert string to Uint8Array. only supports 0x-prefixed hex strings and this string was given: ${v}`); + } + return (0, web3_utils_1.hexToBytes)(padToEven((0, exports.stripHexPrefix)(v))); + } + if (typeof v === 'number') { + return (0, exports.toUint8Array)((0, web3_utils_1.numberToHex)(v)); + } + if (typeof v === 'bigint') { + if (v < BigInt(0)) { + throw new Error(`Cannot convert negative bigint to Uint8Array. Given: ${v}`); + } + let n = v.toString(16); + if (n.length % 2) + n = `0${n}`; + return (0, exports.toUint8Array)(`0x${n}`); + } + if (v.toArray) { + // converts a BN to a Uint8Array + return Uint8Array.from(v.toArray()); + } + throw new Error('invalid type'); +}; +exports.toUint8Array = toUint8Array; +/** + * Converts a {@link Uint8Array} to a {@link bigint} + */ +function uint8ArrayToBigInt(buf) { + const hex = (0, web3_utils_1.bytesToHex)(buf); + if (hex === '0x') { + return BigInt(0); + } + return BigInt(hex); +} +exports.uint8ArrayToBigInt = uint8ArrayToBigInt; +/** + * Converts a {@link bigint} to a {@link Uint8Array} + */ +function bigIntToUint8Array(num) { + return (0, exports.toUint8Array)(`0x${num.toString(16)}`); +} +exports.bigIntToUint8Array = bigIntToUint8Array; +/** + * Returns a Uint8Array filled with 0s. + * @param bytes the number of bytes the Uint8Array should be + */ +const zeros = function (bytes) { + return new Uint8Array(bytes).fill(0); +}; +exports.zeros = zeros; +/** + * Pads a `Uint8Array` with zeros till it has `length` bytes. + * Truncates the beginning or end of input if its length exceeds `length`. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @param right whether to start padding form the left or right + * @return (Uint8Array) + */ +const setLength = function (msg, length, right) { + const buf = (0, exports.zeros)(length); + if (right) { + if (msg.length < length) { + buf.set(msg); + return buf; + } + return msg.subarray(0, length); + } + if (msg.length < length) { + buf.set(msg, length - msg.length); + return buf; + } + return msg.subarray(-length); +}; +/** + * Throws if input is not a Uint8Array + * @param {Uint8Array} input value to check + */ +function assertIsUint8Array(input) { + if (!(input instanceof Uint8Array)) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + const msg = `This method only supports Uint8Array but input was: ${input}`; + throw new Error(msg); + } +} +exports.assertIsUint8Array = assertIsUint8Array; +/** + * Left Pads a `Uint8Array` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @return (Uint8Array) + */ +const setLengthLeft = function (msg, length) { + assertIsUint8Array(msg); + return setLength(msg, length, false); +}; +exports.setLengthLeft = setLengthLeft; +/** + * Trims leading zeros from a `Uint8Array`, `String` or `Number[]`. + * @param a (Uint8Array|Array|String) + * @return (Uint8Array|Array|String) + */ +function stripZeros(a) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + let first = a[0]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + while (a.length > 0 && first.toString() === '0') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, prefer-destructuring, @typescript-eslint/no-unsafe-call, no-param-reassign + a = a.slice(1); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, prefer-destructuring, @typescript-eslint/no-unsafe-member-access + first = a[0]; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return a; +} +exports.stripZeros = stripZeros; +/** + * Trims leading zeros from a `Uint8Array`. + * @param a (Uint8Array) + * @return (Uint8Array) + */ +const unpadUint8Array = function (a) { + assertIsUint8Array(a); + return stripZeros(a); +}; +exports.unpadUint8Array = unpadUint8Array; +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +const bigIntToHex = (num) => `0x${num.toString(16)}`; +exports.bigIntToHex = bigIntToHex; +/** + * Convert value from bigint to an unpadded Uint8Array + * (useful for RLP transport) + * @param value value to convert + */ +function bigIntToUnpaddedUint8Array(value) { + return (0, exports.unpadUint8Array)(bigIntToUint8Array(value)); +} +exports.bigIntToUnpaddedUint8Array = bigIntToUnpaddedUint8Array; +function calculateSigRecovery(v, chainId) { + if (v === BigInt(0) || v === BigInt(1)) + return v; + if (chainId === undefined) { + return v - BigInt(27); + } + return v - (chainId * BigInt(2) + BigInt(35)); +} +function isValidSigRecovery(recovery) { + return recovery === BigInt(0) || recovery === BigInt(1); +} +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +const ecrecover = function (msgHash, v, r, s, chainId) { + const recovery = calculateSigRecovery(v, chainId); + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value'); + } + const senderPubKey = new constants_js_1.secp256k1.Signature(uint8ArrayToBigInt(r), uint8ArrayToBigInt(s)) + .addRecoveryBit(Number(recovery)) + .recoverPublicKey(msgHash) + .toRawBytes(false); + return senderPubKey.slice(1); +}; +exports.ecrecover = ecrecover; +function toType(input, outputType) { + // eslint-disable-next-line no-null/no-null + if (input === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + if (input === undefined) { + return undefined; + } + if (typeof input === 'string' && !(0, web3_validator_1.isHexString)(input)) { + throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`); + } + else if (typeof input === 'number' && !Number.isSafeInteger(input)) { + throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'); + } + const output = (0, exports.toUint8Array)(input); + switch (outputType) { + case types_js_1.TypeOutput.Uint8Array: + return output; + case types_js_1.TypeOutput.BigInt: + return uint8ArrayToBigInt(output); + case types_js_1.TypeOutput.Number: { + const bigInt = uint8ArrayToBigInt(output); + if (bigInt > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)'); + } + return Number(bigInt); + } + case types_js_1.TypeOutput.PrefixedHexString: + return (0, web3_utils_1.bytesToHex)(output); + default: + throw new Error('unknown outputType'); + } +} +exports.toType = toType; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.js.map new file mode 100644 index 0000000..b64097d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/common/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/common/utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,mDAA4D;AAC5D,2CAAiE;AACjE,qDAA+C;AAC/C,yCAAsC;AACtC,yCAAiF;AAOjF;;;;GAIG;AACI,MAAM,cAAc,GAAG,CAAC,GAAW,EAAU,EAAE;IACrD,IAAI,OAAO,GAAG,KAAK,QAAQ;QAC1B,MAAM,IAAI,KAAK,CAAC,0DAA0D,OAAO,GAAG,EAAE,CAAC,CAAC;IAEzF,OAAO,IAAA,8BAAa,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AAChD,CAAC,CAAC;AALW,QAAA,cAAc,kBAKzB;AACF;;;;GAIG;AACH,SAAS,WAAW,CAAC,KAAa;IACjC,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,KAAK,EAAE;QAC9B,OAAO,oBAAoB,CAAC;KAC5B;IACD,IAAI,IAAA,8BAAa,EAAC,KAAK,CAAC,EAAE;QACzB,OAAO,KAAK,IAAA,sBAAc,EAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,CAAC;KACtD;IACD,OAAO,KAAK,KAAK,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,CAAC;AACvC,CAAC;AAED;;;;GAIG;AACH,MAAM,QAAQ,GAAG,UAAU,CAAS;IACnC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QACtC,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,EAAE,CAAC,CAAC;KAC1D;IACD,OAAO,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CA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AA2C;IAC3C,IAAI,KAAK,KAAK,IAAI,EAAE;QACnB,2CAA2C;QAC3C,OAAO,IAAI,CAAC;KACZ;IACD,IAAI,KAAK,KAAK,SAAS,EAAE;QACxB,OAAO,SAAS,CAAC;KACjB;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,EAAE;QACrD,MAAM,IAAI,KAAK,CAAC,sDAAsD,KAAK,EAAE,CAAC,CAAC;KAC/E;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE;QACrE,MAAM,IAAI,KAAK,CACd,6FAA6F,CAC7F,CAAC;KACF;IAED,MAAM,MAAM,GAAG,IAAA,oBAAY,EAAC,KAAK,CAAC,CAAC;IAEnC,QAAQ,UAAU,EAAE;QACnB,KAAK,qBAAU,CAAC,UAAU;YACzB,OAAO,MAAiC,CAAC;QAC1C,KAAK,qBAAU,CAAC,MAAM;YACrB,OAAO,kBAAkB,CAAC,MAAM,CAA4B,CAAC;QAC9D,KAAK,qBAAU,CAAC,MAAM,CAAC,CAAC;YACvB,MAAM,MAAM,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;YAC1C,IAAI,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE;gBAC7C,MAAM,IAAI,KAAK,CACd,8FAA8F,CAC9F,CAAC;aACF;YACD,OAAO,MAAM,CAAC,MAAM,CAA4B,CAAC;SACjD;QACD,KAAK,qBAAU,CAAC,iBAAiB;YAChC,OAAO,IAAA,uBAAU,EAAC,MAAM,CAA4B,CAAC;QACtD;YACC,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;KACvC;AACF,CAAC;AA3CD,wBA2CC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.d.ts new file mode 100644 index 0000000..23730a0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.d.ts @@ -0,0 +1,27 @@ +/** + * The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data. + * + * **_NOTE:_** This package has NOT been audited and might potentially be unsafe. Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production! + * + * + * To use this package standalone and use its methods use: + * ```ts + * import { create, decrypt } from 'web3-eth-accounts'; // .... + * ``` + * + * To use this package within the web3 object use: + * + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // now you have access to the accounts class + * web3.eth.accounts.create(); + * ``` + */ +export * from './wallet.js'; +export * from './account.js'; +export * from './types.js'; +export * from './schemas.js'; +export * from './common/index.js'; +export * from './tx/index.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.js new file mode 100644 index 0000000..818bc33 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.js @@ -0,0 +1,60 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data. + * + * **_NOTE:_** This package has NOT been audited and might potentially be unsafe. Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production! + * + * + * To use this package standalone and use its methods use: + * ```ts + * import { create, decrypt } from 'web3-eth-accounts'; // .... + * ``` + * + * To use this package within the web3 object use: + * + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // now you have access to the accounts class + * web3.eth.accounts.create(); + * ``` + */ +__exportStar(require("./wallet.js"), exports); +__exportStar(require("./account.js"), exports); +__exportStar(require("./types.js"), exports); +__exportStar(require("./schemas.js"), exports); +__exportStar(require("./common/index.js"), exports); +__exportStar(require("./tx/index.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.js.map new file mode 100644 index 0000000..b4221c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,8CAA4B;AAC5B,+CAA6B;AAC7B,6CAA2B;AAC3B,+CAA6B;AAC7B,oDAAkC;AAClC,gDAA8B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.d.ts new file mode 100644 index 0000000..54896d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.d.ts @@ -0,0 +1,42 @@ +export declare const keyStoreSchema: { + type: string; + required: string[]; + properties: { + crypto: { + type: string; + required: string[]; + properties: { + cipher: { + type: string; + }; + ciphertext: { + type: string; + }; + cipherparams: { + type: string; + }; + kdf: { + type: string; + }; + kdfparams: { + type: string; + }; + salt: { + type: string; + }; + mac: { + type: string; + }; + }; + }; + id: { + type: string; + }; + version: { + type: string; + }; + address: { + type: string; + }; + }; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.js new file mode 100644 index 0000000..3db3ee3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.js @@ -0,0 +1,42 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keyStoreSchema = void 0; +exports.keyStoreSchema = { + type: 'object', + required: ['crypto', 'id', 'version', 'address'], + properties: { + crypto: { + type: 'object', + required: ['cipher', 'ciphertext', 'cipherparams', 'kdf', 'kdfparams', 'mac'], + properties: { + cipher: { type: 'string' }, + ciphertext: { type: 'string' }, + cipherparams: { type: 'object' }, + kdf: { type: 'string' }, + kdfparams: { type: 'object' }, + salt: { type: 'string' }, + mac: { type: 'string' }, + }, + }, + id: { type: 'string' }, + version: { type: 'number' }, + address: { type: 'string' }, + }, +}; +//# sourceMappingURL=schemas.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.js.map new file mode 100644 index 0000000..cad74d6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/schemas.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/schemas.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEW,QAAA,cAAc,GAAG;IAC7B,IAAI,EAAE,QAAQ;IACd,QAAQ,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,CAAC;IAChD,UAAU,EAAE;QACX,MAAM,EAAE;YACP,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC;YAC7E,UAAU,EAAE;gBACX,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC1B,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC9B,YAAY,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAChC,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBACvB,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC7B,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBACxB,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;aACvB;SACD;QACD,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QACtB,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QAC3B,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC3B;CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.d.ts new file mode 100644 index 0000000..2394729 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.d.ts @@ -0,0 +1,31 @@ +export declare class Address { + readonly buf: Uint8Array; + constructor(buf: Uint8Array); + /** + * Returns the zero address. + */ + static zero(): Address; + /** + * Is address equal to another. + */ + equals(address: Address): boolean; + /** + * Is address zero. + */ + isZero(): boolean; + /** + * Returns hex encoding of address. + */ + toString(): string; + /** + * Returns Uint8Array representation of address. + */ + toArray(): Uint8Array; + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ + static publicToAddress(_pubKey: Uint8Array, sanitize?: boolean): Uint8Array; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.js new file mode 100644 index 0000000..ff8a506 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Address = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const web3_utils_1 = require("web3-utils"); +const constants_js_1 = require("./constants.js"); +const utils_js_1 = require("../common/utils.js"); +class Address { + constructor(buf) { + if (buf.length !== 20) { + throw new Error('Invalid address length'); + } + this.buf = buf; + } + /** + * Returns the zero address. + */ + static zero() { + return new Address((0, utils_js_1.zeros)(20)); + } + /** + * Is address equal to another. + */ + equals(address) { + return (0, web3_utils_1.uint8ArrayEquals)(this.buf, address.buf); + } + /** + * Is address zero. + */ + isZero() { + return this.equals(Address.zero()); + } + /** + * Returns hex encoding of address. + */ + toString() { + return (0, web3_utils_1.bytesToHex)(this.buf); + } + /** + * Returns Uint8Array representation of address. + */ + toArray() { + return this.buf; + } + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ + static publicToAddress(_pubKey, sanitize = false) { + let pubKey = _pubKey; + (0, utils_js_1.assertIsUint8Array)(pubKey); + if (sanitize && pubKey.length !== 64) { + pubKey = constants_js_1.secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1); + } + if (pubKey.length !== 64) { + throw new Error('Expected pubKey to be of length 64'); + } + // Only take the lower 160bits of the hash + return (0, keccak_js_1.keccak256)(pubKey).slice(-20); + } +} +exports.Address = Address; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.js.map new file mode 100644 index 0000000..7ff5766 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../src/tx/address.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF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,CAAC,CAAC;SACtD;QACD,0CAA0C;QAC1C,OAAO,IAAA,qBAAS,EAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;IACrC,CAAC;CACD;AA/DD,0BA+DC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.d.ts new file mode 100644 index 0000000..9cb1f98 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.d.ts @@ -0,0 +1,197 @@ +import { Numbers } from 'web3-types'; +import { Common } from '../common/common.js'; +import { Hardfork, Chain } from '../common/enums.js'; +import type { AccessListEIP2930TxData, AccessListEIP2930ValuesArray, FeeMarketEIP1559TxData, FeeMarketEIP1559ValuesArray, JsonTx, TxData, TxOptions, TxValuesArray } from './types.js'; +import { Capability } from './types.js'; +import { Address } from './address.js'; +interface TransactionCache { + hash: Uint8Array | undefined; + dataFee?: { + value: bigint; + hardfork: string | Hardfork; + }; +} +/** + * This base class will likely be subject to further + * refactoring along the introduction of additional tx types + * on the Ethereum network. + * + * It is therefore not recommended to use directly. + */ +export declare abstract class BaseTransaction { + private readonly _type; + readonly nonce: bigint; + readonly gasLimit: bigint; + readonly to?: Address; + readonly value: bigint; + readonly data: Uint8Array; + readonly v?: bigint; + readonly r?: bigint; + readonly s?: bigint; + readonly common: Common; + protected cache: TransactionCache; + protected readonly txOptions: TxOptions; + /** + * List of tx type defining EIPs, + * e.g. 1559 (fee market) and 2930 (access lists) + * for FeeMarketEIP1559Transaction objects + */ + protected activeCapabilities: number[]; + /** + * The default chain the tx falls back to if no Common + * is provided and if the chain can't be derived from + * a passed in chainId (only EIP-2718 typed txs) or + * EIP-155 signature (legacy txs). + * + * @hidden + */ + protected DEFAULT_CHAIN: Chain; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string | Hardfork; + constructor(txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData, opts: TxOptions); + /** + * Returns the transaction type. + * + * Note: legacy txs will return tx type `0`. + */ + get type(): number; + /** + * Checks if a tx type defining capability is active + * on a tx, for example the EIP-1559 fee market mechanism + * or the EIP-2930 access list feature. + * + * Note that this is different from the tx type itself, + * so EIP-2930 access lists can very well be active + * on an EIP-1559 tx for example. + * + * This method can be useful for feature checks if the + * tx type is unknown (e.g. when instantiated with + * the tx factory). + * + * See `Capabilites` in the `types` module for a reference + * on all supported capabilities. + */ + supports(capability: Capability): boolean; + /** + * Checks if the transaction has the minimum amount of gas required + * (DataFee + TxFee + Creation Fee). + */ + validate(): boolean; + validate(stringError: false): boolean; + validate(stringError: true): string[]; + protected _validateYParity(): void; + /** + * EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2are considered invalid. + * Reasoning: https://ethereum.stackexchange.com/a/55728 + */ + protected _validateHighS(): void; + /** + * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + */ + getBaseFee(): bigint; + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + */ + abstract getUpfrontCost(): bigint; + /** + * If the tx's `to` is to the creation address + */ + toCreationAddress(): boolean; + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of this transaction, in order. + * + * Use {@link BaseTransaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link BaseTransaction.getMessageToSign}. + */ + abstract raw(): TxValuesArray | AccessListEIP2930ValuesArray | FeeMarketEIP1559ValuesArray; + /** + * Returns the encoding of the transaction. + */ + abstract serialize(): Uint8Array; + abstract getMessageToSign(hashMessage: false): Uint8Array | Uint8Array[]; + abstract getMessageToSign(hashMessage?: true): Uint8Array; + abstract hash(): Uint8Array; + abstract getMessageToVerifySignature(): Uint8Array; + isSigned(): boolean; + /** + * Determines if the signature is valid + */ + verifySignature(): boolean; + /** + * Returns the sender's address + */ + getSenderAddress(): Address; + /** + * Returns the public key of the sender + */ + abstract getSenderPublicKey(): Uint8Array; + /** + * Signs a transaction. + * + * Note that the signed tx is returned as a new object, + * use as follows: + * ```javascript + * const signedTx = tx.sign(privateKey) + * ``` + */ + sign(privateKey: Uint8Array): TransactionObject; + /** + * Returns an object with the JSON representation of the transaction + */ + abstract toJSON(): JsonTx; + protected abstract _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): TransactionObject; + /** + * Does chain ID checks on common and returns a common + * to be used on instantiation + * @hidden + * + * @param common - {@link Common} instance from tx options + * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) + */ + protected _getCommon(common?: Common, chainId?: Numbers): Common; + /** + * Validates that an object with BigInt values cannot exceed the specified bit limit. + * @param values Object containing string keys and BigInt values + * @param bits Number of bits to check (64 or 256) + * @param cannotEqual Pass true if the number also cannot equal one less the maximum value + */ + protected _validateCannotExceedMaxInteger(values: { + [key: string]: bigint | undefined; + }, bits?: number, cannotEqual?: boolean): void; + protected static _validateNotArray(values: { + [key: string]: any; + }): void; + /** + * Return a compact error string representation of the object + */ + abstract errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected abstract _errorMsg(msg: string): string; + /** + * Returns the shared error postfix part for _error() method + * tx type implementations. + */ + protected _getSharedErrorPostfix(): string; + private _ecsign; + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): any; + static fromTxData(txData: any, opts?: TxOptions): any; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.js new file mode 100644 index 0000000..cd592ac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.js @@ -0,0 +1,409 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseTransaction = void 0; +const web3_utils_1 = require("web3-utils"); +const constants_js_1 = require("./constants.js"); +const utils_js_1 = require("../common/utils.js"); +const common_js_1 = require("../common/common.js"); +const enums_js_1 = require("../common/enums.js"); +const types_js_1 = require("./types.js"); +const address_js_1 = require("./address.js"); +const utils_js_2 = require("./utils.js"); +/** + * This base class will likely be subject to further + * refactoring along the introduction of additional tx types + * on the Ethereum network. + * + * It is therefore not recommended to use directly. + */ +class BaseTransaction { + constructor(txData, opts) { + var _a, _b; + this.cache = { + hash: undefined, + dataFee: undefined, + }; + /** + * List of tx type defining EIPs, + * e.g. 1559 (fee market) and 2930 (access lists) + * for FeeMarketEIP1559Transaction objects + */ + this.activeCapabilities = []; + /** + * The default chain the tx falls back to if no Common + * is provided and if the chain can't be derived from + * a passed in chainId (only EIP-2718 typed txs) or + * EIP-155 signature (legacy txs). + * + * @hidden + */ + this.DEFAULT_CHAIN = enums_js_1.Chain.Mainnet; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + this.DEFAULT_HARDFORK = enums_js_1.Hardfork.Merge; + const { nonce, gasLimit, to, value, data, v, r, s, type } = txData; + this._type = Number((0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(type))); + this.txOptions = opts; + const toB = (0, utils_js_1.toUint8Array)(to === '' ? '0x' : to); + const vB = (0, utils_js_1.toUint8Array)(v === '' ? '0x' : v); + const rB = (0, utils_js_1.toUint8Array)(r === '' ? '0x' : r); + const sB = (0, utils_js_1.toUint8Array)(s === '' ? '0x' : s); + this.nonce = (0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(nonce === '' ? '0x' : nonce)); + this.gasLimit = (0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(gasLimit === '' ? '0x' : gasLimit)); + this.to = toB.length > 0 ? new address_js_1.Address(toB) : undefined; + this.value = (0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(value === '' ? '0x' : value)); + this.data = (0, utils_js_1.toUint8Array)(data === '' ? '0x' : data); + this.v = vB.length > 0 ? (0, utils_js_1.uint8ArrayToBigInt)(vB) : undefined; + this.r = rB.length > 0 ? (0, utils_js_1.uint8ArrayToBigInt)(rB) : undefined; + this.s = sB.length > 0 ? (0, utils_js_1.uint8ArrayToBigInt)(sB) : undefined; + this._validateCannotExceedMaxInteger({ value: this.value, r: this.r, s: this.s }); + // geth limits gasLimit to 2^64-1 + this._validateCannotExceedMaxInteger({ gasLimit: this.gasLimit }, 64); + // EIP-2681 limits nonce to 2^64-1 (cannot equal 2^64-1) + this._validateCannotExceedMaxInteger({ nonce: this.nonce }, 64, true); + // eslint-disable-next-line no-null/no-null + const createContract = this.to === undefined || this.to === null; + const allowUnlimitedInitCodeSize = (_a = opts.allowUnlimitedInitCodeSize) !== null && _a !== void 0 ? _a : false; + const common = (_b = opts.common) !== null && _b !== void 0 ? _b : this._getCommon(); + if (createContract && common.isActivatedEIP(3860) && !allowUnlimitedInitCodeSize) { + (0, utils_js_2.checkMaxInitCodeSize)(common, this.data.length); + } + } + /** + * Returns the transaction type. + * + * Note: legacy txs will return tx type `0`. + */ + get type() { + return this._type; + } + /** + * Checks if a tx type defining capability is active + * on a tx, for example the EIP-1559 fee market mechanism + * or the EIP-2930 access list feature. + * + * Note that this is different from the tx type itself, + * so EIP-2930 access lists can very well be active + * on an EIP-1559 tx for example. + * + * This method can be useful for feature checks if the + * tx type is unknown (e.g. when instantiated with + * the tx factory). + * + * See `Capabilites` in the `types` module for a reference + * on all supported capabilities. + */ + supports(capability) { + return this.activeCapabilities.includes(capability); + } + validate(stringError = false) { + const errors = []; + if (this.getBaseFee() > this.gasLimit) { + errors.push(`gasLimit is too low. given ${this.gasLimit}, need at least ${this.getBaseFee()}`); + } + if (this.isSigned() && !this.verifySignature()) { + errors.push('Invalid Signature'); + } + return stringError ? errors : errors.length === 0; + } + _validateYParity() { + const { v } = this; + if (v !== undefined && v !== BigInt(0) && v !== BigInt(1)) { + const msg = this._errorMsg('The y-parity of the transaction should either be 0 or 1'); + throw new Error(msg); + } + } + /** + * EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2are considered invalid. + * Reasoning: https://ethereum.stackexchange.com/a/55728 + */ + _validateHighS() { + const { s } = this; + if (this.common.gteHardfork('homestead') && s !== undefined && s > constants_js_1.SECP256K1_ORDER_DIV_2) { + const msg = this._errorMsg('Invalid Signature: s-values greater than secp256k1n/2 are considered invalid'); + throw new Error(msg); + } + } + /** + * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + */ + getBaseFee() { + const txFee = this.common.param('gasPrices', 'tx'); + let fee = this.getDataFee(); + if (txFee) + fee += txFee; + if (this.common.gteHardfork('homestead') && this.toCreationAddress()) { + const txCreationFee = this.common.param('gasPrices', 'txCreation'); + if (txCreationFee) + fee += txCreationFee; + } + return fee; + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + const txDataZero = this.common.param('gasPrices', 'txDataZero'); + const txDataNonZero = this.common.param('gasPrices', 'txDataNonZero'); + let cost = BigInt(0); + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < this.data.length; i += 1) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-unused-expressions + this.data[i] === 0 ? (cost += txDataZero) : (cost += txDataNonZero); + } + // eslint-disable-next-line no-null/no-null + if ((this.to === undefined || this.to === null) && this.common.isActivatedEIP(3860)) { + const dataLength = BigInt(Math.ceil(this.data.length / 32)); + const initCodeCost = this.common.param('gasPrices', 'initCodeWordCost') * dataLength; + cost += initCodeCost; + } + return cost; + } + /** + * If the tx's `to` is to the creation address + */ + toCreationAddress() { + return this.to === undefined || this.to.buf.length === 0; + } + isSigned() { + const { v, r, s } = this; + if (v === undefined || r === undefined || s === undefined) { + return false; + } + return true; + } + /** + * Determines if the signature is valid + */ + verifySignature() { + try { + // Main signature verification is done in `getSenderPublicKey()` + const publicKey = this.getSenderPublicKey(); + return (0, utils_js_1.unpadUint8Array)(publicKey).length !== 0; + } + catch (e) { + return false; + } + } + /** + * Returns the sender's address + */ + getSenderAddress() { + return new address_js_1.Address(address_js_1.Address.publicToAddress(this.getSenderPublicKey())); + } + /** + * Signs a transaction. + * + * Note that the signed tx is returned as a new object, + * use as follows: + * ```javascript + * const signedTx = tx.sign(privateKey) + * ``` + */ + sign(privateKey) { + if (privateKey.length !== 32) { + const msg = this._errorMsg('Private key must be 32 bytes in length.'); + throw new Error(msg); + } + // Hack for the constellation that we have got a legacy tx after spuriousDragon with a non-EIP155 conforming signature + // and want to recreate a signature (where EIP155 should be applied) + // Leaving this hack lets the legacy.spec.ts -> sign(), verifySignature() test fail + // 2021-06-23 + let hackApplied = false; + if (this.type === 0 && + this.common.gteHardfork('spuriousDragon') && + !this.supports(types_js_1.Capability.EIP155ReplayProtection)) { + this.activeCapabilities.push(types_js_1.Capability.EIP155ReplayProtection); + hackApplied = true; + } + const msgHash = this.getMessageToSign(true); + const { v, r, s } = this._ecsign(msgHash, privateKey); + const tx = this._processSignature(v, r, s); + // Hack part 2 + if (hackApplied) { + const index = this.activeCapabilities.indexOf(types_js_1.Capability.EIP155ReplayProtection); + if (index > -1) { + this.activeCapabilities.splice(index, 1); + } + } + return tx; + } + /** + * Does chain ID checks on common and returns a common + * to be used on instantiation + * @hidden + * + * @param common - {@link Common} instance from tx options + * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) + */ + _getCommon(common, chainId) { + var _a; + // Chain ID provided + if (chainId !== undefined) { + const chainIdBigInt = (0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(chainId)); + if (common) { + if (common.chainId() !== chainIdBigInt) { + const msg = this._errorMsg('The chain ID does not match the chain ID of Common'); + throw new Error(msg); + } + // Common provided, chain ID does match + // -> Return provided Common + return common.copy(); + } + if (common_js_1.Common.isSupportedChainId(chainIdBigInt)) { + // No Common, chain ID supported by Common + // -> Instantiate Common with chain ID + return new common_js_1.Common({ chain: chainIdBigInt, hardfork: this.DEFAULT_HARDFORK }); + } + // No Common, chain ID not supported by Common + // -> Instantiate custom Common derived from DEFAULT_CHAIN + return common_js_1.Common.custom({ + name: 'custom-chain', + networkId: chainIdBigInt, + chainId: chainIdBigInt, + }, { baseChain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK }); + } + // No chain ID provided + // -> return Common provided or create new default Common + return ((_a = common === null || common === void 0 ? void 0 : common.copy()) !== null && _a !== void 0 ? _a : new common_js_1.Common({ chain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK })); + } + /** + * Validates that an object with BigInt values cannot exceed the specified bit limit. + * @param values Object containing string keys and BigInt values + * @param bits Number of bits to check (64 or 256) + * @param cannotEqual Pass true if the number also cannot equal one less the maximum value + */ + _validateCannotExceedMaxInteger(values, bits = 256, cannotEqual = false) { + for (const [key, value] of Object.entries(values)) { + switch (bits) { + case 64: + if (cannotEqual) { + if (value !== undefined && value >= constants_js_1.MAX_UINT64) { + const msg = this._errorMsg(`${key} cannot equal or exceed MAX_UINT64 (2^64-1), given ${value}`); + throw new Error(msg); + } + } + else if (value !== undefined && value > constants_js_1.MAX_UINT64) { + const msg = this._errorMsg(`${key} cannot exceed MAX_UINT64 (2^64-1), given ${value}`); + throw new Error(msg); + } + break; + case 256: + if (cannotEqual) { + if (value !== undefined && value >= constants_js_1.MAX_INTEGER) { + const msg = this._errorMsg(`${key} cannot equal or exceed MAX_INTEGER (2^256-1), given ${value}`); + throw new Error(msg); + } + } + else if (value !== undefined && value > constants_js_1.MAX_INTEGER) { + const msg = this._errorMsg(`${key} cannot exceed MAX_INTEGER (2^256-1), given ${value}`); + throw new Error(msg); + } + break; + default: { + const msg = this._errorMsg('unimplemented bits value'); + throw new Error(msg); + } + } + } + } + static _validateNotArray(values) { + const txDataKeys = [ + 'nonce', + 'gasPrice', + 'gasLimit', + 'to', + 'value', + 'data', + 'v', + 'r', + 's', + 'type', + 'baseFee', + 'maxFeePerGas', + 'chainId', + ]; + for (const [key, value] of Object.entries(values)) { + if (txDataKeys.includes(key)) { + if (Array.isArray(value)) { + throw new Error(`${key} cannot be an array`); + } + } + } + } + /** + * Returns the shared error postfix part for _error() method + * tx type implementations. + */ + _getSharedErrorPostfix() { + let hash = ''; + try { + hash = this.isSigned() ? (0, web3_utils_1.bytesToHex)(this.hash()) : 'not available (unsigned)'; + } + catch (e) { + hash = 'error'; + } + let isSigned = ''; + try { + isSigned = this.isSigned().toString(); + } + catch (e) { + hash = 'error'; + } + let hf = ''; + try { + hf = this.common.hardfork(); + } + catch (e) { + hf = 'error'; + } + let postfix = `tx type=${this.type} hash=${hash} nonce=${this.nonce} value=${this.value} `; + postfix += `signed=${isSigned} hf=${hf}`; + return postfix; + } + // eslint-disable-next-line class-methods-use-this + _ecsign(msgHash, privateKey, chainId) { + const signature = constants_js_1.secp256k1.sign(msgHash, privateKey); + const signatureBytes = signature.toCompactRawBytes(); + const r = signatureBytes.subarray(0, 32); + const s = signatureBytes.subarray(32, 64); + const v = chainId === undefined + ? BigInt(signature.recovery + 27) + : BigInt(signature.recovery + 35) + BigInt(chainId) * BigInt(2); + return { r, s, v }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromSerializedTx( + // @ts-expect-error unused variable + serialized, + // @ts-expect-error unused variable + opts = {}) { } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromTxData( + // @ts-expect-error unused variable + txData, + // @ts-expect-error unused variable + opts = {}) { } +} +exports.BaseTransaction = BaseTransaction; +//# sourceMappingURL=baseTransaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.js.map new file mode 100644 index 0000000..ad24765 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/baseTransaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"baseTransaction.js","sourceRoot":"","sources":["../../../src/tx/baseTransaction.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,2CAAwC;AACxC,iDAA2F;AAC3F,iDAAuF;AACvF,mDAA6C;AAC7C,iDAAqD;AAWrD,yCAAwD;AACxD,6CAAuC;AACvC,yCAAkD;AAUlD;;;;;;GAMG;AACH,MAAsB,eAAe;IA+CpC,YACC,MAAiE,EACjE,IAAe;;QAlCN,UAAK,GAAqB;YACnC,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,SAAS;SAClB,CAAC;QAIF;;;;WAIG;QACO,uBAAkB,GAAa,EAAE,CAAC;QAE5C;;;;;;;WAOG;QACO,kBAAa,GAAG,gBAAK,CAAC,OAAO,CAAC;QAExC;;;;;WAKG;QACO,qBAAgB,GAAsB,mBAAQ,CAAC,KAAK,CAAC;QAM9D,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;QACnE,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,IAAA,6BAAkB,EAAC,IAAA,uBAAY,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAE5D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,MAAM,GAAG,GAAG,IAAA,uBAAY,EAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAA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AChB,CAAC;IACD,kDAAkD;IAC1C,OAAO,CAAC,OAAmB,EAAE,UAAsB,EAAE,OAAgB;QAC5E,MAAM,SAAS,GAAG,wBAAS,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;QACtD,MAAM,cAAc,GAAG,SAAS,CAAC,iBAAiB,EAAE,CAAC;QAErD,MAAM,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACzC,MAAM,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAE1C,MAAM,CAAC,GACN,OAAO,KAAK,SAAS;YACpB,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,QAAS,GAAG,EAAE,CAAC;YAClC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,QAAS,GAAG,EAAE,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAEnE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpB,CAAC;IAED,8DAA8D;IACvD,MAAM,CAAC,gBAAgB;IAC7B,mCAAmC;IACnC,UAAsB;IACtB,mCAAmC;IACnC,OAAkB,EAAE,IAEb,CAAC;IAET,8DAA8D;IACvD,MAAM,CAAC,UAAU;IACvB,mCAAmC;IACnC,MAAW;IACX,mCAAmC;IACnC,OAAkB,EAAE,IAEb,CAAC;CACT;AAhhBD,0CAghBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.d.ts new file mode 100644 index 0000000..615959f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.d.ts @@ -0,0 +1,61 @@ +export declare const secp256k1: Readonly<{ + create: (hash: import("@noble/curves/abstract/utils").CHash) => import("@noble/curves/abstract/weierstrass").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("@noble/curves/abstract/modular").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("@noble/curves/abstract/weierstrass").ProjConstructor, point: import("@noble/curves/abstract/weierstrass").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("@noble/curves/abstract/weierstrass").ProjConstructor, point: import("@noble/curves/abstract/weierstrass").ProjPointType) => import("@noble/curves/abstract/weierstrass").ProjPointType) | undefined; + readonly hash: import("@noble/curves/abstract/utils").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("@noble/curves/abstract/utils").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("@noble/curves/abstract/utils").PrivKey, publicB: import("@noble/curves/abstract/utils").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("@noble/curves/abstract/utils").Hex, privKey: import("@noble/curves/abstract/utils").PrivKey, opts?: import("@noble/curves/abstract/weierstrass").SignOpts | undefined) => import("@noble/curves/abstract/weierstrass").SignatureType; + verify: (signature: import("@noble/curves/abstract/utils").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("@noble/curves/abstract/utils").Hex, publicKey: import("@noble/curves/abstract/utils").Hex, opts?: import("@noble/curves/abstract/weierstrass").VerOpts | undefined) => boolean; + ProjectivePoint: import("@noble/curves/abstract/weierstrass").ProjConstructor; + Signature: import("@noble/curves/abstract/weierstrass").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("@noble/curves/abstract/utils").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("@noble/curves/abstract/utils").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("@noble/curves/abstract/weierstrass").ProjPointType | undefined) => import("@noble/curves/abstract/weierstrass").ProjPointType; + }; +}>; +/** + * 2^64-1 + */ +export declare const MAX_UINT64: bigint; +/** + * The max integer that the evm can handle (2^256-1) + */ +export declare const MAX_INTEGER: bigint; +export declare const SECP256K1_ORDER: bigint; +export declare const SECP256K1_ORDER_DIV_2: bigint; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.js new file mode 100644 index 0000000..80de85f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.js @@ -0,0 +1,57 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SECP256K1_ORDER_DIV_2 = exports.SECP256K1_ORDER = exports.MAX_INTEGER = exports.MAX_UINT64 = exports.secp256k1 = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line import/extensions +const ethereumCryptography = __importStar(require("ethereum-cryptography/secp256k1.js")); +exports.secp256k1 = (_a = ethereumCryptography.secp256k1) !== null && _a !== void 0 ? _a : ethereumCryptography; +/** + * 2^64-1 + */ +exports.MAX_UINT64 = BigInt('0xffffffffffffffff'); +/** + * The max integer that the evm can handle (2^256-1) + */ +exports.MAX_INTEGER = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +exports.SECP256K1_ORDER = exports.secp256k1.CURVE.n; +exports.SECP256K1_ORDER_DIV_2 = exports.SECP256K1_ORDER / BigInt(2); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.js.map new file mode 100644 index 0000000..8c2bf55 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/tx/constants.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAA6C;AAC7C,yFAA2E;AAE9D,QAAA,SAAS,GAAG,MAAA,oBAAoB,CAAC,SAAS,mCAAI,oBAAoB,CAAC;AAChF;;GAEG;AACU,QAAA,UAAU,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAEvD;;GAEG;AACU,QAAA,WAAW,GAAG,MAAM,CAChC,oEAAoE,CACpE,CAAC;AAEW,QAAA,eAAe,GAAG,iBAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AACpC,QAAA,qBAAqB,GAAG,uBAAe,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.d.ts new file mode 100644 index 0000000..7afff12 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.d.ts @@ -0,0 +1,136 @@ +import { BaseTransaction } from './baseTransaction.js'; +import type { AccessList, AccessListUint8Array, FeeMarketEIP1559TxData, FeeMarketEIP1559ValuesArray, JsonTx, TxOptions } from './types.js'; +import type { Common } from '../common/common.js'; +/** + * Typed transaction with a new gas fee market mechanism + * + * - TransactionType: 2 + * - EIP: [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) + */ +export declare class FeeMarketEIP1559Transaction extends BaseTransaction { + readonly chainId: bigint; + readonly accessList: AccessListUint8Array; + readonly AccessListJSON: AccessList; + readonly maxPriorityFeePerGas: bigint; + readonly maxFeePerGas: bigint; + readonly common: Common; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string; + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData: FeeMarketEIP1559TxData, opts?: TxOptions): FeeMarketEIP1559Transaction; + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + */ + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): FeeMarketEIP1559Transaction; + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + */ + static fromValuesArray(values: FeeMarketEIP1559ValuesArray, opts?: TxOptions): FeeMarketEIP1559Transaction; + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData: FeeMarketEIP1559TxData, opts?: TxOptions); + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + * @param baseFee The base fee of the block (will be set to 0 if not provided) + */ + getUpfrontCost(baseFee?: bigint): bigint; + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-1559 transaction, in order. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + * + * Use {@link FeeMarketEIP1559Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link FeeMarketEIP1559Transaction.getMessageToSign}. + */ + raw(): FeeMarketEIP1559ValuesArray; + /** + * Returns the serialized encoding of the EIP-1559 transaction. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize(): Uint8Array; + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage?: boolean): Uint8Array; + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link FeeMarketEIP1559Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash(): Uint8Array; + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature(): Uint8Array; + /** + * Returns the public key of the sender + */ + getSenderPublicKey(): Uint8Array; + _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): FeeMarketEIP1559Transaction; + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON(): JsonTx; + /** + * Return a compact error string representation of the object + */ + errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string): string; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.js new file mode 100644 index 0000000..9056d62 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.js @@ -0,0 +1,350 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FeeMarketEIP1559Transaction = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const web3_validator_1 = require("web3-validator"); +const rlp_1 = require("@ethereumjs/rlp"); +const web3_utils_1 = require("web3-utils"); +const constants_js_1 = require("./constants.js"); +const baseTransaction_js_1 = require("./baseTransaction.js"); +const utils_js_1 = require("./utils.js"); +const utils_js_2 = require("../common/utils.js"); +const TRANSACTION_TYPE = 2; +const TRANSACTION_TYPE_UINT8ARRAY = (0, web3_utils_1.hexToBytes)(TRANSACTION_TYPE.toString(16).padStart(2, '0')); +/** + * Typed transaction with a new gas fee market mechanism + * + * - TransactionType: 2 + * - EIP: [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) + */ +// eslint-disable-next-line no-use-before-define +class FeeMarketEIP1559Transaction extends baseTransaction_js_1.BaseTransaction { + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData, opts = {}) { + var _a; + super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE }), opts); + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + this.DEFAULT_HARDFORK = 'london'; + const { chainId, accessList, maxFeePerGas, maxPriorityFeePerGas } = txData; + this.common = this._getCommon(opts.common, chainId); + this.chainId = this.common.chainId(); + if (!this.common.isActivatedEIP(1559)) { + throw new Error('EIP-1559 not enabled on Common'); + } + this.activeCapabilities = this.activeCapabilities.concat([1559, 2718, 2930]); + // Populate the access list fields + const accessListData = (0, utils_js_1.getAccessListData)(accessList !== null && accessList !== void 0 ? accessList : []); + this.accessList = accessListData.accessList; + this.AccessListJSON = accessListData.AccessListJSON; + // Verify the access list format. + (0, utils_js_1.verifyAccessList)(this.accessList); + this.maxFeePerGas = (0, utils_js_2.uint8ArrayToBigInt)((0, utils_js_2.toUint8Array)(maxFeePerGas === '' ? '0x' : maxFeePerGas)); + this.maxPriorityFeePerGas = (0, utils_js_2.uint8ArrayToBigInt)((0, utils_js_2.toUint8Array)(maxPriorityFeePerGas === '' ? '0x' : maxPriorityFeePerGas)); + this._validateCannotExceedMaxInteger({ + maxFeePerGas: this.maxFeePerGas, + maxPriorityFeePerGas: this.maxPriorityFeePerGas, + }); + baseTransaction_js_1.BaseTransaction._validateNotArray(txData); + if (this.gasLimit * this.maxFeePerGas > constants_js_1.MAX_INTEGER) { + const msg = this._errorMsg('gasLimit * maxFeePerGas cannot exceed MAX_INTEGER (2^256-1)'); + throw new Error(msg); + } + if (this.maxFeePerGas < this.maxPriorityFeePerGas) { + const msg = this._errorMsg('maxFeePerGas cannot be less than maxPriorityFeePerGas (The total must be the larger of the two)'); + throw new Error(msg); + } + this._validateYParity(); + this._validateHighS(); + const freeze = (_a = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _a !== void 0 ? _a : true; + if (freeze) { + Object.freeze(this); + } + } + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData, opts = {}) { + return new FeeMarketEIP1559Transaction(txData, opts); + } + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + */ + static fromSerializedTx(serialized, opts = {}) { + if (!(0, web3_utils_1.uint8ArrayEquals)(serialized.subarray(0, 1), TRANSACTION_TYPE_UINT8ARRAY)) { + throw new Error(`Invalid serialized tx input: not an EIP-1559 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${(0, web3_utils_1.bytesToHex)(serialized.subarray(0, 1))}`); + } + const values = rlp_1.RLP.decode(serialized.subarray(1)); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input: must be array'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return FeeMarketEIP1559Transaction.fromValuesArray(values, opts); + } + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + */ + static fromValuesArray(values, opts = {}) { + if (values.length !== 9 && values.length !== 12) { + throw new Error('Invalid EIP-1559 transaction. Only expecting 9 values (for unsigned tx) or 12 values (for signed tx).'); + } + const [chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList, v, r, s,] = values; + this._validateNotArray({ chainId, v }); + (0, web3_validator_1.validateNoLeadingZeroes)({ + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + value, + v, + r, + s, + }); + return new FeeMarketEIP1559Transaction({ + chainId: (0, utils_js_2.uint8ArrayToBigInt)(chainId), + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + to, + value, + data, + accessList: accessList !== null && accessList !== void 0 ? accessList : [], + v: v !== undefined ? (0, utils_js_2.uint8ArrayToBigInt)(v) : undefined, + r, + s, + }, opts); + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + let cost = super.getDataFee(); + cost += BigInt((0, utils_js_1.getDataFeeEIP2930)(this.accessList, this.common)); + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: cost, + hardfork: this.common.hardfork(), + }; + } + return cost; + } + /** + * The up front amount that an account must have for this transaction to be valid + * @param baseFee The base fee of the block (will be set to 0 if not provided) + */ + getUpfrontCost(baseFee = BigInt(0)) { + const prio = this.maxPriorityFeePerGas; + const maxBase = this.maxFeePerGas - baseFee; + const inclusionFeePerGas = prio < maxBase ? prio : maxBase; + const gasPrice = inclusionFeePerGas + baseFee; + return this.gasLimit * gasPrice + this.value; + } + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-1559 transaction, in order. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + * + * Use {@link FeeMarketEIP1559Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link FeeMarketEIP1559Transaction.getMessageToSign}. + */ + raw() { + return [ + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.chainId), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.nonce), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.maxPriorityFeePerGas), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.maxFeePerGas), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.value), + this.data, + this.accessList, + this.v !== undefined ? (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.v) : Uint8Array.from([]), + this.r !== undefined ? (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.r) : Uint8Array.from([]), + this.s !== undefined ? (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.s) : Uint8Array.from([]), + ]; + } + /** + * Returns the serialized encoding of the EIP-1559 transaction. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize() { + const base = this.raw(); + return (0, web3_utils_1.uint8ArrayConcat)(TRANSACTION_TYPE_UINT8ARRAY, rlp_1.RLP.encode(base)); + } + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage = true) { + const base = this.raw().slice(0, 9); + const message = (0, web3_utils_1.uint8ArrayConcat)(TRANSACTION_TYPE_UINT8ARRAY, rlp_1.RLP.encode(base)); + if (hashMessage) { + return (0, keccak_js_1.keccak256)(message); + } + return message; + } + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link FeeMarketEIP1559Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = (0, keccak_js_1.keccak256)(this.serialize()); + } + return this.cache.hash; + } + return (0, keccak_js_1.keccak256)(this.serialize()); + } + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature() { + return this.getMessageToSign(); + } + /** + * Returns the public key of the sender + */ + getSenderPublicKey() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call this method if transaction is not signed'); + throw new Error(msg); + } + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + this._validateHighS(); + try { + return (0, utils_js_2.ecrecover)(msgHash, v + BigInt(27), // Recover the 27 which was stripped from ecsign + (0, utils_js_2.bigIntToUnpaddedUint8Array)(r), (0, utils_js_2.bigIntToUnpaddedUint8Array)(s)); + } + catch (e) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + _processSignature(v, r, s) { + const opts = Object.assign(Object.assign({}, this.txOptions), { common: this.common }); + return FeeMarketEIP1559Transaction.fromTxData({ + chainId: this.chainId, + nonce: this.nonce, + maxPriorityFeePerGas: this.maxPriorityFeePerGas, + maxFeePerGas: this.maxFeePerGas, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + accessList: this.accessList, + v: v - BigInt(27), + r: (0, utils_js_2.uint8ArrayToBigInt)(r), + s: (0, utils_js_2.uint8ArrayToBigInt)(s), + }, opts); + } + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON() { + const accessListJSON = (0, utils_js_1.getAccessListJSON)(this.accessList); + return { + chainId: (0, utils_js_2.bigIntToHex)(this.chainId), + nonce: (0, utils_js_2.bigIntToHex)(this.nonce), + maxPriorityFeePerGas: (0, utils_js_2.bigIntToHex)(this.maxPriorityFeePerGas), + maxFeePerGas: (0, utils_js_2.bigIntToHex)(this.maxFeePerGas), + gasLimit: (0, utils_js_2.bigIntToHex)(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: (0, utils_js_2.bigIntToHex)(this.value), + data: (0, web3_utils_1.bytesToHex)(this.data), + accessList: accessListJSON, + v: this.v !== undefined ? (0, utils_js_2.bigIntToHex)(this.v) : undefined, + r: this.r !== undefined ? (0, utils_js_2.bigIntToHex)(this.r) : undefined, + s: this.s !== undefined ? (0, utils_js_2.bigIntToHex)(this.s) : undefined, + }; + } + /** + * Return a compact error string representation of the object + */ + errorStr() { + let errorStr = this._getSharedErrorPostfix(); + errorStr += ` maxFeePerGas=${this.maxFeePerGas} maxPriorityFeePerGas=${this.maxPriorityFeePerGas}`; + return errorStr; + } + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + _errorMsg(msg) { + return `${msg} (${this.errorStr()})`; + } +} +exports.FeeMarketEIP1559Transaction = FeeMarketEIP1559Transaction; +//# sourceMappingURL=eip1559Transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.js.map new file mode 100644 index 0000000..b24d89c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip1559Transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eip1559Transaction.js","sourceRoot":"","sources":["../../../src/tx/eip1559Transaction.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,+DAA4D;AAC5D,mDAAyD;AACzD,yCAAsC;AACtC,2CAAwF;AACxF,iDAA6C;AAC7C,6DAAuD;AACvD,yCAKoB;AACpB,iDAM4B;AAW5B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,2BAA2B,GAAG,IAAA,uBAAU,EAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AAE/F;;;;;GAKG;AACH,gDAAgD;AAChD,MAAa,2BAA4B,SAAQ,oCAA4C;IAiH5F;;;;;;OAMG;IACH,YAAmB,MAA8B,EAAE,OAAkB,EAAE;;QACtE,KAAK,iCAAM,MAAM,KAAE,IAAI,EAAE,gBAAgB,KAAI,IAAI,CAAC,CAAC;QAhHpD;;;;;WAKG;QACO,qBAAgB,GAAG,QAAQ,CAAC;QA2GrC,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,oBAAoB,EAAE,GAAG,MAAM,CAAC;QAE3E,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACpD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAErC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE;YACtC,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SAClD;QACD,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;Q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C1B,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;YACzD,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;YACzD,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;SACzD,CAAC;IACH,CAAC;IAED;;OAEG;IACI,QAAQ;QACd,IAAI,QAAQ,GAAG,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC7C,QAAQ,IAAI,iBAAiB,IAAI,CAAC,YAAY,yBAAyB,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACnG,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,GAAW;QAC9B,OAAO,GAAG,GAAG,KAAK,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACtC,CAAC;CACD;AA1YD,kEA0YC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.d.ts new file mode 100644 index 0000000..0c184a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.d.ts @@ -0,0 +1,134 @@ +import { BaseTransaction } from './baseTransaction.js'; +import type { AccessList, AccessListUint8Array, AccessListEIP2930TxData, AccessListEIP2930ValuesArray, JsonTx, TxOptions } from './types.js'; +import type { Common } from '../common/common.js'; +/** + * Typed transaction with optional access lists + * + * - TransactionType: 1 + * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) + */ +export declare class AccessListEIP2930Transaction extends BaseTransaction { + readonly chainId: bigint; + readonly accessList: AccessListUint8Array; + readonly AccessListJSON: AccessList; + readonly gasPrice: bigint; + readonly common: Common; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string; + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData: AccessListEIP2930TxData, opts?: TxOptions): AccessListEIP2930Transaction; + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + */ + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): AccessListEIP2930Transaction; + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + */ + static fromValuesArray(values: AccessListEIP2930ValuesArray, opts?: TxOptions): AccessListEIP2930Transaction; + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData: AccessListEIP2930TxData, opts?: TxOptions); + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost(): bigint; + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-2930 transaction, in order. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + * + * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty UINT8ARRAY values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. + */ + raw(): AccessListEIP2930ValuesArray; + /** + * Returns the serialized encoding of the EIP-2930 transaction. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize(): Uint8Array; + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage?: boolean): Uint8Array; + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash(): Uint8Array; + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature(): Uint8Array; + /** + * Returns the public key of the sender + */ + getSenderPublicKey(): Uint8Array; + _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): AccessListEIP2930Transaction; + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON(): JsonTx; + /** + * Return a compact error string representation of the object + */ + errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string): string; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.js new file mode 100644 index 0000000..8167bbc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.js @@ -0,0 +1,330 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AccessListEIP2930Transaction = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const web3_validator_1 = require("web3-validator"); +const rlp_1 = require("@ethereumjs/rlp"); +const web3_utils_1 = require("web3-utils"); +const constants_js_1 = require("./constants.js"); +const utils_js_1 = require("./utils.js"); +const utils_js_2 = require("../common/utils.js"); +const baseTransaction_js_1 = require("./baseTransaction.js"); +const TRANSACTION_TYPE = 1; +const TRANSACTION_TYPE_UINT8ARRAY = (0, web3_utils_1.hexToBytes)(TRANSACTION_TYPE.toString(16).padStart(2, '0')); +/** + * Typed transaction with optional access lists + * + * - TransactionType: 1 + * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) + */ +// eslint-disable-next-line no-use-before-define +class AccessListEIP2930Transaction extends baseTransaction_js_1.BaseTransaction { + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData, opts = {}) { + var _a; + super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE }), opts); + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + this.DEFAULT_HARDFORK = 'berlin'; + const { chainId, accessList, gasPrice } = txData; + this.common = this._getCommon(opts.common, chainId); + this.chainId = this.common.chainId(); + // EIP-2718 check is done in Common + if (!this.common.isActivatedEIP(2930)) { + throw new Error('EIP-2930 not enabled on Common'); + } + this.activeCapabilities = this.activeCapabilities.concat([2718, 2930]); + // Populate the access list fields + const accessListData = (0, utils_js_1.getAccessListData)(accessList !== null && accessList !== void 0 ? accessList : []); + this.accessList = accessListData.accessList; + this.AccessListJSON = accessListData.AccessListJSON; + // Verify the access list format. + (0, utils_js_1.verifyAccessList)(this.accessList); + this.gasPrice = (0, utils_js_2.uint8ArrayToBigInt)((0, utils_js_2.toUint8Array)(gasPrice === '' ? '0x' : gasPrice)); + this._validateCannotExceedMaxInteger({ + gasPrice: this.gasPrice, + }); + baseTransaction_js_1.BaseTransaction._validateNotArray(txData); + if (this.gasPrice * this.gasLimit > constants_js_1.MAX_INTEGER) { + const msg = this._errorMsg('gasLimit * gasPrice cannot exceed MAX_INTEGER'); + throw new Error(msg); + } + this._validateYParity(); + this._validateHighS(); + const freeze = (_a = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _a !== void 0 ? _a : true; + if (freeze) { + Object.freeze(this); + } + } + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData, opts = {}) { + return new AccessListEIP2930Transaction(txData, opts); + } + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + */ + static fromSerializedTx(serialized, opts = {}) { + if (!(0, web3_utils_1.uint8ArrayEquals)(serialized.subarray(0, 1), TRANSACTION_TYPE_UINT8ARRAY)) { + throw new Error(`Invalid serialized tx input: not an EIP-2930 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${(0, web3_utils_1.bytesToHex)(serialized.subarray(0, 1))}`); + } + const values = rlp_1.RLP.decode(Uint8Array.from(serialized.subarray(1))); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input: must be array'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return AccessListEIP2930Transaction.fromValuesArray(values, opts); + } + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + */ + static fromValuesArray(values, opts = {}) { + if (values.length !== 8 && values.length !== 11) { + throw new Error('Invalid EIP-2930 transaction. Only expecting 8 values (for unsigned tx) or 11 values (for signed tx).'); + } + const [chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, v, r, s] = values; + this._validateNotArray({ chainId, v }); + (0, web3_validator_1.validateNoLeadingZeroes)({ nonce, gasPrice, gasLimit, value, v, r, s }); + const emptyAccessList = []; + return new AccessListEIP2930Transaction({ + chainId: (0, utils_js_2.uint8ArrayToBigInt)(chainId), + nonce, + gasPrice, + gasLimit, + to, + value, + data, + accessList: accessList !== null && accessList !== void 0 ? accessList : emptyAccessList, + v: v !== undefined ? (0, utils_js_2.uint8ArrayToBigInt)(v) : undefined, + r, + s, + }, opts); + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + let cost = super.getDataFee(); + cost += BigInt((0, utils_js_1.getDataFeeEIP2930)(this.accessList, this.common)); + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: cost, + hardfork: this.common.hardfork(), + }; + } + return cost; + } + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost() { + return this.gasLimit * this.gasPrice + this.value; + } + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-2930 transaction, in order. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + * + * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty UINT8ARRAY values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. + */ + raw() { + return [ + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.chainId), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.nonce), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.gasPrice), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.value), + this.data, + this.accessList, + this.v !== undefined ? (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.v) : Uint8Array.from([]), + this.r !== undefined ? (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.r) : Uint8Array.from([]), + this.s !== undefined ? (0, utils_js_2.bigIntToUnpaddedUint8Array)(this.s) : Uint8Array.from([]), + ]; + } + /** + * Returns the serialized encoding of the EIP-2930 transaction. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize() { + const base = this.raw(); + return (0, web3_utils_1.uint8ArrayConcat)(TRANSACTION_TYPE_UINT8ARRAY, rlp_1.RLP.encode(base)); + } + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage = true) { + const base = this.raw().slice(0, 8); + const message = (0, web3_utils_1.uint8ArrayConcat)(TRANSACTION_TYPE_UINT8ARRAY, rlp_1.RLP.encode(base)); + if (hashMessage) { + return (0, keccak_js_1.keccak256)(message); + } + return message; + } + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = (0, keccak_js_1.keccak256)(this.serialize()); + } + return this.cache.hash; + } + return (0, keccak_js_1.keccak256)(this.serialize()); + } + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature() { + return this.getMessageToSign(); + } + /** + * Returns the public key of the sender + */ + getSenderPublicKey() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call this method if transaction is not signed'); + throw new Error(msg); + } + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + this._validateHighS(); + try { + return (0, utils_js_2.ecrecover)(msgHash, v + BigInt(27), // Recover the 27 which was stripped from ecsign + (0, utils_js_2.bigIntToUnpaddedUint8Array)(r), (0, utils_js_2.bigIntToUnpaddedUint8Array)(s)); + } + catch (e) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + _processSignature(v, r, s) { + const opts = Object.assign(Object.assign({}, this.txOptions), { common: this.common }); + return AccessListEIP2930Transaction.fromTxData({ + chainId: this.chainId, + nonce: this.nonce, + gasPrice: this.gasPrice, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + accessList: this.accessList, + v: v - BigInt(27), + r: (0, utils_js_2.uint8ArrayToBigInt)(r), + s: (0, utils_js_2.uint8ArrayToBigInt)(s), + }, opts); + } + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON() { + const accessListJSON = (0, utils_js_1.getAccessListJSON)(this.accessList); + return { + chainId: (0, utils_js_2.bigIntToHex)(this.chainId), + nonce: (0, utils_js_2.bigIntToHex)(this.nonce), + gasPrice: (0, utils_js_2.bigIntToHex)(this.gasPrice), + gasLimit: (0, utils_js_2.bigIntToHex)(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: (0, utils_js_2.bigIntToHex)(this.value), + data: (0, web3_utils_1.bytesToHex)(this.data), + accessList: accessListJSON, + v: this.v !== undefined ? (0, utils_js_2.bigIntToHex)(this.v) : undefined, + r: this.r !== undefined ? (0, utils_js_2.bigIntToHex)(this.r) : undefined, + s: this.s !== undefined ? (0, utils_js_2.bigIntToHex)(this.s) : undefined, + }; + } + /** + * Return a compact error string representation of the object + */ + errorStr() { + var _a, _b; + let errorStr = this._getSharedErrorPostfix(); + // Keep ? for this.accessList since this otherwise causes Hardhat E2E tests to fail + errorStr += ` gasPrice=${this.gasPrice} accessListCount=${(_b = (_a = this.accessList) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0}`; + return errorStr; + } + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + _errorMsg(msg) { + return `${msg} (${this.errorStr()})`; + } +} +exports.AccessListEIP2930Transaction = AccessListEIP2930Transaction; +//# sourceMappingURL=eip2930Transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.js.map new file mode 100644 index 0000000..90c0bc1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/eip2930Transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eip2930Transaction.js","sourceRoot":"","sources":["../../../src/tx/eip2930Transaction.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,+DAA4D;AAC5D,mDAAyD;AACzD,yCAAsC;AACtC,2CAAwF;AACxF,iDAA6C;AAC7C,yCAKoB;AACpB,iDAM4B;AAC5B,6DAAuD;AAWvD,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,2BAA2B,GAAG,IAAA,uBAAU,EAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAA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AU,EAAE,cAAc;YAC1B,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;YACzD,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;YACzD,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,sBAAW,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;SACzD,CAAC;IACH,CAAC;IAED;;OAEG;IACI,QAAQ;;QACd,IAAI,QAAQ,GAAG,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC7C,mFAAmF;QACnF,QAAQ,IAAI,aAAa,IAAI,CAAC,QAAQ,oBAAoB,MAAA,MAAA,IAAI,CAAC,UAAU,0CAAE,MAAM,mCAAI,CAAC,EAAE,CAAC;QACzF,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,GAAW;QAC9B,OAAO,GAAG,GAAG,KAAK,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACtC,CAAC;CACD;AA/VD,oEA+VC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.d.ts new file mode 100644 index 0000000..3dc4819 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.d.ts @@ -0,0 +1,7 @@ +export { FeeMarketEIP1559Transaction } from './eip1559Transaction.js'; +export { AccessListEIP2930Transaction } from './eip2930Transaction.js'; +export { Transaction } from './legacyTransaction.js'; +export { TransactionFactory } from './transactionFactory.js'; +export { BaseTransaction } from './baseTransaction.js'; +export * as txUtils from './utils.js'; +export * from './types.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.js new file mode 100644 index 0000000..c52455f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.js @@ -0,0 +1,59 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.txUtils = exports.BaseTransaction = exports.TransactionFactory = exports.Transaction = exports.AccessListEIP2930Transaction = exports.FeeMarketEIP1559Transaction = void 0; +// @ethereumjs/tx version 4.1.1 +var eip1559Transaction_js_1 = require("./eip1559Transaction.js"); +Object.defineProperty(exports, "FeeMarketEIP1559Transaction", { enumerable: true, get: function () { return eip1559Transaction_js_1.FeeMarketEIP1559Transaction; } }); +var eip2930Transaction_js_1 = require("./eip2930Transaction.js"); +Object.defineProperty(exports, "AccessListEIP2930Transaction", { enumerable: true, get: function () { return eip2930Transaction_js_1.AccessListEIP2930Transaction; } }); +var legacyTransaction_js_1 = require("./legacyTransaction.js"); +Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return legacyTransaction_js_1.Transaction; } }); +var transactionFactory_js_1 = require("./transactionFactory.js"); +Object.defineProperty(exports, "TransactionFactory", { enumerable: true, get: function () { return transactionFactory_js_1.TransactionFactory; } }); +var baseTransaction_js_1 = require("./baseTransaction.js"); +Object.defineProperty(exports, "BaseTransaction", { enumerable: true, get: function () { return baseTransaction_js_1.BaseTransaction; } }); +exports.txUtils = __importStar(require("./utils.js")); +__exportStar(require("./types.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.js.map new file mode 100644 index 0000000..fae0b7d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/tx/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,+BAA+B;AAC/B,iEAAsE;AAA7D,oIAAA,2BAA2B,OAAA;AACpC,iEAAuE;AAA9D,qIAAA,4BAA4B,OAAA;AACrC,+DAAqD;AAA5C,mHAAA,WAAW,OAAA;AACpB,iEAA6D;AAApD,2HAAA,kBAAkB,OAAA;AAC3B,2DAAuD;AAA9C,qHAAA,eAAe,OAAA;AACxB,sDAAsC;AACtC,6CAA2B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.d.ts new file mode 100644 index 0000000..bc938da --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.d.ts @@ -0,0 +1,128 @@ +import { BaseTransaction } from './baseTransaction.js'; +import type { Common } from '../common/common.js'; +import type { JsonTx, TxData, TxOptions, TxValuesArray } from './types.js'; +/** + * An Ethereum non-typed (legacy) transaction + */ +export declare class Transaction extends BaseTransaction { + readonly gasPrice: bigint; + readonly common: Common; + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { nonce, gasPrice, gasLimit, to, value, data, v, r, s } + * + * Notes: + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData: TxData, opts?: TxOptions): Transaction; + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + */ + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): Transaction; + /** + * Create a transaction from a values array. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + */ + static fromValuesArray(values: TxValuesArray, opts?: TxOptions): Transaction; + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData: TxData, opts?: TxOptions); + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the legacy transaction, in order. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + * + * For legacy txs this is also the correct format to add transactions + * to a block with {@link Block.fromValuesArray} (use the `serialize()` method + * for typed txs). + * + * For an unsigned tx this method returns the empty Uint8Array values + * for the signature parameters `v`, `r` and `s`. For an EIP-155 compliant + * representation have a look at {@link Transaction.getMessageToSign}. + */ + raw(): TxValuesArray; + /** + * Returns the serialized encoding of the legacy transaction. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link Transaction.getMessageToSign}. + */ + serialize(): Uint8Array; + private _getMessageToSign; + /** + * Returns the unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: the raw message message format for the legacy tx is not RLP encoded + * and you might need to do yourself with: + * + * ```javascript + * import { bufArrToArr } from '../util' + * import { RLP } from '../rlp' + * const message = tx.getMessageToSign(false) + * const serializedMessage = RLP.encode(message) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage: false): Uint8Array[]; + getMessageToSign(hashMessage?: true): Uint8Array; + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost(): bigint; + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash(): Uint8Array; + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature(): Uint8Array; + /** + * Returns the public key of the sender + */ + getSenderPublicKey(): Uint8Array; + /** + * Process the v, r, s values from the `sign` method of the base transaction. + */ + protected _processSignature(_v: bigint, r: Uint8Array, s: Uint8Array): Transaction; + /** + * Returns an object with the JSON representation of the transaction. + */ + toJSON(): JsonTx; + /** + * Validates tx's `v` value + */ + private _validateTxV; + /** + * Return a compact error string representation of the object + */ + errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string): string; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.js new file mode 100644 index 0000000..5bb917a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.js @@ -0,0 +1,352 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transaction = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const rlp_1 = require("@ethereumjs/rlp"); +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const utils_js_1 = require("../common/utils.js"); +const constants_js_1 = require("./constants.js"); +const baseTransaction_js_1 = require("./baseTransaction.js"); +const types_js_1 = require("./types.js"); +const TRANSACTION_TYPE = 0; +function meetsEIP155(_v, chainId) { + const v = Number(_v); + const chainIdDoubled = Number(chainId) * 2; + return v === chainIdDoubled + 35 || v === chainIdDoubled + 36; +} +/** + * An Ethereum non-typed (legacy) transaction + */ +// eslint-disable-next-line no-use-before-define +class Transaction extends baseTransaction_js_1.BaseTransaction { + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData, opts = {}) { + var _a; + super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE }), opts); + this.common = this._validateTxV(this.v, opts.common); + this.gasPrice = (0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(txData.gasPrice === '' ? '0x' : txData.gasPrice)); + if (this.gasPrice * this.gasLimit > constants_js_1.MAX_INTEGER) { + const msg = this._errorMsg('gas limit * gasPrice cannot exceed MAX_INTEGER (2^256-1)'); + throw new Error(msg); + } + this._validateCannotExceedMaxInteger({ gasPrice: this.gasPrice }); + baseTransaction_js_1.BaseTransaction._validateNotArray(txData); + if (this.common.gteHardfork('spuriousDragon')) { + if (!this.isSigned()) { + this.activeCapabilities.push(types_js_1.Capability.EIP155ReplayProtection); + } + else { + // EIP155 spec: + // If block.number >= 2,675,000 and v = CHAIN_ID * 2 + 35 or v = CHAIN_ID * 2 + 36 + // then when computing the hash of a transaction for purposes of signing or recovering + // instead of hashing only the first six elements (i.e. nonce, gasprice, startgas, to, value, data) + // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0. + // v and chain ID meet EIP-155 conditions + // eslint-disable-next-line no-lonely-if + if (meetsEIP155(this.v, this.common.chainId())) { + this.activeCapabilities.push(types_js_1.Capability.EIP155ReplayProtection); + } + } + } + const freeze = (_a = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _a !== void 0 ? _a : true; + if (freeze) { + Object.freeze(this); + } + } + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { nonce, gasPrice, gasLimit, to, value, data, v, r, s } + * + * Notes: + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData, opts = {}) { + return new Transaction(txData, opts); + } + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + */ + static fromSerializedTx(serialized, opts = {}) { + const values = rlp_1.RLP.decode(serialized); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input. Must be array'); + } + return this.fromValuesArray(values, opts); + } + /** + * Create a transaction from a values array. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + */ + static fromValuesArray(values, opts = {}) { + // If length is not 6, it has length 9. If v/r/s are empty Uint8Array, it is still an unsigned transaction + // This happens if you get the RLP data from `raw()` + if (values.length !== 6 && values.length !== 9) { + throw new Error('Invalid transaction. Only expecting 6 values (for unsigned tx) or 9 values (for signed tx).'); + } + const [nonce, gasPrice, gasLimit, to, value, data, v, r, s] = values; + (0, web3_validator_1.validateNoLeadingZeroes)({ nonce, gasPrice, gasLimit, value, v, r, s }); + return new Transaction({ + nonce, + gasPrice, + gasLimit, + to, + value, + data, + v, + r, + s, + }, opts); + } + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the legacy transaction, in order. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + * + * For legacy txs this is also the correct format to add transactions + * to a block with {@link Block.fromValuesArray} (use the `serialize()` method + * for typed txs). + * + * For an unsigned tx this method returns the empty Uint8Array values + * for the signature parameters `v`, `r` and `s`. For an EIP-155 compliant + * representation have a look at {@link Transaction.getMessageToSign}. + */ + raw() { + return [ + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.nonce), + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.gasPrice), + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.value), + this.data, + this.v !== undefined ? (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.v) : Uint8Array.from([]), + this.r !== undefined ? (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.r) : Uint8Array.from([]), + this.s !== undefined ? (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.s) : Uint8Array.from([]), + ]; + } + /** + * Returns the serialized encoding of the legacy transaction. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link Transaction.getMessageToSign}. + */ + serialize() { + return rlp_1.RLP.encode(this.raw()); + } + _getMessageToSign() { + const values = [ + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.nonce), + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.gasPrice), + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + (0, utils_js_1.bigIntToUnpaddedUint8Array)(this.value), + this.data, + ]; + if (this.supports(types_js_1.Capability.EIP155ReplayProtection)) { + values.push((0, utils_js_1.toUint8Array)(this.common.chainId())); + values.push((0, utils_js_1.unpadUint8Array)((0, utils_js_1.toUint8Array)(0))); + values.push((0, utils_js_1.unpadUint8Array)((0, utils_js_1.toUint8Array)(0))); + } + return values; + } + getMessageToSign(hashMessage = true) { + const message = this._getMessageToSign(); + if (hashMessage) { + return (0, keccak_js_1.keccak256)(rlp_1.RLP.encode(message)); + } + return message; + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: super.getDataFee(), + hardfork: this.common.hardfork(), + }; + } + return super.getDataFee(); + } + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost() { + return this.gasLimit * this.gasPrice + this.value; + } + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = (0, keccak_js_1.keccak256)(rlp_1.RLP.encode(this.raw())); + } + return this.cache.hash; + } + return (0, keccak_js_1.keccak256)(rlp_1.RLP.encode(this.raw())); + } + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature() { + if (!this.isSigned()) { + const msg = this._errorMsg('This transaction is not signed'); + throw new Error(msg); + } + const message = this._getMessageToSign(); + return (0, keccak_js_1.keccak256)(rlp_1.RLP.encode(message)); + } + /** + * Returns the public key of the sender + */ + getSenderPublicKey() { + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + this._validateHighS(); + try { + return (0, utils_js_1.ecrecover)(msgHash, v, (0, utils_js_1.bigIntToUnpaddedUint8Array)(r), (0, utils_js_1.bigIntToUnpaddedUint8Array)(s), this.supports(types_js_1.Capability.EIP155ReplayProtection) + ? this.common.chainId() + : undefined); + } + catch (e) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + /** + * Process the v, r, s values from the `sign` method of the base transaction. + */ + _processSignature(_v, r, s) { + let v = _v; + if (this.supports(types_js_1.Capability.EIP155ReplayProtection)) { + v += this.common.chainId() * BigInt(2) + BigInt(8); + } + const opts = Object.assign(Object.assign({}, this.txOptions), { common: this.common }); + return Transaction.fromTxData({ + nonce: this.nonce, + gasPrice: this.gasPrice, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + v, + r: (0, utils_js_1.uint8ArrayToBigInt)(r), + s: (0, utils_js_1.uint8ArrayToBigInt)(s), + }, opts); + } + /** + * Returns an object with the JSON representation of the transaction. + */ + toJSON() { + return { + nonce: (0, utils_js_1.bigIntToHex)(this.nonce), + gasPrice: (0, utils_js_1.bigIntToHex)(this.gasPrice), + gasLimit: (0, utils_js_1.bigIntToHex)(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: (0, utils_js_1.bigIntToHex)(this.value), + data: (0, web3_utils_1.bytesToHex)(this.data), + v: this.v !== undefined ? (0, utils_js_1.bigIntToHex)(this.v) : undefined, + r: this.r !== undefined ? (0, utils_js_1.bigIntToHex)(this.r) : undefined, + s: this.s !== undefined ? (0, utils_js_1.bigIntToHex)(this.s) : undefined, + }; + } + /** + * Validates tx's `v` value + */ + _validateTxV(_v, common) { + let chainIdBigInt; + const v = _v !== undefined ? Number(_v) : undefined; + // Check for valid v values in the scope of a signed legacy tx + if (v !== undefined) { + // v is 1. not matching the EIP-155 chainId included case and... + // v is 2. not matching the classic v=27 or v=28 case + if (v < 37 && v !== 27 && v !== 28) { + throw new Error(`Legacy txs need either v = 27/28 or v >= 37 (EIP-155 replay protection), got v = ${v}`); + } + } + // No unsigned tx and EIP-155 activated and chain ID included + if (v !== undefined && + v !== 0 && + (!common || common.gteHardfork('spuriousDragon')) && + v !== 27 && + v !== 28) { + if (common) { + if (!meetsEIP155(BigInt(v), common.chainId())) { + throw new Error(`Incompatible EIP155-based V ${v} and chain id ${common.chainId()}. See the Common parameter of the Transaction constructor to set the chain id.`); + } + } + else { + // Derive the original chain ID + let numSub; + if ((v - 35) % 2 === 0) { + numSub = 35; + } + else { + numSub = 36; + } + // Use derived chain ID to create a proper Common + chainIdBigInt = BigInt(v - numSub) / BigInt(2); + } + } + return this._getCommon(common, chainIdBigInt); + } + /** + * Return a compact error string representation of the object + */ + errorStr() { + let errorStr = this._getSharedErrorPostfix(); + errorStr += ` gasPrice=${this.gasPrice}`; + return errorStr; + } + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + _errorMsg(msg) { + return `${msg} (${this.errorStr()})`; + } +} +exports.Transaction = Transaction; +//# sourceMappingURL=legacyTransaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.js.map new file mode 100644 index 0000000..9ac5e8d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/legacyTransaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"legacyTransaction.js","sourceRoot":"","sources":["../../../src/tx/legacyTransaction.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,yCAAsC;AACtC,+DAA4D;AAC5D,2CAAwC;AACxC,mDAAyD;AACzD,iDAO4B;AAC5B,iDAA6C;AAE7C,6DAAuD;AAIvD,yCAAwC;AAExC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B,SAAS,WAAW,CAAC,EAAU,EAAE,OAAe;IAC/C,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E;oBACvB,MAAM,GAAG,EAAE,CAAC;iBACZ;qBAAM;oBACN,MAAM,GAAG,EAAE,CAAC;iBACZ;gBACD,iDAAiD;gBACjD,aAAa,GAAG,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;aAC/C;SACD;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACI,QAAQ;QACd,IAAI,QAAQ,GAAG,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC7C,QAAQ,IAAI,aAAa,IAAI,CAAC,QAAQ,EAAE,CAAC;QACzC,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,GAAW;QAC9B,OAAO,GAAG,GAAG,KAAK,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACtC,CAAC;CACD;AAtYD,kCAsYC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.d.ts new file mode 100644 index 0000000..2abfb1e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.d.ts @@ -0,0 +1,33 @@ +import { Numbers } from 'web3-types'; +import type { TypedTransaction } from '../types.js'; +import type { TxData, TxOptions } from './types.js'; +import { BaseTransaction } from './baseTransaction.js'; +export declare class TransactionFactory { + private constructor(); + static typeToInt(txType: Numbers): number; + static registerTransactionType>(type: Numbers, txClass: NewTxTypeClass): void; + /** + * Create a transaction from a `txData` object + * + * @param txData - The transaction data. The `type` field will determine which transaction type is returned (if undefined, creates a legacy transaction) + * @param txOptions - Options to pass on to the constructor of the transaction + */ + static fromTxData(txData: TxData | TypedTransaction, txOptions?: TxOptions): TypedTransaction; + /** + * This method tries to decode serialized data. + * + * @param data - The data Uint8Array + * @param txOptions - The transaction options + */ + static fromSerializedData(data: Uint8Array, txOptions?: TxOptions): TypedTransaction; + /** + * When decoding a BlockBody, in the transactions field, a field is either: + * A Uint8Array (a TypedTransaction - encoded as TransactionType || rlp(TransactionPayload)) + * A Uint8Array[] (Legacy Transaction) + * This method returns the right transaction. + * + * @param data - A Uint8Array or Uint8Array[] + * @param txOptions - The transaction options + */ + static fromBlockBodyData(data: Uint8Array | Uint8Array[], txOptions?: TxOptions): TypedTransaction; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.js new file mode 100644 index 0000000..39bef45 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.js @@ -0,0 +1,101 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TransactionFactory = void 0; +const utils_js_1 = require("../common/utils.js"); +const eip1559Transaction_js_1 = require("./eip1559Transaction.js"); +const eip2930Transaction_js_1 = require("./eip2930Transaction.js"); +const legacyTransaction_js_1 = require("./legacyTransaction.js"); +const extraTxTypes = new Map(); +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +class TransactionFactory { + // It is not possible to instantiate a TransactionFactory object. + // eslint-disable-next-line @typescript-eslint/no-empty-function, no-useless-constructor + constructor() { } + static typeToInt(txType) { + return Number((0, utils_js_1.uint8ArrayToBigInt)((0, utils_js_1.toUint8Array)(txType))); + } + static registerTransactionType(type, txClass) { + const txType = TransactionFactory.typeToInt(type); + extraTxTypes.set(txType, txClass); + } + /** + * Create a transaction from a `txData` object + * + * @param txData - The transaction data. The `type` field will determine which transaction type is returned (if undefined, creates a legacy transaction) + * @param txOptions - Options to pass on to the constructor of the transaction + */ + static fromTxData(txData, txOptions = {}) { + if (!('type' in txData) || txData.type === undefined) { + // Assume legacy transaction + return legacyTransaction_js_1.Transaction.fromTxData(txData, txOptions); + } + const txType = TransactionFactory.typeToInt(txData.type); + if (txType === 0) { + return legacyTransaction_js_1.Transaction.fromTxData(txData, txOptions); + } + if (txType === 1) { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return eip2930Transaction_js_1.AccessListEIP2930Transaction.fromTxData( + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + txData, txOptions); + } + if (txType === 2) { + return eip1559Transaction_js_1.FeeMarketEIP1559Transaction.fromTxData( + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + txData, txOptions); + } + const ExtraTransaction = extraTxTypes.get(txType); + if (ExtraTransaction === null || ExtraTransaction === void 0 ? void 0 : ExtraTransaction.fromTxData) { + return ExtraTransaction.fromTxData(txData, txOptions); + } + throw new Error(`Tx instantiation with type ${txType} not supported`); + } + /** + * This method tries to decode serialized data. + * + * @param data - The data Uint8Array + * @param txOptions - The transaction options + */ + static fromSerializedData(data, txOptions = {}) { + if (data[0] <= 0x7f) { + // Determine the type. + switch (data[0]) { + case 1: + return eip2930Transaction_js_1.AccessListEIP2930Transaction.fromSerializedTx(data, txOptions); + case 2: + return eip1559Transaction_js_1.FeeMarketEIP1559Transaction.fromSerializedTx(data, txOptions); + default: { + const ExtraTransaction = extraTxTypes.get(Number(data[0])); + if (ExtraTransaction === null || ExtraTransaction === void 0 ? void 0 : ExtraTransaction.fromSerializedTx) { + return ExtraTransaction.fromSerializedTx(data, txOptions); + } + throw new Error(`TypedTransaction with ID ${data[0]} unknown`); + } + } + } + else { + return legacyTransaction_js_1.Transaction.fromSerializedTx(data, txOptions); + } + } + /** + * When decoding a BlockBody, in the transactions field, a field is either: + * A Uint8Array (a TypedTransaction - encoded as TransactionType || rlp(TransactionPayload)) + * A Uint8Array[] (Legacy Transaction) + * This method returns the right transaction. + * + * @param data - A Uint8Array or Uint8Array[] + * @param txOptions - The transaction options + */ + static fromBlockBodyData(data, txOptions = {}) { + if (data instanceof Uint8Array) { + return this.fromSerializedData(data, txOptions); + } + if (Array.isArray(data)) { + // It is a legacy transaction + return legacyTransaction_js_1.Transaction.fromValuesArray(data, txOptions); + } + throw new Error('Cannot decode transaction: unknown type input'); + } +} +exports.TransactionFactory = TransactionFactory; +//# sourceMappingURL=transactionFactory.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.js.map new file mode 100644 index 0000000..19eed15 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/transactionFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transactionFactory.js","sourceRoot":"","sources":["../../../src/tx/transactionFactory.ts"],"names":[],"mappings":";;;AAiBA,iDAAsE;AACtE,mEAAsE;AACtE,mEAAuE;AACvE,iEAAqD;AAWrD,MAAM,YAAY,GAAkD,IAAI,GAAG,EAAE,CAAC;AAE9E,kEAAkE;AAClE,MAAa,kBAAkB;IAC9B,iEAAiE;IACjE,wFAAwF;IACxF,gBAAuB,CAAC;IAEjB,MAAM,CAAC,SAAS,CAAC,MAAe;QACtC,OAAO,MAAM,CAAC,IAAA,6BAAkB,EAAC,IAAA,uBAAY,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACzD,CAAC;IAEM,MAAM,CAAC,uBAAuB,CACpC,IAAa,EACb,OAAuB;QAEvB,MAAM,MAAM,GAAG,kBAAkB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;QAClD,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,UAAU,CACvB,MAAiC,EACjC,YAAuB,EAAE;QAEzB,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE;YACrD,4BAA4B;YAC5B,OAAO,kCAAW,CAAC,UAAU,CAAC,MAAgB,EAAE,SAAS,CAAC,CAAC;SAC3D;QACD,M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AAC;oBAC3D,IAAI,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,gBAAgB,EAAE;wBACvC,OAAO,gBAAgB,CAAC,gBAAgB,CACvC,IAAI,EACJ,SAAS,CACW,CAAC;qBACtB;oBAED,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;iBAC/D;aACD;SACD;aAAM;YACN,OAAO,kCAAW,CAAC,gBAAgB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SACrD;IACF,CAAC;IAED;;;;;;;;OAQG;IACI,MAAM,CAAC,iBAAiB,CAAC,IAA+B,EAAE,YAAuB,EAAE;QACzF,IAAI,IAAI,YAAY,UAAU,EAAE;YAC/B,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SAChD;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACxB,6BAA6B;YAC7B,OAAO,kCAAW,CAAC,eAAe,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SACpD;QACD,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IAClE,CAAC;CACD;AA/GD,gDA+GC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.d.ts new file mode 100644 index 0000000..eb0de02 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.d.ts @@ -0,0 +1,221 @@ +import type { HexString, Numbers } from 'web3-types'; +import type { Common } from '../common/common.js'; +import type { Uint8ArrayLike, PrefixedHexString } from '../common/types'; +import { Address } from './address.js'; +/** + * Can be used in conjunction with {@link Transaction.supports} + * to query on tx capabilities + */ +export declare enum Capability { + /** + * Tx supports EIP-155 replay protection + * See: [155](https://eips.ethereum.org/EIPS/eip-155) Replay Attack Protection EIP + */ + EIP155ReplayProtection = 155, + /** + * Tx supports EIP-1559 gas fee market mechanism + * See: [1559](https://eips.ethereum.org/EIPS/eip-1559) Fee Market EIP + */ + EIP1559FeeMarket = 1559, + /** + * Tx is a typed transaction as defined in EIP-2718 + * See: [2718](https://eips.ethereum.org/EIPS/eip-2718) Transaction Type EIP + */ + EIP2718TypedTransaction = 2718, + /** + * Tx supports access list generation as defined in EIP-2930 + * See: [2930](https://eips.ethereum.org/EIPS/eip-2930) Access Lists EIP + */ + EIP2930AccessLists = 2930 +} +/** + * The options for initializing a {@link Transaction}. + */ +export interface TxOptions { + /** + * A {@link Common} object defining the chain and hardfork for the transaction. + * + * Object will be internally copied so that tx behavior don't incidentally + * change on future HF changes. + * + * Default: {@link Common} object set to `mainnet` and the default hardfork as defined in the {@link Common} class. + * + * Current default hardfork: `istanbul` + */ + common?: Common; + /** + * A transaction object by default gets frozen along initialization. This gives you + * strong additional security guarantees on the consistency of the tx parameters. + * It also enables tx hash caching when the `hash()` method is called multiple times. + * + * If you need to deactivate the tx freeze - e.g. because you want to subclass tx and + * add additional properties - it is strongly encouraged that you do the freeze yourself + * within your code instead. + * + * Default: true + */ + freeze?: boolean; + /** + * Allows unlimited contract code-size init while debugging. This (partially) disables EIP-3860. + * Gas cost for initcode size analysis will still be charged. Use with caution. + */ + allowUnlimitedInitCodeSize?: boolean; +} +export declare type AccessListItem = { + address: PrefixedHexString; + storageKeys: PrefixedHexString[]; +}; +export declare type AccessListUint8ArrayItem = [Uint8Array, Uint8Array[]]; +export declare type AccessListUint8Array = AccessListUint8ArrayItem[]; +export declare type AccessList = AccessListItem[]; +export declare function isAccessListUint8Array(input: AccessListUint8Array | AccessList): input is AccessListUint8Array; +export declare function isAccessList(input: AccessListUint8Array | AccessList): input is AccessList; +export interface ECDSASignature { + v: bigint; + r: Uint8Array; + s: Uint8Array; +} +/** + * Legacy {@link Transaction} Data + */ +export declare type TxData = { + /** + * The transaction's nonce. + */ + nonce?: Numbers | Uint8Array; + /** + * The transaction's gas price. + */ + gasPrice?: Numbers | Uint8Array | null; + /** + * The transaction's gas limit. + */ + gasLimit?: Numbers | Uint8Array; + /** + * The transaction's the address is sent to. + */ + to?: Address | Uint8Array | HexString; + /** + * The amount of Ether sent. + */ + value?: Numbers | Uint8Array; + /** + * This will contain the data of the message or the init of a contract. + */ + data?: Uint8ArrayLike; + /** + * EC recovery ID. + */ + v?: Numbers | Uint8Array; + /** + * EC signature parameter. + */ + r?: Numbers | Uint8Array; + /** + * EC signature parameter. + */ + s?: Numbers | Uint8Array; + /** + * The transaction type + */ + type?: Numbers; +}; +/** + * {@link AccessListEIP2930Transaction} data. + */ +export interface AccessListEIP2930TxData extends TxData { + /** + * The transaction's chain ID + */ + chainId?: Numbers; + /** + * The access list which contains the addresses/storage slots which the transaction wishes to access + */ + accessList?: AccessListUint8Array | AccessList | null; +} +/** + * {@link FeeMarketEIP1559Transaction} data. + */ +export interface FeeMarketEIP1559TxData extends AccessListEIP2930TxData { + /** + * The transaction's gas price, inherited from {@link Transaction}. This property is not used for EIP1559 + * transactions and should always be undefined for this specific transaction type. + */ + gasPrice?: never | null; + /** + * The maximum inclusion fee per gas (this fee is given to the miner) + */ + maxPriorityFeePerGas?: Numbers | Uint8Array; + /** + * The maximum total fee + */ + maxFeePerGas?: Numbers | Uint8Array; +} +/** + * Uint8Array values array for a legacy {@link Transaction} + */ +export declare type TxValuesArray = Uint8Array[]; +/** + * Uint8Array values array for an {@link AccessListEIP2930Transaction} + */ +export declare type AccessListEIP2930ValuesArray = [ + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + AccessListUint8Array, + Uint8Array?, + Uint8Array?, + Uint8Array? +]; +/** + * Uint8Array values array for a {@link FeeMarketEIP1559Transaction} + */ +export declare type FeeMarketEIP1559ValuesArray = [ + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + AccessListUint8Array, + Uint8Array?, + Uint8Array?, + Uint8Array? +]; +declare type JsonAccessListItem = { + address: string; + storageKeys: string[]; +}; +/** + * Generic interface for all tx types with a + * JSON representation of a transaction. + * + * Note that all values are marked as optional + * and not all the values are present on all tx types + * (an EIP1559 tx e.g. lacks a `gasPrice`). + */ +export interface JsonTx { + nonce?: string; + gasPrice?: string; + gasLimit?: string; + to?: string; + data?: string; + v?: string; + r?: string; + s?: string; + value?: string; + chainId?: string; + accessList?: JsonAccessListItem[]; + type?: string; + maxPriorityFeePerGas?: string; + maxFeePerGas?: string; + maxFeePerDataGas?: string; + versionedHashes?: string[]; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.js new file mode 100644 index 0000000..7685739 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAccessList = exports.isAccessListUint8Array = exports.Capability = void 0; +/** + * Can be used in conjunction with {@link Transaction.supports} + * to query on tx capabilities + */ +var Capability; +(function (Capability) { + /** + * Tx supports EIP-155 replay protection + * See: [155](https://eips.ethereum.org/EIPS/eip-155) Replay Attack Protection EIP + */ + Capability[Capability["EIP155ReplayProtection"] = 155] = "EIP155ReplayProtection"; + /** + * Tx supports EIP-1559 gas fee market mechanism + * See: [1559](https://eips.ethereum.org/EIPS/eip-1559) Fee Market EIP + */ + Capability[Capability["EIP1559FeeMarket"] = 1559] = "EIP1559FeeMarket"; + /** + * Tx is a typed transaction as defined in EIP-2718 + * See: [2718](https://eips.ethereum.org/EIPS/eip-2718) Transaction Type EIP + */ + Capability[Capability["EIP2718TypedTransaction"] = 2718] = "EIP2718TypedTransaction"; + /** + * Tx supports access list generation as defined in EIP-2930 + * See: [2930](https://eips.ethereum.org/EIPS/eip-2930) Access Lists EIP + */ + Capability[Capability["EIP2930AccessLists"] = 2930] = "EIP2930AccessLists"; +})(Capability = exports.Capability || (exports.Capability = {})); +function isAccessListUint8Array(input) { + if (input.length === 0) { + return true; + } + const firstItem = input[0]; + if (Array.isArray(firstItem)) { + return true; + } + return false; +} +exports.isAccessListUint8Array = isAccessListUint8Array; +function isAccessList(input) { + return !isAccessListUint8Array(input); // This is exactly the same method, except the output is negated. +} +exports.isAccessList = isAccessList; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.js.map new file mode 100644 index 0000000..3ffe4d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/tx/types.ts"],"names":[],"mappings":";;;AAuBA;;;GAGG;AACH,IAAY,UAwBX;AAxBD,WAAY,UAAU;IACrB;;;OAGG;IACH,iFAA4B,CAAA;IAE5B;;;OAGG;IACH,sEAAuB,CAAA;IAEvB;;;OAGG;IACH,oFAA8B,CAAA;IAE9B;;;OAGG;IACH,0EAAyB,CAAA;AAC1B,CAAC,EAxBW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAwBrB;AAqDD,SAAgB,sBAAsB,CACrC,KAAwC;IAExC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;QACvB,OAAO,IAAI,CAAC;KACZ;IACD,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3B,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QAC7B,OAAO,IAAI,CAAC;KACZ;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAXD,wDAWC;AAED,SAAgB,YAAY,CAAC,KAAwC;IACpE,OAAO,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC,iEAAiE;AACzG,CAAC;AAFD,oCAEC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.d.ts new file mode 100644 index 0000000..7278cbd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.d.ts @@ -0,0 +1,14 @@ +import { HexString } from 'web3-types'; +import type { AccessList, AccessListUint8Array } from './types.js'; +import type { Common } from '../common/common.js'; +export declare const checkMaxInitCodeSize: (common: Common, length: number) => void; +export declare const getAccessListData: (accessList: AccessListUint8Array | AccessList) => { + AccessListJSON: AccessList; + accessList: AccessListUint8Array; +}; +export declare const verifyAccessList: (accessList: AccessListUint8Array) => void; +export declare const getAccessListJSON: (accessList: AccessListUint8Array) => { + address: HexString; + storageKeys: HexString[]; +}[]; +export declare const getDataFeeEIP2930: (accessList: AccessListUint8Array, common: Common) => number; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.js new file mode 100644 index 0000000..6735a57 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDataFeeEIP2930 = exports.getAccessListJSON = exports.verifyAccessList = exports.getAccessListData = exports.checkMaxInitCodeSize = void 0; +const web3_utils_1 = require("web3-utils"); +const utils_js_1 = require("../common/utils.js"); +const types_js_1 = require("./types.js"); +const checkMaxInitCodeSize = (common, length) => { + const maxInitCodeSize = common.param('vm', 'maxInitCodeSize'); + if (maxInitCodeSize && BigInt(length) > maxInitCodeSize) { + throw new Error(`the initcode size of this transaction is too large: it is ${length} while the max is ${common.param('vm', 'maxInitCodeSize')}`); + } +}; +exports.checkMaxInitCodeSize = checkMaxInitCodeSize; +const getAccessListData = (accessList) => { + let AccessListJSON; + let uint8arrayAccessList; + if ((0, types_js_1.isAccessList)(accessList)) { + AccessListJSON = accessList; + const newAccessList = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < accessList.length; i += 1) { + const item = accessList[i]; + const addressBytes = (0, utils_js_1.toUint8Array)(item.address); + const storageItems = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < item.storageKeys.length; index += 1) { + storageItems.push((0, utils_js_1.toUint8Array)(item.storageKeys[index])); + } + newAccessList.push([addressBytes, storageItems]); + } + uint8arrayAccessList = newAccessList; + } + else { + uint8arrayAccessList = accessList !== null && accessList !== void 0 ? accessList : []; + // build the JSON + const json = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < uint8arrayAccessList.length; i += 1) { + const data = uint8arrayAccessList[i]; + const address = (0, web3_utils_1.bytesToHex)(data[0]); + const storageKeys = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let item = 0; item < data[1].length; item += 1) { + storageKeys.push((0, web3_utils_1.bytesToHex)(data[1][item])); + } + const jsonItem = { + address, + storageKeys, + }; + json.push(jsonItem); + } + AccessListJSON = json; + } + return { + AccessListJSON, + accessList: uint8arrayAccessList, + }; +}; +exports.getAccessListData = getAccessListData; +const verifyAccessList = (accessList) => { + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let key = 0; key < accessList.length; key += 1) { + const accessListItem = accessList[key]; + const address = accessListItem[0]; + const storageSlots = accessListItem[1]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions + if (accessListItem[2] !== undefined) { + throw new Error('Access list item cannot have 3 elements. It can only have an address, and an array of storage slots.'); + } + if (address.length !== 20) { + throw new Error('Invalid EIP-2930 transaction: address length should be 20 bytes'); + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let storageSlot = 0; storageSlot < storageSlots.length; storageSlot += 1) { + if (storageSlots[storageSlot].length !== 32) { + throw new Error('Invalid EIP-2930 transaction: storage slot length should be 32 bytes'); + } + } + } +}; +exports.verifyAccessList = verifyAccessList; +const getAccessListJSON = (accessList) => { + const accessListJSON = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < accessList.length; index += 1) { + const item = accessList[index]; + const JSONItem = { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions + address: (0, web3_utils_1.bytesToHex)((0, utils_js_1.setLengthLeft)(item[0], 20)), + storageKeys: [], + }; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/prefer-optional-chain + const storageSlots = item && item[1]; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let slot = 0; slot < storageSlots.length; slot += 1) { + const storageSlot = storageSlots[slot]; + JSONItem.storageKeys.push((0, web3_utils_1.bytesToHex)((0, utils_js_1.setLengthLeft)(storageSlot, 32))); + } + accessListJSON.push(JSONItem); + } + return accessListJSON; +}; +exports.getAccessListJSON = getAccessListJSON; +const getDataFeeEIP2930 = (accessList, common) => { + const accessListStorageKeyCost = common.param('gasPrices', 'accessListStorageKeyCost'); + const accessListAddressCost = common.param('gasPrices', 'accessListAddressCost'); + let slots = 0; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < accessList.length; index += 1) { + const item = accessList[index]; + const storageSlots = item[1]; + slots += storageSlots.length; + } + const addresses = accessList.length; + return addresses * Number(accessListAddressCost) + slots * Number(accessListStorageKeyCost); +}; +exports.getDataFeeEIP2930 = getDataFeeEIP2930; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.js.map new file mode 100644 index 0000000..0a17c84 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/tx/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../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IAAI,GAAG,YAAY,CAAC,MAAM,EAAE,IAAI,IAAI,CAAC,EAAE;YACzD,MAAM,WAAW,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;YACvC,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,IAAA,uBAAU,EAAC,IAAA,wBAAa,EAAC,WAAW,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;SACtE;QACD,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;KAC9B;IACD,OAAO,cAAc,CAAC;AACvB,CAAC,CAAC;AAzBW,QAAA,iBAAiB,qBAyB5B;AAEK,MAAM,iBAAiB,GAAG,CAAC,UAAgC,EAAE,MAAc,EAAU,EAAE;IAC7F,MAAM,wBAAwB,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,0BAA0B,CAAC,CAAC;IACvF,MAAM,qBAAqB,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,uBAAuB,CAAC,CAAC;IAEjF,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,4DAA4D;IAC5D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE;QAC1D,MAAM,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;QAC/B,MAAM,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAC7B,KAAK,IAAI,YAAY,CAAC,MAAM,CAAC;KAC7B;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC;IACpC,OAAO,SAAS,GAAG,MAAM,CAAC,qBAAqB,CAAC,GAAG,KAAK,GAAG,MAAM,CAAC,wBAAwB,CAAC,CAAC;AAC7F,CAAC,CAAC;AAdW,QAAA,iBAAiB,qBAc5B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.d.ts new file mode 100644 index 0000000..fbb6da6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.d.ts @@ -0,0 +1,54 @@ +import { Web3BaseWalletAccount, HexString } from 'web3-types'; +import { FeeMarketEIP1559TxData, AccessListEIP2930TxData, TxData } from './tx/types.js'; +import { AccessListEIP2930Transaction, FeeMarketEIP1559Transaction, Transaction } from './tx'; +export declare type SignatureObject = { + messageHash: string; + r: string; + s: string; + v: string; +}; +export declare type SignTransactionResult = SignatureObject & { + rawTransaction: string; + transactionHash: string; +}; +export declare type SignTransactionFunction = (transaction: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData | Record) => SignTransactionResult; +export declare type SignResult = SignatureObject & { + message?: string; + signature: string; +}; +export declare type SignFunction = (data: string, privateKey: string) => SignResult; +export interface Web3Account extends Web3BaseWalletAccount { + address: HexString; + privateKey: HexString; +} +/** This Web Storage API interface provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items. */ +export interface WebStorage { + /** Returns the number of key/value pairs. */ + readonly length: number; + /** + * Removes all key/value pairs, if there are any. + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + clear(): void; + /** Returns the current value associated with the given key, or null if the given key does not exist. */ + getItem(key: string): string | null; + /** Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs. */ + key(index: number): string | null; + /** + * Removes the key/value pair with the given key, if a key/value pair with the given key exists. + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + removeItem(key: string): void; + /** + * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. + * + * Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + setItem(key: string, value: string): void; + [name: string]: any; +} +export declare type TypedTransaction = Transaction | AccessListEIP2930Transaction | FeeMarketEIP1559Transaction; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.d.ts new file mode 100644 index 0000000..40390f3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.d.ts @@ -0,0 +1,277 @@ +import { Web3BaseWallet, Web3BaseWalletAccount, KeyStore } from 'web3-types'; +import { WebStorage } from './types.js'; +/** + * Wallet is an in memory `wallet` that can hold multiple accounts. + * These accounts can be used when using web3.eth.sendTransaction(). + * + * ### Parameters + * Web3AccountProvider - AccountProvider for the wallet + * + * ```ts + * import Web3 from 'web3'; + * const web3 = new Web3("https://localhost:8454") + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ +export declare class Wallet extends Web3BaseWallet { + private readonly _addressMap; + private readonly _defaultKeyName; + /** + * Get the storage object of the browser + * + * @returns the storage + */ + static getStorage(): WebStorage | undefined; + /** + * Generates one or more accounts in the wallet. If wallets already exist they will not be overridden. + * + * @param numberOfAccounts - Number of accounts to create. Leave empty to create an empty wallet. + * @returns The wallet + * ```ts + * web3.eth.accounts.wallet.create(2) + * > Wallet(2) [ + * { + * address: '0xde38310a42B751AE57d30cFFF4a0A3c52A442fCE', + * privateKey: '0x6422c9d28efdcbee93c1d32a5fc6fd6fa081b985487885296cf8c9bbb5872600', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * { + * address: '0x766BF755246d924B1d017Fdb5390f38a60166691', + * privateKey: '0x756530f13c0eb636ebdda655335f5dea9921e3362e2e588b0ad59e556f7751f0', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(2) { + * '0xde38310a42b751ae57d30cfff4a0a3c52a442fce' => 0, + * '0x766bf755246d924b1d017fdb5390f38a60166691' => 1 + * }, + * _defaultKeyName: 'web3js_wallet' + * ] + * + * ``` + */ + create(numberOfAccounts: number): this; + /** + * Adds an account using a private key or account object to the wallet. + * + * @param account - A private key or account object + * @returns The wallet + * + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * > Wallet(1) [ + * { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(1) { '0x85d70633b90e03e0276b98880286d0d055685ed7' => 0 }, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + add(account: T | string): this; + /** + * Get the account of the wallet with either the index or public address. + * + * @param addressOrIndex - A string of the address or number index within the wallet. + * @returns The account object or undefined if the account doesn't exist + */ + get(addressOrIndex: string | number): T | undefined; + /** + * Removes an account from the wallet. + * + * @param addressOrIndex - The account address, or index in the wallet. + * @returns true if the wallet was removed. false if it couldn't be found. + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * + * web3.eth.accounts.wallet.remove('0x85D70633b90e03e0276B98880286D0D055685ed7'); + * > true + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + remove(addressOrIndex: string | number): boolean; + /** + * Securely empties the wallet and removes all its accounts. + * Use this with *caution as it will remove all accounts stored in local wallet. + * + * @returns The wallet object + * ```ts + * + * web3.eth.accounts.wallet.clear(); + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + clear(): this; + /** + * Encrypts all wallet accounts to an array of encrypted keystore v3 objects. + * + * @param password - The password which will be used for encryption + * @param options - encryption options + * @returns An array of the encrypted keystore v3. + * + * ```ts + * web3.eth.accounts.wallet.create(1) + * web3.eth.accounts.wallet.encrypt("abc").then(console.log); + * > [ + * '{"version":3,"id":"fa46e213-a7c3-4844-b903-dd14d39cc7db", + * "address":"fa3e41a401609103c241431cbdee8623ae2a321a","crypto": + * {"ciphertext":"8d179a911d6146ad2924e86bf493ed89b8ff3596ffec0816e761c542016ab13c", + * "cipherparams":{"iv":"acc888c6cf4a19b86846cef0185a7164"},"cipher":"aes-128-ctr", + * "kdf":"scrypt","kdfparams":{"n":8192,"r":8,"p":1,"dklen":32,"salt":"6a743c9b367d15f4758e4f3f3378ff0fd443708d1c64854e07588ea5331823ae"}, + * "mac":"410544c8307e3691fda305eb3722d82c3431f212a87daa119a21587d96698b57"}}' + * ] + * ``` + */ + encrypt(password: string, options?: Record | undefined): Promise; + /** + * Decrypts keystore v3 objects. + * + * @param encryptedWallets - An array of encrypted keystore v3 objects to decrypt + * @param password - The password to encrypt with + * @param options - decrypt options for the wallets + * @returns The decrypted wallet object + * + * ```ts + * web3.eth.accounts.wallet.decrypt([ + * { version: 3, + * id: '83191a81-aaca-451f-b63d-0c5f3b849289', + * address: '06f702337909c06c82b09b7a22f0a2f0855d1f68', + * crypto: + * { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d', + * cipherparams: { iv: '497f4d26997a84d570778eae874b2333' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } }, + * { version: 3, + * id: '7d6b91fa-3611-407b-b16b-396efb28f97e', + * address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf', + * crypto: + * { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43', + * cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } } + * ], 'test').then(console.log) + * > Wallet { + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _defaultKeyName: 'web3js_wallet', + * _accounts: { + * '0x85d70633b90e03e0276b98880286d0d055685ed7': { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0x06f702337909c06c82b09b7a22f0a2f0855d1f68': { + * address: '0x06F702337909C06C82B09B7A22F0a2f0855d1F68', + * privateKey: '87a51da18900da7398b3bab03996833138f269f8f66dd1237b98df6b9ce14573', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0xb5d89661b59a9af0b34f58d19138baa2de48baaf': { + * address: '0xB5d89661B59a9aF0b34f58D19138bAa2de48BAaf', + * privateKey: '7ee61c5282979aae9dd795bb6a54e8bdc2bfe009acb64eb9a67322eec3b3da6e', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * } + * } + * } + * ``` + */ + decrypt(encryptedWallets: KeyStore[], password: string, options?: Record | undefined): Promise; + /** + * Stores the wallet encrypted and as string in local storage. + * **__NOTE:__** Browser only + * + * @param password - The password to encrypt the wallet + * @param keyName - (optional) The key used for the local storage position, defaults to `"web3js_wallet"`. + * @returns Will return boolean value true if saved properly + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * >true + * ``` + */ + save(password: string, keyName?: string): Promise; + /** + * Loads a wallet from local storage and decrypts it. + * **__NOTE:__** Browser only + * + * @param password - The password to decrypt the wallet. + * @param keyName - (optional)The key used for local storage position, defaults to `web3js_wallet"` + * @returns Returns the wallet object + * + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * > true + * web3.eth.accounts.wallet.load('test#!$'); + * { defaultKeyName: "web3js_wallet", + * length: 0, + * _accounts: Accounts {_requestManager: RequestManager, givenProvider: Proxy, providers: {…}, _provider: WebsocketProvider, …}, + * [[Prototype]]: Object + * } + * ``` + */ + load(password: string, keyName?: string): Promise; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.js new file mode 100644 index 0000000..8792817 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.js @@ -0,0 +1,417 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Wallet = void 0; +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +/** + * Wallet is an in memory `wallet` that can hold multiple accounts. + * These accounts can be used when using web3.eth.sendTransaction(). + * + * ### Parameters + * Web3AccountProvider - AccountProvider for the wallet + * + * ```ts + * import Web3 from 'web3'; + * const web3 = new Web3("https://localhost:8454") + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ +class Wallet extends web3_types_1.Web3BaseWallet { + constructor() { + super(...arguments); + this._addressMap = new Map(); + this._defaultKeyName = 'web3js_wallet'; + } + /** + * Get the storage object of the browser + * + * @returns the storage + */ + static getStorage() { + let storage; + try { + storage = window.localStorage; + const x = '__storage_test__'; + storage.setItem(x, x); + storage.removeItem(x); + return storage; + } + catch (e) { + return e && + // everything except Firefox + (e.code === 22 || + // Firefox + e.code === 1014 || + // test name field too, because code might not be present + // everything except Firefox + e.name === 'QuotaExceededError' || + // Firefox + e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && + // acknowledge QuotaExceededError only if there's something already stored + !(0, web3_validator_1.isNullish)(storage) && + storage.length !== 0 + ? storage + : undefined; + } + } + /** + * Generates one or more accounts in the wallet. If wallets already exist they will not be overridden. + * + * @param numberOfAccounts - Number of accounts to create. Leave empty to create an empty wallet. + * @returns The wallet + * ```ts + * web3.eth.accounts.wallet.create(2) + * > Wallet(2) [ + * { + * address: '0xde38310a42B751AE57d30cFFF4a0A3c52A442fCE', + * privateKey: '0x6422c9d28efdcbee93c1d32a5fc6fd6fa081b985487885296cf8c9bbb5872600', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * { + * address: '0x766BF755246d924B1d017Fdb5390f38a60166691', + * privateKey: '0x756530f13c0eb636ebdda655335f5dea9921e3362e2e588b0ad59e556f7751f0', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(2) { + * '0xde38310a42b751ae57d30cfff4a0a3c52a442fce' => 0, + * '0x766bf755246d924b1d017fdb5390f38a60166691' => 1 + * }, + * _defaultKeyName: 'web3js_wallet' + * ] + * + * ``` + */ + create(numberOfAccounts) { + for (let i = 0; i < numberOfAccounts; i += 1) { + this.add(this._accountProvider.create()); + } + return this; + } + /** + * Adds an account using a private key or account object to the wallet. + * + * @param account - A private key or account object + * @returns The wallet + * + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * > Wallet(1) [ + * { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(1) { '0x85d70633b90e03e0276b98880286d0d055685ed7' => 0 }, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + add(account) { + var _a; + if (typeof account === 'string') { + return this.add(this._accountProvider.privateKeyToAccount(account)); + } + let index = this.length; + const existAccount = this.get(account.address); + if (existAccount) { + console.warn(`Account ${account.address.toLowerCase()} already exists.`); + index = (_a = this._addressMap.get(account.address.toLowerCase())) !== null && _a !== void 0 ? _a : index; + } + this._addressMap.set(account.address.toLowerCase(), index); + this[index] = account; + return this; + } + /** + * Get the account of the wallet with either the index or public address. + * + * @param addressOrIndex - A string of the address or number index within the wallet. + * @returns The account object or undefined if the account doesn't exist + */ + get(addressOrIndex) { + if (typeof addressOrIndex === 'string') { + const index = this._addressMap.get(addressOrIndex.toLowerCase()); + if (!(0, web3_validator_1.isNullish)(index)) { + return this[index]; + } + return undefined; + } + return this[addressOrIndex]; + } + /** + * Removes an account from the wallet. + * + * @param addressOrIndex - The account address, or index in the wallet. + * @returns true if the wallet was removed. false if it couldn't be found. + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * + * web3.eth.accounts.wallet.remove('0x85D70633b90e03e0276B98880286D0D055685ed7'); + * > true + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + remove(addressOrIndex) { + if (typeof addressOrIndex === 'string') { + const index = this._addressMap.get(addressOrIndex.toLowerCase()); + if ((0, web3_validator_1.isNullish)(index)) { + return false; + } + this._addressMap.delete(addressOrIndex.toLowerCase()); + this.splice(index, 1); + return true; + } + if (this[addressOrIndex]) { + this.splice(addressOrIndex, 1); + return true; + } + return false; + } + /** + * Securely empties the wallet and removes all its accounts. + * Use this with *caution as it will remove all accounts stored in local wallet. + * + * @returns The wallet object + * ```ts + * + * web3.eth.accounts.wallet.clear(); + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + clear() { + this._addressMap.clear(); + // Setting length clears the Array in JS. + this.length = 0; + return this; + } + /** + * Encrypts all wallet accounts to an array of encrypted keystore v3 objects. + * + * @param password - The password which will be used for encryption + * @param options - encryption options + * @returns An array of the encrypted keystore v3. + * + * ```ts + * web3.eth.accounts.wallet.create(1) + * web3.eth.accounts.wallet.encrypt("abc").then(console.log); + * > [ + * '{"version":3,"id":"fa46e213-a7c3-4844-b903-dd14d39cc7db", + * "address":"fa3e41a401609103c241431cbdee8623ae2a321a","crypto": + * {"ciphertext":"8d179a911d6146ad2924e86bf493ed89b8ff3596ffec0816e761c542016ab13c", + * "cipherparams":{"iv":"acc888c6cf4a19b86846cef0185a7164"},"cipher":"aes-128-ctr", + * "kdf":"scrypt","kdfparams":{"n":8192,"r":8,"p":1,"dklen":32,"salt":"6a743c9b367d15f4758e4f3f3378ff0fd443708d1c64854e07588ea5331823ae"}, + * "mac":"410544c8307e3691fda305eb3722d82c3431f212a87daa119a21587d96698b57"}}' + * ] + * ``` + */ + encrypt(password, options) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(this.map((account) => __awaiter(this, void 0, void 0, function* () { return account.encrypt(password, options); }))); + }); + } + /** + * Decrypts keystore v3 objects. + * + * @param encryptedWallets - An array of encrypted keystore v3 objects to decrypt + * @param password - The password to encrypt with + * @param options - decrypt options for the wallets + * @returns The decrypted wallet object + * + * ```ts + * web3.eth.accounts.wallet.decrypt([ + * { version: 3, + * id: '83191a81-aaca-451f-b63d-0c5f3b849289', + * address: '06f702337909c06c82b09b7a22f0a2f0855d1f68', + * crypto: + * { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d', + * cipherparams: { iv: '497f4d26997a84d570778eae874b2333' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } }, + * { version: 3, + * id: '7d6b91fa-3611-407b-b16b-396efb28f97e', + * address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf', + * crypto: + * { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43', + * cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } } + * ], 'test').then(console.log) + * > Wallet { + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _defaultKeyName: 'web3js_wallet', + * _accounts: { + * '0x85d70633b90e03e0276b98880286d0d055685ed7': { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0x06f702337909c06c82b09b7a22f0a2f0855d1f68': { + * address: '0x06F702337909C06C82B09B7A22F0a2f0855d1F68', + * privateKey: '87a51da18900da7398b3bab03996833138f269f8f66dd1237b98df6b9ce14573', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0xb5d89661b59a9af0b34f58d19138baa2de48baaf': { + * address: '0xB5d89661B59a9aF0b34f58D19138bAa2de48BAaf', + * privateKey: '7ee61c5282979aae9dd795bb6a54e8bdc2bfe009acb64eb9a67322eec3b3da6e', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * } + * } + * } + * ``` + */ + decrypt(encryptedWallets, password, options) { + return __awaiter(this, void 0, void 0, function* () { + const results = yield Promise.all(encryptedWallets.map((wallet) => __awaiter(this, void 0, void 0, function* () { return this._accountProvider.decrypt(wallet, password, options); }))); + for (const res of results) { + this.add(res); + } + return this; + }); + } + /** + * Stores the wallet encrypted and as string in local storage. + * **__NOTE:__** Browser only + * + * @param password - The password to encrypt the wallet + * @param keyName - (optional) The key used for the local storage position, defaults to `"web3js_wallet"`. + * @returns Will return boolean value true if saved properly + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * >true + * ``` + */ + save(password, keyName) { + return __awaiter(this, void 0, void 0, function* () { + const storage = Wallet.getStorage(); + if (!storage) { + throw new Error('Local storage not available.'); + } + storage.setItem(keyName !== null && keyName !== void 0 ? keyName : this._defaultKeyName, JSON.stringify(yield this.encrypt(password))); + return true; + }); + } + /** + * Loads a wallet from local storage and decrypts it. + * **__NOTE:__** Browser only + * + * @param password - The password to decrypt the wallet. + * @param keyName - (optional)The key used for local storage position, defaults to `web3js_wallet"` + * @returns Returns the wallet object + * + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * > true + * web3.eth.accounts.wallet.load('test#!$'); + * { defaultKeyName: "web3js_wallet", + * length: 0, + * _accounts: Accounts {_requestManager: RequestManager, givenProvider: Proxy, providers: {…}, _provider: WebsocketProvider, …}, + * [[Prototype]]: Object + * } + * ``` + */ + load(password, keyName) { + return __awaiter(this, void 0, void 0, function* () { + const storage = Wallet.getStorage(); + if (!storage) { + throw new Error('Local storage not available.'); + } + const keystore = storage.getItem(keyName !== null && keyName !== void 0 ? keyName : this._defaultKeyName); + if (keystore) { + yield this.decrypt(JSON.parse(keystore) || [], password); + } + return this; + }); + } +} +exports.Wallet = Wallet; +//# sourceMappingURL=wallet.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.js.map new file mode 100644 index 0000000..ae303d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/commonjs/wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wallet.js","sourceRoot":"","sources":["../../src/wallet.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAA6E;AAC7E,mDAA2C;AAK3C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,MAEX,SAAQ,2BAAiB;IAF3B;;QAGkB,gBAAW,GAAG,IAAI,GAAG,EAA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;YACF,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;gBAC1B,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;aACd;YACD,OAAO,IAAI,CAAC;QACb,CAAC;KAAA;IAED;;;;;;;;;;;OAWG;IACU,IAAI,CAAC,QAAgB,EAAE,OAAgB;;YACnD,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;YAEpC,IAAI,CAAC,OAAO,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;aAChD;YAED,OAAO,CAAC,OAAO,CACd,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,IAAI,CAAC,eAAe,EAC/B,IAAI,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAC5C,CAAC;YAEF,OAAO,IAAI,CAAC;QACb,CAAC;KAAA;IAED;;;;;;;;;;;;;;;;;;OAkBG;IACU,IAAI,CAAC,QAAgB,EAAE,OAAgB;;YACnD,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;YAEpC,IAAI,CAAC,OAAO,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;aAChD;YAED,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,IAAI,CAAC,eAAe,CAAC,CAAC;YAElE,IAAI,QAAQ,EAAE;gBACb,MAAM,IAAI,CAAC,OAAO,CAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAgB,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAC;aACzE;YAED,OAAO,IAAI,CAAC;QACb,CAAC;KAAA;CACD;AA1YD,wBA0YC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/account.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/account.js new file mode 100644 index 0000000..aa9a4f8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/account.js @@ -0,0 +1,595 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { decrypt as createDecipheriv, encrypt as createCipheriv, } from 'ethereum-cryptography/aes.js'; +import { pbkdf2Sync } from 'ethereum-cryptography/pbkdf2.js'; +import { scryptSync } from 'ethereum-cryptography/scrypt.js'; +import { InvalidKdfError, InvalidPasswordError, InvalidPrivateKeyError, InvalidSignatureError, IVLengthError, KeyDerivationError, KeyStoreVersionError, PBKDF2IterationsError, PrivateKeyLengthError, TransactionSigningError, UndefinedRawTransactionError, } from 'web3-errors'; +import { bytesToUint8Array, bytesToHex, fromUtf8, hexToBytes, numberToHex, randomBytes, sha3Raw, toChecksumAddress, uint8ArrayConcat, utf8ToHex, uuidV4, } from 'web3-utils'; +import { isHexStrict, isNullish, isString, validator } from 'web3-validator'; +import { secp256k1 } from './tx/constants.js'; +import { keyStoreSchema } from './schemas.js'; +import { TransactionFactory } from './tx/transactionFactory.js'; +/** + * Get the private key Uint8Array after the validation + */ +export const parseAndValidatePrivateKey = (data, ignoreLength) => { + let privateKeyUint8Array; + // To avoid the case of 1 character less in a hex string which is prefixed with '0' by using 'bytesToUint8Array' + if (!ignoreLength && typeof data === 'string' && isHexStrict(data) && data.length !== 66) { + throw new PrivateKeyLengthError(); + } + try { + privateKeyUint8Array = data instanceof Uint8Array ? data : bytesToUint8Array(data); + } + catch (_a) { + throw new InvalidPrivateKeyError(); + } + if (!ignoreLength && privateKeyUint8Array.byteLength !== 32) { + throw new PrivateKeyLengthError(); + } + return privateKeyUint8Array; +}; +/** + * + * Hashes the given message. The data will be UTF-8 HEX decoded and enveloped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message and hashed using keccak256. + * + * @param message - A message to hash, if its HEX it will be UTF8 decoded. + * @returns The hashed message + * + * ```ts + * hashMessage("Hello world") + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * hashMessage(utf8ToHex("Hello world")) // Will be hex decoded in hashMessage + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * ``` + */ +export const hashMessage = (message) => { + const messageHex = isHexStrict(message) ? message : utf8ToHex(message); + const messageBytes = hexToBytes(messageHex); + const preamble = hexToBytes(fromUtf8(`\x19Ethereum Signed Message:\n${messageBytes.byteLength}`)); + const ethMessage = uint8ArrayConcat(preamble, messageBytes); + return sha3Raw(ethMessage); // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different +}; +/** + * Signs arbitrary data with a given private key. + * **_NOTE:_** The value passed as the data parameter will be UTF-8 HEX decoded and wrapped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message + * + * @param data - The data to sign + * @param privateKey - The 32 byte private key to sign with + * @returns The signature Object containing the message, messageHash, signature r, s, v + * + * ```ts + * web3.eth.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318') + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1c', + * r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', + * s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029', + * signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c' + * } + * ``` + */ +export const sign = (data, privateKey) => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + const hash = hashMessage(data); + const signature = secp256k1.sign(hash.substring(2), privateKeyUint8Array); + const signatureBytes = signature.toCompactRawBytes(); + const r = signature.r.toString(16).padStart(64, '0'); + const s = signature.s.toString(16).padStart(64, '0'); + const v = signature.recovery + 27; + return { + message: data, + messageHash: hash, + v: numberToHex(v), + r: `0x${r}`, + s: `0x${s}`, + signature: `${bytesToHex(signatureBytes)}${v.toString(16)}`, + }; +}; +/** + * Signs an Ethereum transaction with a given private key. + * + * @param transaction - The transaction, must be a legacy, EIP2930 or EIP 1559 transaction type + * @param privateKey - The private key to import. This is 32 bytes of random data. + * @returns A signTransactionResult object that contains message hash, r, s, v, transaction hash and raw transaction. + * + * This function is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * This function will rely on user to provide the full transaction to be signed. If you want to sign a partial transaction object + * Use {@link Web3.eth.accounts.sign} instead. + * + * Signing a legacy transaction + * ```ts + * signTransaction({ + * to: '0x118C2E5F57FD62C2B5b46a5ae9216F4FF4011a07', + * value: '0x186A0', + * gasLimit: '0x520812', + * gasPrice: '0x09184e72a000', + * data: '', + * chainId: 1, + * nonce: 0, + * }, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')) + * } + * > { + * messageHash: '0x28b7b75f7ba48d588a902c1ff4d5d13cc0ca9ac0aaa39562368146923fb853bf', + * v: '0x25', + * r: '0x601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5', + * s: '0x690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * rawTransaction: '0xf869808609184e72a0008352081294118c2e5f57fd62c2b5b46a5ae9216f4ff4011a07830186a08025a00601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5a0690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * ``` + * Signing an eip 1559 transaction + * ```ts + * signTransaction({ + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * maxPriorityFeePerGas: '0x3B9ACA00', + * maxFeePerGas: '0xB2D05E00', + * gasLimit: '0x6A4012', + * value: '0x186A0', + * data: '', + * chainId: 1, + * nonce: 0, + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0x5744f24d5f0aff6c70487c8e85adf07d8564e50b08558788f00479611d7bae5f', + * v: '0x25', + * r: '0x78a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347', + * s: '0x9cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * rawTransaction: '0xf8638080836a401294f0109fc8df283027b6285cc889f5aa624eac1f55830186a08025a078a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347a009cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + * Signing an eip 2930 transaction + * ```ts + * signTransaction({ + * chainId: 1, + * nonce: 0, + * gasPrice: '0x09184e72a000', + * gasLimit: '0x2710321', + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * value: '0x186A0', + * data: '', + * accessList: [ + * { + * address: '0x0000000000000000000000000000000000000101', + * storageKeys: [ + * '0x0000000000000000000000000000000000000000000000000000000000000000', + * '0x00000000000000000000000000000000000000000000000000000000000060a7', + * ], + * }, + * ], + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0xc55ea24bdb4c379550a7c9a6818ac39ca33e75bc78ddb862bd82c31cc1c7a073', + * v: '0x26', + * r: '0x27344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098e', + * s: '0x519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * rawTransaction: '0xf86a808609184e72a000840271032194f0109fc8df283027b6285cc889f5aa624eac1f55830186a08026a027344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098ea0519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + */ +export const signTransaction = (transaction, privateKey) => __awaiter(void 0, void 0, void 0, function* () { + const signedTx = transaction.sign(hexToBytes(privateKey)); + if (isNullish(signedTx.v) || isNullish(signedTx.r) || isNullish(signedTx.s)) + throw new TransactionSigningError('Signer Error'); + const validationErrors = signedTx.validate(true); + if (validationErrors.length > 0) { + let errorString = 'Signer Error '; + for (const validationError of validationErrors) { + errorString += `${errorString} ${validationError}.`; + } + throw new TransactionSigningError(errorString); + } + const rawTx = bytesToHex(signedTx.serialize()); + const txHash = sha3Raw(rawTx); // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different + return { + messageHash: bytesToHex(signedTx.getMessageToSign(true)), + v: `0x${signedTx.v.toString(16)}`, + r: `0x${signedTx.r.toString(16).padStart(64, '0')}`, + s: `0x${signedTx.s.toString(16).padStart(64, '0')}`, + rawTransaction: rawTx, + transactionHash: bytesToHex(txHash), + }; +}); +/** + * Recovers the Ethereum address which was used to sign the given RLP encoded transaction. + * + * @param rawTransaction - The hex string having RLP encoded transaction + * @returns The Ethereum address used to sign this transaction + * ```ts + * recoverTransaction('0xf869808504e3b29200831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a0c9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895a0727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68'); + * > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23" + * ``` + */ +export const recoverTransaction = (rawTransaction) => { + if (isNullish(rawTransaction)) + throw new UndefinedRawTransactionError(); + const tx = TransactionFactory.fromSerializedData(hexToBytes(rawTransaction)); + return toChecksumAddress(tx.getSenderAddress().toString()); +}; +/** + * Recovers the Ethereum address which was used to sign the given data + * + * @param data - Either a signed message, hash, or the {@link signatureObject} + * @param signature - The raw RLP encoded signature + * @param signatureOrV - signatureOrV + * @param prefixedOrR - prefixedOrR + * @param s - s + * @param prefixed - (default: false) If the last parameter is true, the given message will NOT automatically be prefixed with "\\x19Ethereum Signed Message:\\n" + message.length + message, and assumed to be already prefixed. + * @returns The Ethereum address used to sign this data + * ```ts + * sign('Some data', '0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728'); + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1b', + * r: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f9', + * s: '0x53e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb150', + * signature: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b' + * } + * recover('0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b'); + * > '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0' + * ``` + */ +export const recover = (data, signatureOrV, prefixedOrR, s, prefixed) => { + if (typeof data === 'object') { + const signatureStr = `${data.r}${data.s.slice(2)}${data.v.slice(2)}`; + return recover(data.messageHash, signatureStr, prefixedOrR); + } + if (typeof signatureOrV === 'string' && typeof prefixedOrR === 'string' && !isNullish(s)) { + const signatureStr = `${prefixedOrR}${s.slice(2)}${signatureOrV.slice(2)}`; + return recover(data, signatureStr, prefixed); + } + if (isNullish(signatureOrV)) + throw new InvalidSignatureError('signature string undefined'); + const V_INDEX = 130; // r = first 32 bytes, s = second 32 bytes, v = last byte of signature + const hashedMessage = prefixedOrR ? data : hashMessage(data); + let v = parseInt(signatureOrV.substring(V_INDEX), 16); // 0x + r + s + v + if (v > 26) { + v -= 27; + } + const ecPublicKey = secp256k1.Signature.fromCompact(signatureOrV.slice(2, V_INDEX)) + .addRecoveryBit(v) + .recoverPublicKey(hashedMessage.replace('0x', '')) + .toRawBytes(false); + const publicHash = sha3Raw(ecPublicKey.subarray(1)); + const address = toChecksumAddress(`0x${publicHash.slice(-40)}`); + return address; +}; +/** + * Get the ethereum Address from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns The Ethereum address + * @example + * ```ts + * privateKeyToAddress("0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728") + * > "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0" + * ``` + */ +export const privateKeyToAddress = (privateKey) => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + // Get public key from private key in compressed format + const publicKey = secp256k1.getPublicKey(privateKeyUint8Array, false); + // Uncompressed ECDSA public key contains the prefix `0x04` which is not used in the Ethereum public key + const publicKeyHash = sha3Raw(publicKey.slice(1)); + // The hash is returned as 256 bits (32 bytes) or 64 hex characters + // To get the address, take the last 20 bytes of the public hash + const address = publicKeyHash.slice(-40); + return toChecksumAddress(`0x${address}`); +}; +/** + * Get the public key from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param isCompressed - if true, will generate a 33 byte compressed public key instead of a 65 byte public key + * @returns The public key + * @example + * ```ts + * privateKeyToAddress("0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", true) + * > "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a" // uncompressed public key + * ``` + */ +export const privateKeyToPublicKey = (privateKey, isCompressed) => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + // Get public key from private key in compressed format + return `0x${bytesToHex(secp256k1.getPublicKey(privateKeyUint8Array, isCompressed)).slice(4)}`; // 0x and removing compression byte +}; +/** + * encrypt a private key with a password, returns a V3 JSON Keystore + * + * Read more: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + * + * @param privateKey - The private key to encrypt, 32 bytes. + * @param password - The password used for encryption. + * @param options - Options to configure to encrypt the keystore either scrypt or pbkdf2 + * @returns Returns a V3 JSON Keystore + * + * + * Encrypt using scrypt options + * ```ts + * encrypt('0x67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * '123', + * { + * n: 8192, + * iv: web3.utils.hexToBytes('0xbfb43120ae00e9de110f8325143a2709'), + * salt: web3.utils.hexToBytes('0x210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'), + * ), + * }).then(console.log) + * > { + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + *} + *``` + * Encrypting using pbkdf2 options + * ```ts + * encrypt('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + *'123', + *{ + * iv: 'bfb43120ae00e9de110f8325143a2709', + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * kdf: 'pbkdf2', + *}).then(console.log) + * > + * { + * version: 3, + * id: '77381417-0973-4e4b-b590-8eb3ace0fe2d', + * address: 'b8ce9ab6943e0eced004cde8e3bbed6568b2fa01', + * crypto: { + * ciphertext: '76512156a34105fa6473ad040c666ae7b917d14c06543accc0d2dc28e6073b12', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'pbkdf2', + * kdfparams: { + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * prf: 'hmac-sha256' + * }, + * mac: '46eb4884e82dc43b5aa415faba53cc653b7038e9d61cc32fd643cf8c396189b7' + * } + * } + *``` + */ +export const encrypt = (privateKey, password, options) => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d, _e, _f, _g; + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + // if given salt or iv is a string, convert it to a Uint8Array + let salt; + if (options === null || options === void 0 ? void 0 : options.salt) { + salt = typeof options.salt === 'string' ? hexToBytes(options.salt) : options.salt; + } + else { + salt = randomBytes(32); + } + if (!(isString(password) || password instanceof Uint8Array)) { + throw new InvalidPasswordError(); + } + const uint8ArrayPassword = typeof password === 'string' ? hexToBytes(utf8ToHex(password)) : password; + let initializationVector; + if (options === null || options === void 0 ? void 0 : options.iv) { + initializationVector = typeof options.iv === 'string' ? hexToBytes(options.iv) : options.iv; + if (initializationVector.length !== 16) { + throw new IVLengthError(); + } + } + else { + initializationVector = randomBytes(16); + } + const kdf = (_a = options === null || options === void 0 ? void 0 : options.kdf) !== null && _a !== void 0 ? _a : 'scrypt'; + let derivedKey; + let kdfparams; + // derive key from key derivation function + if (kdf === 'pbkdf2') { + kdfparams = { + dklen: (_b = options === null || options === void 0 ? void 0 : options.dklen) !== null && _b !== void 0 ? _b : 32, + salt: bytesToHex(salt).replace('0x', ''), + c: (_c = options === null || options === void 0 ? void 0 : options.c) !== null && _c !== void 0 ? _c : 262144, + prf: 'hmac-sha256', + }; + if (kdfparams.c < 1000) { + // error when c < 1000, pbkdf2 is less secure with less iterations + throw new PBKDF2IterationsError(); + } + derivedKey = pbkdf2Sync(uint8ArrayPassword, salt, kdfparams.c, kdfparams.dklen, 'sha256'); + } + else if (kdf === 'scrypt') { + kdfparams = { + n: (_d = options === null || options === void 0 ? void 0 : options.n) !== null && _d !== void 0 ? _d : 8192, + r: (_e = options === null || options === void 0 ? void 0 : options.r) !== null && _e !== void 0 ? _e : 8, + p: (_f = options === null || options === void 0 ? void 0 : options.p) !== null && _f !== void 0 ? _f : 1, + dklen: (_g = options === null || options === void 0 ? void 0 : options.dklen) !== null && _g !== void 0 ? _g : 32, + salt: bytesToHex(salt).replace('0x', ''), + }; + derivedKey = scryptSync(uint8ArrayPassword, salt, kdfparams.n, kdfparams.p, kdfparams.r, kdfparams.dklen); + } + else { + throw new InvalidKdfError(); + } + const cipher = yield createCipheriv(privateKeyUint8Array, derivedKey.slice(0, 16), initializationVector, 'aes-128-ctr'); + const ciphertext = bytesToHex(cipher).slice(2); + const mac = sha3Raw(uint8ArrayConcat(derivedKey.slice(16, 32), cipher)).replace('0x', ''); + return { + version: 3, + id: uuidV4(), + address: privateKeyToAddress(privateKeyUint8Array).toLowerCase().replace('0x', ''), + crypto: { + ciphertext, + cipherparams: { + iv: bytesToHex(initializationVector).replace('0x', ''), + }, + cipher: 'aes-128-ctr', + kdf, + kdfparams, + mac, + }, + }; +}); +/** + * Get an Account object from the privateKey + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns A Web3Account object + * + * The `Web3Account.signTransaction` is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * Use {@link Web3.eth.accounts.signTransaction} instead. + * + * ```ts + * privateKeyToAccount("0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709"); + * > { + * address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01', + * privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + * sign, + * signTransaction, + * encrypt, + * } + * ``` + */ +export const privateKeyToAccount = (privateKey, ignoreLength) => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey, ignoreLength); + return { + address: privateKeyToAddress(privateKeyUint8Array), + privateKey: bytesToHex(privateKeyUint8Array), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + signTransaction: (_tx) => { + throw new TransactionSigningError('Do not have network access to sign the transaction'); + }, + sign: (data) => sign(typeof data === 'string' ? data : JSON.stringify(data), privateKeyUint8Array), + encrypt: (password, options) => __awaiter(void 0, void 0, void 0, function* () { return encrypt(privateKeyUint8Array, password, options); }), + }; +}; +/** + * + * Generates and returns a Web3Account object that includes the private and public key + * For creation of private key, it uses an audited package ethereum-cryptography/secp256k1 + * that is cryptographically secure random number with certain characteristics. + * Read more: https://www.npmjs.com/package/ethereum-cryptography#secp256k1-curve + * + * @returns A Web3Account object + * ```ts + * web3.eth.accounts.create(); + * { + * address: '0xbD504f977021b5E5DdccD8741A368b147B3B38bB', + * privateKey: '0x964ced1c69ad27a311c432fdc0d8211e987595f7eb34ab405a5f16bdc9563ec5', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export const create = () => { + const privateKey = secp256k1.utils.randomPrivateKey(); + return privateKeyToAccount(`${bytesToHex(privateKey)}`); +}; +/** + * Decrypts a v3 keystore JSON, and creates the account. + * + * @param keystore - the encrypted Keystore object or string to decrypt + * @param password - The password that was used for encryption + * @param nonStrict - if true and given a json string, the keystore will be parsed as lowercase. + * @returns Returns the decrypted Web3Account object + * Decrypting scrypt + * + * ```ts + * decrypt({ + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + * }, '123').then(console.log) + * > { + * address: '0xcdA9A91875fc35c8Ac1320E098e584495d66e47c', + * privateKey: '67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export const decrypt = (keystore, password, nonStrict) => __awaiter(void 0, void 0, void 0, function* () { + const json = typeof keystore === 'object' + ? keystore + : JSON.parse(nonStrict ? keystore.toLowerCase() : keystore); + validator.validateJSONSchema(keyStoreSchema, json); + if (json.version !== 3) + throw new KeyStoreVersionError(); + const uint8ArrayPassword = typeof password === 'string' ? hexToBytes(utf8ToHex(password)) : password; + validator.validate(['bytes'], [uint8ArrayPassword]); + let derivedKey; + if (json.crypto.kdf === 'scrypt') { + const kdfparams = json.crypto.kdfparams; + const uint8ArraySalt = typeof kdfparams.salt === 'string' ? hexToBytes(kdfparams.salt) : kdfparams.salt; + derivedKey = scryptSync(uint8ArrayPassword, uint8ArraySalt, kdfparams.n, kdfparams.p, kdfparams.r, kdfparams.dklen); + } + else if (json.crypto.kdf === 'pbkdf2') { + const kdfparams = json.crypto.kdfparams; + const uint8ArraySalt = typeof kdfparams.salt === 'string' ? hexToBytes(kdfparams.salt) : kdfparams.salt; + derivedKey = pbkdf2Sync(uint8ArrayPassword, uint8ArraySalt, kdfparams.c, kdfparams.dklen, 'sha256'); + } + else { + throw new InvalidKdfError(); + } + const ciphertext = hexToBytes(json.crypto.ciphertext); + const mac = sha3Raw(uint8ArrayConcat(derivedKey.slice(16, 32), ciphertext)).replace('0x', ''); + if (mac !== json.crypto.mac) { + throw new KeyDerivationError(); + } + const seed = yield createDecipheriv(hexToBytes(json.crypto.ciphertext), derivedKey.slice(0, 16), hexToBytes(json.crypto.cipherparams.iv)); + return privateKeyToAccount(seed); +}); +//# sourceMappingURL=account.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/account.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/account.js.map new file mode 100644 index 0000000..b4feee0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/account.js.map @@ -0,0 +1 @@ +{"version":3,"file":"account.js","sourceRoot":"","sources":["../../src/account.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EACN,OAAO,IAAI,gBAAgB,EAC3B,OAAO,IAAI,cAAc,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EACN,eAAe,EACf,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,aAAa,EACb,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,EACvB,4BAA4B,GAC5B,MAAM,aAAa,CAAC;AAWrB,OAAO,EACN,iBAAiB,EACjB,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,EACX,WAAW,EACX,OAAO,EACP,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACT,MAAM,GACN,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,WAAW,EAAE,SAAS,E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K,CACf,CAAC;KACF;SAAM,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,KAAK,QAAQ,EAAE;QACxC,MAAM,SAAS,GAAuB,IAAI,CAAC,MAAM,CAAC,SAA+B,CAAC;QAElF,MAAM,cAAc,GACnB,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC;QAElF,UAAU,GAAG,UAAU,CACtB,kBAAkB,EAClB,cAAc,EACd,SAAS,CAAC,CAAC,EACX,SAAS,CAAC,KAAK,EACf,QAAQ,CACR,CAAC;KACF;SAAM;QACN,MAAM,IAAI,eAAe,EAAE,CAAC;KAC5B;IAED,MAAM,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IACtD,MAAM,GAAG,GAAG,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAE9F,IAAI,GAAG,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;QAC5B,MAAM,IAAI,kBAAkB,EAAE,CAAC;KAC/B;IAED,MAAM,IAAI,GAAG,MAAM,gBAAgB,CAClC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,EAClC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EACvB,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC,CACvC,CAAC;IAEF,OAAO,mBAAmB,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC,CAAA,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/goerli.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/goerli.js new file mode 100644 index 0000000..2dcb0db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/goerli.js @@ -0,0 +1,97 @@ +export default { + "name": "goerli", + "chainId": 5, + "networkId": 5, + "defaultHardfork": "merge", + "consensus": { + "type": "poa", + "algorithm": "clique", + "clique": { + "period": 15, + "epoch": 30000 + } + }, + "comment": "Cross-client PoA test network", + "url": "https://github.com/goerli/testnet", + "genesis": { + "timestamp": "0x5c51a607", + "gasLimit": 10485760, + "difficulty": 1, + "nonce": "0x0000000000000000", + "extraData": "0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "homestead", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "tangerineWhistle", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "spuriousDragon", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "byzantium", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "constantinople", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "petersburg", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "istanbul", + "block": 1561651, + "forkHash": "0xc25efa5c" + }, + { + "name": "berlin", + "block": 4460644, + "forkHash": "0x757a1c47" + }, + { + "name": "london", + "block": 5062605, + "forkHash": "0xb8c6299d" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://goerli.etherscan.io/block/7382818", + "name": "merge", + "ttd": "10790000", + "block": 7382819, + "forkHash": "0xb8c6299d" + }, + { + "name": "mergeForkIdTransition", + "block": null, + "forkHash": null + }, + { + "name": "shanghai", + "block": null, + "forkHash": null + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.goerli.ethdisco.net" + ] +}; +//# sourceMappingURL=goerli.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/goerli.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/goerli.js.map new file mode 100644 index 0000000..50076db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/goerli.js.map @@ -0,0 +1 @@ +{"version":3,"file":"goerli.js","sourceRoot":"","sources":["../../../../src/common/chains/goerli.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,QAAQ;IAChB,SAAS,EAAE,CAAC;IACZ,WAAW,EAAE,CAAC;IACd,iBAAiB,EAAE,OAAO;IAC1B,WAAW,EAAE;QACZ,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE;YACT,QAAQ,EAAE,EAAE;YACZ,OAAO,EAAE,KAAK;SACd;KACD;IACD,SAAS,EAAE,+BAA+B;IAC1C,KAAK,EAAE,mCAAmC;IAC1C,SAAS,EAAE;QACV,WAAW,EAAE,YAAY;QACzB,UAAU,EAAE,QAAQ;QACpB,YAAY,EAAE,CAAC;QACf,OAAO,EAAE,oBAAoB;QAC7B,WAAW,EAAE,8OAA8O;KAC3P;IACD,WAAW,EAAE;QACZ;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,kBAAkB;YAC1B,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,gBAAgB;YACxB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,gBAAgB;YACxB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,YAAY,EAAE,iIAAiI;YAC/I,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,UAAU;YACjB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,uBAAuB;YAC/B,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;SAChB;KACD;IACD,gBAAgB,EAAE,EAAE;IACpB,aAAa,EAAE;QACd,yFAAyF;KACzF;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/mainnet.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/mainnet.js new file mode 100644 index 0000000..1c2e6e9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/mainnet.js @@ -0,0 +1,113 @@ +export default { + "name": "mainnet", + "chainId": 1, + "networkId": 1, + "defaultHardfork": "merge", + "consensus": { + "type": "pow", + "algorithm": "ethash", + "ethash": {} + }, + "comment": "The Ethereum main chain", + "url": "https://ethstats.net/", + "genesis": { + "gasLimit": 5000, + "difficulty": 17179869184, + "nonce": "0x0000000000000042", + "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xfc64ec04" + }, + { + "name": "homestead", + "block": 1150000, + "forkHash": "0x97c2c34c" + }, + { + "name": "dao", + "block": 1920000, + "forkHash": "0x91d1f948" + }, + { + "name": "tangerineWhistle", + "block": 2463000, + "forkHash": "0x7a64da13" + }, + { + "name": "spuriousDragon", + "block": 2675000, + "forkHash": "0x3edd5b10" + }, + { + "name": "byzantium", + "block": 4370000, + "forkHash": "0xa00bc324" + }, + { + "name": "constantinople", + "block": 7280000, + "forkHash": "0x668db0af" + }, + { + "name": "petersburg", + "block": 7280000, + "forkHash": "0x668db0af" + }, + { + "name": "istanbul", + "block": 9069000, + "forkHash": "0x879d6e30" + }, + { + "name": "muirGlacier", + "block": 9200000, + "forkHash": "0xe029e991" + }, + { + "name": "berlin", + "block": 12244000, + "forkHash": "0x0eb440f6" + }, + { + "name": "london", + "block": 12965000, + "forkHash": "0xb715077d" + }, + { + "name": "arrowGlacier", + "block": 13773000, + "forkHash": "0x20c327fc" + }, + { + "name": "grayGlacier", + "block": 15050000, + "forkHash": "0xf0afd0e3" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://etherscan.io/block/15537393", + "name": "merge", + "ttd": "58750000000000000000000", + "block": 15537394, + "forkHash": "0xf0afd0e3" + }, + { + "name": "mergeForkIdTransition", + "block": null, + "forkHash": null + }, + { + "name": "shanghai", + "block": null, + "forkHash": null + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.mainnet.ethdisco.net" + ] +}; +//# sourceMappingURL=mainnet.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/mainnet.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/mainnet.js.map new file mode 100644 index 0000000..4b0c7c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/mainnet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mainnet.js","sourceRoot":"","sources":["../../../../src/common/chains/mainnet.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,SAAS;IACjB,SAAS,EAAE,CAAC;IACZ,WAAW,EAAE,CAAC;IACd,iBAAiB,EAAE,OAAO;IAC1B,WAAW,EAAE;QACZ,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,EAAE;KACZ;IACD,SAAS,EAAE,yBAAyB;IACpC,KAAK,EAAE,uBAAuB;IAC9B,SAAS,EAAE;QACV,UAAU,EAAE,IAAI;QAChB,YAAY,EAAE,WAAW;QACzB,OAAO,EAAE,oBAAoB;QAC7B,WAAW,EAAE,oEAAoE;KACjF;IACD,WAAW,EAAE;QACZ;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,KAAK;YACb,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,kBAAkB;YAC1B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,gBAAgB;YACxB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,gBAAgB;YACxB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,aAAa;YACrB,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,QAAQ;YACjB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,QAAQ;YACjB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,cAAc;YACtB,OAAO,EAAE,QAAQ;YACjB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,aAAa;YACrB,OAAO,EAAE,QAAQ;YACjB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,YAAY,EAAE,2HAA2H;YACzI,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,yBAAyB;YAChC,OAAO,EAAE,QAAQ;YACjB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,uBAAuB;YAC/B,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;SAChB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;SAChB;KACD;IACD,gBAAgB,EAAE,EAAE;IACpB,aAAa,EAAE;QACd,0FAA0F;KAC1F;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/sepolia.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/sepolia.js new file mode 100644 index 0000000..f011122 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/sepolia.js @@ -0,0 +1,100 @@ +export default { + "name": "sepolia", + "chainId": 11155111, + "networkId": 11155111, + "defaultHardfork": "merge", + "consensus": { + "type": "pow", + "algorithm": "ethash", + "ethash": {} + }, + "comment": "PoW test network to replace Ropsten", + "url": "https://github.com/ethereum/go-ethereum/pull/23730", + "genesis": { + "timestamp": "0x6159af19", + "gasLimit": 30000000, + "difficulty": 131072, + "nonce": "0x0000000000000000", + "extraData": "0x5365706f6c69612c20417468656e732c204174746963612c2047726565636521" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "homestead", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "tangerineWhistle", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "spuriousDragon", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "byzantium", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "constantinople", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "petersburg", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "istanbul", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "muirGlacier", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "berlin", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "london", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://sepolia.etherscan.io/block/1450408", + "name": "merge", + "ttd": "17000000000000000", + "block": 1450409, + "forkHash": "0xfe3366e7" + }, + { + "name": "mergeForkIdTransition", + "block": 1735371, + "forkHash": "0xb96cbd13" + }, + { + "name": "shanghai", + "block": null, + "timestamp": "1677557088", + "forkHash": "0xf7f9bc08" + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.sepolia.ethdisco.net" + ] +}; +//# sourceMappingURL=sepolia.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/sepolia.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/sepolia.js.map new file mode 100644 index 0000000..6ad5fae --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/chains/sepolia.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sepolia.js","sourceRoot":"","sources":["../../../../src/common/chains/sepolia.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,SAAS;IACjB,SAAS,EAAE,QAAQ;IACnB,WAAW,EAAE,QAAQ;IACrB,iBAAiB,EAAE,OAAO;IAC1B,WAAW,EAAE;QACZ,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,EAAE;KACZ;IACD,SAAS,EAAE,qCAAqC;IAChD,KAAK,EAAE,oDAAoD;IAC3D,SAAS,EAAE;QACV,WAAW,EAAE,YAAY;QACzB,UAAU,EAAE,QAAQ;QACpB,YAAY,EAAE,MAAM;QACpB,OAAO,EAAE,oBAAoB;QAC7B,WAAW,EAAE,oEAAoE;KACjF;IACD,WAAW,EAAE;QACZ;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,kBAAkB;YAC1B,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,gBAAgB;YACxB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,gBAAgB;YACxB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,aAAa;YACrB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,YAAY;SACxB;QACD;YACC,YAAY,EAAE,kIAAkI;YAChJ,MAAM,EAAE,OAAO;YACf,KAAK,EAAE,mBAAmB;YAC1B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,uBAAuB;YAC/B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,YAAY;SACxB;QACD;YACC,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,IAAI;YACb,WAAW,EAAE,YAAY;YACzB,UAAU,EAAE,YAAY;SACxB;KACD;IACD,gBAAgB,EAAE,EAAE;IACpB,aAAa,EAAE;QACd,0FAA0F;KAC1F;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/common.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/common.js new file mode 100644 index 0000000..e78315c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/common.js @@ -0,0 +1,1043 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import pkg from 'crc-32'; +import { EventEmitter, bytesToHex, hexToBytes, uint8ArrayConcat } from 'web3-utils'; +import { TypeOutput } from './types.js'; +import { intToUint8Array, toType, parseGethGenesis } from './utils.js'; +import goerli from './chains/goerli.js'; +import mainnet from './chains/mainnet.js'; +import sepolia from './chains/sepolia.js'; +import { EIPs } from './eips/index.js'; +import { Chain, CustomChain, Hardfork } from './enums.js'; +import { hardforks as HARDFORK_SPECS } from './hardforks/index.js'; +const { buf: crc32Uint8Array } = pkg; +/** + * Common class to access chain and hardfork parameters and to provide + * a unified and shared view on the network and hardfork state. + * + * Use the {@link Common.custom} static constructor for creating simple + * custom chain {@link Common} objects (more complete custom chain setups + * can be created via the main constructor and the {@link CommonOpts.customChains} parameter). + */ +export class Common extends EventEmitter { + constructor(opts) { + var _a, _b; + super(); + this._eips = []; + this._customChains = (_a = opts.customChains) !== null && _a !== void 0 ? _a : []; + this._chainParams = this.setChain(opts.chain); + this.DEFAULT_HARDFORK = (_b = this._chainParams.defaultHardfork) !== null && _b !== void 0 ? _b : Hardfork.Merge; + // Assign hardfork changes in the sequence of the applied hardforks + this.HARDFORK_CHANGES = this.hardforks().map(hf => [ + hf.name, + HARDFORK_SPECS[hf.name], + ]); + this._hardfork = this.DEFAULT_HARDFORK; + if (opts.hardfork !== undefined) { + this.setHardfork(opts.hardfork); + } + if (opts.eips) { + this.setEIPs(opts.eips); + } + } + /** + * Creates a {@link Common} object for a custom chain, based on a standard one. + * + * It uses all the {@link Chain} parameters from the {@link baseChain} option except the ones overridden + * in a provided {@link chainParamsOrName} dictionary. Some usage example: + * + * ```javascript + * Common.custom({chainId: 123}) + * ``` + * + * There are also selected supported custom chains which can be initialized by using one of the + * {@link CustomChains} for {@link chainParamsOrName}, e.g.: + * + * ```javascript + * Common.custom(CustomChains.MaticMumbai) + * ``` + * + * Note that these supported custom chains only provide some base parameters (usually the chain and + * network ID and a name) and can only be used for selected use cases (e.g. sending a tx with + * the `web3-utils/tx` library to a Layer-2 chain). + * + * @param chainParamsOrName Custom parameter dict (`name` will default to `custom-chain`) or string with name of a supported custom chain + * @param opts Custom chain options to set the {@link CustomCommonOpts.baseChain}, selected {@link CustomCommonOpts.hardfork} and others + */ + static custom(chainParamsOrName, opts = {}) { + var _a; + const baseChain = (_a = opts.baseChain) !== null && _a !== void 0 ? _a : 'mainnet'; + const standardChainParams = Object.assign({}, Common._getChainParams(baseChain)); + standardChainParams.name = 'custom-chain'; + if (typeof chainParamsOrName !== 'string') { + return new Common(Object.assign({ chain: Object.assign(Object.assign({}, standardChainParams), chainParamsOrName) }, opts)); + } + if (chainParamsOrName === CustomChain.PolygonMainnet) { + return Common.custom({ + name: CustomChain.PolygonMainnet, + chainId: 137, + networkId: 137, + }, opts); + } + if (chainParamsOrName === CustomChain.PolygonMumbai) { + return Common.custom({ + name: CustomChain.PolygonMumbai, + chainId: 80001, + networkId: 80001, + }, opts); + } + if (chainParamsOrName === CustomChain.ArbitrumRinkebyTestnet) { + return Common.custom({ + name: CustomChain.ArbitrumRinkebyTestnet, + chainId: 421611, + networkId: 421611, + }, opts); + } + if (chainParamsOrName === CustomChain.ArbitrumOne) { + return Common.custom({ + name: CustomChain.ArbitrumOne, + chainId: 42161, + networkId: 42161, + }, opts); + } + if (chainParamsOrName === CustomChain.xDaiChain) { + return Common.custom({ + name: CustomChain.xDaiChain, + chainId: 100, + networkId: 100, + }, opts); + } + if (chainParamsOrName === CustomChain.OptimisticKovan) { + return Common.custom({ + name: CustomChain.OptimisticKovan, + chainId: 69, + networkId: 69, + }, Object.assign({ hardfork: Hardfork.Berlin }, opts)); + } + if (chainParamsOrName === CustomChain.OptimisticEthereum) { + return Common.custom({ + name: CustomChain.OptimisticEthereum, + chainId: 10, + networkId: 10, + }, Object.assign({ hardfork: Hardfork.Berlin }, opts)); + } + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + throw new Error(`Custom chain ${chainParamsOrName} not supported`); + } + /** + * Static method to load and set common from a geth genesis json + * @param genesisJson json of geth configuration + * @param { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge } to further configure the common instance + * @returns Common + */ + static fromGethGenesis(genesisJson, { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge }) { + var _a; + const genesisParams = parseGethGenesis(genesisJson, chain, mergeForkIdPostMerge); + const common = new Common({ + chain: (_a = genesisParams.name) !== null && _a !== void 0 ? _a : 'custom', + customChains: [genesisParams], + eips, + hardfork: hardfork !== null && hardfork !== void 0 ? hardfork : genesisParams.hardfork, + }); + if (genesisHash !== undefined) { + common.setForkHashes(genesisHash); + } + return common; + } + /** + * Static method to determine if a {@link chainId} is supported as a standard chain + * @param chainId bigint id (`1`) of a standard chain + * @returns boolean + */ + static isSupportedChainId(chainId) { + const initializedChains = this._getInitializedChains(); + return Boolean(initializedChains.names[chainId.toString()]); + } + static _getChainParams(_chain, customChains) { + let chain = _chain; + const initializedChains = this._getInitializedChains(customChains); + if (typeof chain === 'number' || typeof chain === 'bigint') { + chain = chain.toString(); + if (initializedChains.names[chain]) { + const name = initializedChains.names[chain]; + return initializedChains[name]; + } + throw new Error(`Chain with ID ${chain} not supported`); + } + if (initializedChains[chain] !== undefined) { + return initializedChains[chain]; + } + throw new Error(`Chain with name ${chain} not supported`); + } + /** + * Sets the chain + * @param chain String ('mainnet') or Number (1) chain representation. + * Or, a Dictionary of chain parameters for a private network. + * @returns The dictionary with parameters set as chain + */ + setChain(chain) { + if (typeof chain === 'number' || typeof chain === 'bigint' || typeof chain === 'string') { + this._chainParams = Common._getChainParams(chain, this._customChains); + } + else if (typeof chain === 'object') { + if (this._customChains.length > 0) { + throw new Error('Chain must be a string, number, or bigint when initialized with customChains passed in'); + } + const required = ['networkId', 'genesis', 'hardforks', 'bootstrapNodes']; + for (const param of required) { + if (!(param in chain)) { + throw new Error(`Missing required chain parameter: ${param}`); + } + } + this._chainParams = chain; + } + else { + throw new Error('Wrong input format'); + } + for (const hf of this.hardforks()) { + if (hf.block === undefined) { + throw new Error(`Hardfork cannot have undefined block number`); + } + } + return this._chainParams; + } + /** + * Sets the hardfork to get params for + * @param hardfork String identifier (e.g. 'byzantium') or {@link Hardfork} enum + */ + setHardfork(hardfork) { + let existing = false; + for (const hfChanges of this.HARDFORK_CHANGES) { + if (hfChanges[0] === hardfork) { + if (this._hardfork !== hardfork) { + this._hardfork = hardfork; + this.emit('hardforkChanged', hardfork); + } + existing = true; + } + } + if (!existing) { + throw new Error(`Hardfork with name ${hardfork} not supported`); + } + } + /** + * Returns the hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td : total difficulty of the parent block (for block hf) OR of the chain latest (for chain hf) + * @param timestamp: timestamp in seconds at which block was/is to be minted + * @returns The name of the HF + */ + getHardforkByBlockNumber(_blockNumber, _td, _timestamp) { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const td = toType(_td, TypeOutput.BigInt); + const timestamp = toType(_timestamp, TypeOutput.Number); + // Filter out hardforks with no block number, no ttd or no timestamp (i.e. unapplied hardforks) + const hfs = this.hardforks().filter(hf => + // eslint-disable-next-line no-null/no-null + hf.block !== null || + // eslint-disable-next-line no-null/no-null + (hf.ttd !== null && hf.ttd !== undefined) || + hf.timestamp !== undefined); + // eslint-disable-next-line no-null/no-null + const mergeIndex = hfs.findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + const doubleTTDHF = hfs + .slice(mergeIndex + 1) + // eslint-disable-next-line no-null/no-null + .findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + if (doubleTTDHF >= 0) { + throw Error(`More than one merge hardforks found with ttd specified`); + } + // Find the first hardfork that has a block number greater than `blockNumber` + // (skips the merge hardfork since it cannot have a block number specified). + // If timestamp is not provided, it also skips timestamps hardforks to continue + // discovering/checking number hardforks. + let hfIndex = hfs.findIndex(hf => + // eslint-disable-next-line no-null/no-null + (hf.block !== null && hf.block > blockNumber) || + (timestamp !== undefined && Number(hf.timestamp) > timestamp)); + if (hfIndex === -1) { + // all hardforks apply, set hfIndex to the last one as that's the candidate + hfIndex = hfs.length; + } + else if (hfIndex === 0) { + // cannot have a case where a block number is before all applied hardforks + // since the chain has to start with a hardfork + throw Error('Must have at least one hardfork at block 0'); + } + // If timestamp is not provided, we need to rollback to the last hf with block or ttd + if (timestamp === undefined) { + const stepBack = hfs + .slice(0, hfIndex) + .reverse() + // eslint-disable-next-line no-null/no-null + .findIndex(hf => hf.block !== null || hf.ttd !== undefined); + hfIndex -= stepBack; + } + // Move hfIndex one back to arrive at candidate hardfork + hfIndex -= 1; + // If the timestamp was not provided, we could have skipped timestamp hardforks to look for number + // hardforks. so it will now be needed to rollback + // eslint-disable-next-line no-null/no-null + if (hfs[hfIndex].block === null && hfs[hfIndex].timestamp === undefined) { + // We're on the merge hardfork. Let's check the TTD + // eslint-disable-next-line no-null/no-null + if (td === undefined || td === null || BigInt(hfs[hfIndex].ttd) > td) { + // Merge ttd greater than current td so we're on hardfork before merge + hfIndex -= 1; + } + // eslint-disable-next-line no-null/no-null + } + else if (mergeIndex >= 0 && td !== undefined && td !== null) { + if (hfIndex >= mergeIndex && BigInt(hfs[mergeIndex].ttd) > td) { + throw Error('Maximum HF determined by total difficulty is lower than the block number HF'); + } + else if (hfIndex < mergeIndex && BigInt(hfs[mergeIndex].ttd) <= td) { + throw Error('HF determined by block number is lower than the minimum total difficulty HF'); + } + } + const hfStartIndex = hfIndex; + // Move the hfIndex to the end of the hardforks that might be scheduled on the same block/timestamp + // This won't anyway be the case with Merge hfs + for (; hfIndex < hfs.length - 1; hfIndex += 1) { + // break out if hfIndex + 1 is not scheduled at hfIndex + if (hfs[hfIndex].block !== hfs[hfIndex + 1].block || + hfs[hfIndex].timestamp !== hfs[hfIndex + 1].timestamp) { + break; + } + } + if (timestamp) { + const minTimeStamp = hfs + .slice(0, hfStartIndex) + .reduce((acc, hf) => { var _a; return Math.max(Number((_a = hf.timestamp) !== null && _a !== void 0 ? _a : '0'), acc); }, 0); + if (minTimeStamp > timestamp) { + throw Error(`Maximum HF determined by timestamp is lower than the block number/ttd HF`); + } + const maxTimeStamp = hfs + .slice(hfIndex + 1) + .reduce((acc, hf) => { var _a; return Math.min(Number((_a = hf.timestamp) !== null && _a !== void 0 ? _a : timestamp), acc); }, timestamp); + if (maxTimeStamp < timestamp) { + throw Error(`Maximum HF determined by block number/ttd is lower than timestamp HF`); + } + } + const hardfork = hfs[hfIndex]; + return hardfork.name; + } + /** + * Sets a new hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td + * @param timestamp + * @returns The name of the HF set + */ + setHardforkByBlockNumber(blockNumber, td, timestamp) { + const hardfork = this.getHardforkByBlockNumber(blockNumber, td, timestamp); + this.setHardfork(hardfork); + return hardfork; + } + /** + * Internal helper function, returns the params for the given hardfork for the chain set + * @param hardfork Hardfork name + * @returns Dictionary with hardfork params or null if hardfork not on chain + */ + // eslint-disable-next-line @typescript-eslint/ban-types + _getHardfork(hardfork) { + const hfs = this.hardforks(); + for (const hf of hfs) { + if (hf.name === hardfork) + return hf; + } + // eslint-disable-next-line no-null/no-null + return null; + } + /** + * Sets the active EIPs + * @param eips + */ + setEIPs(eips = []) { + for (const eip of eips) { + if (!(eip in EIPs)) { + throw new Error(`${eip} not supported`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument + const minHF = this.gteHardfork(EIPs[eip].minimumHardfork); + if (!minHF) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${eip} cannot be activated on hardfork ${this.hardfork()}, minimumHardfork: ${minHF}`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (EIPs[eip].requiredEIPs !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + for (const elem of EIPs[eip].requiredEIPs) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + if (!(eips.includes(elem) || this.isActivatedEIP(elem))) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${eip} requires EIP ${elem}, but is not included in the EIP list`); + } + } + } + } + this._eips = eips; + } + /** + * Returns a parameter for the current chain setup + * + * If the parameter is present in an EIP, the EIP always takes precedence. + * Otherwise the parameter if taken from the latest applied HF with + * a change on the respective parameter. + * + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @returns The value requested or `BigInt(0)` if not found + */ + param(topic, name) { + // TODO: consider the case that different active EIPs + // can change the same parameter + let value; + for (const eip of this._eips) { + value = this.paramByEIP(topic, name, eip); + if (value !== undefined) + return value; + } + return this.paramByHardfork(topic, name, this._hardfork); + } + /** + * Returns the parameter corresponding to a hardfork + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param hardfork Hardfork name + * @returns The value requested or `BigInt(0)` if not found + */ + paramByHardfork(topic, name, hardfork) { + // eslint-disable-next-line no-null/no-null + let value = null; + for (const hfChanges of this.HARDFORK_CHANGES) { + // EIP-referencing HF file (e.g. berlin.json) + if ('eips' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + const hfEIPs = hfChanges[1].eips; + for (const eip of hfEIPs) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const valueEIP = this.paramByEIP(topic, name, eip); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + value = typeof valueEIP === 'bigint' ? valueEIP : value; + } + // Parameter-inlining HF file (e.g. istanbul.json) + } + else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hfChanges[1][topic] === undefined) { + throw new Error(`Topic ${topic} not defined`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hfChanges[1][topic][name] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1][topic][name].v; + } + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return BigInt(value !== null && value !== void 0 ? value : 0); + } + /** + * Returns a parameter corresponding to an EIP + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param eip Number of the EIP + * @returns The value requested or `undefined` if not found + */ + // eslint-disable-next-line class-methods-use-this + paramByEIP(topic, name, eip) { + if (!(eip in EIPs)) { + throw new Error(`${eip} not supported`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const eipParams = EIPs[eip]; + if (!(topic in eipParams)) { + throw new Error(`Topic ${topic} not defined`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (eipParams[topic][name] === undefined) { + return undefined; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + const value = eipParams[topic][name].v; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return BigInt(value); + } + /** + * Returns a parameter for the hardfork active on block number or + * optional provided total difficulty (Merge HF) + * @param topic Parameter topic + * @param name Parameter name + * @param blockNumber Block number + * @param td Total difficulty + * * @returns The value requested or `BigInt(0)` if not found + */ + paramByBlock(topic, name, blockNumber, td, timestamp) { + const hardfork = this.getHardforkByBlockNumber(blockNumber, td, timestamp); + return this.paramByHardfork(topic, name, hardfork); + } + /** + * Checks if an EIP is activated by either being included in the EIPs + * manually passed in with the {@link CommonOpts.eips} or in a + * hardfork currently being active + * + * Note: this method only works for EIPs being supported + * by the {@link CommonOpts.eips} constructor option + * @param eip + */ + isActivatedEIP(eip) { + if (this.eips().includes(eip)) { + return true; + } + for (const hfChanges of this.HARDFORK_CHANGES) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const hf = hfChanges[1]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument + if (this.gteHardfork(hf.name) && 'eips' in hf) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hf.eips.includes(eip)) { + return true; + } + } + } + return false; + } + /** + * Checks if set or provided hardfork is active on block number + * @param hardfork Hardfork name or null (for HF set) + * @param blockNumber + * @returns True if HF is active on block number + */ + hardforkIsActiveOnBlock( + // eslint-disable-next-line @typescript-eslint/ban-types + _hardfork, _blockNumber) { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const hfBlock = this.hardforkBlock(hardfork); + if (typeof hfBlock === 'bigint' && hfBlock !== BigInt(0) && blockNumber >= hfBlock) { + return true; + } + return false; + } + /** + * Alias to hardforkIsActiveOnBlock when hardfork is set + * @param blockNumber + * @returns True if HF is active on block number + */ + activeOnBlock(blockNumber) { + // eslint-disable-next-line no-null/no-null + return this.hardforkIsActiveOnBlock(null, blockNumber); + } + /** + * Sequence based check if given or set HF1 is greater than or equal HF2 + * @param hardfork1 Hardfork name or null (if set) + * @param hardfork2 Hardfork name + * @param opts Hardfork options + * @returns True if HF1 gte HF2 + */ + hardforkGteHardfork( + // eslint-disable-next-line @typescript-eslint/ban-types + _hardfork1, hardfork2) { + const hardfork1 = _hardfork1 !== null && _hardfork1 !== void 0 ? _hardfork1 : this._hardfork; + const hardforks = this.hardforks(); + let posHf1 = -1; + let posHf2 = -1; + let index = 0; + for (const hf of hardforks) { + if (hf.name === hardfork1) + posHf1 = index; + if (hf.name === hardfork2) + posHf2 = index; + index += 1; + } + return posHf1 >= posHf2 && posHf2 !== -1; + } + /** + * Alias to hardforkGteHardfork when hardfork is set + * @param hardfork Hardfork name + * @returns True if hardfork set is greater than hardfork provided + */ + gteHardfork(hardfork) { + // eslint-disable-next-line no-null/no-null + return this.hardforkGteHardfork(null, hardfork); + } + /** + * Returns the hardfork change block for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if unscheduled + */ + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkBlock(_hardfork) { + var _a; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const block = (_a = this._getHardfork(hardfork)) === null || _a === void 0 ? void 0 : _a.block; + // eslint-disable-next-line no-null/no-null + if (block === undefined || block === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(block); + } + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkTimestamp(_hardfork) { + var _a; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const timestamp = (_a = this._getHardfork(hardfork)) === null || _a === void 0 ? void 0 : _a.timestamp; + // eslint-disable-next-line no-null/no-null + if (timestamp === undefined || timestamp === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(timestamp); + } + /** + * Returns the hardfork change block for eip + * @param eip EIP number + * @returns Block number or null if unscheduled + */ + // eslint-disable-next-line @typescript-eslint/ban-types + eipBlock(eip) { + for (const hfChanges of this.HARDFORK_CHANGES) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const hf = hfChanges[1]; + if ('eips' in hf) { + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + if (hf.eips.includes(eip)) { + return this.hardforkBlock(typeof hfChanges[0] === 'number' ? String(hfChanges[0]) : hfChanges[0]); + } + } + } + // eslint-disable-next-line no-null/no-null + return null; + } + /** + * Returns the hardfork change total difficulty (Merge HF) for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Total difficulty or null if no set + */ + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkTTD(_hardfork) { + var _a; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const ttd = (_a = this._getHardfork(hardfork)) === null || _a === void 0 ? void 0 : _a.ttd; + // eslint-disable-next-line no-null/no-null + if (ttd === undefined || ttd === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(ttd); + } + /** + * True if block number provided is the hardfork (given or set) change block + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isHardforkBlock(_blockNumber, _hardfork) { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const block = this.hardforkBlock(hardfork); + return typeof block === 'bigint' && block !== BigInt(0) ? block === blockNumber : false; + } + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block timestamp, number or null if not available + */ + // eslint-disable-next-line @typescript-eslint/ban-types + nextHardforkBlockOrTimestamp(_hardfork) { + var _a, _b; + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const hfs = this.hardforks(); + let hfIndex = hfs.findIndex(hf => hf.name === hardfork); + // If the current hardfork is merge, go one behind as merge hf is not part of these + // calcs even if the merge hf block is set + if (hardfork === Hardfork.Merge) { + hfIndex -= 1; + } + // Hardfork not found + if (hfIndex < 0) { + // eslint-disable-next-line no-null/no-null + return null; + } + let currHfTimeOrBlock = (_a = hfs[hfIndex].timestamp) !== null && _a !== void 0 ? _a : hfs[hfIndex].block; + currHfTimeOrBlock = + // eslint-disable-next-line no-null/no-null + currHfTimeOrBlock !== null && currHfTimeOrBlock !== undefined + ? Number(currHfTimeOrBlock) + : // eslint-disable-next-line no-null/no-null + null; + const nextHf = hfs.slice(hfIndex + 1).find(hf => { + var _a; + let hfTimeOrBlock = (_a = hf.timestamp) !== null && _a !== void 0 ? _a : hf.block; + hfTimeOrBlock = + // eslint-disable-next-line no-null/no-null + hfTimeOrBlock !== null && hfTimeOrBlock !== undefined + ? Number(hfTimeOrBlock) + : // eslint-disable-next-line no-null/no-null + null; + return (hf.name !== Hardfork.Merge && + // eslint-disable-next-line no-null/no-null + hfTimeOrBlock !== null && + hfTimeOrBlock !== undefined && + hfTimeOrBlock !== currHfTimeOrBlock); + }); + // If no next hf found with valid block or timestamp return null + if (nextHf === undefined) { + // eslint-disable-next-line no-null/no-null + return null; + } + const nextHfBlock = (_b = nextHf.timestamp) !== null && _b !== void 0 ? _b : nextHf.block; + // eslint-disable-next-line no-null/no-null + if (nextHfBlock === null || nextHfBlock === undefined) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(nextHfBlock); + } + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if not available + * @deprecated + */ + // eslint-disable-next-line @typescript-eslint/ban-types + nextHardforkBlock(_hardfork) { + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + let hfBlock = this.hardforkBlock(hardfork); + // If this is a merge hardfork with block not set, then we fallback to previous hardfork + // to find the nextHardforkBlock + // eslint-disable-next-line no-null/no-null + if (hfBlock === null && hardfork === Hardfork.Merge) { + const hfs = this.hardforks(); + // eslint-disable-next-line no-null/no-null + const mergeIndex = hfs.findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + if (mergeIndex < 0) { + throw Error(`Merge hardfork should have been found`); + } + hfBlock = this.hardforkBlock(hfs[mergeIndex - 1].name); + } + // eslint-disable-next-line no-null/no-null + if (hfBlock === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + // Next fork block number or null if none available + // Logic: if accumulator is still null and on the first occurrence of + // a block greater than the current hfBlock set the accumulator, + // pass on the accumulator as the final result from this time on + // eslint-disable-next-line no-null/no-null, @typescript-eslint/ban-types + const nextHfBlock = this.hardforks().reduce((acc, hf) => { + // We need to ignore the merge block in our next hardfork calc + const block = BigInt( + // eslint-disable-next-line no-null/no-null + hf.block === null || (hf.ttd !== undefined && hf.ttd !== null) ? 0 : hf.block); + // Typescript can't seem to follow that the hfBlock is not null at this point + // eslint-disable-next-line no-null/no-null + return block > hfBlock && acc === null ? block : acc; + // eslint-disable-next-line no-null/no-null + }, null); + return nextHfBlock; + } + /** + * True if block number provided is the hardfork change block following the hardfork given or set + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isNextHardforkBlock(_blockNumber, _hardfork) { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + // eslint-disable-next-line deprecation/deprecation + const nextHardforkBlock = this.nextHardforkBlock(hardfork); + // eslint-disable-next-line no-null/no-null + return nextHardforkBlock === null ? false : nextHardforkBlock === blockNumber; + } + /** + * Internal helper function to calculate a fork hash + * @param hardfork Hardfork name + * @param genesisHash Genesis block hash of the chain + * @returns Fork hash as hex string + */ + _calcForkHash(hardfork, genesisHash) { + let hfUint8Array = new Uint8Array(); + let prevBlockOrTime = 0; + for (const hf of this.hardforks()) { + const { block, timestamp, name } = hf; + // Timestamp to be used for timestamp based hfs even if we may bundle + // block number with them retrospectively + let blockOrTime = timestamp !== null && timestamp !== void 0 ? timestamp : block; + // eslint-disable-next-line no-null/no-null + blockOrTime = blockOrTime !== null ? Number(blockOrTime) : null; + // Skip for chainstart (0), not applied HFs (null) and + // when already applied on same blockOrTime HFs + // and on the merge since forkhash doesn't change on merge hf + if (typeof blockOrTime === 'number' && + blockOrTime !== 0 && + blockOrTime !== prevBlockOrTime && + name !== Hardfork.Merge) { + const hfBlockUint8Array = hexToBytes(blockOrTime.toString(16).padStart(16, '0')); + hfUint8Array = uint8ArrayConcat(hfUint8Array, hfBlockUint8Array); + prevBlockOrTime = blockOrTime; + } + if (hf.name === hardfork) + break; + } + const inputUint8Array = uint8ArrayConcat(genesisHash, hfUint8Array); + // CRC32 delivers result as signed (negative) 32-bit integer, + // convert to hex string + // eslint-disable-next-line no-bitwise + const forkhash = bytesToHex(intToUint8Array(crc32Uint8Array(inputUint8Array) >>> 0)); + return forkhash; + } + /** + * Returns an eth/64 compliant fork hash (EIP-2124) + * @param hardfork Hardfork name, optional if HF set + * @param genesisHash Genesis block hash of the chain, optional if already defined and not needed to be calculated + */ + forkHash(_hardfork, genesisHash) { + const hardfork = _hardfork !== null && _hardfork !== void 0 ? _hardfork : this._hardfork; + const data = this._getHardfork(hardfork); + if ( + // eslint-disable-next-line no-null/no-null + data === null || + // eslint-disable-next-line no-null/no-null + ((data === null || data === void 0 ? void 0 : data.block) === null && (data === null || data === void 0 ? void 0 : data.timestamp) === undefined && (data === null || data === void 0 ? void 0 : data.ttd) === undefined)) { + const msg = 'No fork hash calculation possible for future hardfork'; + throw new Error(msg); + } + // eslint-disable-next-line no-null/no-null + if ((data === null || data === void 0 ? void 0 : data.forkHash) !== null && (data === null || data === void 0 ? void 0 : data.forkHash) !== undefined) { + return data.forkHash; + } + if (!genesisHash) + throw new Error('genesisHash required for forkHash calculation'); + return this._calcForkHash(hardfork, genesisHash); + } + /** + * + * @param forkHash Fork hash as a hex string + * @returns Array with hardfork data (name, block, forkHash) + */ + // eslint-disable-next-line @typescript-eslint/ban-types + hardforkForForkHash(forkHash) { + const resArray = this.hardforks().filter((hf) => hf.forkHash === forkHash); + // eslint-disable-next-line no-null/no-null + return resArray.length >= 1 ? resArray[resArray.length - 1] : null; + } + /** + * Sets any missing forkHashes on the passed-in {@link Common} instance + * @param common The {@link Common} to set the forkHashes for + * @param genesisHash The genesis block hash + */ + setForkHashes(genesisHash) { + var _a; + for (const hf of this.hardforks()) { + const blockOrTime = (_a = hf.timestamp) !== null && _a !== void 0 ? _a : hf.block; + if ( + // eslint-disable-next-line no-null/no-null + (hf.forkHash === null || hf.forkHash === undefined) && + // eslint-disable-next-line no-null/no-null + ((blockOrTime !== null && blockOrTime !== undefined) || + typeof hf.ttd !== 'undefined')) { + hf.forkHash = this.forkHash(hf.name, genesisHash); + } + } + } + /** + * Returns the Genesis parameters of the current chain + * @returns Genesis dictionary + */ + genesis() { + return this._chainParams.genesis; + } + /** + * Returns the hardforks for current chain + * @returns {Array} Array with arrays of hardforks + */ + hardforks() { + return this._chainParams.hardforks; + } + /** + * Returns bootstrap nodes for the current chain + * @returns {Dictionary} Dict with bootstrap nodes + */ + bootstrapNodes() { + return this._chainParams.bootstrapNodes; + } + /** + * Returns DNS networks for the current chain + * @returns {String[]} Array of DNS ENR urls + */ + dnsNetworks() { + return this._chainParams.dnsNetworks; + } + /** + * Returns the hardfork set + * @returns Hardfork name + */ + hardfork() { + return this._hardfork; + } + /** + * Returns the Id of current chain + * @returns chain Id + */ + chainId() { + return BigInt(this._chainParams.chainId); + } + /** + * Returns the name of current chain + * @returns chain name (lower case) + */ + chainName() { + return this._chainParams.name; + } + /** + * Returns the Id of current network + * @returns network Id + */ + networkId() { + return BigInt(this._chainParams.networkId); + } + /** + * Returns the active EIPs + * @returns List of EIPs + */ + eips() { + return this._eips; + } + /** + * Returns the consensus type of the network + * Possible values: "pow"|"poa"|"pos" + * + * Note: This value can update along a Hardfork. + */ + consensusType() { + const hardfork = this.hardfork(); + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus.type; + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value !== null && value !== void 0 ? value : this._chainParams.consensus.type; + } + /** + * Returns the concrete consensus implementation + * algorithm or protocol for the network + * e.g. "ethash" for "pow" consensus type, + * "clique" for "poa" consensus type or + * "casper" for "pos" consensus type. + * + * Note: This value can update along a Hardfork. + */ + consensusAlgorithm() { + const hardfork = this.hardfork(); + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus.algorithm; + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value !== null && value !== void 0 ? value : this._chainParams.consensus.algorithm; + } + /** + * Returns a dictionary with consensus configuration + * parameters based on the consensus algorithm + * + * Expected returns (parameters must be present in + * the respective chain json files): + * + * ethash: empty object + * clique: period, epoch + * casper: empty object + * + * Note: This value can update along a Hardfork. + */ + consensusConfig() { + var _a; + const hardfork = this.hardfork(); + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // The config parameter is named after the respective consensus algorithm + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus[hfChanges[1].consensus.algorithm]; + } + if (hfChanges[0] === hardfork) + break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return ((_a = value !== null && value !== void 0 ? value : this._chainParams.consensus[this.consensusAlgorithm()]) !== null && _a !== void 0 ? _a : {}); + } + /** + * Returns a deep copy of this {@link Common} instance. + */ + copy() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment + const copy = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + copy.removeAllListeners(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return copy; + } + static _getInitializedChains(customChains) { + const names = {}; + for (const [name, id] of Object.entries(Chain)) { + names[id] = name.toLowerCase(); + } + const chains = { mainnet, goerli, sepolia }; + if (customChains) { + for (const chain of customChains) { + const { name } = chain; + names[chain.chainId.toString()] = name; + chains[name] = chain; + } + } + chains.names = names; + return chains; + } +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/common.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/common.js.map new file mode 100644 index 0000000..9fe788b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["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AAO,IAAI,CAAC;IACb,CAAC;IAEM,MAAM,CAAC,qBAAqB,CAAC,YAA4B;QAC/D,MAAM,KAAK,GAAc,EAAE,CAAC;QAC5B,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YAC/C,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;SAC/B;QACD,MAAM,MAAM,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAkB,CAAC;QAC5D,IAAI,YAAY,EAAE;YACjB,KAAK,MAAM,KAAK,IAAI,YAAY,EAAE;gBACjC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;gBACvB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC;gBACvC,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;aACrB;SACD;QACD,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;QACrB,OAAO,MAAM,CAAC;IACf,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1153.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1153.js new file mode 100644 index 0000000..aef3eac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1153.js @@ -0,0 +1,23 @@ +export default { + "name": "EIP-1153", + "number": 1153, + "comment": "Transient Storage", + "url": "https://eips.ethereum.org/EIPS/eip-1153", + "status": "Review", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "tstore": { + "v": 100, + "d": "Base fee of the TSTORE opcode" + }, + "tload": { + "v": 100, + "d": "Base fee of the TLOAD opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=1153.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1153.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1153.js.map new file mode 100644 index 0000000..7046cbc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1153.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1153.js","sourceRoot":"","sources":["../../../../src/common/eips/1153.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,mBAAmB;IAC9B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,YAAY;IAC/B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,QAAQ,EAAE;YACT,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,+BAA+B;SACpC;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,8BAA8B;SACnC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1559.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1559.js new file mode 100644 index 0000000..8ee40e6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1559.js @@ -0,0 +1,27 @@ +export default { + "name": "EIP-1559", + "number": 1559, + "comment": "Fee market change for ETH 1.0 chain", + "url": "https://eips.ethereum.org/EIPS/eip-1559", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [2930], + "gasConfig": { + "baseFeeMaxChangeDenominator": { + "v": 8, + "d": "Maximum base fee change denominator" + }, + "elasticityMultiplier": { + "v": 2, + "d": "Maximum block gas target elasticity" + }, + "initialBaseFee": { + "v": 1000000000, + "d": "Initial base fee on first EIP1559 block" + } + }, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=1559.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1559.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1559.js.map new file mode 100644 index 0000000..b3abb5e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/1559.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1559.js","sourceRoot":"","sources":["../../../../src/common/eips/1559.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,qCAAqC;IAChD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE;QACZ,6BAA6B,EAAE;YAC9B,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,UAAU;YACf,GAAG,EAAE,yCAAyC;SAC9C;KACD;IACD,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2315.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2315.js new file mode 100644 index 0000000..8ca3dbb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2315.js @@ -0,0 +1,26 @@ +export default { + "name": "EIP-2315", + "number": 2315, + "comment": "Simple subroutines for the EVM", + "url": "https://eips.ethereum.org/EIPS/eip-2315", + "status": "Draft", + "minimumHardfork": "istanbul", + "gasConfig": {}, + "gasPrices": { + "beginsub": { + "v": 2, + "d": "Base fee of the BEGINSUB opcode" + }, + "returnsub": { + "v": 5, + "d": "Base fee of the RETURNSUB opcode" + }, + "jumpsub": { + "v": 10, + "d": "Base fee of the JUMPSUB opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2315.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2315.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2315.js.map new file mode 100644 index 0000000..11e1633 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2315.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2315.js","sourceRoot":"","sources":["../../../../src/common/eips/2315.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,gCAAgC;IAC3C,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,UAAU;IAC7B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;QACD,WAAW,EAAE;YACZ,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,kCAAkC;SACvC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,gCAAgC;SACrC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2537.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2537.js new file mode 100644 index 0000000..c96c72d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2537.js @@ -0,0 +1,179 @@ +export default { + "name": "EIP-2537", + "number": 2537, + "comment": "BLS12-381 precompiles", + "url": "https://eips.ethereum.org/EIPS/eip-2537", + "status": "Draft", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": { + "Bls12381G1AddGas": { + "v": 600, + "d": "Gas cost of a single BLS12-381 G1 addition precompile-call" + }, + "Bls12381G1MulGas": { + "v": 12000, + "d": "Gas cost of a single BLS12-381 G1 multiplication precompile-call" + }, + "Bls12381G2AddGas": { + "v": 4500, + "d": "Gas cost of a single BLS12-381 G2 addition precompile-call" + }, + "Bls12381G2MulGas": { + "v": 55000, + "d": "Gas cost of a single BLS12-381 G2 multiplication precompile-call" + }, + "Bls12381PairingBaseGas": { + "v": 115000, + "d": "Base gas cost of BLS12-381 pairing check" + }, + "Bls12381PairingPerPairGas": { + "v": 23000, + "d": "Per-pair gas cost of BLS12-381 pairing check" + }, + "Bls12381MapG1Gas": { + "v": 5500, + "d": "Gas cost of BLS12-381 map field element to G1" + }, + "Bls12381MapG2Gas": { + "v": 110000, + "d": "Gas cost of BLS12-381 map field element to G2" + }, + "Bls12381MultiExpGasDiscount": { + "v": [ + [1, 1200], + [2, 888], + [3, 764], + [4, 641], + [5, 594], + [6, 547], + [7, 500], + [8, 453], + [9, 438], + [10, 423], + [11, 408], + [12, 394], + [13, 379], + [14, 364], + [15, 349], + [16, 334], + [17, 330], + [18, 326], + [19, 322], + [20, 318], + [21, 314], + [22, 310], + [23, 306], + [24, 302], + [25, 298], + [26, 294], + [27, 289], + [28, 285], + [29, 281], + [30, 277], + [31, 273], + [32, 269], + [33, 268], + [34, 266], + [35, 265], + [36, 263], + [37, 262], + [38, 260], + [39, 259], + [40, 257], + [41, 256], + [42, 254], + [43, 253], + [44, 251], + [45, 250], + [46, 248], + [47, 247], + [48, 245], + [49, 244], + [50, 242], + [51, 241], + [52, 239], + [53, 238], + [54, 236], + [55, 235], + [56, 233], + [57, 232], + [58, 231], + [59, 229], + [60, 228], + [61, 226], + [62, 225], + [63, 223], + [64, 222], + [65, 221], + [66, 220], + [67, 219], + [68, 219], + [69, 218], + [70, 217], + [71, 216], + [72, 216], + [73, 215], + [74, 214], + [75, 213], + [76, 213], + [77, 212], + [78, 211], + [79, 211], + [80, 210], + [81, 209], + [82, 208], + [83, 208], + [84, 207], + [85, 206], + [86, 205], + [87, 205], + [88, 204], + [89, 203], + [90, 202], + [91, 202], + [92, 201], + [93, 200], + [94, 199], + [95, 199], + [96, 198], + [97, 197], + [98, 196], + [99, 196], + [100, 195], + [101, 194], + [102, 193], + [103, 193], + [104, 192], + [105, 191], + [106, 191], + [107, 190], + [108, 189], + [109, 188], + [110, 188], + [111, 187], + [112, 186], + [113, 185], + [114, 185], + [115, 184], + [116, 183], + [117, 182], + [118, 182], + [119, 181], + [120, 180], + [121, 179], + [122, 179], + [123, 178], + [124, 177], + [125, 176], + [126, 176], + [127, 175], + [128, 174] + ], + "d": "Discount gas costs of calls to the MultiExp precompiles with `k` (point, scalar) pair" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2537.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2537.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2537.js.map new file mode 100644 index 0000000..ee52bdf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2537.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2537.js","sourceRoot":"","sources":["../../../../src/common/eips/2537.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,uBAAuB;IAClC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,4DAA4D;SACjE;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,kE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,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;gBACV,CAAC,GAAG,EAAE,GAAG,CAAC;aACV;YACD,GAAG,EAAE,uFAAuF;SAC5F;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2565.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2565.js new file mode 100644 index 0000000..607905d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2565.js @@ -0,0 +1,18 @@ +export default { + "name": "EIP-2565", + "number": 2565, + "comment": "ModExp gas cost", + "url": "https://eips.ethereum.org/EIPS/eip-2565", + "status": "Final", + "minimumHardfork": "byzantium", + "gasConfig": {}, + "gasPrices": { + "modexpGquaddivisor": { + "v": 3, + "d": "Gquaddivisor from modexp precompile for gas calculation" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2565.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2565.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2565.js.map new file mode 100644 index 0000000..f21e2f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2565.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2565.js","sourceRoot":"","sources":["../../../../src/common/eips/2565.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,iBAAiB;IAC5B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,WAAW;IAC9B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,oBAAoB,EAAE;YACrB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,yDAAyD;SAC9D;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2718.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2718.js new file mode 100644 index 0000000..385b131 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2718.js @@ -0,0 +1,12 @@ +export default { + "name": "EIP-2718", + "comment": "Typed Transaction Envelope", + "url": "https://eips.ethereum.org/EIPS/eip-2718", + "status": "Final", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2718.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2718.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2718.js.map new file mode 100644 index 0000000..8fda8f2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2718.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2718.js","sourceRoot":"","sources":["../../../../src/common/eips/2718.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,4BAA4B;IACvC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2929.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2929.js new file mode 100644 index 0000000..557bf95 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2929.js @@ -0,0 +1,85 @@ +export default { + "name": "EIP-2929", + "comment": "Gas cost increases for state access opcodes", + "url": "https://eips.ethereum.org/EIPS/eip-2929", + "status": "Final", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": { + "coldsload": { + "v": 2100, + "d": "Gas cost of the first read of storage from a given location (per transaction)" + }, + "coldaccountaccess": { + "v": 2600, + "d": "Gas cost of the first read of a given address (per transaction)" + }, + "warmstorageread": { + "v": 100, + "d": "Gas cost of reading storage locations which have already loaded 'cold'" + }, + "sstoreCleanGasEIP2200": { + "v": 2900, + "d": "Once per SSTORE operation from clean non-zero to something else" + }, + "sstoreNoopGasEIP2200": { + "v": 100, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "sstoreDirtyGasEIP2200": { + "v": 100, + "d": "Once per SSTORE operation if a dirty value is changed" + }, + "sstoreInitRefundEIP2200": { + "v": 19900, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "sstoreCleanRefundEIP2200": { + "v": 4900, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "call": { + "v": 0, + "d": "Base fee of the CALL opcode" + }, + "callcode": { + "v": 0, + "d": "Base fee of the CALLCODE opcode" + }, + "delegatecall": { + "v": 0, + "d": "Base fee of the DELEGATECALL opcode" + }, + "staticcall": { + "v": 0, + "d": "Base fee of the STATICCALL opcode" + }, + "balance": { + "v": 0, + "d": "Base fee of the BALANCE opcode" + }, + "extcodesize": { + "v": 0, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 0, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "extcodehash": { + "v": 0, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "sload": { + "v": 0, + "d": "Base fee of the SLOAD opcode" + }, + "sstore": { + "v": 0, + "d": "Base fee of the SSTORE opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2929.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2929.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2929.js.map new file mode 100644 index 0000000..e9ed7eb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2929.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2929.js","sourceRoot":"","sources":["../../../../src/common/eips/2929.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,6CAA6C;IACxD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,WAAW,EAAE;YACZ,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+EAA+E;SACpF;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,iBAAiB,EAAE;YAClB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,wEAAwE;SAC7E;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,yBAAyB,EAAE;YAC1B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,oEAAoE;SACzE;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wEAAwE;SAC7E;QACD,MAAM,EAAE;YACP,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,6BAA6B;SAClC;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;QACD,cAAc,EAAE;YACf,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,qCAAqC;SAC1C;QACD,YAAY,EAAE;YACb,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,mCAAmC;SACxC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gCAAgC;SACrC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,OAAO,EAAE;YACR,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,8BAA8B;SACnC;QACD,QAAQ,EAAE;YACT,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,+BAA+B;SACpC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2930.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2930.js new file mode 100644 index 0000000..81a4f4f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2930.js @@ -0,0 +1,22 @@ +export default { + "name": "EIP-2930", + "comment": "Optional access lists", + "url": "https://eips.ethereum.org/EIPS/eip-2930", + "status": "Final", + "minimumHardfork": "istanbul", + "requiredEIPs": [2718, 2929], + "gasConfig": {}, + "gasPrices": { + "accessListStorageKeyCost": { + "v": 1900, + "d": "Gas cost per storage key in an Access List transaction" + }, + "accessListAddressCost": { + "v": 2400, + "d": "Gas cost per storage key in an Access List transaction" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=2930.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2930.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2930.js.map new file mode 100644 index 0000000..9725424 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/2930.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2930.js","sourceRoot":"","sources":["../../../../src/common/eips/2930.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,uBAAuB;IAClC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,UAAU;IAC7B,cAAc,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IAC5B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wDAAwD;SAC7D;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wDAAwD;SAC7D;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3074.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3074.js new file mode 100644 index 0000000..92563d8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3074.js @@ -0,0 +1,26 @@ +export default { + "name": "EIP-3074", + "number": 3074, + "comment": "AUTH and AUTHCALL opcodes", + "url": "https://eips.ethereum.org/EIPS/eip-3074", + "status": "Review", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": { + "auth": { + "v": 3100, + "d": "Gas cost of the AUTH opcode" + }, + "authcall": { + "v": 0, + "d": "Gas cost of the AUTHCALL opcode" + }, + "authcallValueTransfer": { + "v": 6700, + "d": "Paid for CALL when the value transfer is non-zero" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3074.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3074.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3074.js.map new file mode 100644 index 0000000..41651f2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3074.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3074.js","sourceRoot":"","sources":["../../../../src/common/eips/3074.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,2BAA2B;IACtC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,MAAM,EAAE;YACP,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,6BAA6B;SAClC;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,mDAAmD;SACxD;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3198.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3198.js new file mode 100644 index 0000000..b68a127 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3198.js @@ -0,0 +1,18 @@ +export default { + "name": "EIP-3198", + "number": 3198, + "comment": "BASEFEE opcode", + "url": "https://eips.ethereum.org/EIPS/eip-3198", + "status": "Final", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": { + "basefee": { + "v": 2, + "d": "Gas cost of the BASEFEE opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3198.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3198.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3198.js.map new file mode 100644 index 0000000..0c1f93d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3198.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3198.js","sourceRoot":"","sources":["../../../../src/common/eips/3198.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,gBAAgB;IAC3B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,SAAS,EAAE;YACV,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gCAAgC;SACrC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3529.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3529.js new file mode 100644 index 0000000..2353901 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3529.js @@ -0,0 +1,27 @@ +export default { + "name": "EIP-3529", + "comment": "Reduction in refunds", + "url": "https://eips.ethereum.org/EIPS/eip-3529", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [2929], + "gasConfig": { + "maxRefundQuotient": { + "v": 5, + "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" + } + }, + "gasPrices": { + "selfdestructRefund": { + "v": 0, + "d": "Refunded following a selfdestruct operation" + }, + "sstoreClearRefundEIP2200": { + "v": 4800, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3529.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3529.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3529.js.map new file mode 100644 index 0000000..84ce28c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3529.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3529.js","sourceRoot":"","sources":["../../../../src/common/eips/3529.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,sBAAsB;IACjC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE;QACZ,mBAAmB,EAAE;YACpB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,2FAA2F;SAChG;KACD;IACD,WAAW,EAAE;QACZ,oBAAoB,EAAE;YACrB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,6CAA6C;SAClD;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,4EAA4E;SACjF;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3540.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3540.js new file mode 100644 index 0000000..3db5402 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3540.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3540", + "number": 3540, + "comment": "EVM Object Format (EOF) v1", + "url": "https://eips.ethereum.org/EIPS/eip-3540", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [3541], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3540.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3540.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3540.js.map new file mode 100644 index 0000000..5ad5aaa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3540.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3540.js","sourceRoot":"","sources":["../../../../src/common/eips/3540.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,4BAA4B;IACvC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3541.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3541.js new file mode 100644 index 0000000..329f903 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3541.js @@ -0,0 +1,13 @@ +export default { + "name": "EIP-3541", + "comment": "Reject new contracts starting with the 0xEF byte", + "url": "https://eips.ethereum.org/EIPS/eip-3541", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3541.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3541.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3541.js.map new file mode 100644 index 0000000..b8c1cf8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3541.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3541.js","sourceRoot":"","sources":["../../../../src/common/eips/3541.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,kDAAkD;IAC7D,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3554.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3554.js new file mode 100644 index 0000000..004a98b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3554.js @@ -0,0 +1,18 @@ +export default { + "name": "EIP-3554", + "comment": "Reduction in refunds", + "url": "Difficulty Bomb Delay to December 1st 2021", + "status": "Final", + "minimumHardfork": "muirGlacier", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 9500000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=3554.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3554.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3554.js.map new file mode 100644 index 0000000..785689c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3554.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3554.js","sourceRoot":"","sources":["../../../../src/common/eips/3554.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,sBAAsB;IACjC,KAAK,EAAE,4CAA4C;IACnD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,aAAa;IAChC,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3607.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3607.js new file mode 100644 index 0000000..a8ea418 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3607.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3607", + "number": 3607, + "comment": "Reject transactions from senders with deployed code", + "url": "https://eips.ethereum.org/EIPS/eip-3607", + "status": "Final", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3607.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3607.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3607.js.map new file mode 100644 index 0000000..5d6da33 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3607.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3607.js","sourceRoot":"","sources":["../../../../src/common/eips/3607.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,qDAAqD;IAChE,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,YAAY;IAC/B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3651.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3651.js new file mode 100644 index 0000000..96e6bce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3651.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3651", + "number": 3198, + "comment": "Warm COINBASE", + "url": "https://eips.ethereum.org/EIPS/eip-3651", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [2929], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3651.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3651.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3651.js.map new file mode 100644 index 0000000..2905510 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3651.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3651.js","sourceRoot":"","sources":["../../../../src/common/eips/3651.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,eAAe;IAC1B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3670.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3670.js new file mode 100644 index 0000000..bbe81a3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3670.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3670", + "number": 3670, + "comment": "EOF - Code Validation", + "url": "https://eips.ethereum.org/EIPS/eip-3670", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [3540], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3670.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3670.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3670.js.map new file mode 100644 index 0000000..41cda2b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3670.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3670.js","sourceRoot":"","sources":["../../../../src/common/eips/3670.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,uBAAuB;IAClC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,CAAC,IAAI,CAAC;IACtB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3675.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3675.js new file mode 100644 index 0000000..f89cb7c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3675.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3675", + "number": 3675, + "comment": "Upgrade consensus to Proof-of-Stake", + "url": "https://eips.ethereum.org/EIPS/eip-3675", + "status": "Final", + "minimumHardfork": "london", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3675.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3675.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3675.js.map new file mode 100644 index 0000000..50e3f29 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3675.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3675.js","sourceRoot":"","sources":["../../../../src/common/eips/3675.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,qCAAqC;IAChD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3855.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3855.js new file mode 100644 index 0000000..6b47b53 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3855.js @@ -0,0 +1,19 @@ +export default { + "name": "EIP-3855", + "number": 3855, + "comment": "PUSH0 instruction", + "url": "https://eips.ethereum.org/EIPS/eip-3855", + "status": "Review", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "push0": { + "v": 2, + "d": "Base fee of the PUSH0 opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=3855.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3855.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3855.js.map new file mode 100644 index 0000000..ae1c834 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3855.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3855.js","sourceRoot":"","sources":["../../../../src/common/eips/3855.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,mBAAmB;IAC9B,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,YAAY;IAC/B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,OAAO,EAAE;YACR,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,8BAA8B;SACnC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3860.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3860.js new file mode 100644 index 0000000..214fe0e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3860.js @@ -0,0 +1,24 @@ +export default { + "name": "EIP-3860", + "number": 3860, + "comment": "Limit and meter initcode", + "url": "https://eips.ethereum.org/EIPS/eip-3860", + "status": "Review", + "minimumHardfork": "spuriousDragon", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "initCodeWordCost": { + "v": 2, + "d": "Gas to pay for each word (32 bytes) of initcode when creating a contract" + } + }, + "vm": { + "maxInitCodeSize": { + "v": 49152, + "d": "Maximum length of initialization code when creating a contract" + } + }, + "pow": {} +}; +//# sourceMappingURL=3860.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3860.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3860.js.map new file mode 100644 index 0000000..54fbedd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/3860.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3860.js","sourceRoot":"","sources":["../../../../src/common/eips/3860.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,0BAA0B;IACrC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,gBAAgB;IACnC,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,0EAA0E;SAC/E;KACD;IACD,IAAI,EAAE;QACL,iBAAiB,EAAE;YAClB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,gEAAgE;SACrE;KACD;IACD,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4345.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4345.js new file mode 100644 index 0000000..4a0828f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4345.js @@ -0,0 +1,18 @@ +export default { + "name": "EIP-4345", + "number": 4345, + "comment": "Difficulty Bomb Delay to June 2022", + "url": "https://eips.ethereum.org/EIPS/eip-4345", + "status": "Final", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 10700000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=4345.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4345.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4345.js.map new file mode 100644 index 0000000..b20cb74 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4345.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4345.js","sourceRoot":"","sources":["../../../../src/common/eips/4345.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,oCAAoC;IAC/C,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,QAAQ;YACb,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4399.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4399.js new file mode 100644 index 0000000..9a61091 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4399.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-4399", + "number": 4399, + "comment": "Supplant DIFFICULTY opcode with PREVRANDAO", + "url": "https://eips.ethereum.org/EIPS/eip-4399", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=4399.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4399.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4399.js.map new file mode 100644 index 0000000..187c016 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4399.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4399.js","sourceRoot":"","sources":["../../../../src/common/eips/4399.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,4CAA4C;IACvD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,QAAQ;IAC3B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4844.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4844.js new file mode 100644 index 0000000..211ac21 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4844.js @@ -0,0 +1,58 @@ +export default { + "name": "EIP-4844", + "number": 4844, + "comment": "Shard Blob Transactions", + "url": "https://eips.ethereum.org/EIPS/eip-4844", + "status": "Draft", + "minimumHardfork": "merge", + "requiredEIPs": [1559, 2718, 2930, 4895], + "gasConfig": { + "dataGasPerBlob": { + "v": 131072, + "d": "The base fee for data gas per blob" + }, + "targetDataGasPerBlock": { + "v": 262144, + "d": "The target data gas consumed per block" + }, + "maxDataGasPerBlock": { + "v": 524288, + "d": "The max data gas allowable per block" + }, + "dataGasPriceUpdateFraction": { + "v": 2225652, + "d": "The denominator used in the exponential when calculating a data gas price" + } + }, + "gasPrices": { + "simpleGasPerBlob": { + "v": 12000, + "d": "The basic gas fee for each blob" + }, + "minDataGasPrice": { + "v": 1, + "d": "The minimum fee per data gas" + }, + "kzgPointEvaluationGasPrecompilePrice": { + "v": 50000, + "d": "The fee associated with the point evaluation precompile" + }, + "datahash": { + "v": 3, + "d": "Base fee of the DATAHASH opcode" + } + }, + "sharding": { + "blobCommitmentVersionKzg": { + "v": 1, + "d": "The number indicated a versioned hash is a KZG commitment" + }, + "fieldElementsPerBlob": { + "v": 4096, + "d": "The number of field elements allowed per blob" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=4844.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4844.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4844.js.map new file mode 100644 index 0000000..1839971 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4844.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4844.js","sourceRoot":"","sources":["../../../../src/common/eips/4844.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,yBAAyB;IACpC,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,OAAO;IAC1B,cAAc,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IACxC,WAAW,EAAE;QACZ,gBAAgB,EAAE;YACjB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,oCAAoC;SACzC;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,wCAAwC;SAC7C;QACD,oBAAoB,EAAE;YACrB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,sCAAsC;SAC3C;QACD,4BAA4B,EAAE;YAC7B,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,2EAA2E;SAChF;KACD;IACD,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,iCAAiC;SACtC;QACD,iBAAiB,EAAE;YAClB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,8BAA8B;SACnC;QACD,sCAAsC,EAAE;YACvC,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,yDAAyD;SAC9D;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,iCAAiC;SACtC;KACD;IACD,UAAU,EAAE;QACX,0BAA0B,EAAE;YAC3B,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,2DAA2D;SAChE;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+CAA+C;SACpD;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4895.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4895.js new file mode 100644 index 0000000..8d7bcdb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4895.js @@ -0,0 +1,14 @@ +export default { + "name": "EIP-4895", + "number": 4895, + "comment": "Beacon chain push withdrawals as operations", + "url": "https://eips.ethereum.org/EIPS/eip-4895", + "status": "Review", + "minimumHardfork": "merge", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=4895.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4895.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4895.js.map new file mode 100644 index 0000000..6e8cc66 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/4895.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4895.js","sourceRoot":"","sources":["../../../../src/common/eips/4895.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,6CAA6C;IACxD,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,QAAQ;IAClB,iBAAiB,EAAE,OAAO;IAC1B,cAAc,EAAE,EAAE;IAClB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/5133.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/5133.js new file mode 100644 index 0000000..2883081 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/5133.js @@ -0,0 +1,18 @@ +export default { + "name": "EIP-5133", + "number": 5133, + "comment": "Delaying Difficulty Bomb to mid-September 2022", + "url": "https://eips.ethereum.org/EIPS/eip-5133", + "status": "Draft", + "minimumHardfork": "grayGlacier", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 11400000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=5133.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/5133.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/5133.js.map new file mode 100644 index 0000000..96dcf3d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/5133.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5133.js","sourceRoot":"","sources":["../../../../src/common/eips/5133.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,gDAAgD;IAC3D,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,iBAAiB,EAAE,aAAa;IAChC,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,QAAQ;YACb,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/index.js new file mode 100644 index 0000000..e6f00e0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/index.js @@ -0,0 +1,63 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import e1153 from './1153.js'; +import e1559 from './1559.js'; +import e2315 from './2315.js'; +import e2537 from './2537.js'; +import e2565 from './2565.js'; +import e2718 from './2718.js'; +import e2929 from './2929.js'; +import e2930 from './2930.js'; +import e3198 from './3198.js'; +import e3529 from './3529.js'; +import e3540 from './3540.js'; +import e3541 from './3541.js'; +import e3554 from './3554.js'; +import e3607 from './3607.js'; +import e3651 from './3651.js'; +import e3670 from './3670.js'; +import e3675 from './3675.js'; +import e3855 from './3855.js'; +import e3860 from './3860.js'; +import e4345 from './4345.js'; +import e4399 from './4399.js'; +import e5133 from './5133.js'; +export const EIPs = { + 1153: e1153, + 1559: e1559, + 2315: e2315, + 2537: e2537, + 2565: e2565, + 2718: e2718, + 2929: e2929, + 2930: e2930, + 3198: e3198, + 3529: e3529, + 3540: e3540, + 3541: e3541, + 3554: e3554, + 3607: e3607, + 3651: e3651, + 3670: e3670, + 3675: e3675, + 3855: e3855, + 3860: e3860, + 4345: e4345, + 4399: e4399, + 5133: e5133, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/index.js.map new file mode 100644 index 0000000..e5a96a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/eips/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/eips/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,KAAK,MAAM,WAAW,CAAC;AAC9B,OAAO,KAAK,MAAM,WAAW,CAAC;AAC9B,OAAO,KAAK,MAAM,WAAW,CAAC;AAC9B,OAAO,KA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AAK;CACX,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/enums.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/enums.js new file mode 100644 index 0000000..9d24f07 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/enums.js @@ -0,0 +1,101 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export var Chain; +(function (Chain) { + Chain[Chain["Mainnet"] = 1] = "Mainnet"; + Chain[Chain["Goerli"] = 5] = "Goerli"; + Chain[Chain["Sepolia"] = 11155111] = "Sepolia"; +})(Chain || (Chain = {})); +export var Hardfork; +(function (Hardfork) { + Hardfork["Chainstart"] = "chainstart"; + Hardfork["Homestead"] = "homestead"; + Hardfork["Dao"] = "dao"; + Hardfork["TangerineWhistle"] = "tangerineWhistle"; + Hardfork["SpuriousDragon"] = "spuriousDragon"; + Hardfork["Byzantium"] = "byzantium"; + Hardfork["Constantinople"] = "constantinople"; + Hardfork["Petersburg"] = "petersburg"; + Hardfork["Istanbul"] = "istanbul"; + Hardfork["MuirGlacier"] = "muirGlacier"; + Hardfork["Berlin"] = "berlin"; + Hardfork["London"] = "london"; + Hardfork["ArrowGlacier"] = "arrowGlacier"; + Hardfork["GrayGlacier"] = "grayGlacier"; + Hardfork["MergeForkIdTransition"] = "mergeForkIdTransition"; + Hardfork["Merge"] = "merge"; + Hardfork["Shanghai"] = "shanghai"; + Hardfork["ShardingForkDev"] = "shardingFork"; +})(Hardfork || (Hardfork = {})); +export var ConsensusType; +(function (ConsensusType) { + ConsensusType["ProofOfStake"] = "pos"; + ConsensusType["ProofOfWork"] = "pow"; + ConsensusType["ProofOfAuthority"] = "poa"; +})(ConsensusType || (ConsensusType = {})); +export var ConsensusAlgorithm; +(function (ConsensusAlgorithm) { + ConsensusAlgorithm["Ethash"] = "ethash"; + ConsensusAlgorithm["Clique"] = "clique"; + ConsensusAlgorithm["Casper"] = "casper"; +})(ConsensusAlgorithm || (ConsensusAlgorithm = {})); +export var CustomChain; +(function (CustomChain) { + /** + * Polygon (Matic) Mainnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + CustomChain["PolygonMainnet"] = "polygon-mainnet"; + /** + * Polygon (Matic) Mumbai Testnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + CustomChain["PolygonMumbai"] = "polygon-mumbai"; + /** + * Arbitrum Rinkeby Testnet + * + * - [Documentation](https://developer.offchainlabs.com/docs/public_testnet) + */ + CustomChain["ArbitrumRinkebyTestnet"] = "arbitrum-rinkeby-testnet"; + /** + * Arbitrum One - mainnet for Arbitrum roll-up + * + * - [Documentation](https://developer.offchainlabs.com/public-chains) + */ + CustomChain["ArbitrumOne"] = "arbitrum-one"; + /** + * xDai EVM sidechain with a native stable token + * + * - [Documentation](https://www.xdaichain.com/) + */ + CustomChain["xDaiChain"] = "x-dai-chain"; + /** + * Optimistic Kovan - testnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + CustomChain["OptimisticKovan"] = "optimistic-kovan"; + /** + * Optimistic Ethereum - mainnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + CustomChain["OptimisticEthereum"] = "optimistic-ethereum"; +})(CustomChain || (CustomChain = {})); +//# sourceMappingURL=enums.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/enums.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/enums.js.map new file mode 100644 index 0000000..69ccbb1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/enums.js.map @@ -0,0 +1 @@ +{"version":3,"file":"enums.js","sourceRoot":"","sources":["../../../src/common/enums.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,MAAM,CAAN,IAAY,KAIX;AAJD,WAAY,KAAK;IAChB,uCAAW,CAAA;IACX,qCAAU,CAAA;IACV,8CAAkB,CAAA;AACnB,CAAC,EAJW,KAAK,KAAL,KAAK,QAIhB;AAED,MAAM,CAAN,IAAY,QAmBX;AAnBD,WAAY,QAAQ;IACnB,qCAAyB,CAAA;IACzB,mCAAuB,CAAA;IACvB,uBAAW,CAAA;IACX,iDAAqC,CAAA;IACrC,6CAAiC,CAAA;IACjC,mCAAuB,CAAA;IACvB,6CAAiC,CAAA;IACjC,qCAAyB,CAAA;IACzB,iCAAqB,CAAA;IACrB,uCAA2B,CAAA;IAC3B,6BAAiB,CAAA;IACjB,6BAAiB,CAAA;IACjB,yCAA6B,CAAA;IAC7B,uCAA2B,CAAA;IAC3B,2DAA+C,CAAA;IAC/C,2BAAe,CAAA;IACf,iCAAqB,CAAA;IACrB,4CAAgC,CAAA;AACjC,CAAC,EAnBW,QAAQ,KAAR,QAAQ,QAmBnB;AAED,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACxB,qCAAoB,CAAA;IACpB,oCAAmB,CAAA;IACnB,yCAAwB,CAAA;AACzB,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB;AAED,MAAM,CAAN,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC7B,uCAAiB,CAAA;IACjB,uCAAiB,CAAA;IACjB,uCAAiB,CAAA;AAClB,CAAC,EAJW,kBAAkB,KAAlB,kBAAkB,QAI7B;AAED,MAAM,CAAN,IAAY,WAiDX;AAjDD,WAAY,WAAW;IACtB;;;;OAIG;IACH,iDAAkC,CAAA;IAElC;;;;OAIG;IACH,+CAAgC,CAAA;IAEhC;;;;OAIG;IACH,kEAAmD,CAAA;IAEnD;;;;OAIG;IACH,2CAA4B,CAAA;IAE5B;;;;OAIG;IACH,wCAAyB,CAAA;IAEzB;;;;OAIG;IACH,mDAAoC,CAAA;IAEpC;;;;OAIG;IACH,yDAA0C,CAAA;AAC3C,CAAC,EAjDW,WAAW,KAAX,WAAW,QAiDtB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/arrowGlacier.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/arrowGlacier.js new file mode 100644 index 0000000..7b1e260 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/arrowGlacier.js @@ -0,0 +1,12 @@ +export default { + "name": "arrowGlacier", + "comment": "HF to delay the difficulty bomb", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/arrow-glacier.md", + "status": "Final", + "eips": [4345], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=arrowGlacier.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/arrowGlacier.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/arrowGlacier.js.map new file mode 100644 index 0000000..a4d4fdc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/arrowGlacier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arrowGlacier.js","sourceRoot":"","sources":["../../../../src/common/hardforks/arrowGlacier.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,cAAc;IACtB,SAAS,EAAE,iCAAiC;IAC5C,KAAK,EAAE,4GAA4G;IACnH,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,CAAC;IACd,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/berlin.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/berlin.js new file mode 100644 index 0000000..1864dcf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/berlin.js @@ -0,0 +1,8 @@ +export default { + "name": "berlin", + "comment": "HF targeted for July 2020 following the Muir Glacier HF", + "url": "https://eips.ethereum.org/EIPS/eip-2070", + "status": "Final", + "eips": [2565, 2929, 2718, 2930] +}; +//# sourceMappingURL=berlin.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/berlin.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/berlin.js.map new file mode 100644 index 0000000..cbc0bcf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/berlin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"berlin.js","sourceRoot":"","sources":["../../../../src/common/hardforks/berlin.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,QAAQ;IAChB,SAAS,EAAE,yDAAyD;IACpE,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;CAChC,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/byzantium.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/byzantium.js new file mode 100644 index 0000000..6f0f7e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/byzantium.js @@ -0,0 +1,57 @@ +export default { + "name": "byzantium", + "comment": "Hardfork with new precompiles, instructions and other protocol changes", + "url": "https://eips.ethereum.org/EIPS/eip-609", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "modexpGquaddivisor": { + "v": 20, + "d": "Gquaddivisor from modexp precompile for gas calculation" + }, + "ecAdd": { + "v": 500, + "d": "Gas costs for curve addition precompile" + }, + "ecMul": { + "v": 40000, + "d": "Gas costs for curve multiplication precompile" + }, + "ecPairing": { + "v": 100000, + "d": "Base gas costs for curve pairing precompile" + }, + "ecPairingWord": { + "v": 80000, + "d": "Gas costs regarding curve pairing precompile input length" + }, + "revert": { + "v": 0, + "d": "Base fee of the REVERT opcode" + }, + "staticcall": { + "v": 700, + "d": "Base fee of the STATICCALL opcode" + }, + "returndatasize": { + "v": 2, + "d": "Base fee of the RETURNDATASIZE opcode" + }, + "returndatacopy": { + "v": 3, + "d": "Base fee of the RETURNDATACOPY opcode" + } + }, + "vm": {}, + "pow": { + "minerReward": { + "v": "3000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 3000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=byzantium.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/byzantium.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/byzantium.js.map new file mode 100644 index 0000000..7a73a44 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/byzantium.js.map @@ -0,0 +1 @@ +{"version":3,"file":"byzantium.js","sourceRoot":"","sources":["../../../../src/common/hardforks/byzantium.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,WAAW;IACnB,SAAS,EAAE,wEAAwE;IACnF,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,oBAAoB,EAAE;YACrB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,yDAAyD;SAC9D;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,yCAAyC;SAC9C;QACD,OAAO,EAAE;YACR,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,+CAA+C;SACpD;QACD,WAAW,EAAE;YACZ,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,6CAA6C;SAClD;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,2DAA2D;SAChE;QACD,QAAQ,EAAE;YACT,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,+BAA+B;SACpC;QACD,YAAY,EAAE;YACb,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,mCAAmC;SACxC;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,uCAAuC;SAC5C;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,uCAAuC;SAC5C;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,aAAa,EAAE;YACd,GAAG,EAAE,qBAAqB;YAC1B,GAAG,EAAE,oDAAoD;SACzD;QACD,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/chainstart.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/chainstart.js new file mode 100644 index 0000000..eaaf87b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/chainstart.js @@ -0,0 +1,439 @@ +export default { + "name": "chainstart", + "comment": "Start of the Ethereum main chain", + "url": "", + "status": "", + "gasConfig": { + "minGasLimit": { + "v": 5000, + "d": "Minimum the gas limit may ever be" + }, + "gasLimitBoundDivisor": { + "v": 1024, + "d": "The bound divisor of the gas limit, used in update calculations" + }, + "maxRefundQuotient": { + "v": 2, + "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" + } + }, + "gasPrices": { + "base": { + "v": 2, + "d": "Gas base cost, used e.g. for ChainID opcode (Istanbul)" + }, + "tierStep": { + "v": [0, 2, 3, 5, 8, 10, 20], + "d": "Once per operation, for a selection of them" + }, + "exp": { + "v": 10, + "d": "Base fee of the EXP opcode" + }, + "expByte": { + "v": 10, + "d": "Times ceil(log256(exponent)) for the EXP instruction" + }, + "sha3": { + "v": 30, + "d": "Base fee of the SHA3 opcode" + }, + "sha3Word": { + "v": 6, + "d": "Once per word of the SHA3 operation's data" + }, + "sload": { + "v": 50, + "d": "Base fee of the SLOAD opcode" + }, + "sstoreSet": { + "v": 20000, + "d": "Once per SSTORE operation if the zeroness changes from zero" + }, + "sstoreReset": { + "v": 5000, + "d": "Once per SSTORE operation if the zeroness does not change from zero" + }, + "sstoreRefund": { + "v": 15000, + "d": "Once per SSTORE operation if the zeroness changes to zero" + }, + "jumpdest": { + "v": 1, + "d": "Base fee of the JUMPDEST opcode" + }, + "log": { + "v": 375, + "d": "Base fee of the LOG opcode" + }, + "logData": { + "v": 8, + "d": "Per byte in a LOG* operation's data" + }, + "logTopic": { + "v": 375, + "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas" + }, + "create": { + "v": 32000, + "d": "Base fee of the CREATE opcode" + }, + "call": { + "v": 40, + "d": "Base fee of the CALL opcode" + }, + "callStipend": { + "v": 2300, + "d": "Free gas given at beginning of call" + }, + "callValueTransfer": { + "v": 9000, + "d": "Paid for CALL when the value transfor is non-zero" + }, + "callNewAccount": { + "v": 25000, + "d": "Paid for CALL when the destination address didn't exist prior" + }, + "selfdestructRefund": { + "v": 24000, + "d": "Refunded following a selfdestruct operation" + }, + "memory": { + "v": 3, + "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL" + }, + "quadCoeffDiv": { + "v": 512, + "d": "Divisor for the quadratic particle of the memory cost equation" + }, + "createData": { + "v": 200, + "d": "" + }, + "tx": { + "v": 21000, + "d": "Per transaction. NOTE: Not payable on data of calls between transactions" + }, + "txCreation": { + "v": 32000, + "d": "The cost of creating a contract via tx" + }, + "txDataZero": { + "v": 4, + "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions" + }, + "txDataNonZero": { + "v": 68, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + }, + "copy": { + "v": 3, + "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added" + }, + "ecRecover": { + "v": 3000, + "d": "" + }, + "sha256": { + "v": 60, + "d": "" + }, + "sha256Word": { + "v": 12, + "d": "" + }, + "ripemd160": { + "v": 600, + "d": "" + }, + "ripemd160Word": { + "v": 120, + "d": "" + }, + "identity": { + "v": 15, + "d": "" + }, + "identityWord": { + "v": 3, + "d": "" + }, + "stop": { + "v": 0, + "d": "Base fee of the STOP opcode" + }, + "add": { + "v": 3, + "d": "Base fee of the ADD opcode" + }, + "mul": { + "v": 5, + "d": "Base fee of the MUL opcode" + }, + "sub": { + "v": 3, + "d": "Base fee of the SUB opcode" + }, + "div": { + "v": 5, + "d": "Base fee of the DIV opcode" + }, + "sdiv": { + "v": 5, + "d": "Base fee of the SDIV opcode" + }, + "mod": { + "v": 5, + "d": "Base fee of the MOD opcode" + }, + "smod": { + "v": 5, + "d": "Base fee of the SMOD opcode" + }, + "addmod": { + "v": 8, + "d": "Base fee of the ADDMOD opcode" + }, + "mulmod": { + "v": 8, + "d": "Base fee of the MULMOD opcode" + }, + "signextend": { + "v": 5, + "d": "Base fee of the SIGNEXTEND opcode" + }, + "lt": { + "v": 3, + "d": "Base fee of the LT opcode" + }, + "gt": { + "v": 3, + "d": "Base fee of the GT opcode" + }, + "slt": { + "v": 3, + "d": "Base fee of the SLT opcode" + }, + "sgt": { + "v": 3, + "d": "Base fee of the SGT opcode" + }, + "eq": { + "v": 3, + "d": "Base fee of the EQ opcode" + }, + "iszero": { + "v": 3, + "d": "Base fee of the ISZERO opcode" + }, + "and": { + "v": 3, + "d": "Base fee of the AND opcode" + }, + "or": { + "v": 3, + "d": "Base fee of the OR opcode" + }, + "xor": { + "v": 3, + "d": "Base fee of the XOR opcode" + }, + "not": { + "v": 3, + "d": "Base fee of the NOT opcode" + }, + "byte": { + "v": 3, + "d": "Base fee of the BYTE opcode" + }, + "address": { + "v": 2, + "d": "Base fee of the ADDRESS opcode" + }, + "balance": { + "v": 20, + "d": "Base fee of the BALANCE opcode" + }, + "origin": { + "v": 2, + "d": "Base fee of the ORIGIN opcode" + }, + "caller": { + "v": 2, + "d": "Base fee of the CALLER opcode" + }, + "callvalue": { + "v": 2, + "d": "Base fee of the CALLVALUE opcode" + }, + "calldataload": { + "v": 3, + "d": "Base fee of the CALLDATALOAD opcode" + }, + "calldatasize": { + "v": 2, + "d": "Base fee of the CALLDATASIZE opcode" + }, + "calldatacopy": { + "v": 3, + "d": "Base fee of the CALLDATACOPY opcode" + }, + "codesize": { + "v": 2, + "d": "Base fee of the CODESIZE opcode" + }, + "codecopy": { + "v": 3, + "d": "Base fee of the CODECOPY opcode" + }, + "gasprice": { + "v": 2, + "d": "Base fee of the GASPRICE opcode" + }, + "extcodesize": { + "v": 20, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 20, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "blockhash": { + "v": 20, + "d": "Base fee of the BLOCKHASH opcode" + }, + "coinbase": { + "v": 2, + "d": "Base fee of the COINBASE opcode" + }, + "timestamp": { + "v": 2, + "d": "Base fee of the TIMESTAMP opcode" + }, + "number": { + "v": 2, + "d": "Base fee of the NUMBER opcode" + }, + "difficulty": { + "v": 2, + "d": "Base fee of the DIFFICULTY opcode" + }, + "gaslimit": { + "v": 2, + "d": "Base fee of the GASLIMIT opcode" + }, + "pop": { + "v": 2, + "d": "Base fee of the POP opcode" + }, + "mload": { + "v": 3, + "d": "Base fee of the MLOAD opcode" + }, + "mstore": { + "v": 3, + "d": "Base fee of the MSTORE opcode" + }, + "mstore8": { + "v": 3, + "d": "Base fee of the MSTORE8 opcode" + }, + "sstore": { + "v": 0, + "d": "Base fee of the SSTORE opcode" + }, + "jump": { + "v": 8, + "d": "Base fee of the JUMP opcode" + }, + "jumpi": { + "v": 10, + "d": "Base fee of the JUMPI opcode" + }, + "pc": { + "v": 2, + "d": "Base fee of the PC opcode" + }, + "msize": { + "v": 2, + "d": "Base fee of the MSIZE opcode" + }, + "gas": { + "v": 2, + "d": "Base fee of the GAS opcode" + }, + "push": { + "v": 3, + "d": "Base fee of the PUSH opcode" + }, + "dup": { + "v": 3, + "d": "Base fee of the DUP opcode" + }, + "swap": { + "v": 3, + "d": "Base fee of the SWAP opcode" + }, + "callcode": { + "v": 40, + "d": "Base fee of the CALLCODE opcode" + }, + "return": { + "v": 0, + "d": "Base fee of the RETURN opcode" + }, + "invalid": { + "v": 0, + "d": "Base fee of the INVALID opcode" + }, + "selfdestruct": { + "v": 0, + "d": "Base fee of the SELFDESTRUCT opcode" + } + }, + "vm": { + "stackLimit": { + "v": 1024, + "d": "Maximum size of VM stack allowed" + }, + "callCreateDepth": { + "v": 1024, + "d": "Maximum depth of call/create stack" + }, + "maxExtraDataSize": { + "v": 32, + "d": "Maximum size extra data may be after Genesis" + } + }, + "pow": { + "minimumDifficulty": { + "v": 131072, + "d": "The minimum that the difficulty may ever be" + }, + "difficultyBoundDivisor": { + "v": 2048, + "d": "The bound divisor of the difficulty, used in the update calculations" + }, + "durationLimit": { + "v": 13, + "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not" + }, + "epochDuration": { + "v": 30000, + "d": "Duration between proof-of-work epochs" + }, + "timebombPeriod": { + "v": 100000, + "d": "Exponential difficulty timebomb period" + }, + "minerReward": { + "v": "5000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 0, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=chainstart.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/chainstart.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/chainstart.js.map new file mode 100644 index 0000000..2c07d83 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/chainstart.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chainstart.js","sourceRoot":"","sources":["../../../../src/common/hardforks/chainstart.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,YAAY;IACpB,SAAS,EAAE,kCAAkC;IAC7C,KAAK,EAAE,EAAE;IACT,QAAQ,EAAE,EAAE;IACZ,WAAW,EAAE;QACZ,aAAa,EAAE;YACd,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,mCAAmC;SACxC;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,2FAA2F;SAChG;KACD;IACD,WAAW,EAAE;QACZ,MAAM,EAAE;YACP,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,wDAAwD;SAC7D;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC;YAC5B,GAAG,EAAE,6CAA6C;SAClD;QACD,KAAK,EAAE;YACN,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,4BAA4B;SACjC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,sDAAsD;SAC3D;QACD,MAAM,EAAE;YACP,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,6BAA6B;SAClC;QACD,UAAU,EAAE;YACX,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4CAA4C;SACjD;QACD,OAAO,EAAE;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AAE,qCAAqC;SAC1C;KACD;IACD,IAAI,EAAE;QACL,YAAY,EAAE;YACb,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,kCAAkC;SACvC;QACD,iBAAiB,EAAE;YAClB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,oCAAoC;SACzC;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,8CAA8C;SACnD;KACD;IACD,KAAK,EAAE;QACN,mBAAmB,EAAE;YACpB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,6CAA6C;SAClD;QACD,wBAAwB,EAAE;YACzB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,sEAAsE;SAC3E;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,0GAA0G;SAC/G;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,uCAAuC;SAC5C;QACD,gBAAgB,EAAE;YACjB,GAAG,EAAE,MAAM;YACX,GAAG,EAAE,wCAAwC;SAC7C;QACD,aAAa,EAAE;YACd,GAAG,EAAE,qBAAqB;YAC1B,GAAG,EAAE,oDAAoD;SACzD;QACD,qBAAqB,EAAE;YACtB,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/constantinople.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/constantinople.js new file mode 100644 index 0000000..1392a9b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/constantinople.js @@ -0,0 +1,69 @@ +export default { + "name": "constantinople", + "comment": "Postponed hardfork including EIP-1283 (SSTORE gas metering changes)", + "url": "https://eips.ethereum.org/EIPS/eip-1013", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "netSstoreNoopGas": { + "v": 200, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "netSstoreInitGas": { + "v": 20000, + "d": "Once per SSTORE operation from clean zero" + }, + "netSstoreCleanGas": { + "v": 5000, + "d": "Once per SSTORE operation from clean non-zero" + }, + "netSstoreDirtyGas": { + "v": 200, + "d": "Once per SSTORE operation from dirty" + }, + "netSstoreClearRefund": { + "v": 15000, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + }, + "netSstoreResetRefund": { + "v": 4800, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "netSstoreResetClearRefund": { + "v": 19800, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "shl": { + "v": 3, + "d": "Base fee of the SHL opcode" + }, + "shr": { + "v": 3, + "d": "Base fee of the SHR opcode" + }, + "sar": { + "v": 3, + "d": "Base fee of the SAR opcode" + }, + "extcodehash": { + "v": 400, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "create2": { + "v": 32000, + "d": "Base fee of the CREATE2 opcode" + } + }, + "vm": {}, + "pow": { + "minerReward": { + "v": "2000000000000000000", + "d": "The amount a miner gets rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 5000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=constantinople.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/constantinople.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/constantinople.js.map new file mode 100644 index 0000000..17de9db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/constantinople.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constantinople.js","sourceRoot":"","sources":["../../../../src/common/hardforks/constantinople.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,gBAAgB;IACxB,SAAS,EAAE,qEAAqE;IAChF,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,2CAA2C;SAChD;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+CAA+C;SACpD;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,sCAAsC;SAC3C;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,4EAA4E;SACjF;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wEAAwE;SAC7E;QACD,2BAA2B,EAAE;YAC5B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,oEAAoE;SACzE;QACD,KAAK,EAAE;YACN,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4BAA4B;SACjC;QACD,KAAK,EAAE;YACN,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4BAA4B;SACjC;QACD,KAAK,EAAE;YACN,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,4BAA4B;SACjC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,gCAAgC;SACrC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,aAAa,EAAE;YACd,GAAG,EAAE,qBAAqB;YAC1B,GAAG,EAAE,qDAAqD;SAC1D;QACD,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/dao.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/dao.js new file mode 100644 index 0000000..1c52132 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/dao.js @@ -0,0 +1,11 @@ +export default { + "name": "dao", + "comment": "DAO rescue hardfork", + "url": "https://eips.ethereum.org/EIPS/eip-779", + "status": "Final", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=dao.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/dao.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/dao.js.map new file mode 100644 index 0000000..fffbb6c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/dao.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dao.js","sourceRoot":"","sources":["../../../../src/common/hardforks/dao.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,qBAAqB;IAChC,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/grayGlacier.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/grayGlacier.js new file mode 100644 index 0000000..a5a8f6a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/grayGlacier.js @@ -0,0 +1,12 @@ +export default { + "name": "grayGlacier", + "comment": "Delaying the difficulty bomb to Mid September 2022", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md", + "status": "Draft", + "eips": [5133], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=grayGlacier.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/grayGlacier.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/grayGlacier.js.map new file mode 100644 index 0000000..4f354f8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/grayGlacier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"grayGlacier.js","sourceRoot":"","sources":["../../../../src/common/hardforks/grayGlacier.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,aAAa;IACrB,SAAS,EAAE,oDAAoD;IAC/D,KAAK,EAAE,2GAA2G;IAClH,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,CAAC;IACd,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/homestead.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/homestead.js new file mode 100644 index 0000000..6dbffec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/homestead.js @@ -0,0 +1,16 @@ +export default { + "name": "homestead", + "comment": "Homestead hardfork with protocol and network changes", + "url": "https://eips.ethereum.org/EIPS/eip-606", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "delegatecall": { + "v": 40, + "d": "Base fee of the DELEGATECALL opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=homestead.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/homestead.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/homestead.js.map new file mode 100644 index 0000000..6ad4c9b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/homestead.js.map @@ -0,0 +1 @@ +{"version":3,"file":"homestead.js","sourceRoot":"","sources":["../../../../src/common/hardforks/homestead.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,WAAW;IACnB,SAAS,EAAE,sDAAsD;IACjE,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,cAAc,EAAE;YACf,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,qCAAqC;SAC1C;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/index.js new file mode 100644 index 0000000..2547fbb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/index.js @@ -0,0 +1,53 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import chainstart from './chainstart.js'; +import dao from './dao.js'; +import homestead from './homestead.js'; +import tangerineWhistle from './tangerineWhistle.js'; +import spuriousDragon from './spuriousDragon.js'; +import byzantium from './byzantium.js'; +import constantinople from './constantinople.js'; +import petersburg from './petersburg.js'; +import istanbul from './istanbul.js'; +import muirGlacier from './muirGlacier.js'; +import berlin from './berlin.js'; +import london from './london.js'; +import shanghai from './shanghai.js'; +import arrowGlacier from './arrowGlacier.js'; +import grayGlacier from './grayGlacier.js'; +import mergeForkIdTransition from './mergeForkIdTransition.js'; +import merge from './merge.js'; +export const hardforks = { + chainstart, + homestead, + dao, + tangerineWhistle, + spuriousDragon, + byzantium, + constantinople, + petersburg, + istanbul, + muirGlacier, + berlin, + london, + shanghai, + arrowGlacier, + grayGlacier, + mergeForkIdTransition, + merge, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/index.js.map new file mode 100644 index 0000000..a0c0153 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/hardforks/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,UAAU,MAAM,iBAAiB,CAAC;AACzC,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,SAAS,MAAM,gBAAgB,CAAC;AACvC,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,cAAc,MAAM,qBAAqB,CAAC;AACjD,OAAO,SAAS,MAAM,gBAAgB,CAAC;AACvC,OAAO,cAAc,MAAM,qBAAqB,CAAC;AACjD,OAAO,UAAU,MAAM,iBAAiB,CAAC;AACzC,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAC3C,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,YAAY,MAAM,mBAAmB,CAAC;AAC7C,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAC3C,OAAO,qBAAqB,MAAM,4BAA4B,CAAC;AAC/D,OAAO,KAAK,MAAM,YAAY,CAAC;AAE/B,MAAM,CAAC,MAAM,SAAS,GAA2B;IAChD,UAAU;IACV,SAAS;IACT,GAAG;IACH,gBAAgB;IAChB,cAAc;IACd,SAAS;IACT,cAAc;IACd,UAAU;IACV,QAAQ;IACR,WAAW;IACX,MAAM;IACN,MAAM;IACN,QAAQ;IACR,YAAY;IACZ,WAAW;IACX,qBAAqB;IACrB,KAAK;CACL,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/istanbul.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/istanbul.js new file mode 100644 index 0000000..0e16991 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/istanbul.js @@ -0,0 +1,88 @@ +export default { + "name": "istanbul", + "comment": "HF targeted for December 2019 following the Constantinople/Petersburg HF", + "url": "https://eips.ethereum.org/EIPS/eip-1679", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "blake2Round": { + "v": 1, + "d": "Gas cost per round for the Blake2 F precompile" + }, + "ecAdd": { + "v": 150, + "d": "Gas costs for curve addition precompile" + }, + "ecMul": { + "v": 6000, + "d": "Gas costs for curve multiplication precompile" + }, + "ecPairing": { + "v": 45000, + "d": "Base gas costs for curve pairing precompile" + }, + "ecPairingWord": { + "v": 34000, + "d": "Gas costs regarding curve pairing precompile input length" + }, + "txDataNonZero": { + "v": 16, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + }, + "sstoreSentryGasEIP2200": { + "v": 2300, + "d": "Minimum gas required to be present for an SSTORE call, not consumed" + }, + "sstoreNoopGasEIP2200": { + "v": 800, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "sstoreDirtyGasEIP2200": { + "v": 800, + "d": "Once per SSTORE operation if a dirty value is changed" + }, + "sstoreInitGasEIP2200": { + "v": 20000, + "d": "Once per SSTORE operation from clean zero to non-zero" + }, + "sstoreInitRefundEIP2200": { + "v": 19200, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "sstoreCleanGasEIP2200": { + "v": 5000, + "d": "Once per SSTORE operation from clean non-zero to something else" + }, + "sstoreCleanRefundEIP2200": { + "v": 4200, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "sstoreClearRefundEIP2200": { + "v": 15000, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + }, + "balance": { + "v": 700, + "d": "Base fee of the BALANCE opcode" + }, + "extcodehash": { + "v": 700, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "chainid": { + "v": 2, + "d": "Base fee of the CHAINID opcode" + }, + "selfbalance": { + "v": 5, + "d": "Base fee of the SELFBALANCE opcode" + }, + "sload": { + "v": 800, + "d": "Base fee of the SLOAD opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=istanbul.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/istanbul.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/istanbul.js.map new file mode 100644 index 0000000..0009684 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/istanbul.js.map @@ -0,0 +1 @@ +{"version":3,"file":"istanbul.js","sourceRoot":"","sources":["../../../../src/common/hardforks/istanbul.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,0EAA0E;IACrF,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gDAAgD;SACrD;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,yCAAyC;SAC9C;QACD,OAAO,EAAE;YACR,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,+CAA+C;SACpD;QACD,WAAW,EAAE;YACZ,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,6CAA6C;SAClD;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,2DAA2D;SAChE;QACD,eAAe,EAAE;YAChB,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,+HAA+H;SACpI;QACD,wBAAwB,EAAE;YACzB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,qEAAqE;SAC1E;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,uDAAuD;SAC5D;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,uDAAuD;SAC5D;QACD,yBAAyB,EAAE;YAC1B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,oEAAoE;SACzE;QACD,uBAAuB,EAAE;YACxB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,iEAAiE;SACtE;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wEAAwE;SAC7E;QACD,0BAA0B,EAAE;YAC3B,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,4EAA4E;SACjF;QACD,SAAS,EAAE;YACV,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,gCAAgC;SACrC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,gCAAgC;SACrC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,oCAAoC;SACzC;QACD,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,8BAA8B;SACnC;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/london.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/london.js new file mode 100644 index 0000000..a556701 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/london.js @@ -0,0 +1,8 @@ +export default { + "name": "london", + "comment": "HF targeted for July 2021 following the Berlin fork", + "url": "https://github.com/ethereum/eth1.0-specs/blob/master/network-upgrades/mainnet-upgrades/london.md", + "status": "Final", + "eips": [1559, 3198, 3529, 3541] +}; +//# sourceMappingURL=london.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/london.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/london.js.map new file mode 100644 index 0000000..9022a81 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/london.js.map @@ -0,0 +1 @@ +{"version":3,"file":"london.js","sourceRoot":"","sources":["../../../../src/common/hardforks/london.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,QAAQ;IAChB,SAAS,EAAE,qDAAqD;IAChE,KAAK,EAAE,kGAAkG;IACzG,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;CAChC,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/merge.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/merge.js new file mode 100644 index 0000000..787fe7d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/merge.js @@ -0,0 +1,13 @@ +export default { + "name": "merge", + "comment": "Hardfork to upgrade the consensus mechanism to Proof-of-Stake", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/merge.md", + "status": "Final", + "consensus": { + "type": "pos", + "algorithm": "casper", + "casper": {} + }, + "eips": [3675, 4399] +}; +//# sourceMappingURL=merge.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/merge.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/merge.js.map new file mode 100644 index 0000000..6e81c61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/merge.js.map @@ -0,0 +1 @@ +{"version":3,"file":"merge.js","sourceRoot":"","sources":["../../../../src/common/hardforks/merge.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,OAAO;IACf,SAAS,EAAE,+DAA+D;IAC1E,KAAK,EAAE,oGAAoG;IAC3G,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE;QACZ,MAAM,EAAE,KAAK;QACb,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,EAAE;KACZ;IACD,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;CACpB,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/mergeForkIdTransition.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/mergeForkIdTransition.js new file mode 100644 index 0000000..26fa036 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/mergeForkIdTransition.js @@ -0,0 +1,8 @@ +export default { + "name": "mergeForkIdTransition", + "comment": "Pre-merge hardfork to fork off non-upgraded clients", + "url": "https://eips.ethereum.org/EIPS/eip-3675", + "status": "Draft", + "eips": [] +}; +//# sourceMappingURL=mergeForkIdTransition.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/mergeForkIdTransition.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/mergeForkIdTransition.js.map new file mode 100644 index 0000000..c5acf0c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/mergeForkIdTransition.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mergeForkIdTransition.js","sourceRoot":"","sources":["../../../../src/common/hardforks/mergeForkIdTransition.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,uBAAuB;IAC/B,SAAS,EAAE,qDAAqD;IAChE,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,EAAE;CACV,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/muirGlacier.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/muirGlacier.js new file mode 100644 index 0000000..c95cabc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/muirGlacier.js @@ -0,0 +1,16 @@ +export default { + "name": "muirGlacier", + "comment": "HF to delay the difficulty bomb", + "url": "https://eips.ethereum.org/EIPS/eip-2384", + "status": "Final", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 9000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +}; +//# sourceMappingURL=muirGlacier.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/muirGlacier.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/muirGlacier.js.map new file mode 100644 index 0000000..d0ec66d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/muirGlacier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"muirGlacier.js","sourceRoot":"","sources":["../../../../src/common/hardforks/muirGlacier.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,aAAa;IACrB,SAAS,EAAE,iCAAiC;IAC5C,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;IACf,IAAI,EAAE,EAAE;IACR,KAAK,EAAE;QACN,qBAAqB,EAAE;YACtB,GAAG,EAAE,OAAO;YACZ,GAAG,EAAE,wDAAwD;SAC7D;KACD;CACD,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/petersburg.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/petersburg.js new file mode 100644 index 0000000..44ef549 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/petersburg.js @@ -0,0 +1,40 @@ +export default { + "name": "petersburg", + "comment": "Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople", + "url": "https://eips.ethereum.org/EIPS/eip-1716", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "netSstoreNoopGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreInitGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreCleanGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreDirtyGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreClearRefund": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreResetRefund": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreResetClearRefund": { + "v": null, + "d": "Removed along EIP-1283" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=petersburg.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/petersburg.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/petersburg.js.map new file mode 100644 index 0000000..9c7a5ec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/petersburg.js.map @@ -0,0 +1 @@ +{"version":3,"file":"petersburg.js","sourceRoot":"","sources":["../../../../src/common/hardforks/petersburg.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,YAAY;IACpB,SAAS,EAAE,yFAAyF;IACpG,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,kBAAkB,EAAE;YACnB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,kBAAkB,EAAE;YACnB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,mBAAmB,EAAE;YACpB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,sBAAsB,EAAE;YACvB,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;QACD,2BAA2B,EAAE;YAC5B,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,wBAAwB;SAC7B;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/shanghai.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/shanghai.js new file mode 100644 index 0000000..45d80e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/shanghai.js @@ -0,0 +1,8 @@ +export default { + "name": "shanghai", + "comment": "Next feature hardfork after the merge hardfork having withdrawals, warm coinbase, push0, limit/meter initcode", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md", + "status": "Final", + "eips": [3651, 3855, 3860, 4895] +}; +//# sourceMappingURL=shanghai.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/shanghai.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/shanghai.js.map new file mode 100644 index 0000000..bc89e5e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/shanghai.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shanghai.js","sourceRoot":"","sources":["../../../../src/common/hardforks/shanghai.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,UAAU;IAClB,SAAS,EAAE,+GAA+G;IAC1H,KAAK,EAAE,uGAAuG;IAC9G,QAAQ,EAAE,OAAO;IACjB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;CAChC,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/sharding.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/sharding.js new file mode 100644 index 0000000..252f16b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/sharding.js @@ -0,0 +1,8 @@ +export default { + "name": "shardingFork", + "comment": "Internal hardfork to test proto-danksharding (do not use in production)", + "url": "https://eips.ethereum.org/EIPS/eip-4844", + "status": "Experimental", + "eips": [4844] +}; +//# sourceMappingURL=sharding.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/sharding.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/sharding.js.map new file mode 100644 index 0000000..4f7c276 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/sharding.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sharding.js","sourceRoot":"","sources":["../../../../src/common/hardforks/sharding.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,cAAc;IACtB,SAAS,EAAE,yEAAyE;IACpF,KAAK,EAAE,yCAAyC;IAChD,QAAQ,EAAE,cAAc;IACxB,MAAM,EAAE,CAAC,IAAI,CAAC;CACd,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/spuriousDragon.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/spuriousDragon.js new file mode 100644 index 0000000..f4c6a37 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/spuriousDragon.js @@ -0,0 +1,21 @@ +export default { + "name": "spuriousDragon", + "comment": "HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit", + "url": "https://eips.ethereum.org/EIPS/eip-607", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "expByte": { + "v": 50, + "d": "Times ceil(log256(exponent)) for the EXP instruction" + } + }, + "vm": { + "maxCodeSize": { + "v": 24576, + "d": "Maximum length of contract code" + } + }, + "pow": {} +}; +//# sourceMappingURL=spuriousDragon.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/spuriousDragon.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/spuriousDragon.js.map new file mode 100644 index 0000000..906e6ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/spuriousDragon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spuriousDragon.js","sourceRoot":"","sources":["../../../../src/common/hardforks/spuriousDragon.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,gBAAgB;IACxB,SAAS,EAAE,oHAAoH;IAC/H,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,SAAS,EAAE;YACV,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,sDAAsD;SAC3D;KACD;IACD,IAAI,EAAE;QACL,aAAa,EAAE;YACd,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,iCAAiC;SACtC;KACD;IACD,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/tangerineWhistle.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/tangerineWhistle.js new file mode 100644 index 0000000..4580ebe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/tangerineWhistle.js @@ -0,0 +1,44 @@ +export default { + "name": "tangerineWhistle", + "comment": "Hardfork with gas cost changes for IO-heavy operations", + "url": "https://eips.ethereum.org/EIPS/eip-608", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "sload": { + "v": 200, + "d": "Once per SLOAD operation" + }, + "call": { + "v": 700, + "d": "Once per CALL operation & message call transaction" + }, + "extcodesize": { + "v": 700, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 700, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "balance": { + "v": 400, + "d": "Base fee of the BALANCE opcode" + }, + "delegatecall": { + "v": 700, + "d": "Base fee of the DELEGATECALL opcode" + }, + "callcode": { + "v": 700, + "d": "Base fee of the CALLCODE opcode" + }, + "selfdestruct": { + "v": 5000, + "d": "Base fee of the SELFDESTRUCT opcode" + } + }, + "vm": {}, + "pow": {} +}; +//# sourceMappingURL=tangerineWhistle.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/tangerineWhistle.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/tangerineWhistle.js.map new file mode 100644 index 0000000..bc834fe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/hardforks/tangerineWhistle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tangerineWhistle.js","sourceRoot":"","sources":["../../../../src/common/hardforks/tangerineWhistle.ts"],"names":[],"mappings":"AAAA,eAAe;IACd,MAAM,EAAE,kBAAkB;IAC1B,SAAS,EAAE,wDAAwD;IACnE,KAAK,EAAE,wCAAwC;IAC/C,QAAQ,EAAE,OAAO;IACjB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE;QACZ,OAAO,EAAE;YACR,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,0BAA0B;SAC/B;QACD,MAAM,EAAE;YACP,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oDAAoD;SACzD;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,aAAa,EAAE;YACd,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,oCAAoC;SACzC;QACD,SAAS,EAAE;YACV,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,gCAAgC;SACrC;QACD,cAAc,EAAE;YACf,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,qCAAqC;SAC1C;QACD,UAAU,EAAE;YACX,GAAG,EAAE,GAAG;YACR,GAAG,EAAE,iCAAiC;SACtC;QACD,cAAc,EAAE;YACf,GAAG,EAAE,IAAI;YACT,GAAG,EAAE,qCAAqC;SAC1C;KACD;IACD,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;CACT,CACC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/index.js new file mode 100644 index 0000000..fe8a691 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/index.js @@ -0,0 +1,22 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// @ethereumjs/common version 3.1.1 +export * from './common.js'; +export * from './enums.js'; +export * from './types.js'; +export * from './utils.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/index.js.map new file mode 100644 index 0000000..252c687 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,mCAAmC;AACnC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/types.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/types.js new file mode 100644 index 0000000..e6b34c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/types.js @@ -0,0 +1,11 @@ +/** + * Type output options + */ +export var TypeOutput; +(function (TypeOutput) { + TypeOutput[TypeOutput["Number"] = 0] = "Number"; + TypeOutput[TypeOutput["BigInt"] = 1] = "BigInt"; + TypeOutput[TypeOutput["Uint8Array"] = 2] = "Uint8Array"; + TypeOutput[TypeOutput["PrefixedHexString"] = 3] = "PrefixedHexString"; +})(TypeOutput || (TypeOutput = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/types.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/types.js.map new file mode 100644 index 0000000..142c54a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/common/types.ts"],"names":[],"mappings":"AAqKA;;GAEG;AACH,MAAM,CAAN,IAAY,UAKX;AALD,WAAY,UAAU;IACrB,+CAAM,CAAA;IACN,+CAAM,CAAA;IACN,uDAAU,CAAA;IACV,qEAAiB,CAAA;AAClB,CAAC,EALW,UAAU,KAAV,UAAU,QAKrB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/utils.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/utils.js new file mode 100644 index 0000000..b250d78 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/utils.js @@ -0,0 +1,477 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isHexPrefixed, isHexString } from 'web3-validator'; +import { bytesToHex, hexToBytes, numberToHex } from 'web3-utils'; +import { secp256k1 } from '../tx/constants.js'; +import { Hardfork } from './enums.js'; +import { TypeOutput } from './types.js'; +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +export const stripHexPrefix = (str) => { + if (typeof str !== 'string') + throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`); + return isHexPrefixed(str) ? str.slice(2) : str; +}; +/** + * Transforms Geth formatted nonce (i.e. hex string) to 8 byte 0x-prefixed string used internally + * @param nonce string parsed from the Geth genesis file + * @returns nonce as a 0x-prefixed 8 byte string + */ +function formatNonce(nonce) { + if (!nonce || nonce === '0x0') { + return '0x0000000000000000'; + } + if (isHexPrefixed(nonce)) { + return `0x${stripHexPrefix(nonce).padStart(16, '0')}`; + } + return `0x${nonce.padStart(16, '0')}`; +} +/** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ +const intToHex = function (i) { + if (!Number.isSafeInteger(i) || i < 0) { + throw new Error(`Received an invalid integer type: ${i}`); + } + return `0x${i.toString(16)}`; +}; +/** + * Converts Geth genesis parameters to an EthereumJS compatible `CommonOpts` object + * @param json object representing the Geth genesis file + * @param optional mergeForkIdPostMerge which clarifies the placement of MergeForkIdTransition + * hardfork, which by default is post merge as with the merged eth networks but could also come + * before merge like in kiln genesis + * @returns genesis parameters in a `CommonOpts` compliant object + */ +function parseGethParams(json, mergeForkIdPostMerge = true) { + var _a, _b; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { name, config, difficulty, mixHash, gasLimit, coinbase, baseFeePerGas, } = json; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + let { extraData, timestamp, nonce } = json; + const genesisTimestamp = Number(timestamp); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { chainId } = config; + // geth is not strictly putting empty fields with a 0x prefix + if (extraData === '') { + extraData = '0x'; + } + // geth may use number for timestamp + if (!isHexPrefixed(timestamp)) { + // eslint-disable-next-line radix + timestamp = intToHex(parseInt(timestamp)); + } + // geth may not give us a nonce strictly formatted to an 8 byte hex string + if (nonce.length !== 18) { + nonce = formatNonce(nonce); + } + // EIP155 and EIP158 are both part of Spurious Dragon hardfork and must occur at the same time + // but have different configuration parameters in geth genesis parameters + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (config.eip155Block !== config.eip158Block) { + throw new Error('EIP155 block number must equal EIP 158 block number since both are part of SpuriousDragon hardfork and the client only supports activating the full hardfork'); + } + const params = { + name, + chainId, + networkId: chainId, + genesis: { + timestamp, + // eslint-disable-next-line radix + gasLimit: parseInt(gasLimit), + // eslint-disable-next-line radix + difficulty: parseInt(difficulty), + nonce, + extraData, + mixHash, + coinbase, + baseFeePerGas, + }, + hardfork: undefined, + hardforks: [], + bootstrapNodes: [], + consensus: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config.clique !== undefined + ? { + type: 'poa', + algorithm: 'clique', + clique: { + // The recent geth genesis seems to be using blockperiodseconds + // and epochlength for clique specification + // see: https://hackmd.io/PqZgMpnkSWCWv5joJoFymQ + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + period: (_a = config.clique.period) !== null && _a !== void 0 ? _a : config.clique.blockperiodseconds, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + epoch: (_b = config.clique.epoch) !== null && _b !== void 0 ? _b : config.clique.epochlength, + }, + } + : { + type: 'pow', + algorithm: 'ethash', + ethash: {}, + }, + }; + const forkMap = { + [Hardfork.Homestead]: { name: 'homesteadBlock' }, + [Hardfork.Dao]: { name: 'daoForkBlock' }, + [Hardfork.TangerineWhistle]: { name: 'eip150Block' }, + [Hardfork.SpuriousDragon]: { name: 'eip155Block' }, + [Hardfork.Byzantium]: { name: 'byzantiumBlock' }, + [Hardfork.Constantinople]: { name: 'constantinopleBlock' }, + [Hardfork.Petersburg]: { name: 'petersburgBlock' }, + [Hardfork.Istanbul]: { name: 'istanbulBlock' }, + [Hardfork.MuirGlacier]: { name: 'muirGlacierBlock' }, + [Hardfork.Berlin]: { name: 'berlinBlock' }, + [Hardfork.London]: { name: 'londonBlock' }, + [Hardfork.MergeForkIdTransition]: { + name: 'mergeForkBlock', + postMerge: mergeForkIdPostMerge, + }, + [Hardfork.Shanghai]: { name: 'shanghaiTime', postMerge: true, isTimestamp: true }, + [Hardfork.ShardingForkDev]: { + name: 'shardingForkTime', + postMerge: true, + isTimestamp: true, + }, + }; + // forkMapRev is the map from config field name to Hardfork + const forkMapRev = Object.keys(forkMap).reduce((acc, elem) => { + acc[forkMap[elem].name] = elem; + return acc; + }, {}); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const configHardforkNames = Object.keys(config).filter( + // eslint-disable-next-line no-null/no-null, @typescript-eslint/no-unsafe-member-access + key => forkMapRev[key] !== undefined && config[key] !== undefined && config[key] !== null); + params.hardforks = configHardforkNames + .map(nameBlock => ({ + name: forkMapRev[nameBlock], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + block: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + forkMap[forkMapRev[nameBlock]].isTimestamp === true || + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof config[nameBlock] !== 'number' + ? // eslint-disable-next-line no-null/no-null + null + : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config[nameBlock], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + timestamp: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + forkMap[forkMapRev[nameBlock]].isTimestamp === true && + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof config[nameBlock] === 'number' + ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config[nameBlock] + : undefined, + })) + // eslint-disable-next-line no-null/no-null + .filter(fork => fork.block !== null || fork.timestamp !== undefined); + params.hardforks.sort((a, b) => { var _a, _b; return ((_a = a.block) !== null && _a !== void 0 ? _a : Infinity) - ((_b = b.block) !== null && _b !== void 0 ? _b : Infinity); }); + params.hardforks.sort((a, b) => { var _a, _b; return ((_a = a.timestamp) !== null && _a !== void 0 ? _a : genesisTimestamp) - ((_b = b.timestamp) !== null && _b !== void 0 ? _b : genesisTimestamp); }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (config.terminalTotalDifficulty !== undefined) { + // Following points need to be considered for placement of merge hf + // - Merge hardfork can't be placed at genesis + // - Place merge hf before any hardforks that require CL participation for e.g. withdrawals + // - Merge hardfork has to be placed just after genesis if any of the genesis hardforks make CL + // necessary for e.g. withdrawals + const mergeConfig = { + name: Hardfork.Merge, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + ttd: config.terminalTotalDifficulty, + // eslint-disable-next-line no-null/no-null + block: null, + }; + // Merge hardfork has to be placed before first hardfork that is dependent on merge + const postMergeIndex = params.hardforks.findIndex( + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (hf) => { var _a; return ((_a = forkMap[hf.name]) === null || _a === void 0 ? void 0 : _a.postMerge) === true; }); + if (postMergeIndex !== -1) { + params.hardforks.splice(postMergeIndex, 0, mergeConfig); + } + else { + params.hardforks.push(mergeConfig); + } + } + const latestHardfork = params.hardforks.length > 0 ? params.hardforks.slice(-1)[0] : undefined; + params.hardfork = latestHardfork === null || latestHardfork === void 0 ? void 0 : latestHardfork.name; + params.hardforks.unshift({ name: Hardfork.Chainstart, block: 0 }); + return params; +} +/** + * Parses a genesis.json exported from Geth into parameters for Common instance + * @param json representing the Geth genesis file + * @param name optional chain name + * @returns parsed params + */ +export function parseGethGenesis(json, name, mergeForkIdPostMerge) { + try { + if (['config', 'difficulty', 'gasLimit', 'alloc'].some(field => !(field in json))) { + throw new Error('Invalid format, expected geth genesis fields missing'); + } + if (name !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-param-reassign + json.name = name; + } + return parseGethParams(json, mergeForkIdPostMerge); + } + catch (e) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-template-expressions + throw new Error(`Error parsing parameters file: ${e.message}`); + } +} +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +export function padToEven(value) { + let a = value; + if (typeof a !== 'string') { + throw new Error(`[padToEven] value must be type 'string', received ${typeof a}`); + } + if (a.length % 2) + a = `0${a}`; + return a; +} +/** + * Converts an `Number` to a `Uint8Array` + * @param {Number} i + * @return {Uint8Array} + */ +export const intToUint8Array = function (i) { + const hex = intToHex(i); + return hexToBytes(`0x${padToEven(hex.slice(2))}`); +}; +/** + * Attempts to turn a value into a `Uint8Array`. + * Inputs supported: `Uint8Array` `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toUint8Array()` method. + * @param v the value + */ +export const toUint8Array = function (v) { + // eslint-disable-next-line no-null/no-null + if (v === null || v === undefined) { + return new Uint8Array(); + } + if (v instanceof Uint8Array) { + return v; + } + if (Array.isArray(v)) { + return Uint8Array.from(v); + } + if (typeof v === 'string') { + if (!isHexString(v)) { + throw new Error(`Cannot convert string to Uint8Array. only supports 0x-prefixed hex strings and this string was given: ${v}`); + } + return hexToBytes(padToEven(stripHexPrefix(v))); + } + if (typeof v === 'number') { + return toUint8Array(numberToHex(v)); + } + if (typeof v === 'bigint') { + if (v < BigInt(0)) { + throw new Error(`Cannot convert negative bigint to Uint8Array. Given: ${v}`); + } + let n = v.toString(16); + if (n.length % 2) + n = `0${n}`; + return toUint8Array(`0x${n}`); + } + if (v.toArray) { + // converts a BN to a Uint8Array + return Uint8Array.from(v.toArray()); + } + throw new Error('invalid type'); +}; +/** + * Converts a {@link Uint8Array} to a {@link bigint} + */ +export function uint8ArrayToBigInt(buf) { + const hex = bytesToHex(buf); + if (hex === '0x') { + return BigInt(0); + } + return BigInt(hex); +} +/** + * Converts a {@link bigint} to a {@link Uint8Array} + */ +export function bigIntToUint8Array(num) { + return toUint8Array(`0x${num.toString(16)}`); +} +/** + * Returns a Uint8Array filled with 0s. + * @param bytes the number of bytes the Uint8Array should be + */ +export const zeros = function (bytes) { + return new Uint8Array(bytes).fill(0); +}; +/** + * Pads a `Uint8Array` with zeros till it has `length` bytes. + * Truncates the beginning or end of input if its length exceeds `length`. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @param right whether to start padding form the left or right + * @return (Uint8Array) + */ +const setLength = function (msg, length, right) { + const buf = zeros(length); + if (right) { + if (msg.length < length) { + buf.set(msg); + return buf; + } + return msg.subarray(0, length); + } + if (msg.length < length) { + buf.set(msg, length - msg.length); + return buf; + } + return msg.subarray(-length); +}; +/** + * Throws if input is not a Uint8Array + * @param {Uint8Array} input value to check + */ +export function assertIsUint8Array(input) { + if (!(input instanceof Uint8Array)) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + const msg = `This method only supports Uint8Array but input was: ${input}`; + throw new Error(msg); + } +} +/** + * Left Pads a `Uint8Array` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @return (Uint8Array) + */ +export const setLengthLeft = function (msg, length) { + assertIsUint8Array(msg); + return setLength(msg, length, false); +}; +/** + * Trims leading zeros from a `Uint8Array`, `String` or `Number[]`. + * @param a (Uint8Array|Array|String) + * @return (Uint8Array|Array|String) + */ +export function stripZeros(a) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + let first = a[0]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + while (a.length > 0 && first.toString() === '0') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, prefer-destructuring, @typescript-eslint/no-unsafe-call, no-param-reassign + a = a.slice(1); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, prefer-destructuring, @typescript-eslint/no-unsafe-member-access + first = a[0]; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return a; +} +/** + * Trims leading zeros from a `Uint8Array`. + * @param a (Uint8Array) + * @return (Uint8Array) + */ +export const unpadUint8Array = function (a) { + assertIsUint8Array(a); + return stripZeros(a); +}; +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +export const bigIntToHex = (num) => `0x${num.toString(16)}`; +/** + * Convert value from bigint to an unpadded Uint8Array + * (useful for RLP transport) + * @param value value to convert + */ +export function bigIntToUnpaddedUint8Array(value) { + return unpadUint8Array(bigIntToUint8Array(value)); +} +function calculateSigRecovery(v, chainId) { + if (v === BigInt(0) || v === BigInt(1)) + return v; + if (chainId === undefined) { + return v - BigInt(27); + } + return v - (chainId * BigInt(2) + BigInt(35)); +} +function isValidSigRecovery(recovery) { + return recovery === BigInt(0) || recovery === BigInt(1); +} +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +export const ecrecover = function (msgHash, v, r, s, chainId) { + const recovery = calculateSigRecovery(v, chainId); + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value'); + } + const senderPubKey = new secp256k1.Signature(uint8ArrayToBigInt(r), uint8ArrayToBigInt(s)) + .addRecoveryBit(Number(recovery)) + .recoverPublicKey(msgHash) + .toRawBytes(false); + return senderPubKey.slice(1); +}; +export function toType(input, outputType) { + // eslint-disable-next-line no-null/no-null + if (input === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + if (input === undefined) { + return undefined; + } + if (typeof input === 'string' && !isHexString(input)) { + throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`); + } + else if (typeof input === 'number' && !Number.isSafeInteger(input)) { + throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'); + } + const output = toUint8Array(input); + switch (outputType) { + case TypeOutput.Uint8Array: + return output; + case TypeOutput.BigInt: + return uint8ArrayToBigInt(output); + case TypeOutput.Number: { + const bigInt = uint8ArrayToBigInt(output); + if (bigInt > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)'); + } + return Number(bigInt); + } + case TypeOutput.PrefixedHexString: + return bytesToHex(output); + default: + throw new Error('unknown outputType'); + } +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/utils.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/utils.js.map new file mode 100644 index 0000000..19d4ecf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/common/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/common/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO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;IAED,MAAM,MAAM,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IAEnC,QAAQ,UAAU,EAAE;QACnB,KAAK,UAAU,CAAC,UAAU;YACzB,OAAO,MAAiC,CAAC;QAC1C,KAAK,UAAU,CAAC,MAAM;YACrB,OAAO,kBAAkB,CAAC,MAAM,CAA4B,CAAC;QAC9D,KAAK,UAAU,CAAC,MAAM,CAAC,CAAC;YACvB,MAAM,MAAM,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;YAC1C,IAAI,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE;gBAC7C,MAAM,IAAI,KAAK,CACd,8FAA8F,CAC9F,CAAC;aACF;YACD,OAAO,MAAM,CAAC,MAAM,CAA4B,CAAC;SACjD;QACD,KAAK,UAAU,CAAC,iBAAiB;YAChC,OAAO,UAAU,CAAC,MAAM,CAA4B,CAAC;QACtD;YACC,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;KACvC;AACF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/index.js new file mode 100644 index 0000000..d043893 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/index.js @@ -0,0 +1,44 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data. + * + * **_NOTE:_** This package has NOT been audited and might potentially be unsafe. Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production! + * + * + * To use this package standalone and use its methods use: + * ```ts + * import { create, decrypt } from 'web3-eth-accounts'; // .... + * ``` + * + * To use this package within the web3 object use: + * + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // now you have access to the accounts class + * web3.eth.accounts.create(); + * ``` + */ +export * from './wallet.js'; +export * from './account.js'; +export * from './types.js'; +export * from './schemas.js'; +export * from './common/index.js'; +export * from './tx/index.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/index.js.map new file mode 100644 index 0000000..62fe891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/schemas.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/schemas.js new file mode 100644 index 0000000..29c8015 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/schemas.js @@ -0,0 +1,39 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export const keyStoreSchema = { + type: 'object', + required: ['crypto', 'id', 'version', 'address'], + properties: { + crypto: { + type: 'object', + required: ['cipher', 'ciphertext', 'cipherparams', 'kdf', 'kdfparams', 'mac'], + properties: { + cipher: { type: 'string' }, + ciphertext: { type: 'string' }, + cipherparams: { type: 'object' }, + kdf: { type: 'string' }, + kdfparams: { type: 'object' }, + salt: { type: 'string' }, + mac: { type: 'string' }, + }, + }, + id: { type: 'string' }, + version: { type: 'number' }, + address: { type: 'string' }, + }, +}; +//# sourceMappingURL=schemas.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/schemas.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/schemas.js.map new file mode 100644 index 0000000..7249559 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/schemas.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B,IAAI,EAAE,QAAQ;IACd,QAAQ,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,CAAC;IAChD,UAAU,EAAE;QACX,MAAM,EAAE;YACP,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC;YAC7E,UAAU,EAAE;gBACX,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC1B,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC9B,YAAY,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAChC,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBACvB,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC7B,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBACxB,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;aACvB;SACD;QACD,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QACtB,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;QAC3B,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC3B;CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/address.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/address.js new file mode 100644 index 0000000..26de463 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/address.js @@ -0,0 +1,77 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { bytesToHex, uint8ArrayEquals } from 'web3-utils'; +import { secp256k1 } from './constants.js'; +import { assertIsUint8Array, zeros } from '../common/utils.js'; +export class Address { + constructor(buf) { + if (buf.length !== 20) { + throw new Error('Invalid address length'); + } + this.buf = buf; + } + /** + * Returns the zero address. + */ + static zero() { + return new Address(zeros(20)); + } + /** + * Is address equal to another. + */ + equals(address) { + return uint8ArrayEquals(this.buf, address.buf); + } + /** + * Is address zero. + */ + isZero() { + return this.equals(Address.zero()); + } + /** + * Returns hex encoding of address. + */ + toString() { + return bytesToHex(this.buf); + } + /** + * Returns Uint8Array representation of address. + */ + toArray() { + return this.buf; + } + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ + static publicToAddress(_pubKey, sanitize = false) { + let pubKey = _pubKey; + assertIsUint8Array(pubKey); + if (sanitize && pubKey.length !== 64) { + pubKey = secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1); + } + if (pubKey.length !== 64) { + throw new Error('Expected pubKey to be of length 64'); + } + // Only take the lower 160bits of the hash + return keccak256(pubKey).slice(-20); + } +} +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/address.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/address.js.map new file mode 100644 index 0000000..1bc45d1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../src/tx/address.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE/D,MAAM,OAAO,OAAO;IAGnB,YAAmB,GAAe;QACjC,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,EAAE;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC1C;QACD,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IAChB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,IAAI;QACjB,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/B,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,OAAgB;QAC7B,OAAO,gBAAgB,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAChD,CAAC;IAED;;OAEG;IACI,MAAM;QACZ,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACpC,CAAC;IAED;;OAEG;IACI,QAAQ;QACd,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IAED;;OAEG;IACI,OAAO;QACb,OAAO,IAAI,CAAC,GAAG,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,eAAe,CAAC,OAAmB,EAAE,QAAQ,GAAG,KAAK;QAClE,IAAI,MAAM,GAAG,OAAO,CAAC;QACrB,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAC3B,IAAI,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,EAAE,EAAE;YACrC,MAAM,GAAG,SAAS,CAAC,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;SAC9E;QACD,IAAI,MAAM,CAAC,MAAM,KAAK,EAAE,EAAE;YACzB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;SACtD;QACD,0CAA0C;QAC1C,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;IACrC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/baseTransaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/baseTransaction.js new file mode 100644 index 0000000..e8ae51c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/baseTransaction.js @@ -0,0 +1,405 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { bytesToHex } from 'web3-utils'; +import { MAX_INTEGER, MAX_UINT64, SECP256K1_ORDER_DIV_2, secp256k1 } from './constants.js'; +import { toUint8Array, uint8ArrayToBigInt, unpadUint8Array } from '../common/utils.js'; +import { Common } from '../common/common.js'; +import { Hardfork, Chain } from '../common/enums.js'; +import { Capability } from './types.js'; +import { Address } from './address.js'; +import { checkMaxInitCodeSize } from './utils.js'; +/** + * This base class will likely be subject to further + * refactoring along the introduction of additional tx types + * on the Ethereum network. + * + * It is therefore not recommended to use directly. + */ +export class BaseTransaction { + constructor(txData, opts) { + var _a, _b; + this.cache = { + hash: undefined, + dataFee: undefined, + }; + /** + * List of tx type defining EIPs, + * e.g. 1559 (fee market) and 2930 (access lists) + * for FeeMarketEIP1559Transaction objects + */ + this.activeCapabilities = []; + /** + * The default chain the tx falls back to if no Common + * is provided and if the chain can't be derived from + * a passed in chainId (only EIP-2718 typed txs) or + * EIP-155 signature (legacy txs). + * + * @hidden + */ + this.DEFAULT_CHAIN = Chain.Mainnet; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + this.DEFAULT_HARDFORK = Hardfork.Merge; + const { nonce, gasLimit, to, value, data, v, r, s, type } = txData; + this._type = Number(uint8ArrayToBigInt(toUint8Array(type))); + this.txOptions = opts; + const toB = toUint8Array(to === '' ? '0x' : to); + const vB = toUint8Array(v === '' ? '0x' : v); + const rB = toUint8Array(r === '' ? '0x' : r); + const sB = toUint8Array(s === '' ? '0x' : s); + this.nonce = uint8ArrayToBigInt(toUint8Array(nonce === '' ? '0x' : nonce)); + this.gasLimit = uint8ArrayToBigInt(toUint8Array(gasLimit === '' ? '0x' : gasLimit)); + this.to = toB.length > 0 ? new Address(toB) : undefined; + this.value = uint8ArrayToBigInt(toUint8Array(value === '' ? '0x' : value)); + this.data = toUint8Array(data === '' ? '0x' : data); + this.v = vB.length > 0 ? uint8ArrayToBigInt(vB) : undefined; + this.r = rB.length > 0 ? uint8ArrayToBigInt(rB) : undefined; + this.s = sB.length > 0 ? uint8ArrayToBigInt(sB) : undefined; + this._validateCannotExceedMaxInteger({ value: this.value, r: this.r, s: this.s }); + // geth limits gasLimit to 2^64-1 + this._validateCannotExceedMaxInteger({ gasLimit: this.gasLimit }, 64); + // EIP-2681 limits nonce to 2^64-1 (cannot equal 2^64-1) + this._validateCannotExceedMaxInteger({ nonce: this.nonce }, 64, true); + // eslint-disable-next-line no-null/no-null + const createContract = this.to === undefined || this.to === null; + const allowUnlimitedInitCodeSize = (_a = opts.allowUnlimitedInitCodeSize) !== null && _a !== void 0 ? _a : false; + const common = (_b = opts.common) !== null && _b !== void 0 ? _b : this._getCommon(); + if (createContract && common.isActivatedEIP(3860) && !allowUnlimitedInitCodeSize) { + checkMaxInitCodeSize(common, this.data.length); + } + } + /** + * Returns the transaction type. + * + * Note: legacy txs will return tx type `0`. + */ + get type() { + return this._type; + } + /** + * Checks if a tx type defining capability is active + * on a tx, for example the EIP-1559 fee market mechanism + * or the EIP-2930 access list feature. + * + * Note that this is different from the tx type itself, + * so EIP-2930 access lists can very well be active + * on an EIP-1559 tx for example. + * + * This method can be useful for feature checks if the + * tx type is unknown (e.g. when instantiated with + * the tx factory). + * + * See `Capabilites` in the `types` module for a reference + * on all supported capabilities. + */ + supports(capability) { + return this.activeCapabilities.includes(capability); + } + validate(stringError = false) { + const errors = []; + if (this.getBaseFee() > this.gasLimit) { + errors.push(`gasLimit is too low. given ${this.gasLimit}, need at least ${this.getBaseFee()}`); + } + if (this.isSigned() && !this.verifySignature()) { + errors.push('Invalid Signature'); + } + return stringError ? errors : errors.length === 0; + } + _validateYParity() { + const { v } = this; + if (v !== undefined && v !== BigInt(0) && v !== BigInt(1)) { + const msg = this._errorMsg('The y-parity of the transaction should either be 0 or 1'); + throw new Error(msg); + } + } + /** + * EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2are considered invalid. + * Reasoning: https://ethereum.stackexchange.com/a/55728 + */ + _validateHighS() { + const { s } = this; + if (this.common.gteHardfork('homestead') && s !== undefined && s > SECP256K1_ORDER_DIV_2) { + const msg = this._errorMsg('Invalid Signature: s-values greater than secp256k1n/2 are considered invalid'); + throw new Error(msg); + } + } + /** + * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + */ + getBaseFee() { + const txFee = this.common.param('gasPrices', 'tx'); + let fee = this.getDataFee(); + if (txFee) + fee += txFee; + if (this.common.gteHardfork('homestead') && this.toCreationAddress()) { + const txCreationFee = this.common.param('gasPrices', 'txCreation'); + if (txCreationFee) + fee += txCreationFee; + } + return fee; + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + const txDataZero = this.common.param('gasPrices', 'txDataZero'); + const txDataNonZero = this.common.param('gasPrices', 'txDataNonZero'); + let cost = BigInt(0); + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < this.data.length; i += 1) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-unused-expressions + this.data[i] === 0 ? (cost += txDataZero) : (cost += txDataNonZero); + } + // eslint-disable-next-line no-null/no-null + if ((this.to === undefined || this.to === null) && this.common.isActivatedEIP(3860)) { + const dataLength = BigInt(Math.ceil(this.data.length / 32)); + const initCodeCost = this.common.param('gasPrices', 'initCodeWordCost') * dataLength; + cost += initCodeCost; + } + return cost; + } + /** + * If the tx's `to` is to the creation address + */ + toCreationAddress() { + return this.to === undefined || this.to.buf.length === 0; + } + isSigned() { + const { v, r, s } = this; + if (v === undefined || r === undefined || s === undefined) { + return false; + } + return true; + } + /** + * Determines if the signature is valid + */ + verifySignature() { + try { + // Main signature verification is done in `getSenderPublicKey()` + const publicKey = this.getSenderPublicKey(); + return unpadUint8Array(publicKey).length !== 0; + } + catch (e) { + return false; + } + } + /** + * Returns the sender's address + */ + getSenderAddress() { + return new Address(Address.publicToAddress(this.getSenderPublicKey())); + } + /** + * Signs a transaction. + * + * Note that the signed tx is returned as a new object, + * use as follows: + * ```javascript + * const signedTx = tx.sign(privateKey) + * ``` + */ + sign(privateKey) { + if (privateKey.length !== 32) { + const msg = this._errorMsg('Private key must be 32 bytes in length.'); + throw new Error(msg); + } + // Hack for the constellation that we have got a legacy tx after spuriousDragon with a non-EIP155 conforming signature + // and want to recreate a signature (where EIP155 should be applied) + // Leaving this hack lets the legacy.spec.ts -> sign(), verifySignature() test fail + // 2021-06-23 + let hackApplied = false; + if (this.type === 0 && + this.common.gteHardfork('spuriousDragon') && + !this.supports(Capability.EIP155ReplayProtection)) { + this.activeCapabilities.push(Capability.EIP155ReplayProtection); + hackApplied = true; + } + const msgHash = this.getMessageToSign(true); + const { v, r, s } = this._ecsign(msgHash, privateKey); + const tx = this._processSignature(v, r, s); + // Hack part 2 + if (hackApplied) { + const index = this.activeCapabilities.indexOf(Capability.EIP155ReplayProtection); + if (index > -1) { + this.activeCapabilities.splice(index, 1); + } + } + return tx; + } + /** + * Does chain ID checks on common and returns a common + * to be used on instantiation + * @hidden + * + * @param common - {@link Common} instance from tx options + * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) + */ + _getCommon(common, chainId) { + var _a; + // Chain ID provided + if (chainId !== undefined) { + const chainIdBigInt = uint8ArrayToBigInt(toUint8Array(chainId)); + if (common) { + if (common.chainId() !== chainIdBigInt) { + const msg = this._errorMsg('The chain ID does not match the chain ID of Common'); + throw new Error(msg); + } + // Common provided, chain ID does match + // -> Return provided Common + return common.copy(); + } + if (Common.isSupportedChainId(chainIdBigInt)) { + // No Common, chain ID supported by Common + // -> Instantiate Common with chain ID + return new Common({ chain: chainIdBigInt, hardfork: this.DEFAULT_HARDFORK }); + } + // No Common, chain ID not supported by Common + // -> Instantiate custom Common derived from DEFAULT_CHAIN + return Common.custom({ + name: 'custom-chain', + networkId: chainIdBigInt, + chainId: chainIdBigInt, + }, { baseChain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK }); + } + // No chain ID provided + // -> return Common provided or create new default Common + return ((_a = common === null || common === void 0 ? void 0 : common.copy()) !== null && _a !== void 0 ? _a : new Common({ chain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK })); + } + /** + * Validates that an object with BigInt values cannot exceed the specified bit limit. + * @param values Object containing string keys and BigInt values + * @param bits Number of bits to check (64 or 256) + * @param cannotEqual Pass true if the number also cannot equal one less the maximum value + */ + _validateCannotExceedMaxInteger(values, bits = 256, cannotEqual = false) { + for (const [key, value] of Object.entries(values)) { + switch (bits) { + case 64: + if (cannotEqual) { + if (value !== undefined && value >= MAX_UINT64) { + const msg = this._errorMsg(`${key} cannot equal or exceed MAX_UINT64 (2^64-1), given ${value}`); + throw new Error(msg); + } + } + else if (value !== undefined && value > MAX_UINT64) { + const msg = this._errorMsg(`${key} cannot exceed MAX_UINT64 (2^64-1), given ${value}`); + throw new Error(msg); + } + break; + case 256: + if (cannotEqual) { + if (value !== undefined && value >= MAX_INTEGER) { + const msg = this._errorMsg(`${key} cannot equal or exceed MAX_INTEGER (2^256-1), given ${value}`); + throw new Error(msg); + } + } + else if (value !== undefined && value > MAX_INTEGER) { + const msg = this._errorMsg(`${key} cannot exceed MAX_INTEGER (2^256-1), given ${value}`); + throw new Error(msg); + } + break; + default: { + const msg = this._errorMsg('unimplemented bits value'); + throw new Error(msg); + } + } + } + } + static _validateNotArray(values) { + const txDataKeys = [ + 'nonce', + 'gasPrice', + 'gasLimit', + 'to', + 'value', + 'data', + 'v', + 'r', + 's', + 'type', + 'baseFee', + 'maxFeePerGas', + 'chainId', + ]; + for (const [key, value] of Object.entries(values)) { + if (txDataKeys.includes(key)) { + if (Array.isArray(value)) { + throw new Error(`${key} cannot be an array`); + } + } + } + } + /** + * Returns the shared error postfix part for _error() method + * tx type implementations. + */ + _getSharedErrorPostfix() { + let hash = ''; + try { + hash = this.isSigned() ? bytesToHex(this.hash()) : 'not available (unsigned)'; + } + catch (e) { + hash = 'error'; + } + let isSigned = ''; + try { + isSigned = this.isSigned().toString(); + } + catch (e) { + hash = 'error'; + } + let hf = ''; + try { + hf = this.common.hardfork(); + } + catch (e) { + hf = 'error'; + } + let postfix = `tx type=${this.type} hash=${hash} nonce=${this.nonce} value=${this.value} `; + postfix += `signed=${isSigned} hf=${hf}`; + return postfix; + } + // eslint-disable-next-line class-methods-use-this + _ecsign(msgHash, privateKey, chainId) { + const signature = secp256k1.sign(msgHash, privateKey); + const signatureBytes = signature.toCompactRawBytes(); + const r = signatureBytes.subarray(0, 32); + const s = signatureBytes.subarray(32, 64); + const v = chainId === undefined + ? BigInt(signature.recovery + 27) + : BigInt(signature.recovery + 35) + BigInt(chainId) * BigInt(2); + return { r, s, v }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromSerializedTx( + // @ts-expect-error unused variable + serialized, + // @ts-expect-error unused variable + opts = {}) { } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromTxData( + // @ts-expect-error unused variable + txData, + // @ts-expect-error unused variable + opts = {}) { } +} +//# sourceMappingURL=baseTransaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/baseTransaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/baseTransaction.js.map new file mode 100644 index 0000000..fcfa67a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/baseTransaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"baseTransaction.js","sourceRoot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AAG,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;QACtD,MAAM,cAAc,GAAG,SAAS,CAAC,iBAAiB,EAAE,CAAC;QAErD,MAAM,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACzC,MAAM,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAE1C,MAAM,CAAC,GACN,OAAO,KAAK,SAAS;YACpB,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,QAAS,GAAG,EAAE,CAAC;YAClC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,QAAS,GAAG,EAAE,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAEnE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpB,CAAC;IAED,8DAA8D;IACvD,MAAM,CAAC,gBAAgB;IAC7B,mCAAmC;IACnC,UAAsB;IACtB,mCAAmC;IACnC,OAAkB,EAAE,IAEb,CAAC;IAET,8DAA8D;IACvD,MAAM,CAAC,UAAU;IACvB,mCAAmC;IACnC,MAAW;IACX,mCAAmC;IACnC,OAAkB,EAAE,IAEb,CAAC;CACT"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/constants.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/constants.js new file mode 100644 index 0000000..576d69e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/constants.js @@ -0,0 +1,31 @@ +var _a; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line import/extensions +import * as ethereumCryptography from 'ethereum-cryptography/secp256k1.js'; +export const secp256k1 = (_a = ethereumCryptography.secp256k1) !== null && _a !== void 0 ? _a : ethereumCryptography; +/** + * 2^64-1 + */ +export const MAX_UINT64 = BigInt('0xffffffffffffffff'); +/** + * The max integer that the evm can handle (2^256-1) + */ +export const MAX_INTEGER = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +export const SECP256K1_ORDER = secp256k1.CURVE.n; +export const SECP256K1_ORDER_DIV_2 = SECP256K1_ORDER / BigInt(2); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/constants.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/constants.js.map new file mode 100644 index 0000000..3944b94 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/tx/constants.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAA6C;AAC7C,OAAO,KAAK,oBAAoB,MAAM,oCAAoC,CAAC;AAE3E,MAAM,CAAC,MAAM,SAAS,GAAG,MAAA,oBAAoB,CAAC,SAAS,mCAAI,oBAAoB,CAAC;AAChF;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,CAChC,oEAAoE,CACpE,CAAC;AAEF,MAAM,CAAC,MAAM,eAAe,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AACjD,MAAM,CAAC,MAAM,qBAAqB,GAAG,eAAe,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip1559Transaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip1559Transaction.js new file mode 100644 index 0000000..8d9e5c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip1559Transaction.js @@ -0,0 +1,346 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { validateNoLeadingZeroes } from 'web3-validator'; +import { RLP } from '@ethereumjs/rlp'; +import { bytesToHex, hexToBytes, uint8ArrayConcat, uint8ArrayEquals } from 'web3-utils'; +import { MAX_INTEGER } from './constants.js'; +import { BaseTransaction } from './baseTransaction.js'; +import { getAccessListData, getAccessListJSON, getDataFeeEIP2930, verifyAccessList, } from './utils.js'; +import { bigIntToHex, toUint8Array, ecrecover, uint8ArrayToBigInt, bigIntToUnpaddedUint8Array, } from '../common/utils.js'; +const TRANSACTION_TYPE = 2; +const TRANSACTION_TYPE_UINT8ARRAY = hexToBytes(TRANSACTION_TYPE.toString(16).padStart(2, '0')); +/** + * Typed transaction with a new gas fee market mechanism + * + * - TransactionType: 2 + * - EIP: [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) + */ +// eslint-disable-next-line no-use-before-define +export class FeeMarketEIP1559Transaction extends BaseTransaction { + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData, opts = {}) { + var _a; + super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE }), opts); + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + this.DEFAULT_HARDFORK = 'london'; + const { chainId, accessList, maxFeePerGas, maxPriorityFeePerGas } = txData; + this.common = this._getCommon(opts.common, chainId); + this.chainId = this.common.chainId(); + if (!this.common.isActivatedEIP(1559)) { + throw new Error('EIP-1559 not enabled on Common'); + } + this.activeCapabilities = this.activeCapabilities.concat([1559, 2718, 2930]); + // Populate the access list fields + const accessListData = getAccessListData(accessList !== null && accessList !== void 0 ? accessList : []); + this.accessList = accessListData.accessList; + this.AccessListJSON = accessListData.AccessListJSON; + // Verify the access list format. + verifyAccessList(this.accessList); + this.maxFeePerGas = uint8ArrayToBigInt(toUint8Array(maxFeePerGas === '' ? '0x' : maxFeePerGas)); + this.maxPriorityFeePerGas = uint8ArrayToBigInt(toUint8Array(maxPriorityFeePerGas === '' ? '0x' : maxPriorityFeePerGas)); + this._validateCannotExceedMaxInteger({ + maxFeePerGas: this.maxFeePerGas, + maxPriorityFeePerGas: this.maxPriorityFeePerGas, + }); + BaseTransaction._validateNotArray(txData); + if (this.gasLimit * this.maxFeePerGas > MAX_INTEGER) { + const msg = this._errorMsg('gasLimit * maxFeePerGas cannot exceed MAX_INTEGER (2^256-1)'); + throw new Error(msg); + } + if (this.maxFeePerGas < this.maxPriorityFeePerGas) { + const msg = this._errorMsg('maxFeePerGas cannot be less than maxPriorityFeePerGas (The total must be the larger of the two)'); + throw new Error(msg); + } + this._validateYParity(); + this._validateHighS(); + const freeze = (_a = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _a !== void 0 ? _a : true; + if (freeze) { + Object.freeze(this); + } + } + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData, opts = {}) { + return new FeeMarketEIP1559Transaction(txData, opts); + } + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + */ + static fromSerializedTx(serialized, opts = {}) { + if (!uint8ArrayEquals(serialized.subarray(0, 1), TRANSACTION_TYPE_UINT8ARRAY)) { + throw new Error(`Invalid serialized tx input: not an EIP-1559 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${bytesToHex(serialized.subarray(0, 1))}`); + } + const values = RLP.decode(serialized.subarray(1)); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input: must be array'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return FeeMarketEIP1559Transaction.fromValuesArray(values, opts); + } + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + */ + static fromValuesArray(values, opts = {}) { + if (values.length !== 9 && values.length !== 12) { + throw new Error('Invalid EIP-1559 transaction. Only expecting 9 values (for unsigned tx) or 12 values (for signed tx).'); + } + const [chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList, v, r, s,] = values; + this._validateNotArray({ chainId, v }); + validateNoLeadingZeroes({ + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + value, + v, + r, + s, + }); + return new FeeMarketEIP1559Transaction({ + chainId: uint8ArrayToBigInt(chainId), + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + to, + value, + data, + accessList: accessList !== null && accessList !== void 0 ? accessList : [], + v: v !== undefined ? uint8ArrayToBigInt(v) : undefined, + r, + s, + }, opts); + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + let cost = super.getDataFee(); + cost += BigInt(getDataFeeEIP2930(this.accessList, this.common)); + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: cost, + hardfork: this.common.hardfork(), + }; + } + return cost; + } + /** + * The up front amount that an account must have for this transaction to be valid + * @param baseFee The base fee of the block (will be set to 0 if not provided) + */ + getUpfrontCost(baseFee = BigInt(0)) { + const prio = this.maxPriorityFeePerGas; + const maxBase = this.maxFeePerGas - baseFee; + const inclusionFeePerGas = prio < maxBase ? prio : maxBase; + const gasPrice = inclusionFeePerGas + baseFee; + return this.gasLimit * gasPrice + this.value; + } + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-1559 transaction, in order. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + * + * Use {@link FeeMarketEIP1559Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link FeeMarketEIP1559Transaction.getMessageToSign}. + */ + raw() { + return [ + bigIntToUnpaddedUint8Array(this.chainId), + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.maxPriorityFeePerGas), + bigIntToUnpaddedUint8Array(this.maxFeePerGas), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + this.accessList, + this.v !== undefined ? bigIntToUnpaddedUint8Array(this.v) : Uint8Array.from([]), + this.r !== undefined ? bigIntToUnpaddedUint8Array(this.r) : Uint8Array.from([]), + this.s !== undefined ? bigIntToUnpaddedUint8Array(this.s) : Uint8Array.from([]), + ]; + } + /** + * Returns the serialized encoding of the EIP-1559 transaction. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize() { + const base = this.raw(); + return uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + } + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage = true) { + const base = this.raw().slice(0, 9); + const message = uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + if (hashMessage) { + return keccak256(message); + } + return message; + } + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link FeeMarketEIP1559Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = keccak256(this.serialize()); + } + return this.cache.hash; + } + return keccak256(this.serialize()); + } + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature() { + return this.getMessageToSign(); + } + /** + * Returns the public key of the sender + */ + getSenderPublicKey() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call this method if transaction is not signed'); + throw new Error(msg); + } + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + this._validateHighS(); + try { + return ecrecover(msgHash, v + BigInt(27), // Recover the 27 which was stripped from ecsign + bigIntToUnpaddedUint8Array(r), bigIntToUnpaddedUint8Array(s)); + } + catch (e) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + _processSignature(v, r, s) { + const opts = Object.assign(Object.assign({}, this.txOptions), { common: this.common }); + return FeeMarketEIP1559Transaction.fromTxData({ + chainId: this.chainId, + nonce: this.nonce, + maxPriorityFeePerGas: this.maxPriorityFeePerGas, + maxFeePerGas: this.maxFeePerGas, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + accessList: this.accessList, + v: v - BigInt(27), + r: uint8ArrayToBigInt(r), + s: uint8ArrayToBigInt(s), + }, opts); + } + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON() { + const accessListJSON = getAccessListJSON(this.accessList); + return { + chainId: bigIntToHex(this.chainId), + nonce: bigIntToHex(this.nonce), + maxPriorityFeePerGas: bigIntToHex(this.maxPriorityFeePerGas), + maxFeePerGas: bigIntToHex(this.maxFeePerGas), + gasLimit: bigIntToHex(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: bigIntToHex(this.value), + data: bytesToHex(this.data), + accessList: accessListJSON, + v: this.v !== undefined ? bigIntToHex(this.v) : undefined, + r: this.r !== undefined ? bigIntToHex(this.r) : undefined, + s: this.s !== undefined ? bigIntToHex(this.s) : undefined, + }; + } + /** + * Return a compact error string representation of the object + */ + errorStr() { + let errorStr = this._getSharedErrorPostfix(); + errorStr += ` maxFeePerGas=${this.maxFeePerGas} maxPriorityFeePerGas=${this.maxPriorityFeePerGas}`; + return errorStr; + } + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + _errorMsg(msg) { + return `${msg} (${this.errorStr()})`; + } +} +//# sourceMappingURL=eip1559Transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip1559Transaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip1559Transaction.js.map new file mode 100644 index 0000000..f0da9b9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip1559Transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eip1559Transaction.js","sourceRoot":"","sources":["../../../src/tx/eip1559Transaction.ts"],"names":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AAI,CAAC;YAC3B,UAAU,EAAE,cAAc;YAC1B,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;YACzD,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;YACzD,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;SACzD,CAAC;IACH,CAAC;IAED;;OAEG;IACI,QAAQ;QACd,IAAI,QAAQ,GAAG,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC7C,QAAQ,IAAI,iBAAiB,IAAI,CAAC,YAAY,yBAAyB,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACnG,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,GAAW;QAC9B,OAAO,GAAG,GAAG,KAAK,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACtC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip2930Transaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip2930Transaction.js new file mode 100644 index 0000000..7ddeb6c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip2930Transaction.js @@ -0,0 +1,326 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { validateNoLeadingZeroes } from 'web3-validator'; +import { RLP } from '@ethereumjs/rlp'; +import { bytesToHex, hexToBytes, uint8ArrayConcat, uint8ArrayEquals } from 'web3-utils'; +import { MAX_INTEGER } from './constants.js'; +import { getAccessListData, verifyAccessList, getAccessListJSON, getDataFeeEIP2930, } from './utils.js'; +import { bigIntToHex, toUint8Array, ecrecover, uint8ArrayToBigInt, bigIntToUnpaddedUint8Array, } from '../common/utils.js'; +import { BaseTransaction } from './baseTransaction.js'; +const TRANSACTION_TYPE = 1; +const TRANSACTION_TYPE_UINT8ARRAY = hexToBytes(TRANSACTION_TYPE.toString(16).padStart(2, '0')); +/** + * Typed transaction with optional access lists + * + * - TransactionType: 1 + * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) + */ +// eslint-disable-next-line no-use-before-define +export class AccessListEIP2930Transaction extends BaseTransaction { + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData, opts = {}) { + var _a; + super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE }), opts); + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + this.DEFAULT_HARDFORK = 'berlin'; + const { chainId, accessList, gasPrice } = txData; + this.common = this._getCommon(opts.common, chainId); + this.chainId = this.common.chainId(); + // EIP-2718 check is done in Common + if (!this.common.isActivatedEIP(2930)) { + throw new Error('EIP-2930 not enabled on Common'); + } + this.activeCapabilities = this.activeCapabilities.concat([2718, 2930]); + // Populate the access list fields + const accessListData = getAccessListData(accessList !== null && accessList !== void 0 ? accessList : []); + this.accessList = accessListData.accessList; + this.AccessListJSON = accessListData.AccessListJSON; + // Verify the access list format. + verifyAccessList(this.accessList); + this.gasPrice = uint8ArrayToBigInt(toUint8Array(gasPrice === '' ? '0x' : gasPrice)); + this._validateCannotExceedMaxInteger({ + gasPrice: this.gasPrice, + }); + BaseTransaction._validateNotArray(txData); + if (this.gasPrice * this.gasLimit > MAX_INTEGER) { + const msg = this._errorMsg('gasLimit * gasPrice cannot exceed MAX_INTEGER'); + throw new Error(msg); + } + this._validateYParity(); + this._validateHighS(); + const freeze = (_a = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _a !== void 0 ? _a : true; + if (freeze) { + Object.freeze(this); + } + } + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData, opts = {}) { + return new AccessListEIP2930Transaction(txData, opts); + } + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + */ + static fromSerializedTx(serialized, opts = {}) { + if (!uint8ArrayEquals(serialized.subarray(0, 1), TRANSACTION_TYPE_UINT8ARRAY)) { + throw new Error(`Invalid serialized tx input: not an EIP-2930 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${bytesToHex(serialized.subarray(0, 1))}`); + } + const values = RLP.decode(Uint8Array.from(serialized.subarray(1))); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input: must be array'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return AccessListEIP2930Transaction.fromValuesArray(values, opts); + } + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + */ + static fromValuesArray(values, opts = {}) { + if (values.length !== 8 && values.length !== 11) { + throw new Error('Invalid EIP-2930 transaction. Only expecting 8 values (for unsigned tx) or 11 values (for signed tx).'); + } + const [chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, v, r, s] = values; + this._validateNotArray({ chainId, v }); + validateNoLeadingZeroes({ nonce, gasPrice, gasLimit, value, v, r, s }); + const emptyAccessList = []; + return new AccessListEIP2930Transaction({ + chainId: uint8ArrayToBigInt(chainId), + nonce, + gasPrice, + gasLimit, + to, + value, + data, + accessList: accessList !== null && accessList !== void 0 ? accessList : emptyAccessList, + v: v !== undefined ? uint8ArrayToBigInt(v) : undefined, + r, + s, + }, opts); + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + let cost = super.getDataFee(); + cost += BigInt(getDataFeeEIP2930(this.accessList, this.common)); + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: cost, + hardfork: this.common.hardfork(), + }; + } + return cost; + } + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost() { + return this.gasLimit * this.gasPrice + this.value; + } + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-2930 transaction, in order. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + * + * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty UINT8ARRAY values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. + */ + raw() { + return [ + bigIntToUnpaddedUint8Array(this.chainId), + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.gasPrice), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + this.accessList, + this.v !== undefined ? bigIntToUnpaddedUint8Array(this.v) : Uint8Array.from([]), + this.r !== undefined ? bigIntToUnpaddedUint8Array(this.r) : Uint8Array.from([]), + this.s !== undefined ? bigIntToUnpaddedUint8Array(this.s) : Uint8Array.from([]), + ]; + } + /** + * Returns the serialized encoding of the EIP-2930 transaction. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize() { + const base = this.raw(); + return uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + } + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage = true) { + const base = this.raw().slice(0, 8); + const message = uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + if (hashMessage) { + return keccak256(message); + } + return message; + } + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = keccak256(this.serialize()); + } + return this.cache.hash; + } + return keccak256(this.serialize()); + } + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature() { + return this.getMessageToSign(); + } + /** + * Returns the public key of the sender + */ + getSenderPublicKey() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call this method if transaction is not signed'); + throw new Error(msg); + } + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + this._validateHighS(); + try { + return ecrecover(msgHash, v + BigInt(27), // Recover the 27 which was stripped from ecsign + bigIntToUnpaddedUint8Array(r), bigIntToUnpaddedUint8Array(s)); + } + catch (e) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + _processSignature(v, r, s) { + const opts = Object.assign(Object.assign({}, this.txOptions), { common: this.common }); + return AccessListEIP2930Transaction.fromTxData({ + chainId: this.chainId, + nonce: this.nonce, + gasPrice: this.gasPrice, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + accessList: this.accessList, + v: v - BigInt(27), + r: uint8ArrayToBigInt(r), + s: uint8ArrayToBigInt(s), + }, opts); + } + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON() { + const accessListJSON = getAccessListJSON(this.accessList); + return { + chainId: bigIntToHex(this.chainId), + nonce: bigIntToHex(this.nonce), + gasPrice: bigIntToHex(this.gasPrice), + gasLimit: bigIntToHex(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: bigIntToHex(this.value), + data: bytesToHex(this.data), + accessList: accessListJSON, + v: this.v !== undefined ? bigIntToHex(this.v) : undefined, + r: this.r !== undefined ? bigIntToHex(this.r) : undefined, + s: this.s !== undefined ? bigIntToHex(this.s) : undefined, + }; + } + /** + * Return a compact error string representation of the object + */ + errorStr() { + var _a, _b; + let errorStr = this._getSharedErrorPostfix(); + // Keep ? for this.accessList since this otherwise causes Hardhat E2E tests to fail + errorStr += ` gasPrice=${this.gasPrice} accessListCount=${(_b = (_a = this.accessList) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0}`; + return errorStr; + } + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + _errorMsg(msg) { + return `${msg} (${this.errorStr()})`; + } +} +//# sourceMappingURL=eip2930Transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip2930Transaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip2930Transaction.js.map new file mode 100644 index 0000000..2385180 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/eip2930Transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eip2930Transaction.js","sourceRoot":"","sources":["../../../src/tx/eip2930Transaction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACxF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EACN,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EACN,WAAW,EACX,YAAY,EACZ,SAAS,EACT,kBAAkB,EAClB,0BAA0B,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAWvD,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,2BAA2B,GAAG,UAAU,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AAE/F;;;;;GAKG;AACH,gDAAgD;AAChD,MAAM,OAAO,4BAA6B,SAAQ,eAA6C;IA2F9F;;;;;;OAMG;IACH,YAAmB,MAA+B,EAAE,OAAkB,EAAE;;QACvE,KAAK,iCAAM,MAAM,KAAE,IAAI,EAAE,gBAAgB,KAAI,IAAI,CAAC,CAAC;QA3FpD;;;;;WAKG;QACO,qBAAgB,GAAG,QAAQ,CAAC;QAsFrC,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,MAAM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U,0CAAE,MAAM,mCAAI,CAAC,EAAE,CAAC;QACzF,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,GAAW;QAC9B,OAAO,GAAG,GAAG,KAAK,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACtC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/index.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/index.js new file mode 100644 index 0000000..48ea65d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/index.js @@ -0,0 +1,25 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// @ethereumjs/tx version 4.1.1 +export { FeeMarketEIP1559Transaction } from './eip1559Transaction.js'; +export { AccessListEIP2930Transaction } from './eip2930Transaction.js'; +export { Transaction } from './legacyTransaction.js'; +export { TransactionFactory } from './transactionFactory.js'; +export { BaseTransaction } from './baseTransaction.js'; +export * as txUtils from './utils.js'; +export * from './types.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/index.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/index.js.map new file mode 100644 index 0000000..d11cc5f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/tx/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,+BAA+B;AAC/B,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AACtC,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/legacyTransaction.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/legacyTransaction.js new file mode 100644 index 0000000..3882ed3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/legacyTransaction.js @@ -0,0 +1,348 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { RLP } from '@ethereumjs/rlp'; +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { bytesToHex } from 'web3-utils'; +import { validateNoLeadingZeroes } from 'web3-validator'; +import { bigIntToHex, bigIntToUnpaddedUint8Array, ecrecover, toUint8Array, uint8ArrayToBigInt, unpadUint8Array, } from '../common/utils.js'; +import { MAX_INTEGER } from './constants.js'; +import { BaseTransaction } from './baseTransaction.js'; +import { Capability } from './types.js'; +const TRANSACTION_TYPE = 0; +function meetsEIP155(_v, chainId) { + const v = Number(_v); + const chainIdDoubled = Number(chainId) * 2; + return v === chainIdDoubled + 35 || v === chainIdDoubled + 36; +} +/** + * An Ethereum non-typed (legacy) transaction + */ +// eslint-disable-next-line no-use-before-define +export class Transaction extends BaseTransaction { + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData, opts = {}) { + var _a; + super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE }), opts); + this.common = this._validateTxV(this.v, opts.common); + this.gasPrice = uint8ArrayToBigInt(toUint8Array(txData.gasPrice === '' ? '0x' : txData.gasPrice)); + if (this.gasPrice * this.gasLimit > MAX_INTEGER) { + const msg = this._errorMsg('gas limit * gasPrice cannot exceed MAX_INTEGER (2^256-1)'); + throw new Error(msg); + } + this._validateCannotExceedMaxInteger({ gasPrice: this.gasPrice }); + BaseTransaction._validateNotArray(txData); + if (this.common.gteHardfork('spuriousDragon')) { + if (!this.isSigned()) { + this.activeCapabilities.push(Capability.EIP155ReplayProtection); + } + else { + // EIP155 spec: + // If block.number >= 2,675,000 and v = CHAIN_ID * 2 + 35 or v = CHAIN_ID * 2 + 36 + // then when computing the hash of a transaction for purposes of signing or recovering + // instead of hashing only the first six elements (i.e. nonce, gasprice, startgas, to, value, data) + // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0. + // v and chain ID meet EIP-155 conditions + // eslint-disable-next-line no-lonely-if + if (meetsEIP155(this.v, this.common.chainId())) { + this.activeCapabilities.push(Capability.EIP155ReplayProtection); + } + } + } + const freeze = (_a = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _a !== void 0 ? _a : true; + if (freeze) { + Object.freeze(this); + } + } + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { nonce, gasPrice, gasLimit, to, value, data, v, r, s } + * + * Notes: + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData, opts = {}) { + return new Transaction(txData, opts); + } + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + */ + static fromSerializedTx(serialized, opts = {}) { + const values = RLP.decode(serialized); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input. Must be array'); + } + return this.fromValuesArray(values, opts); + } + /** + * Create a transaction from a values array. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + */ + static fromValuesArray(values, opts = {}) { + // If length is not 6, it has length 9. If v/r/s are empty Uint8Array, it is still an unsigned transaction + // This happens if you get the RLP data from `raw()` + if (values.length !== 6 && values.length !== 9) { + throw new Error('Invalid transaction. Only expecting 6 values (for unsigned tx) or 9 values (for signed tx).'); + } + const [nonce, gasPrice, gasLimit, to, value, data, v, r, s] = values; + validateNoLeadingZeroes({ nonce, gasPrice, gasLimit, value, v, r, s }); + return new Transaction({ + nonce, + gasPrice, + gasLimit, + to, + value, + data, + v, + r, + s, + }, opts); + } + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the legacy transaction, in order. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + * + * For legacy txs this is also the correct format to add transactions + * to a block with {@link Block.fromValuesArray} (use the `serialize()` method + * for typed txs). + * + * For an unsigned tx this method returns the empty Uint8Array values + * for the signature parameters `v`, `r` and `s`. For an EIP-155 compliant + * representation have a look at {@link Transaction.getMessageToSign}. + */ + raw() { + return [ + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.gasPrice), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + this.v !== undefined ? bigIntToUnpaddedUint8Array(this.v) : Uint8Array.from([]), + this.r !== undefined ? bigIntToUnpaddedUint8Array(this.r) : Uint8Array.from([]), + this.s !== undefined ? bigIntToUnpaddedUint8Array(this.s) : Uint8Array.from([]), + ]; + } + /** + * Returns the serialized encoding of the legacy transaction. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link Transaction.getMessageToSign}. + */ + serialize() { + return RLP.encode(this.raw()); + } + _getMessageToSign() { + const values = [ + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.gasPrice), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + ]; + if (this.supports(Capability.EIP155ReplayProtection)) { + values.push(toUint8Array(this.common.chainId())); + values.push(unpadUint8Array(toUint8Array(0))); + values.push(unpadUint8Array(toUint8Array(0))); + } + return values; + } + getMessageToSign(hashMessage = true) { + const message = this._getMessageToSign(); + if (hashMessage) { + return keccak256(RLP.encode(message)); + } + return message; + } + /** + * The amount of gas paid for the data in this tx + */ + getDataFee() { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: super.getDataFee(), + hardfork: this.common.hardfork(), + }; + } + return super.getDataFee(); + } + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost() { + return this.gasLimit * this.gasPrice + this.value; + } + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash() { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = keccak256(RLP.encode(this.raw())); + } + return this.cache.hash; + } + return keccak256(RLP.encode(this.raw())); + } + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature() { + if (!this.isSigned()) { + const msg = this._errorMsg('This transaction is not signed'); + throw new Error(msg); + } + const message = this._getMessageToSign(); + return keccak256(RLP.encode(message)); + } + /** + * Returns the public key of the sender + */ + getSenderPublicKey() { + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + this._validateHighS(); + try { + return ecrecover(msgHash, v, bigIntToUnpaddedUint8Array(r), bigIntToUnpaddedUint8Array(s), this.supports(Capability.EIP155ReplayProtection) + ? this.common.chainId() + : undefined); + } + catch (e) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + /** + * Process the v, r, s values from the `sign` method of the base transaction. + */ + _processSignature(_v, r, s) { + let v = _v; + if (this.supports(Capability.EIP155ReplayProtection)) { + v += this.common.chainId() * BigInt(2) + BigInt(8); + } + const opts = Object.assign(Object.assign({}, this.txOptions), { common: this.common }); + return Transaction.fromTxData({ + nonce: this.nonce, + gasPrice: this.gasPrice, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + v, + r: uint8ArrayToBigInt(r), + s: uint8ArrayToBigInt(s), + }, opts); + } + /** + * Returns an object with the JSON representation of the transaction. + */ + toJSON() { + return { + nonce: bigIntToHex(this.nonce), + gasPrice: bigIntToHex(this.gasPrice), + gasLimit: bigIntToHex(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: bigIntToHex(this.value), + data: bytesToHex(this.data), + v: this.v !== undefined ? bigIntToHex(this.v) : undefined, + r: this.r !== undefined ? bigIntToHex(this.r) : undefined, + s: this.s !== undefined ? bigIntToHex(this.s) : undefined, + }; + } + /** + * Validates tx's `v` value + */ + _validateTxV(_v, common) { + let chainIdBigInt; + const v = _v !== undefined ? Number(_v) : undefined; + // Check for valid v values in the scope of a signed legacy tx + if (v !== undefined) { + // v is 1. not matching the EIP-155 chainId included case and... + // v is 2. not matching the classic v=27 or v=28 case + if (v < 37 && v !== 27 && v !== 28) { + throw new Error(`Legacy txs need either v = 27/28 or v >= 37 (EIP-155 replay protection), got v = ${v}`); + } + } + // No unsigned tx and EIP-155 activated and chain ID included + if (v !== undefined && + v !== 0 && + (!common || common.gteHardfork('spuriousDragon')) && + v !== 27 && + v !== 28) { + if (common) { + if (!meetsEIP155(BigInt(v), common.chainId())) { + throw new Error(`Incompatible EIP155-based V ${v} and chain id ${common.chainId()}. See the Common parameter of the Transaction constructor to set the chain id.`); + } + } + else { + // Derive the original chain ID + let numSub; + if ((v - 35) % 2 === 0) { + numSub = 35; + } + else { + numSub = 36; + } + // Use derived chain ID to create a proper Common + chainIdBigInt = BigInt(v - numSub) / BigInt(2); + } + } + return this._getCommon(common, chainIdBigInt); + } + /** + * Return a compact error string representation of the object + */ + errorStr() { + let errorStr = this._getSharedErrorPostfix(); + errorStr += ` gasPrice=${this.gasPrice}`; + return errorStr; + } + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + _errorMsg(msg) { + return `${msg} (${this.errorStr()})`; + } +} +//# sourceMappingURL=legacyTransaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/legacyTransaction.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/legacyTransaction.js.map new file mode 100644 index 0000000..cad3b76 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/legacyTransaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"legacyTransaction.js","sourceRoot":"","sources":["../../../src/tx/legacyTransaction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EACN,WAAW,EACX,0BAA0B,EAC1B,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,eAAe,GACf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,OAAO,EAAE,eAAe,EAAE,MAA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ACD,iDAAiD;gBACjD,aAAa,GAAG,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;aAC/C;SACD;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACI,QAAQ;QACd,IAAI,QAAQ,GAAG,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC7C,QAAQ,IAAI,aAAa,IAAI,CAAC,QAAQ,EAAE,CAAC;QACzC,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,GAAW;QAC9B,OAAO,GAAG,GAAG,KAAK,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACtC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/transactionFactory.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/transactionFactory.js new file mode 100644 index 0000000..a548d0f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/transactionFactory.js @@ -0,0 +1,97 @@ +import { toUint8Array, uint8ArrayToBigInt } from '../common/utils.js'; +import { FeeMarketEIP1559Transaction } from './eip1559Transaction.js'; +import { AccessListEIP2930Transaction } from './eip2930Transaction.js'; +import { Transaction } from './legacyTransaction.js'; +const extraTxTypes = new Map(); +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export class TransactionFactory { + // It is not possible to instantiate a TransactionFactory object. + // eslint-disable-next-line @typescript-eslint/no-empty-function, no-useless-constructor + constructor() { } + static typeToInt(txType) { + return Number(uint8ArrayToBigInt(toUint8Array(txType))); + } + static registerTransactionType(type, txClass) { + const txType = TransactionFactory.typeToInt(type); + extraTxTypes.set(txType, txClass); + } + /** + * Create a transaction from a `txData` object + * + * @param txData - The transaction data. The `type` field will determine which transaction type is returned (if undefined, creates a legacy transaction) + * @param txOptions - Options to pass on to the constructor of the transaction + */ + static fromTxData(txData, txOptions = {}) { + if (!('type' in txData) || txData.type === undefined) { + // Assume legacy transaction + return Transaction.fromTxData(txData, txOptions); + } + const txType = TransactionFactory.typeToInt(txData.type); + if (txType === 0) { + return Transaction.fromTxData(txData, txOptions); + } + if (txType === 1) { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return AccessListEIP2930Transaction.fromTxData( + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + txData, txOptions); + } + if (txType === 2) { + return FeeMarketEIP1559Transaction.fromTxData( + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + txData, txOptions); + } + const ExtraTransaction = extraTxTypes.get(txType); + if (ExtraTransaction === null || ExtraTransaction === void 0 ? void 0 : ExtraTransaction.fromTxData) { + return ExtraTransaction.fromTxData(txData, txOptions); + } + throw new Error(`Tx instantiation with type ${txType} not supported`); + } + /** + * This method tries to decode serialized data. + * + * @param data - The data Uint8Array + * @param txOptions - The transaction options + */ + static fromSerializedData(data, txOptions = {}) { + if (data[0] <= 0x7f) { + // Determine the type. + switch (data[0]) { + case 1: + return AccessListEIP2930Transaction.fromSerializedTx(data, txOptions); + case 2: + return FeeMarketEIP1559Transaction.fromSerializedTx(data, txOptions); + default: { + const ExtraTransaction = extraTxTypes.get(Number(data[0])); + if (ExtraTransaction === null || ExtraTransaction === void 0 ? void 0 : ExtraTransaction.fromSerializedTx) { + return ExtraTransaction.fromSerializedTx(data, txOptions); + } + throw new Error(`TypedTransaction with ID ${data[0]} unknown`); + } + } + } + else { + return Transaction.fromSerializedTx(data, txOptions); + } + } + /** + * When decoding a BlockBody, in the transactions field, a field is either: + * A Uint8Array (a TypedTransaction - encoded as TransactionType || rlp(TransactionPayload)) + * A Uint8Array[] (Legacy Transaction) + * This method returns the right transaction. + * + * @param data - A Uint8Array or Uint8Array[] + * @param txOptions - The transaction options + */ + static fromBlockBodyData(data, txOptions = {}) { + if (data instanceof Uint8Array) { + return this.fromSerializedData(data, txOptions); + } + if (Array.isArray(data)) { + // It is a legacy transaction + return Transaction.fromValuesArray(data, txOptions); + } + throw new Error('Cannot decode transaction: unknown type input'); + } +} +//# sourceMappingURL=transactionFactory.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/transactionFactory.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/transactionFactory.js.map new file mode 100644 index 0000000..11c2537 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/transactionFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transactionFactory.js","sourceRoot":"","sources":["../../../src/tx/transactionFactory.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAWrD,MAAM,YAAY,GAAkD,IAAI,GAAG,EAAE,CAAC;AAE9E,kEAAkE;AAClE,MAAM,OAAO,kBAAkB;IAC9B,iEAAiE;IACjE,wFAAwF;IACxF,gBAAuB,CAAC;IAEjB,MAAM,CAAC,SAAS,CAAC,MAAe;QACtC,OAAO,MAAM,CAAC,kBAAkB,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACzD,CAAC;IAEM,MAAM,CAAC,uBAAuB,CACpC,IAAa,EACb,OAAuB;QAEvB,MAAM,MAAM,GAAG,kBAAkB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;QAClD,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,UAAU,CACvB,MAAiC,EACjC,YAAuB,EAAE;QAEzB,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,MAAM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;gBACtE,OAAO,CAAC,CAAC;oBACR,MAAM,gBAAgB,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC3D,IAAI,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,gBAAgB,EAAE;wBACvC,OAAO,gBAAgB,CAAC,gBAAgB,CACvC,IAAI,EACJ,SAAS,CACW,CAAC;qBACtB;oBAED,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;iBAC/D;aACD;SACD;aAAM;YACN,OAAO,WAAW,CAAC,gBAAgB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SACrD;IACF,CAAC;IAED;;;;;;;;OAQG;IACI,MAAM,CAAC,iBAAiB,CAAC,IAA+B,EAAE,YAAuB,EAAE;QACzF,IAAI,IAAI,YAAY,UAAU,EAAE;YAC/B,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SAChD;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACxB,6BAA6B;YAC7B,OAAO,WAAW,CAAC,eAAe,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SACpD;QACD,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IAClE,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/types.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/types.js new file mode 100644 index 0000000..d3ca2b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/types.js @@ -0,0 +1,41 @@ +/** + * Can be used in conjunction with {@link Transaction.supports} + * to query on tx capabilities + */ +export var Capability; +(function (Capability) { + /** + * Tx supports EIP-155 replay protection + * See: [155](https://eips.ethereum.org/EIPS/eip-155) Replay Attack Protection EIP + */ + Capability[Capability["EIP155ReplayProtection"] = 155] = "EIP155ReplayProtection"; + /** + * Tx supports EIP-1559 gas fee market mechanism + * See: [1559](https://eips.ethereum.org/EIPS/eip-1559) Fee Market EIP + */ + Capability[Capability["EIP1559FeeMarket"] = 1559] = "EIP1559FeeMarket"; + /** + * Tx is a typed transaction as defined in EIP-2718 + * See: [2718](https://eips.ethereum.org/EIPS/eip-2718) Transaction Type EIP + */ + Capability[Capability["EIP2718TypedTransaction"] = 2718] = "EIP2718TypedTransaction"; + /** + * Tx supports access list generation as defined in EIP-2930 + * See: [2930](https://eips.ethereum.org/EIPS/eip-2930) Access Lists EIP + */ + Capability[Capability["EIP2930AccessLists"] = 2930] = "EIP2930AccessLists"; +})(Capability || (Capability = {})); +export function isAccessListUint8Array(input) { + if (input.length === 0) { + return true; + } + const firstItem = input[0]; + if (Array.isArray(firstItem)) { + return true; + } + return false; +} +export function isAccessList(input) { + return !isAccessListUint8Array(input); // This is exactly the same method, except the output is negated. +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/types.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/types.js.map new file mode 100644 index 0000000..8443ac5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/tx/types.ts"],"names":[],"mappings":"AAuBA;;;GAGG;AACH,MAAM,CAAN,IAAY,UAwBX;AAxBD,WAAY,UAAU;IACrB;;;OAGG;IACH,iFAA4B,CAAA;IAE5B;;;OAGG;IACH,sEAAuB,CAAA;IAEvB;;;OAGG;IACH,oFAA8B,CAAA;IAE9B;;;OAGG;IACH,0EAAyB,CAAA;AAC1B,CAAC,EAxBW,UAAU,KAAV,UAAU,QAwBrB;AAqDD,MAAM,UAAU,sBAAsB,CACrC,KAAwC;IAExC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;QACvB,OAAO,IAAI,CAAC;KACZ;IACD,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3B,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QAC7B,OAAO,IAAI,CAAC;KACZ;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,KAAwC;IACpE,OAAO,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC,iEAAiE;AACzG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/utils.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/utils.js new file mode 100644 index 0000000..a276d61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/utils.js @@ -0,0 +1,110 @@ +import { bytesToHex } from 'web3-utils'; +import { setLengthLeft, toUint8Array } from '../common/utils.js'; +import { isAccessList } from './types.js'; +export const checkMaxInitCodeSize = (common, length) => { + const maxInitCodeSize = common.param('vm', 'maxInitCodeSize'); + if (maxInitCodeSize && BigInt(length) > maxInitCodeSize) { + throw new Error(`the initcode size of this transaction is too large: it is ${length} while the max is ${common.param('vm', 'maxInitCodeSize')}`); + } +}; +export const getAccessListData = (accessList) => { + let AccessListJSON; + let uint8arrayAccessList; + if (isAccessList(accessList)) { + AccessListJSON = accessList; + const newAccessList = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < accessList.length; i += 1) { + const item = accessList[i]; + const addressBytes = toUint8Array(item.address); + const storageItems = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < item.storageKeys.length; index += 1) { + storageItems.push(toUint8Array(item.storageKeys[index])); + } + newAccessList.push([addressBytes, storageItems]); + } + uint8arrayAccessList = newAccessList; + } + else { + uint8arrayAccessList = accessList !== null && accessList !== void 0 ? accessList : []; + // build the JSON + const json = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < uint8arrayAccessList.length; i += 1) { + const data = uint8arrayAccessList[i]; + const address = bytesToHex(data[0]); + const storageKeys = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let item = 0; item < data[1].length; item += 1) { + storageKeys.push(bytesToHex(data[1][item])); + } + const jsonItem = { + address, + storageKeys, + }; + json.push(jsonItem); + } + AccessListJSON = json; + } + return { + AccessListJSON, + accessList: uint8arrayAccessList, + }; +}; +export const verifyAccessList = (accessList) => { + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let key = 0; key < accessList.length; key += 1) { + const accessListItem = accessList[key]; + const address = accessListItem[0]; + const storageSlots = accessListItem[1]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions + if (accessListItem[2] !== undefined) { + throw new Error('Access list item cannot have 3 elements. It can only have an address, and an array of storage slots.'); + } + if (address.length !== 20) { + throw new Error('Invalid EIP-2930 transaction: address length should be 20 bytes'); + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let storageSlot = 0; storageSlot < storageSlots.length; storageSlot += 1) { + if (storageSlots[storageSlot].length !== 32) { + throw new Error('Invalid EIP-2930 transaction: storage slot length should be 32 bytes'); + } + } + } +}; +export const getAccessListJSON = (accessList) => { + const accessListJSON = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < accessList.length; index += 1) { + const item = accessList[index]; + const JSONItem = { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions + address: bytesToHex(setLengthLeft(item[0], 20)), + storageKeys: [], + }; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/prefer-optional-chain + const storageSlots = item && item[1]; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let slot = 0; slot < storageSlots.length; slot += 1) { + const storageSlot = storageSlots[slot]; + JSONItem.storageKeys.push(bytesToHex(setLengthLeft(storageSlot, 32))); + } + accessListJSON.push(JSONItem); + } + return accessListJSON; +}; +export const getDataFeeEIP2930 = (accessList, common) => { + const accessListStorageKeyCost = common.param('gasPrices', 'accessListStorageKeyCost'); + const accessListAddressCost = common.param('gasPrices', 'accessListAddressCost'); + let slots = 0; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < accessList.length; index += 1) { + const item = accessList[index]; + const storageSlots = item[1]; + slots += storageSlots.length; + } + const addresses = accessList.length; + return addresses * Number(accessListAddressCost) + slots * Number(accessListStorageKeyCost); +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/utils.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/utils.js.map new file mode 100644 index 0000000..d6d4990 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/tx/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/tx/utils.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAI1C,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,MAAc,EAAE,MAAc,EAAE,EAAE;IACtE,MAAM,eAAe,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;IAC9D,IAAI,eAAe,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,eAAe,EAAE;QACxD,MAAM,IAAI,KAAK,CACd,6DAA6D,MAAM,qBAAqB,MAAM,CAAC,KAAK,CACnG,IAAI,EACJ,iBAAiB,CACjB,EAAE,CACH,CAAC;KACF;AACF,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,UAA6C,EAA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AAG,CAAC,CAAC;IACd,4DAA4D;IAC5D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE;QAC1D,MAAM,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;QAC/B,MAAM,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAC7B,KAAK,IAAI,YAAY,CAAC,MAAM,CAAC;KAC7B;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC;IACpC,OAAO,SAAS,GAAG,MAAM,CAAC,qBAAqB,CAAC,GAAG,KAAK,GAAG,MAAM,CAAC,wBAAwB,CAAC,CAAC;AAC7F,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/types.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/wallet.js b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/wallet.js new file mode 100644 index 0000000..babe364 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/wallet.js @@ -0,0 +1,413 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { Web3BaseWallet } from 'web3-types'; +import { isNullish } from 'web3-validator'; +/** + * Wallet is an in memory `wallet` that can hold multiple accounts. + * These accounts can be used when using web3.eth.sendTransaction(). + * + * ### Parameters + * Web3AccountProvider - AccountProvider for the wallet + * + * ```ts + * import Web3 from 'web3'; + * const web3 = new Web3("https://localhost:8454") + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ +export class Wallet extends Web3BaseWallet { + constructor() { + super(...arguments); + this._addressMap = new Map(); + this._defaultKeyName = 'web3js_wallet'; + } + /** + * Get the storage object of the browser + * + * @returns the storage + */ + static getStorage() { + let storage; + try { + storage = window.localStorage; + const x = '__storage_test__'; + storage.setItem(x, x); + storage.removeItem(x); + return storage; + } + catch (e) { + return e && + // everything except Firefox + (e.code === 22 || + // Firefox + e.code === 1014 || + // test name field too, because code might not be present + // everything except Firefox + e.name === 'QuotaExceededError' || + // Firefox + e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && + // acknowledge QuotaExceededError only if there's something already stored + !isNullish(storage) && + storage.length !== 0 + ? storage + : undefined; + } + } + /** + * Generates one or more accounts in the wallet. If wallets already exist they will not be overridden. + * + * @param numberOfAccounts - Number of accounts to create. Leave empty to create an empty wallet. + * @returns The wallet + * ```ts + * web3.eth.accounts.wallet.create(2) + * > Wallet(2) [ + * { + * address: '0xde38310a42B751AE57d30cFFF4a0A3c52A442fCE', + * privateKey: '0x6422c9d28efdcbee93c1d32a5fc6fd6fa081b985487885296cf8c9bbb5872600', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * { + * address: '0x766BF755246d924B1d017Fdb5390f38a60166691', + * privateKey: '0x756530f13c0eb636ebdda655335f5dea9921e3362e2e588b0ad59e556f7751f0', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(2) { + * '0xde38310a42b751ae57d30cfff4a0a3c52a442fce' => 0, + * '0x766bf755246d924b1d017fdb5390f38a60166691' => 1 + * }, + * _defaultKeyName: 'web3js_wallet' + * ] + * + * ``` + */ + create(numberOfAccounts) { + for (let i = 0; i < numberOfAccounts; i += 1) { + this.add(this._accountProvider.create()); + } + return this; + } + /** + * Adds an account using a private key or account object to the wallet. + * + * @param account - A private key or account object + * @returns The wallet + * + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * > Wallet(1) [ + * { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(1) { '0x85d70633b90e03e0276b98880286d0d055685ed7' => 0 }, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + add(account) { + var _a; + if (typeof account === 'string') { + return this.add(this._accountProvider.privateKeyToAccount(account)); + } + let index = this.length; + const existAccount = this.get(account.address); + if (existAccount) { + console.warn(`Account ${account.address.toLowerCase()} already exists.`); + index = (_a = this._addressMap.get(account.address.toLowerCase())) !== null && _a !== void 0 ? _a : index; + } + this._addressMap.set(account.address.toLowerCase(), index); + this[index] = account; + return this; + } + /** + * Get the account of the wallet with either the index or public address. + * + * @param addressOrIndex - A string of the address or number index within the wallet. + * @returns The account object or undefined if the account doesn't exist + */ + get(addressOrIndex) { + if (typeof addressOrIndex === 'string') { + const index = this._addressMap.get(addressOrIndex.toLowerCase()); + if (!isNullish(index)) { + return this[index]; + } + return undefined; + } + return this[addressOrIndex]; + } + /** + * Removes an account from the wallet. + * + * @param addressOrIndex - The account address, or index in the wallet. + * @returns true if the wallet was removed. false if it couldn't be found. + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * + * web3.eth.accounts.wallet.remove('0x85D70633b90e03e0276B98880286D0D055685ed7'); + * > true + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + remove(addressOrIndex) { + if (typeof addressOrIndex === 'string') { + const index = this._addressMap.get(addressOrIndex.toLowerCase()); + if (isNullish(index)) { + return false; + } + this._addressMap.delete(addressOrIndex.toLowerCase()); + this.splice(index, 1); + return true; + } + if (this[addressOrIndex]) { + this.splice(addressOrIndex, 1); + return true; + } + return false; + } + /** + * Securely empties the wallet and removes all its accounts. + * Use this with *caution as it will remove all accounts stored in local wallet. + * + * @returns The wallet object + * ```ts + * + * web3.eth.accounts.wallet.clear(); + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + clear() { + this._addressMap.clear(); + // Setting length clears the Array in JS. + this.length = 0; + return this; + } + /** + * Encrypts all wallet accounts to an array of encrypted keystore v3 objects. + * + * @param password - The password which will be used for encryption + * @param options - encryption options + * @returns An array of the encrypted keystore v3. + * + * ```ts + * web3.eth.accounts.wallet.create(1) + * web3.eth.accounts.wallet.encrypt("abc").then(console.log); + * > [ + * '{"version":3,"id":"fa46e213-a7c3-4844-b903-dd14d39cc7db", + * "address":"fa3e41a401609103c241431cbdee8623ae2a321a","crypto": + * {"ciphertext":"8d179a911d6146ad2924e86bf493ed89b8ff3596ffec0816e761c542016ab13c", + * "cipherparams":{"iv":"acc888c6cf4a19b86846cef0185a7164"},"cipher":"aes-128-ctr", + * "kdf":"scrypt","kdfparams":{"n":8192,"r":8,"p":1,"dklen":32,"salt":"6a743c9b367d15f4758e4f3f3378ff0fd443708d1c64854e07588ea5331823ae"}, + * "mac":"410544c8307e3691fda305eb3722d82c3431f212a87daa119a21587d96698b57"}}' + * ] + * ``` + */ + encrypt(password, options) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(this.map((account) => __awaiter(this, void 0, void 0, function* () { return account.encrypt(password, options); }))); + }); + } + /** + * Decrypts keystore v3 objects. + * + * @param encryptedWallets - An array of encrypted keystore v3 objects to decrypt + * @param password - The password to encrypt with + * @param options - decrypt options for the wallets + * @returns The decrypted wallet object + * + * ```ts + * web3.eth.accounts.wallet.decrypt([ + * { version: 3, + * id: '83191a81-aaca-451f-b63d-0c5f3b849289', + * address: '06f702337909c06c82b09b7a22f0a2f0855d1f68', + * crypto: + * { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d', + * cipherparams: { iv: '497f4d26997a84d570778eae874b2333' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } }, + * { version: 3, + * id: '7d6b91fa-3611-407b-b16b-396efb28f97e', + * address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf', + * crypto: + * { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43', + * cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } } + * ], 'test').then(console.log) + * > Wallet { + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _defaultKeyName: 'web3js_wallet', + * _accounts: { + * '0x85d70633b90e03e0276b98880286d0d055685ed7': { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0x06f702337909c06c82b09b7a22f0a2f0855d1f68': { + * address: '0x06F702337909C06C82B09B7A22F0a2f0855d1F68', + * privateKey: '87a51da18900da7398b3bab03996833138f269f8f66dd1237b98df6b9ce14573', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0xb5d89661b59a9af0b34f58d19138baa2de48baaf': { + * address: '0xB5d89661B59a9aF0b34f58D19138bAa2de48BAaf', + * privateKey: '7ee61c5282979aae9dd795bb6a54e8bdc2bfe009acb64eb9a67322eec3b3da6e', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * } + * } + * } + * ``` + */ + decrypt(encryptedWallets, password, options) { + return __awaiter(this, void 0, void 0, function* () { + const results = yield Promise.all(encryptedWallets.map((wallet) => __awaiter(this, void 0, void 0, function* () { return this._accountProvider.decrypt(wallet, password, options); }))); + for (const res of results) { + this.add(res); + } + return this; + }); + } + /** + * Stores the wallet encrypted and as string in local storage. + * **__NOTE:__** Browser only + * + * @param password - The password to encrypt the wallet + * @param keyName - (optional) The key used for the local storage position, defaults to `"web3js_wallet"`. + * @returns Will return boolean value true if saved properly + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * >true + * ``` + */ + save(password, keyName) { + return __awaiter(this, void 0, void 0, function* () { + const storage = Wallet.getStorage(); + if (!storage) { + throw new Error('Local storage not available.'); + } + storage.setItem(keyName !== null && keyName !== void 0 ? keyName : this._defaultKeyName, JSON.stringify(yield this.encrypt(password))); + return true; + }); + } + /** + * Loads a wallet from local storage and decrypts it. + * **__NOTE:__** Browser only + * + * @param password - The password to decrypt the wallet. + * @param keyName - (optional)The key used for local storage position, defaults to `web3js_wallet"` + * @returns Returns the wallet object + * + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * > true + * web3.eth.accounts.wallet.load('test#!$'); + * { defaultKeyName: "web3js_wallet", + * length: 0, + * _accounts: Accounts {_requestManager: RequestManager, givenProvider: Proxy, providers: {…}, _provider: WebsocketProvider, …}, + * [[Prototype]]: Object + * } + * ``` + */ + load(password, keyName) { + return __awaiter(this, void 0, void 0, function* () { + const storage = Wallet.getStorage(); + if (!storage) { + throw new Error('Local storage not available.'); + } + const keystore = storage.getItem(keyName !== null && keyName !== void 0 ? keyName : this._defaultKeyName); + if (keystore) { + yield this.decrypt(JSON.parse(keystore) || [], password); + } + return this; + }); + } +} +//# sourceMappingURL=wallet.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/wallet.js.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/wallet.js.map new file mode 100644 index 0000000..15abe63 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/esm/wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wallet.js","sourceRoot":"","sources":["../../src/wallet.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAAE,cAAc,EAAmC,MAAM,YAAY,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAK3C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,OAAO,MAEX,SAAQ,cAAiB;IAF3B;;QAGkB,gBAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;QACxC,oBAAe,GAAG,eAAe,CAAC;IAsYpD,CAAC;IApYA;;;;OAIG;IACI,MAAM,CAAC,UAAU;QACvB,IAAI,OAA+B,CAAC;QAEpC,IAAI;YACH,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC;YAC9B,MAAM,CAAC,GAAG,kBAAkB,CAAC;YAC7B,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YACtB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAEtB,OAAO,OAAO,CAAC;SACf;QAAC,OAAO,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cAAP,OAAO,GAAI,IAAI,CAAC,eAAe,EAC/B,IAAI,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAC5C,CAAC;YAEF,OAAO,IAAI,CAAC;QACb,CAAC;KAAA;IAED;;;;;;;;;;;;;;;;;;OAkBG;IACU,IAAI,CAAC,QAAgB,EAAE,OAAgB;;YACnD,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;YAEpC,IAAI,CAAC,OAAO,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;aAChD;YAED,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,IAAI,CAAC,eAAe,CAAC,CAAC;YAElE,IAAI,QAAQ,EAAE;gBACb,MAAM,IAAI,CAAC,OAAO,CAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAgB,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAC;aACzE;YAED,OAAO,IAAI,CAAC;QACb,CAAC;KAAA;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/account.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/account.d.ts new file mode 100644 index 0000000..ad349fb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/account.d.ts @@ -0,0 +1,342 @@ +import { Address, Bytes, CipherOptions, HexString, KeyStore } from 'web3-types'; +import type { SignatureObject, SignTransactionResult, TypedTransaction, Web3Account, SignResult } from './types.js'; +/** + * Get the private key Uint8Array after the validation + */ +export declare const parseAndValidatePrivateKey: (data: Bytes, ignoreLength?: boolean) => Uint8Array; +/** + * + * Hashes the given message. The data will be UTF-8 HEX decoded and enveloped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message and hashed using keccak256. + * + * @param message - A message to hash, if its HEX it will be UTF8 decoded. + * @returns The hashed message + * + * ```ts + * hashMessage("Hello world") + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * hashMessage(utf8ToHex("Hello world")) // Will be hex decoded in hashMessage + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * ``` + */ +export declare const hashMessage: (message: string) => string; +/** + * Signs arbitrary data with a given private key. + * **_NOTE:_** The value passed as the data parameter will be UTF-8 HEX decoded and wrapped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message + * + * @param data - The data to sign + * @param privateKey - The 32 byte private key to sign with + * @returns The signature Object containing the message, messageHash, signature r, s, v + * + * ```ts + * web3.eth.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318') + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1c', + * r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', + * s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029', + * signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c' + * } + * ``` + */ +export declare const sign: (data: string, privateKey: Bytes) => SignResult; +/** + * Signs an Ethereum transaction with a given private key. + * + * @param transaction - The transaction, must be a legacy, EIP2930 or EIP 1559 transaction type + * @param privateKey - The private key to import. This is 32 bytes of random data. + * @returns A signTransactionResult object that contains message hash, r, s, v, transaction hash and raw transaction. + * + * This function is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * This function will rely on user to provide the full transaction to be signed. If you want to sign a partial transaction object + * Use {@link Web3.eth.accounts.sign} instead. + * + * Signing a legacy transaction + * ```ts + * signTransaction({ + * to: '0x118C2E5F57FD62C2B5b46a5ae9216F4FF4011a07', + * value: '0x186A0', + * gasLimit: '0x520812', + * gasPrice: '0x09184e72a000', + * data: '', + * chainId: 1, + * nonce: 0, + * }, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')) + * } + * > { + * messageHash: '0x28b7b75f7ba48d588a902c1ff4d5d13cc0ca9ac0aaa39562368146923fb853bf', + * v: '0x25', + * r: '0x601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5', + * s: '0x690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * rawTransaction: '0xf869808609184e72a0008352081294118c2e5f57fd62c2b5b46a5ae9216f4ff4011a07830186a08025a00601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5a0690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * ``` + * Signing an eip 1559 transaction + * ```ts + * signTransaction({ + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * maxPriorityFeePerGas: '0x3B9ACA00', + * maxFeePerGas: '0xB2D05E00', + * gasLimit: '0x6A4012', + * value: '0x186A0', + * data: '', + * chainId: 1, + * nonce: 0, + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0x5744f24d5f0aff6c70487c8e85adf07d8564e50b08558788f00479611d7bae5f', + * v: '0x25', + * r: '0x78a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347', + * s: '0x9cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * rawTransaction: '0xf8638080836a401294f0109fc8df283027b6285cc889f5aa624eac1f55830186a08025a078a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347a009cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + * Signing an eip 2930 transaction + * ```ts + * signTransaction({ + * chainId: 1, + * nonce: 0, + * gasPrice: '0x09184e72a000', + * gasLimit: '0x2710321', + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * value: '0x186A0', + * data: '', + * accessList: [ + * { + * address: '0x0000000000000000000000000000000000000101', + * storageKeys: [ + * '0x0000000000000000000000000000000000000000000000000000000000000000', + * '0x00000000000000000000000000000000000000000000000000000000000060a7', + * ], + * }, + * ], + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0xc55ea24bdb4c379550a7c9a6818ac39ca33e75bc78ddb862bd82c31cc1c7a073', + * v: '0x26', + * r: '0x27344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098e', + * s: '0x519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * rawTransaction: '0xf86a808609184e72a000840271032194f0109fc8df283027b6285cc889f5aa624eac1f55830186a08026a027344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098ea0519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + */ +export declare const signTransaction: (transaction: TypedTransaction, privateKey: HexString) => Promise; +/** + * Recovers the Ethereum address which was used to sign the given RLP encoded transaction. + * + * @param rawTransaction - The hex string having RLP encoded transaction + * @returns The Ethereum address used to sign this transaction + * ```ts + * recoverTransaction('0xf869808504e3b29200831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a0c9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895a0727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68'); + * > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23" + * ``` + */ +export declare const recoverTransaction: (rawTransaction: HexString) => Address; +/** + * Recovers the Ethereum address which was used to sign the given data + * + * @param data - Either a signed message, hash, or the {@link signatureObject} + * @param signature - The raw RLP encoded signature + * @param signatureOrV - signatureOrV + * @param prefixedOrR - prefixedOrR + * @param s - s + * @param prefixed - (default: false) If the last parameter is true, the given message will NOT automatically be prefixed with "\\x19Ethereum Signed Message:\\n" + message.length + message, and assumed to be already prefixed. + * @returns The Ethereum address used to sign this data + * ```ts + * sign('Some data', '0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728'); + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1b', + * r: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f9', + * s: '0x53e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb150', + * signature: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b' + * } + * recover('0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b'); + * > '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0' + * ``` + */ +export declare const recover: (data: string | SignatureObject, signatureOrV?: string, prefixedOrR?: boolean | string, s?: string, prefixed?: boolean) => Address; +/** + * Get the ethereum Address from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns The Ethereum address + * @example + * ```ts + * privateKeyToAddress("0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728") + * > "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0" + * ``` + */ +export declare const privateKeyToAddress: (privateKey: Bytes) => string; +/** + * Get the public key from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param isCompressed - if true, will generate a 33 byte compressed public key instead of a 65 byte public key + * @returns The public key + * @example + * ```ts + * privateKeyToAddress("0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", true) + * > "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a" // uncompressed public key + * ``` + */ +export declare const privateKeyToPublicKey: (privateKey: Bytes, isCompressed: boolean) => string; +/** + * encrypt a private key with a password, returns a V3 JSON Keystore + * + * Read more: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + * + * @param privateKey - The private key to encrypt, 32 bytes. + * @param password - The password used for encryption. + * @param options - Options to configure to encrypt the keystore either scrypt or pbkdf2 + * @returns Returns a V3 JSON Keystore + * + * + * Encrypt using scrypt options + * ```ts + * encrypt('0x67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * '123', + * { + * n: 8192, + * iv: web3.utils.hexToBytes('0xbfb43120ae00e9de110f8325143a2709'), + * salt: web3.utils.hexToBytes('0x210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'), + * ), + * }).then(console.log) + * > { + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + *} + *``` + * Encrypting using pbkdf2 options + * ```ts + * encrypt('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + *'123', + *{ + * iv: 'bfb43120ae00e9de110f8325143a2709', + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * kdf: 'pbkdf2', + *}).then(console.log) + * > + * { + * version: 3, + * id: '77381417-0973-4e4b-b590-8eb3ace0fe2d', + * address: 'b8ce9ab6943e0eced004cde8e3bbed6568b2fa01', + * crypto: { + * ciphertext: '76512156a34105fa6473ad040c666ae7b917d14c06543accc0d2dc28e6073b12', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'pbkdf2', + * kdfparams: { + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * prf: 'hmac-sha256' + * }, + * mac: '46eb4884e82dc43b5aa415faba53cc653b7038e9d61cc32fd643cf8c396189b7' + * } + * } + *``` + */ +export declare const encrypt: (privateKey: Bytes, password: string | Uint8Array, options?: CipherOptions) => Promise; +/** + * Get an Account object from the privateKey + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns A Web3Account object + * + * The `Web3Account.signTransaction` is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * Use {@link Web3.eth.accounts.signTransaction} instead. + * + * ```ts + * privateKeyToAccount("0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709"); + * > { + * address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01', + * privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + * sign, + * signTransaction, + * encrypt, + * } + * ``` + */ +export declare const privateKeyToAccount: (privateKey: Bytes, ignoreLength?: boolean) => Web3Account; +/** + * + * Generates and returns a Web3Account object that includes the private and public key + * For creation of private key, it uses an audited package ethereum-cryptography/secp256k1 + * that is cryptographically secure random number with certain characteristics. + * Read more: https://www.npmjs.com/package/ethereum-cryptography#secp256k1-curve + * + * @returns A Web3Account object + * ```ts + * web3.eth.accounts.create(); + * { + * address: '0xbD504f977021b5E5DdccD8741A368b147B3B38bB', + * privateKey: '0x964ced1c69ad27a311c432fdc0d8211e987595f7eb34ab405a5f16bdc9563ec5', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export declare const create: () => Web3Account; +/** + * Decrypts a v3 keystore JSON, and creates the account. + * + * @param keystore - the encrypted Keystore object or string to decrypt + * @param password - The password that was used for encryption + * @param nonStrict - if true and given a json string, the keystore will be parsed as lowercase. + * @returns Returns the decrypted Web3Account object + * Decrypting scrypt + * + * ```ts + * decrypt({ + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + * }, '123').then(console.log) + * > { + * address: '0xcdA9A91875fc35c8Ac1320E098e584495d66e47c', + * privateKey: '67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export declare const decrypt: (keystore: KeyStore | string, password: string | Uint8Array, nonStrict?: boolean) => Promise; +//# sourceMappingURL=account.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/account.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/account.d.ts.map new file mode 100644 index 0000000..fe6390f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/account.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../src/account.ts"],"names":[],"mappings":"AAoCA,OAAO,EACN,OAAO,EACP,KAAK,EACL,aAAa,EACb,SAAS,EACT,QAAQ,EAIR,MAAM,YAAY,CAAC;AAmBpB,OAAO,KAAK,EACX,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,eAAO,MAAM,0BAA0B,SAAU,KAAK,iBAAiB,OAAO,KAAG,UAmBhF,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,WAAW,YAAa,MAAM,KAAG,MAY7C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,IAAI,SAAU,MAAM,cAAc,KAAK,KAAG,UAmBtD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiFG;AACH,eAAO,MAAM,eAAe,gBACd,gBAAgB,cACjB,SAAS,KAGnB,QAAQ,qBAAqB,CA0B/B,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB,mBAAoB,SAAS,KAAG,OAM9D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,OAAO,SACb,MAAM,GAAG,eAAe,iBACf,MAAM,gBACP,OAAO,GAAG,MAAM,MAC1B,MAAM,aACC,OAAO,KAChB,OA8BF,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,mBAAmB,eAAgB,KAAK,KAAG,MAcvD,CAAC;AAEF;;;;;;;;;;;GAWG;AACF,eAAO,MAAM,qBAAqB,eAAgB,KAAK,gBAAgB,OAAO,KAAG,MAKjF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AACH,eAAO,MAAM,OAAO,eACP,KAAK,YACP,MAAM,GAAG,UAAU,YACnB,aAAa,KACrB,QAAQ,QAAQ,CA4FlB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,mBAAmB,eAAgB,KAAK,iBAAiB,OAAO,KAAG,WAe/E,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,MAAM,QAAO,WAIzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,eAAO,MAAM,OAAO,aACT,QAAQ,GAAG,MAAM,YACjB,MAAM,GAAG,UAAU,cACjB,OAAO,KACjB,QAAQ,WAAW,CA2DrB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/goerli.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/goerli.d.ts new file mode 100644 index 0000000..97e340b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/goerli.d.ts @@ -0,0 +1,46 @@ +declare const _default: { + name: string; + chainId: number; + networkId: number; + defaultHardfork: string; + consensus: { + type: string; + algorithm: string; + clique: { + period: number; + epoch: number; + }; + }; + comment: string; + url: string; + genesis: { + timestamp: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + }; + hardforks: ({ + name: string; + block: number; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + } | { + "//_comment": string; + name: string; + ttd: string; + block: number; + forkHash: string; + } | { + name: string; + block: null; + forkHash: null; + "//_comment"?: undefined; + ttd?: undefined; + })[]; + bootstrapNodes: never[]; + dnsNetworks: string[]; +}; +export default _default; +//# sourceMappingURL=goerli.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/goerli.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/goerli.d.ts.map new file mode 100644 index 0000000..095313f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/goerli.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"goerli.d.ts","sourceRoot":"","sources":["../../../../src/common/chains/goerli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAgGE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/mainnet.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/mainnet.d.ts new file mode 100644 index 0000000..75bcce3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/mainnet.d.ts @@ -0,0 +1,42 @@ +declare const _default: { + name: string; + chainId: number; + networkId: number; + defaultHardfork: string; + consensus: { + type: string; + algorithm: string; + ethash: {}; + }; + comment: string; + url: string; + genesis: { + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + }; + hardforks: ({ + name: string; + block: number; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + } | { + "//_comment": string; + name: string; + ttd: string; + block: number; + forkHash: string; + } | { + name: string; + block: null; + forkHash: null; + "//_comment"?: undefined; + ttd?: undefined; + })[]; + bootstrapNodes: never[]; + dnsNetworks: string[]; +}; +export default _default; +//# sourceMappingURL=mainnet.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/mainnet.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/mainnet.d.ts.map new file mode 100644 index 0000000..c821508 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/mainnet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mainnet.d.ts","sourceRoot":"","sources":["../../../../src/common/chains/mainnet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAgHE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/sepolia.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/sepolia.d.ts new file mode 100644 index 0000000..411b7d7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/sepolia.d.ts @@ -0,0 +1,46 @@ +declare const _default: { + name: string; + chainId: number; + networkId: number; + defaultHardfork: string; + consensus: { + type: string; + algorithm: string; + ethash: {}; + }; + comment: string; + url: string; + genesis: { + timestamp: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + }; + hardforks: ({ + name: string; + block: number; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + timestamp?: undefined; + } | { + "//_comment": string; + name: string; + ttd: string; + block: number; + forkHash: string; + timestamp?: undefined; + } | { + name: string; + block: null; + timestamp: string; + forkHash: string; + "//_comment"?: undefined; + ttd?: undefined; + })[]; + bootstrapNodes: never[]; + dnsNetworks: string[]; +}; +export default _default; +//# sourceMappingURL=sepolia.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/sepolia.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/sepolia.d.ts.map new file mode 100644 index 0000000..5a8442e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/chains/sepolia.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sepolia.d.ts","sourceRoot":"","sources":["../../../../src/common/chains/sepolia.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAmGE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/common.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/common.d.ts new file mode 100644 index 0000000..f82ee84 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/common.d.ts @@ -0,0 +1,344 @@ +import { EventEmitter } from 'web3-utils'; +import type { Numbers } from 'web3-types'; +import type { ConsensusAlgorithm, ConsensusType } from './enums.js'; +import { Chain, CustomChain, Hardfork } from './enums.js'; +import type { BootstrapNodeConfig, CasperConfig, ChainConfig, ChainsConfig, CliqueConfig, CommonOpts, CustomCommonOpts, EthashConfig, GenesisBlockConfig, GethConfigOpts, HardforkConfig } from './types.js'; +/** + * Common class to access chain and hardfork parameters and to provide + * a unified and shared view on the network and hardfork state. + * + * Use the {@link Common.custom} static constructor for creating simple + * custom chain {@link Common} objects (more complete custom chain setups + * can be created via the main constructor and the {@link CommonOpts.customChains} parameter). + */ +export declare class Common extends EventEmitter { + readonly DEFAULT_HARDFORK: string | Hardfork; + private _chainParams; + private _hardfork; + private _eips; + private readonly _customChains; + private readonly HARDFORK_CHANGES; + /** + * Creates a {@link Common} object for a custom chain, based on a standard one. + * + * It uses all the {@link Chain} parameters from the {@link baseChain} option except the ones overridden + * in a provided {@link chainParamsOrName} dictionary. Some usage example: + * + * ```javascript + * Common.custom({chainId: 123}) + * ``` + * + * There are also selected supported custom chains which can be initialized by using one of the + * {@link CustomChains} for {@link chainParamsOrName}, e.g.: + * + * ```javascript + * Common.custom(CustomChains.MaticMumbai) + * ``` + * + * Note that these supported custom chains only provide some base parameters (usually the chain and + * network ID and a name) and can only be used for selected use cases (e.g. sending a tx with + * the `web3-utils/tx` library to a Layer-2 chain). + * + * @param chainParamsOrName Custom parameter dict (`name` will default to `custom-chain`) or string with name of a supported custom chain + * @param opts Custom chain options to set the {@link CustomCommonOpts.baseChain}, selected {@link CustomCommonOpts.hardfork} and others + */ + static custom(chainParamsOrName: Partial | CustomChain, opts?: CustomCommonOpts): Common; + /** + * Static method to load and set common from a geth genesis json + * @param genesisJson json of geth configuration + * @param { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge } to further configure the common instance + * @returns Common + */ + static fromGethGenesis(genesisJson: any, { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge }: GethConfigOpts): Common; + /** + * Static method to determine if a {@link chainId} is supported as a standard chain + * @param chainId bigint id (`1`) of a standard chain + * @returns boolean + */ + static isSupportedChainId(chainId: bigint): boolean; + private static _getChainParams; + constructor(opts: CommonOpts); + /** + * Sets the chain + * @param chain String ('mainnet') or Number (1) chain representation. + * Or, a Dictionary of chain parameters for a private network. + * @returns The dictionary with parameters set as chain + */ + setChain(chain: string | number | Chain | bigint | object): ChainConfig; + /** + * Sets the hardfork to get params for + * @param hardfork String identifier (e.g. 'byzantium') or {@link Hardfork} enum + */ + setHardfork(hardfork: string | Hardfork): void; + /** + * Returns the hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td : total difficulty of the parent block (for block hf) OR of the chain latest (for chain hf) + * @param timestamp: timestamp in seconds at which block was/is to be minted + * @returns The name of the HF + */ + getHardforkByBlockNumber(_blockNumber: Numbers, _td?: Numbers, _timestamp?: Numbers): string; + /** + * Sets a new hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td + * @param timestamp + * @returns The name of the HF set + */ + setHardforkByBlockNumber(blockNumber: Numbers, td?: Numbers, timestamp?: Numbers): string; + /** + * Internal helper function, returns the params for the given hardfork for the chain set + * @param hardfork Hardfork name + * @returns Dictionary with hardfork params or null if hardfork not on chain + */ + _getHardfork(hardfork: string | Hardfork): HardforkConfig | null; + /** + * Sets the active EIPs + * @param eips + */ + setEIPs(eips?: number[]): void; + /** + * Returns a parameter for the current chain setup + * + * If the parameter is present in an EIP, the EIP always takes precedence. + * Otherwise the parameter if taken from the latest applied HF with + * a change on the respective parameter. + * + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @returns The value requested or `BigInt(0)` if not found + */ + param(topic: string, name: string): bigint; + /** + * Returns the parameter corresponding to a hardfork + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param hardfork Hardfork name + * @returns The value requested or `BigInt(0)` if not found + */ + paramByHardfork(topic: string, name: string, hardfork: string | Hardfork): bigint; + /** + * Returns a parameter corresponding to an EIP + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param eip Number of the EIP + * @returns The value requested or `undefined` if not found + */ + paramByEIP(topic: string, name: string, eip: number): bigint | undefined; + /** + * Returns a parameter for the hardfork active on block number or + * optional provided total difficulty (Merge HF) + * @param topic Parameter topic + * @param name Parameter name + * @param blockNumber Block number + * @param td Total difficulty + * * @returns The value requested or `BigInt(0)` if not found + */ + paramByBlock(topic: string, name: string, blockNumber: Numbers, td?: Numbers, timestamp?: Numbers): bigint; + /** + * Checks if an EIP is activated by either being included in the EIPs + * manually passed in with the {@link CommonOpts.eips} or in a + * hardfork currently being active + * + * Note: this method only works for EIPs being supported + * by the {@link CommonOpts.eips} constructor option + * @param eip + */ + isActivatedEIP(eip: number): boolean; + /** + * Checks if set or provided hardfork is active on block number + * @param hardfork Hardfork name or null (for HF set) + * @param blockNumber + * @returns True if HF is active on block number + */ + hardforkIsActiveOnBlock(_hardfork: string | Hardfork | null, _blockNumber: Numbers): boolean; + /** + * Alias to hardforkIsActiveOnBlock when hardfork is set + * @param blockNumber + * @returns True if HF is active on block number + */ + activeOnBlock(blockNumber: Numbers): boolean; + /** + * Sequence based check if given or set HF1 is greater than or equal HF2 + * @param hardfork1 Hardfork name or null (if set) + * @param hardfork2 Hardfork name + * @param opts Hardfork options + * @returns True if HF1 gte HF2 + */ + hardforkGteHardfork(_hardfork1: string | Hardfork | null, hardfork2: string | Hardfork): boolean; + /** + * Alias to hardforkGteHardfork when hardfork is set + * @param hardfork Hardfork name + * @returns True if hardfork set is greater than hardfork provided + */ + gteHardfork(hardfork: string | Hardfork): boolean; + /** + * Returns the hardfork change block for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if unscheduled + */ + hardforkBlock(_hardfork?: string | Hardfork): bigint | null; + hardforkTimestamp(_hardfork?: string | Hardfork): bigint | null; + /** + * Returns the hardfork change block for eip + * @param eip EIP number + * @returns Block number or null if unscheduled + */ + eipBlock(eip: number): bigint | null; + /** + * Returns the hardfork change total difficulty (Merge HF) for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Total difficulty or null if no set + */ + hardforkTTD(_hardfork?: string | Hardfork): bigint | null; + /** + * True if block number provided is the hardfork (given or set) change block + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isHardforkBlock(_blockNumber: Numbers, _hardfork?: string | Hardfork): boolean; + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block timestamp, number or null if not available + */ + nextHardforkBlockOrTimestamp(_hardfork?: string | Hardfork): bigint | null; + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if not available + * @deprecated + */ + nextHardforkBlock(_hardfork?: string | Hardfork): bigint | null; + /** + * True if block number provided is the hardfork change block following the hardfork given or set + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + isNextHardforkBlock(_blockNumber: Numbers, _hardfork?: string | Hardfork): boolean; + /** + * Internal helper function to calculate a fork hash + * @param hardfork Hardfork name + * @param genesisHash Genesis block hash of the chain + * @returns Fork hash as hex string + */ + _calcForkHash(hardfork: string | Hardfork, genesisHash: Uint8Array): string; + /** + * Returns an eth/64 compliant fork hash (EIP-2124) + * @param hardfork Hardfork name, optional if HF set + * @param genesisHash Genesis block hash of the chain, optional if already defined and not needed to be calculated + */ + forkHash(_hardfork?: string | Hardfork, genesisHash?: Uint8Array): string; + /** + * + * @param forkHash Fork hash as a hex string + * @returns Array with hardfork data (name, block, forkHash) + */ + hardforkForForkHash(forkHash: string): HardforkConfig | null; + /** + * Sets any missing forkHashes on the passed-in {@link Common} instance + * @param common The {@link Common} to set the forkHashes for + * @param genesisHash The genesis block hash + */ + setForkHashes(genesisHash: Uint8Array): void; + /** + * Returns the Genesis parameters of the current chain + * @returns Genesis dictionary + */ + genesis(): GenesisBlockConfig; + /** + * Returns the hardforks for current chain + * @returns {Array} Array with arrays of hardforks + */ + hardforks(): HardforkConfig[]; + /** + * Returns bootstrap nodes for the current chain + * @returns {Dictionary} Dict with bootstrap nodes + */ + bootstrapNodes(): BootstrapNodeConfig[] | undefined; + /** + * Returns DNS networks for the current chain + * @returns {String[]} Array of DNS ENR urls + */ + dnsNetworks(): string[]; + /** + * Returns the hardfork set + * @returns Hardfork name + */ + hardfork(): string | Hardfork; + /** + * Returns the Id of current chain + * @returns chain Id + */ + chainId(): bigint; + /** + * Returns the name of current chain + * @returns chain name (lower case) + */ + chainName(): string; + /** + * Returns the Id of current network + * @returns network Id + */ + networkId(): bigint; + /** + * Returns the active EIPs + * @returns List of EIPs + */ + eips(): number[]; + /** + * Returns the consensus type of the network + * Possible values: "pow"|"poa"|"pos" + * + * Note: This value can update along a Hardfork. + */ + consensusType(): string | ConsensusType; + /** + * Returns the concrete consensus implementation + * algorithm or protocol for the network + * e.g. "ethash" for "pow" consensus type, + * "clique" for "poa" consensus type or + * "casper" for "pos" consensus type. + * + * Note: This value can update along a Hardfork. + */ + consensusAlgorithm(): string | ConsensusAlgorithm; + /** + * Returns a dictionary with consensus configuration + * parameters based on the consensus algorithm + * + * Expected returns (parameters must be present in + * the respective chain json files): + * + * ethash: empty object + * clique: period, epoch + * casper: empty object + * + * Note: This value can update along a Hardfork. + */ + consensusConfig(): { + [key: string]: CliqueConfig | EthashConfig | CasperConfig; + }; + /** + * Returns a deep copy of this {@link Common} instance. + */ + copy(): Common; + static _getInitializedChains(customChains?: ChainConfig[]): ChainsConfig; +} +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/common.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/common.d.ts.map new file mode 100644 index 0000000..ebe517d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../src/common/common.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAA4C,MAAM,YAAY,CAAC;AACpF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAO1C,OAAO,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAG1D,OAAO,KAAK,EACX,mBAAmB,EACnB,YAAY,EACZ,WAAW,EAEX,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,MAAM,YAAY,CAAC;AAMpB;;;;;;;GAOG;AACH,qBAAa,MAAO,SAAQ,YAAY;IACvC,SAAgB,gBAAgB,EAAE,MAAM,GAAG,QAAQ,CAAC;IAEpD,OAAO,CAAC,YAAY,CAAc;IAClC,OAAO,CAAC,SAAS,CAAoB;IACrC,OAAO,CAAC,KAAK,CAAgB;IAC7B,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAgB;IAE9C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA2C;IAE5E;;;;;;;;;;;;;;;;;;;;;;;OAuBG;WACW,MAAM,CACnB,iBAAiB,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,WAAW,EACrD,IAAI,GAAE,gBAAqB,GACzB,MAAM;IA4FT;;;;;OAKG;WACW,eAAe,CAC5B,WAAW,EAAE,GAAG,EAChB,EA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of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1153.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1153.d.ts new file mode 100644 index 0000000..eceb3d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1153.d.ts @@ -0,0 +1,24 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: { + tstore: { + v: number; + d: string; + }; + tload: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=1153.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1153.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1153.d.ts.map new file mode 100644 index 0000000..af283c9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1153.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"1153.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/1153.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,wBAsBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1559.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1559.d.ts new file mode 100644 index 0000000..4c2de51 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1559.d.ts @@ -0,0 +1,28 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: { + baseFeeMaxChangeDenominator: { + v: number; + d: string; + }; + elasticityMultiplier: { + v: number; + d: string; + }; + initialBaseFee: { + v: number; + d: string; + }; + }; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=1559.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1559.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1559.d.ts.map new file mode 100644 index 0000000..871770f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/1559.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"1559.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/1559.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBA0BE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2315.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2315.d.ts new file mode 100644 index 0000000..75854c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2315.d.ts @@ -0,0 +1,27 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + beginsub: { + v: number; + d: string; + }; + returnsub: { + v: number; + d: string; + }; + jumpsub: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=2315.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2315.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2315.d.ts.map new file mode 100644 index 0000000..ea3a5a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2315.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"2315.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/2315.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAyBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2537.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2537.d.ts new file mode 100644 index 0000000..fdad7e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2537.d.ts @@ -0,0 +1,51 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + Bls12381G1AddGas: { + v: number; + d: string; + }; + Bls12381G1MulGas: { + v: number; + d: string; + }; + Bls12381G2AddGas: { + v: number; + d: string; + }; + Bls12381G2MulGas: { + v: number; + d: string; + }; + Bls12381PairingBaseGas: { + v: number; + d: string; + }; + Bls12381PairingPerPairGas: { + v: number; + d: string; + }; + Bls12381MapG1Gas: { + v: number; + d: string; + }; + Bls12381MapG2Gas: { + v: number; + d: string; + }; + Bls12381MultiExpGasDiscount: { + v: number[][]; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=2537.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2537.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2537.d.ts.map new file mode 100644 index 0000000..7217855 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2537.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"2537.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/2537.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAkLE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2565.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2565.d.ts new file mode 100644 index 0000000..3b5996a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2565.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + modexpGquaddivisor: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=2565.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2565.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2565.d.ts.map new file mode 100644 index 0000000..3da4997 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2565.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"2565.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/2565.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wBAiBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2718.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2718.d.ts new file mode 100644 index 0000000..dc67b3a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2718.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=2718.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2718.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2718.d.ts.map new file mode 100644 index 0000000..39bd448 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2718.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"2718.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/2718.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,wBAWE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2929.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2929.d.ts new file mode 100644 index 0000000..086af67 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2929.d.ts @@ -0,0 +1,86 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + coldsload: { + v: number; + d: string; + }; + coldaccountaccess: { + v: number; + d: string; + }; + warmstorageread: { + v: number; + d: string; + }; + sstoreCleanGasEIP2200: { + v: number; + d: string; + }; + sstoreNoopGasEIP2200: { + v: number; + d: string; + }; + sstoreDirtyGasEIP2200: { + v: number; + d: string; + }; + sstoreInitRefundEIP2200: { + v: number; + d: string; + }; + sstoreCleanRefundEIP2200: { + v: number; + d: string; + }; + call: { + v: number; + d: string; + }; + callcode: { + v: number; + d: string; + }; + delegatecall: { + v: number; + d: string; + }; + staticcall: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + extcodesize: { + v: number; + d: string; + }; + extcodecopy: { + v: number; + d: string; + }; + extcodehash: { + v: number; + d: string; + }; + sload: { + v: number; + d: string; + }; + sstore: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=2929.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2929.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2929.d.ts.map new file mode 100644 index 0000000..254b1d7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2929.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"2929.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/2929.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAoFE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2930.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2930.d.ts new file mode 100644 index 0000000..3d2a6a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2930.d.ts @@ -0,0 +1,23 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: { + accessListStorageKeyCost: { + v: number; + d: string; + }; + accessListAddressCost: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=2930.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2930.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2930.d.ts.map new file mode 100644 index 0000000..1251290 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/2930.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"2930.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/2930.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,wBAqBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3074.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3074.d.ts new file mode 100644 index 0000000..1be2611 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3074.d.ts @@ -0,0 +1,27 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + auth: { + v: number; + d: string; + }; + authcall: { + v: number; + d: string; + }; + authcallValueTransfer: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3074.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3074.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3074.d.ts.map new file mode 100644 index 0000000..fdd09a6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3074.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3074.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3074.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAyBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3198.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3198.d.ts new file mode 100644 index 0000000..b56f03d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3198.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: { + basefee: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3198.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3198.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3198.d.ts.map new file mode 100644 index 0000000..37ee139 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3198.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3198.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3198.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wBAiBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3529.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3529.d.ts new file mode 100644 index 0000000..b47e99e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3529.d.ts @@ -0,0 +1,28 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: { + maxRefundQuotient: { + v: number; + d: string; + }; + }; + gasPrices: { + selfdestructRefund: { + v: number; + d: string; + }; + sstoreClearRefundEIP2200: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3529.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3529.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3529.d.ts.map new file mode 100644 index 0000000..3a98575 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3529.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3529.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3529.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBA0BE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3540.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3540.d.ts new file mode 100644 index 0000000..55470bb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3540.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3540.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3540.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3540.d.ts.map new file mode 100644 index 0000000..2e9f19d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3540.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3540.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3540.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3541.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3541.d.ts new file mode 100644 index 0000000..b316c44 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3541.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3541.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3541.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3541.d.ts.map new file mode 100644 index 0000000..8a3544b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3541.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3541.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3541.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAYE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3554.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3554.d.ts new file mode 100644 index 0000000..a0a19c4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3554.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=3554.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3554.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3554.d.ts.map new file mode 100644 index 0000000..7d9b8c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3554.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3554.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3554.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wBAiBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3607.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3607.d.ts new file mode 100644 index 0000000..5e7d1d5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3607.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3607.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3607.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3607.d.ts.map new file mode 100644 index 0000000..9598d8e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3607.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3607.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3607.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3651.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3651.d.ts new file mode 100644 index 0000000..9542c9a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3651.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3651.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3651.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3651.d.ts.map new file mode 100644 index 0000000..3a08e94 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3651.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3651.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3651.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3670.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3670.d.ts new file mode 100644 index 0000000..89cd1e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3670.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3670.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3670.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3670.d.ts.map new file mode 100644 index 0000000..60a0ba2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3670.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3670.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3670.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3675.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3675.d.ts new file mode 100644 index 0000000..f7b435c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3675.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3675.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3675.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3675.d.ts.map new file mode 100644 index 0000000..c8b6ad7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3675.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3675.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3675.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3855.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3855.d.ts new file mode 100644 index 0000000..015285e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3855.d.ts @@ -0,0 +1,20 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: { + push0: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3855.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3855.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3855.d.ts.map new file mode 100644 index 0000000..18af462 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3855.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3855.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3855.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,wBAkBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3860.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3860.d.ts new file mode 100644 index 0000000..0719bcb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3860.d.ts @@ -0,0 +1,25 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: { + initCodeWordCost: { + v: number; + d: string; + }; + }; + vm: { + maxInitCodeSize: { + v: number; + d: string; + }; + }; + pow: {}; +}; +export default _default; +//# sourceMappingURL=3860.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3860.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3860.d.ts.map new file mode 100644 index 0000000..ed58af7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/3860.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"3860.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/3860.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAuBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4345.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4345.d.ts new file mode 100644 index 0000000..3247df1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4345.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=4345.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4345.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4345.d.ts.map new file mode 100644 index 0000000..555fcf4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4345.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"4345.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/4345.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wBAiBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4399.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4399.d.ts new file mode 100644 index 0000000..bb5bd24 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4399.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=4399.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4399.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4399.d.ts.map new file mode 100644 index 0000000..920379e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4399.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"4399.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/4399.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4844.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4844.d.ts new file mode 100644 index 0000000..32e9a17 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4844.d.ts @@ -0,0 +1,59 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: number[]; + gasConfig: { + dataGasPerBlob: { + v: number; + d: string; + }; + targetDataGasPerBlock: { + v: number; + d: string; + }; + maxDataGasPerBlock: { + v: number; + d: string; + }; + dataGasPriceUpdateFraction: { + v: number; + d: string; + }; + }; + gasPrices: { + simpleGasPerBlob: { + v: number; + d: string; + }; + minDataGasPrice: { + v: number; + d: string; + }; + kzgPointEvaluationGasPrecompilePrice: { + v: number; + d: string; + }; + datahash: { + v: number; + d: string; + }; + }; + sharding: { + blobCommitmentVersionKzg: { + v: number; + d: string; + }; + fieldElementsPerBlob: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=4844.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4844.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4844.d.ts.map new file mode 100644 index 0000000..7a9f323 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4844.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"4844.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/4844.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAyDE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4895.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4895.d.ts new file mode 100644 index 0000000..089ee55 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4895.d.ts @@ -0,0 +1,15 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + requiredEIPs: never[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=4895.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4895.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4895.d.ts.map new file mode 100644 index 0000000..cec2bec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/4895.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"4895.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/4895.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,wBAaE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/5133.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/5133.d.ts new file mode 100644 index 0000000..187bd34 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/5133.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + name: string; + number: number; + comment: string; + url: string; + status: string; + minimumHardfork: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=5133.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/5133.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/5133.d.ts.map new file mode 100644 index 0000000..bb3d581 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/5133.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"5133.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/5133.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wBAiBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/index.d.ts new file mode 100644 index 0000000..d1e2e1f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/index.d.ts @@ -0,0 +1,4 @@ +export declare const EIPs: { + [key: number]: any; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/index.d.ts.map new file mode 100644 index 0000000..e1d4e5f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/eips/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/common/eips/index.ts"],"names":[],"mappings":"AAuCA,eAAO,MAAM,IAAI,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAuBtC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/enums.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/enums.d.ts new file mode 100644 index 0000000..6671af3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/enums.d.ts @@ -0,0 +1,80 @@ +export declare enum Chain { + Mainnet = 1, + Goerli = 5, + Sepolia = 11155111 +} +export declare enum Hardfork { + Chainstart = "chainstart", + Homestead = "homestead", + Dao = "dao", + TangerineWhistle = "tangerineWhistle", + SpuriousDragon = "spuriousDragon", + Byzantium = "byzantium", + Constantinople = "constantinople", + Petersburg = "petersburg", + Istanbul = "istanbul", + MuirGlacier = "muirGlacier", + Berlin = "berlin", + London = "london", + ArrowGlacier = "arrowGlacier", + GrayGlacier = "grayGlacier", + MergeForkIdTransition = "mergeForkIdTransition", + Merge = "merge", + Shanghai = "shanghai", + ShardingForkDev = "shardingFork" +} +export declare enum ConsensusType { + ProofOfStake = "pos", + ProofOfWork = "pow", + ProofOfAuthority = "poa" +} +export declare enum ConsensusAlgorithm { + Ethash = "ethash", + Clique = "clique", + Casper = "casper" +} +export declare enum CustomChain { + /** + * Polygon (Matic) Mainnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + PolygonMainnet = "polygon-mainnet", + /** + * Polygon (Matic) Mumbai Testnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + PolygonMumbai = "polygon-mumbai", + /** + * Arbitrum Rinkeby Testnet + * + * - [Documentation](https://developer.offchainlabs.com/docs/public_testnet) + */ + ArbitrumRinkebyTestnet = "arbitrum-rinkeby-testnet", + /** + * Arbitrum One - mainnet for Arbitrum roll-up + * + * - [Documentation](https://developer.offchainlabs.com/public-chains) + */ + ArbitrumOne = "arbitrum-one", + /** + * xDai EVM sidechain with a native stable token + * + * - [Documentation](https://www.xdaichain.com/) + */ + xDaiChain = "x-dai-chain", + /** + * Optimistic Kovan - testnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + OptimisticKovan = "optimistic-kovan", + /** + * Optimistic Ethereum - mainnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + OptimisticEthereum = "optimistic-ethereum" +} +//# sourceMappingURL=enums.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/enums.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/enums.d.ts.map new file mode 100644 index 0000000..9981dd7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/enums.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"enums.d.ts","sourceRoot":"","sources":["../../../src/common/enums.ts"],"names":[],"mappings":"AAgBA,oBAAY,KAAK;IAChB,OAAO,IAAI;IACX,MAAM,IAAI;IACV,OAAO,WAAW;CAClB;AAED,oBAAY,QAAQ;IACnB,UAAU,eAAe;IACzB,SAAS,cAAc;IACvB,GAAG,QAAQ;IACX,gBAAgB,qBAAqB;IACrC,cAAc,mBAAmB;IACjC,SAAS,cAAc;IACvB,cAAc,mBAAmB;IACjC,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,WAAW,gBAAgB;IAC3B,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,YAAY,iBAAiB;IAC7B,WAAW,gBAAgB;IAC3B,qBAAqB,0BAA0B;IAC/C,KAAK,UAAU;IACf,QAAQ,aAAa;IACrB,eAAe,iBAAiB;CAChC;AAED,oBAAY,aAAa;IACxB,YAAY,QAAQ;IACpB,WAAW,QAAQ;IACnB,gBAAgB,QAAQ;CACxB;AAED,oBAAY,kBAAkB;IAC7B,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,MAAM,WAAW;CACjB;AAED,oBAAY,WAAW;IACtB;;;;OAIG;IACH,cAAc,oBAAoB;IAElC;;;;OAIG;IACH,aAAa,mBAAmB;IAEhC;;;;OAIG;IACH,sBAAsB,6BAA6B;IAEnD;;;;OAIG;IACH,WAAW,iBAAiB;IAE5B;;;;OAIG;IACH,SAAS,gBAAgB;IAEzB;;;;OAIG;IACH,eAAe,qBAAqB;IAEpC;;;;OAIG;IACH,kBAAkB,wBAAwB;CAC1C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/arrowGlacier.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/arrowGlacier.d.ts new file mode 100644 index 0000000..ecbb8ec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/arrowGlacier.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=arrowGlacier.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/arrowGlacier.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/arrowGlacier.d.ts.map new file mode 100644 index 0000000..62c0c34 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/arrowGlacier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"arrowGlacier.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/arrowGlacier.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,wBAWE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/berlin.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/berlin.d.ts new file mode 100644 index 0000000..4777cd5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/berlin.d.ts @@ -0,0 +1,9 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; +//# sourceMappingURL=berlin.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/berlin.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/berlin.d.ts.map new file mode 100644 index 0000000..9167f7d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/berlin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"berlin.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/berlin.ts"],"names":[],"mappings":";;;;;;;AAAA,wBAOE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/byzantium.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/byzantium.d.ts new file mode 100644 index 0000000..beb7439 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/byzantium.d.ts @@ -0,0 +1,58 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + modexpGquaddivisor: { + v: number; + d: string; + }; + ecAdd: { + v: number; + d: string; + }; + ecMul: { + v: number; + d: string; + }; + ecPairing: { + v: number; + d: string; + }; + ecPairingWord: { + v: number; + d: string; + }; + revert: { + v: number; + d: string; + }; + staticcall: { + v: number; + d: string; + }; + returndatasize: { + v: number; + d: string; + }; + returndatacopy: { + v: number; + d: string; + }; + }; + vm: {}; + pow: { + minerReward: { + v: string; + d: string; + }; + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=byzantium.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/byzantium.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/byzantium.d.ts.map new file mode 100644 index 0000000..1753439 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/byzantium.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"byzantium.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/byzantium.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAwDE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/chainstart.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/chainstart.d.ts new file mode 100644 index 0000000..2f5d829 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/chainstart.d.ts @@ -0,0 +1,440 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: { + minGasLimit: { + v: number; + d: string; + }; + gasLimitBoundDivisor: { + v: number; + d: string; + }; + maxRefundQuotient: { + v: number; + d: string; + }; + }; + gasPrices: { + base: { + v: number; + d: string; + }; + tierStep: { + v: number[]; + d: string; + }; + exp: { + v: number; + d: string; + }; + expByte: { + v: number; + d: string; + }; + sha3: { + v: number; + d: string; + }; + sha3Word: { + v: number; + d: string; + }; + sload: { + v: number; + d: string; + }; + sstoreSet: { + v: number; + d: string; + }; + sstoreReset: { + v: number; + d: string; + }; + sstoreRefund: { + v: number; + d: string; + }; + jumpdest: { + v: number; + d: string; + }; + log: { + v: number; + d: string; + }; + logData: { + v: number; + d: string; + }; + logTopic: { + v: number; + d: string; + }; + create: { + v: number; + d: string; + }; + call: { + v: number; + d: string; + }; + callStipend: { + v: number; + d: string; + }; + callValueTransfer: { + v: number; + d: string; + }; + callNewAccount: { + v: number; + d: string; + }; + selfdestructRefund: { + v: number; + d: string; + }; + memory: { + v: number; + d: string; + }; + quadCoeffDiv: { + v: number; + d: string; + }; + createData: { + v: number; + d: string; + }; + tx: { + v: number; + d: string; + }; + txCreation: { + v: number; + d: string; + }; + txDataZero: { + v: number; + d: string; + }; + txDataNonZero: { + v: number; + d: string; + }; + copy: { + v: number; + d: string; + }; + ecRecover: { + v: number; + d: string; + }; + sha256: { + v: number; + d: string; + }; + sha256Word: { + v: number; + d: string; + }; + ripemd160: { + v: number; + d: string; + }; + ripemd160Word: { + v: number; + d: string; + }; + identity: { + v: number; + d: string; + }; + identityWord: { + v: number; + d: string; + }; + stop: { + v: number; + d: string; + }; + add: { + v: number; + d: string; + }; + mul: { + v: number; + d: string; + }; + sub: { + v: number; + d: string; + }; + div: { + v: number; + d: string; + }; + sdiv: { + v: number; + d: string; + }; + mod: { + v: number; + d: string; + }; + smod: { + v: number; + d: string; + }; + addmod: { + v: number; + d: string; + }; + mulmod: { + v: number; + d: string; + }; + signextend: { + v: number; + d: string; + }; + lt: { + v: number; + d: string; + }; + gt: { + v: number; + d: string; + }; + slt: { + v: number; + d: string; + }; + sgt: { + v: number; + d: string; + }; + eq: { + v: number; + d: string; + }; + iszero: { + v: number; + d: string; + }; + and: { + v: number; + d: string; + }; + or: { + v: number; + d: string; + }; + xor: { + v: number; + d: string; + }; + not: { + v: number; + d: string; + }; + byte: { + v: number; + d: string; + }; + address: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + origin: { + v: number; + d: string; + }; + caller: { + v: number; + d: string; + }; + callvalue: { + v: number; + d: string; + }; + calldataload: { + v: number; + d: string; + }; + calldatasize: { + v: number; + d: string; + }; + calldatacopy: { + v: number; + d: string; + }; + codesize: { + v: number; + d: string; + }; + codecopy: { + v: number; + d: string; + }; + gasprice: { + v: number; + d: string; + }; + extcodesize: { + v: number; + d: string; + }; + extcodecopy: { + v: number; + d: string; + }; + blockhash: { + v: number; + d: string; + }; + coinbase: { + v: number; + d: string; + }; + timestamp: { + v: number; + d: string; + }; + number: { + v: number; + d: string; + }; + difficulty: { + v: number; + d: string; + }; + gaslimit: { + v: number; + d: string; + }; + pop: { + v: number; + d: string; + }; + mload: { + v: number; + d: string; + }; + mstore: { + v: number; + d: string; + }; + mstore8: { + v: number; + d: string; + }; + sstore: { + v: number; + d: string; + }; + jump: { + v: number; + d: string; + }; + jumpi: { + v: number; + d: string; + }; + pc: { + v: number; + d: string; + }; + msize: { + v: number; + d: string; + }; + gas: { + v: number; + d: string; + }; + push: { + v: number; + d: string; + }; + dup: { + v: number; + d: string; + }; + swap: { + v: number; + d: string; + }; + callcode: { + v: number; + d: string; + }; + return: { + v: number; + d: string; + }; + invalid: { + v: number; + d: string; + }; + selfdestruct: { + v: number; + d: string; + }; + }; + vm: { + stackLimit: { + v: number; + d: string; + }; + callCreateDepth: { + v: number; + d: string; + }; + maxExtraDataSize: { + v: number; + d: string; + }; + }; + pow: { + minimumDifficulty: { + v: number; + d: string; + }; + difficultyBoundDivisor: { + v: number; + d: string; + }; + durationLimit: { + v: number; + d: string; + }; + epochDuration: { + v: number; + d: string; + }; + timebombPeriod: { + v: number; + d: string; + }; + minerReward: { + v: string; + d: string; + }; + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=chainstart.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/chainstart.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/chainstart.d.ts.map new file mode 100644 index 0000000..f56c848 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/chainstart.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chainstart.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/chainstart.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAsbE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/constantinople.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/constantinople.d.ts new file mode 100644 index 0000000..87cd1af --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/constantinople.d.ts @@ -0,0 +1,70 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + netSstoreNoopGas: { + v: number; + d: string; + }; + netSstoreInitGas: { + v: number; + d: string; + }; + netSstoreCleanGas: { + v: number; + d: string; + }; + netSstoreDirtyGas: { + v: number; + d: string; + }; + netSstoreClearRefund: { + v: number; + d: string; + }; + netSstoreResetRefund: { + v: number; + d: string; + }; + netSstoreResetClearRefund: { + v: number; + d: string; + }; + shl: { + v: number; + d: string; + }; + shr: { + v: number; + d: string; + }; + sar: { + v: number; + d: string; + }; + extcodehash: { + v: number; + d: string; + }; + create2: { + v: number; + d: string; + }; + }; + vm: {}; + pow: { + minerReward: { + v: string; + d: string; + }; + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=constantinople.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/constantinople.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/constantinople.d.ts.map new file mode 100644 index 0000000..86f3925 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/constantinople.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constantinople.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/constantinople.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAoEE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/dao.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/dao.d.ts new file mode 100644 index 0000000..6c7f0ce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/dao.d.ts @@ -0,0 +1,12 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=dao.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/dao.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/dao.d.ts.map new file mode 100644 index 0000000..24775f3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/dao.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dao.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/dao.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,wBAUE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/grayGlacier.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/grayGlacier.d.ts new file mode 100644 index 0000000..f3358d8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/grayGlacier.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=grayGlacier.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/grayGlacier.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/grayGlacier.d.ts.map new file mode 100644 index 0000000..c458cf6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/grayGlacier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"grayGlacier.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/grayGlacier.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,wBAWE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/homestead.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/homestead.d.ts new file mode 100644 index 0000000..d72a040 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/homestead.d.ts @@ -0,0 +1,17 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + delegatecall: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=homestead.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/homestead.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/homestead.d.ts.map new file mode 100644 index 0000000..1b7042f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/homestead.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"homestead.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/homestead.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wBAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/index.d.ts new file mode 100644 index 0000000..f82423a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/index.d.ts @@ -0,0 +1,4 @@ +export declare const hardforks: { + [key: string]: any; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/index.d.ts.map new file mode 100644 index 0000000..dd69f39 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/index.ts"],"names":[],"mappings":"AAkCA,eAAO,MAAM,SAAS,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAkB3C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/istanbul.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/istanbul.d.ts new file mode 100644 index 0000000..0ad9ebd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/istanbul.d.ts @@ -0,0 +1,89 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + blake2Round: { + v: number; + d: string; + }; + ecAdd: { + v: number; + d: string; + }; + ecMul: { + v: number; + d: string; + }; + ecPairing: { + v: number; + d: string; + }; + ecPairingWord: { + v: number; + d: string; + }; + txDataNonZero: { + v: number; + d: string; + }; + sstoreSentryGasEIP2200: { + v: number; + d: string; + }; + sstoreNoopGasEIP2200: { + v: number; + d: string; + }; + sstoreDirtyGasEIP2200: { + v: number; + d: string; + }; + sstoreInitGasEIP2200: { + v: number; + d: string; + }; + sstoreInitRefundEIP2200: { + v: number; + d: string; + }; + sstoreCleanGasEIP2200: { + v: number; + d: string; + }; + sstoreCleanRefundEIP2200: { + v: number; + d: string; + }; + sstoreClearRefundEIP2200: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + extcodehash: { + v: number; + d: string; + }; + chainid: { + v: number; + d: string; + }; + selfbalance: { + v: number; + d: string; + }; + sload: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=istanbul.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/istanbul.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/istanbul.d.ts.map new file mode 100644 index 0000000..017b722 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/istanbul.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"istanbul.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/istanbul.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAuFE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/london.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/london.d.ts new file mode 100644 index 0000000..29bd548 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/london.d.ts @@ -0,0 +1,9 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; +//# sourceMappingURL=london.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/london.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/london.d.ts.map new file mode 100644 index 0000000..efc8ced --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/london.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"london.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/london.ts"],"names":[],"mappings":";;;;;;;AAAA,wBAOE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/merge.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/merge.d.ts new file mode 100644 index 0000000..6522690 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/merge.d.ts @@ -0,0 +1,14 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + consensus: { + type: string; + algorithm: string; + casper: {}; + }; + eips: number[]; +}; +export default _default; +//# sourceMappingURL=merge.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/merge.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/merge.d.ts.map new file mode 100644 index 0000000..2522bbb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/merge.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"merge.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/merge.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAYE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/mergeForkIdTransition.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/mergeForkIdTransition.d.ts new file mode 100644 index 0000000..e225509 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/mergeForkIdTransition.d.ts @@ -0,0 +1,9 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: never[]; +}; +export default _default; +//# sourceMappingURL=mergeForkIdTransition.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/mergeForkIdTransition.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/mergeForkIdTransition.d.ts.map new file mode 100644 index 0000000..8e82e15 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/mergeForkIdTransition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mergeForkIdTransition.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/mergeForkIdTransition.ts"],"names":[],"mappings":";;;;;;;AAAA,wBAOE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/muirGlacier.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/muirGlacier.d.ts new file mode 100644 index 0000000..dcbedd4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/muirGlacier.d.ts @@ -0,0 +1,17 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: {}; + vm: {}; + pow: { + difficultyBombDelay: { + v: number; + d: string; + }; + }; +}; +export default _default; +//# sourceMappingURL=muirGlacier.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/muirGlacier.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/muirGlacier.d.ts.map new file mode 100644 index 0000000..54eb113 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/muirGlacier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"muirGlacier.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/muirGlacier.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wBAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/petersburg.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/petersburg.d.ts new file mode 100644 index 0000000..397f50b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/petersburg.d.ts @@ -0,0 +1,41 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + netSstoreNoopGas: { + v: null; + d: string; + }; + netSstoreInitGas: { + v: null; + d: string; + }; + netSstoreCleanGas: { + v: null; + d: string; + }; + netSstoreDirtyGas: { + v: null; + d: string; + }; + netSstoreClearRefund: { + v: null; + d: string; + }; + netSstoreResetRefund: { + v: null; + d: string; + }; + netSstoreResetClearRefund: { + v: null; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=petersburg.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/petersburg.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/petersburg.d.ts.map new file mode 100644 index 0000000..849fdc9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/petersburg.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"petersburg.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/petersburg.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBAuCE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/shanghai.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/shanghai.d.ts new file mode 100644 index 0000000..222eff6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/shanghai.d.ts @@ -0,0 +1,9 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; +//# sourceMappingURL=shanghai.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/shanghai.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/shanghai.d.ts.map new file mode 100644 index 0000000..ad29d6b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/shanghai.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shanghai.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/shanghai.ts"],"names":[],"mappings":";;;;;;;AAAA,wBAOE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/sharding.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/sharding.d.ts new file mode 100644 index 0000000..bfb4dff --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/sharding.d.ts @@ -0,0 +1,9 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + eips: number[]; +}; +export default _default; +//# sourceMappingURL=sharding.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/sharding.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/sharding.d.ts.map new file mode 100644 index 0000000..0137b79 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/sharding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sharding.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/sharding.ts"],"names":[],"mappings":";;;;;;;AAAA,wBAOE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/spuriousDragon.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/spuriousDragon.d.ts new file mode 100644 index 0000000..45cc829 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/spuriousDragon.d.ts @@ -0,0 +1,22 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + expByte: { + v: number; + d: string; + }; + }; + vm: { + maxCodeSize: { + v: number; + d: string; + }; + }; + pow: {}; +}; +export default _default; +//# sourceMappingURL=spuriousDragon.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/spuriousDragon.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/spuriousDragon.d.ts.map new file mode 100644 index 0000000..288c370 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/spuriousDragon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spuriousDragon.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/spuriousDragon.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,wBAoBE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/tangerineWhistle.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/tangerineWhistle.d.ts new file mode 100644 index 0000000..5137cd1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/tangerineWhistle.d.ts @@ -0,0 +1,45 @@ +declare const _default: { + name: string; + comment: string; + url: string; + status: string; + gasConfig: {}; + gasPrices: { + sload: { + v: number; + d: string; + }; + call: { + v: number; + d: string; + }; + extcodesize: { + v: number; + d: string; + }; + extcodecopy: { + v: number; + d: string; + }; + balance: { + v: number; + d: string; + }; + delegatecall: { + v: number; + d: string; + }; + callcode: { + v: number; + d: string; + }; + selfdestruct: { + v: number; + d: string; + }; + }; + vm: {}; + pow: {}; +}; +export default _default; +//# sourceMappingURL=tangerineWhistle.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/tangerineWhistle.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/tangerineWhistle.d.ts.map new file mode 100644 index 0000000..0308fbc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/hardforks/tangerineWhistle.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tangerineWhistle.d.ts","sourceRoot":"","sources":["../../../../src/common/hardforks/tangerineWhistle.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wBA2CE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/index.d.ts new file mode 100644 index 0000000..f598319 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/index.d.ts @@ -0,0 +1,5 @@ +export * from './common.js'; +export * from './enums.js'; +export * from './types.js'; +export * from './utils.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/index.d.ts.map new file mode 100644 index 0000000..7a7171f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/common/index.ts"],"names":[],"mappings":"AAiBA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/types.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/types.d.ts new file mode 100644 index 0000000..9ab6670 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/types.d.ts @@ -0,0 +1,136 @@ +import type { Chain, ConsensusAlgorithm, ConsensusType, Hardfork } from './enums.js'; +export interface ChainName { + [chainId: string]: string; +} +export declare type CliqueConfig = { + period: number; + epoch: number; +}; +export declare type EthashConfig = Record; +export declare type CasperConfig = Record; +export interface GenesisBlockConfig { + timestamp?: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + baseFeePerGas?: string; +} +export interface HardforkConfig { + name: Hardfork | string; + block: number | null; + ttd?: bigint | string; + timestamp?: number | string; + forkHash?: string | null; +} +export interface BootstrapNodeConfig { + ip: string; + port: number | string; + network?: string; + chainId?: number; + id: string; + location: string; + comment: string; +} +export interface ChainConfig { + name: string; + chainId: number | bigint; + networkId: number | bigint; + defaultHardfork?: string; + comment?: string; + url?: string; + genesis: GenesisBlockConfig; + hardforks: HardforkConfig[]; + bootstrapNodes?: BootstrapNodeConfig[]; + dnsNetworks?: string[]; + consensus: { + type: ConsensusType | string; + algorithm: ConsensusAlgorithm | string; + clique?: CliqueConfig; + ethash?: EthashConfig; + casper?: CasperConfig; + }; +} +export interface ChainsConfig { + [key: string]: ChainConfig | ChainName; +} +interface BaseOpts { + /** + * String identifier ('byzantium') for hardfork or {@link Hardfork} enum. + * + * Default: Hardfork.London + */ + hardfork?: string | Hardfork; + /** + * Selected EIPs which can be activated, please use an array for instantiation + * (e.g. `eips: [ 2537, ]`) + * + * Currently supported: + * + * - [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537) - BLS12-381 precompiles + */ + eips?: number[]; +} +/** + * Options for instantiating a {@link Common} instance. + */ +export interface CommonOpts extends BaseOpts { + /** + * Chain name ('mainnet'), id (1), or {@link Chain} enum, + * either from a chain directly supported or a custom chain + * passed in via {@link CommonOpts.customChains}. + */ + chain: string | number | Chain | bigint | object; + /** + * Initialize (in addition to the supported chains) with the selected + * custom chains. Custom genesis state should be passed to the Blockchain class if used. + * + * Usage (directly with the respective chain initialization via the {@link CommonOpts.chain} option): + * + * ```javascript + * import myCustomChain1 from '[PATH_TO_MY_CHAINS]/myCustomChain1.json' + * const common = new Common({ chain: 'myCustomChain1', customChains: [ myCustomChain1 ]}) + * ``` + */ + customChains?: ChainConfig[]; +} +/** + * Options to be used with the {@link Common.custom} static constructor. + */ +export interface CustomCommonOpts extends BaseOpts { + /** + * The name (`mainnet`), id (`1`), or {@link Chain} enum of + * a standard chain used to base the custom chain params on. + */ + baseChain?: string | number | Chain | bigint; +} +export interface GethConfigOpts extends BaseOpts { + chain?: string; + genesisHash?: Uint8Array; + mergeForkIdPostMerge?: boolean; +} +export declare type PrefixedHexString = string; +export declare type Uint8ArrayLike = Uint8Array | number[] | number | bigint | PrefixedHexString; +export declare type BigIntLike = bigint | PrefixedHexString | number | Uint8Array; +export interface TransformableToArray { + toArray(): Uint8Array; +} +export declare type NestedUint8Array = Array; +/** + * Type output options + */ +export declare enum TypeOutput { + Number = 0, + BigInt = 1, + Uint8Array = 2, + PrefixedHexString = 3 +} +export declare type TypeOutputReturnType = { + [TypeOutput.Number]: number; + [TypeOutput.BigInt]: bigint; + [TypeOutput.Uint8Array]: Uint8Array; + [TypeOutput.PrefixedHexString]: PrefixedHexString; +}; +export declare type ToBytesInputTypes = PrefixedHexString | number | bigint | Uint8Array | number[] | TransformableToArray | null | undefined; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/types.d.ts.map new file mode 100644 index 0000000..00762d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/common/types.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAErF,MAAM,WAAW,SAAS;IACzB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC;CAC1B;AAED,oBAAY,YAAY,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,oBAAY,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnD,oBAAY,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnD,MAAM,WAAW,kBAAkB;IAClC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,QAAQ,GAAG,MAAM,CAAC;IAExB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAE5B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,MAAM,WAAW,mBAAmB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAA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,WAAW,gBAAiB,SAAQ,QAAQ;IACjD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,CAAC;CAC7C;AAED,MAAM,WAAW,cAAe,SAAQ,QAAQ;IAC/C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,UAAU,CAAC;IACzB,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAKD,oBAAY,iBAAiB,GAAG,MAAM,CAAC;AAKvC,oBAAY,cAAc,GAAG,UAAU,GAAG,MAAM,EAAE,GAAG,MAAM,GAAG,MAAM,GAAG,iBAAiB,CAAC;AAKzF,oBAAY,UAAU,GAAG,MAAM,GAAG,iBAAiB,GAAG,MAAM,GAAG,UAAU,CAAC;AAK1E,MAAM,WAAW,oBAAoB;IACpC,OAAO,IAAI,UAAU,CAAC;CACtB;AAED,oBAAY,gBAAgB,GAAG,KAAK,CAAC,UAAU,GAAG,gBAAgB,CAAC,CAAC;AACpE;;GAEG;AACH,oBAAY,UAAU;IACrB,MAAM,IAAA;IACN,MAAM,IAAA;IACN,UAAU,IAAA;IACV,iBAAiB,IAAA;CACjB;AAED,oBAAY,oBAAoB,GAAG;IAClC,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAC5B,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAC5B,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACpC,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CAClD,CAAC;AACF,oBAAY,iBAAiB,GAC1B,iBAAiB,GACjB,MAAM,GACN,MAAM,GACN,UAAU,GACV,MAAM,EAAE,GACR,oBAAoB,GAEpB,IAAI,GACJ,SAAS,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/utils.d.ts new file mode 100644 index 0000000..1bf3438 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/utils.d.ts @@ -0,0 +1,138 @@ +import { ToBytesInputTypes, TypeOutput, TypeOutputReturnType } from './types.js'; +declare type ConfigHardfork = { + name: string; + block: null; + timestamp: number; +} | { + name: string; + block: number; + timestamp?: number; +}; +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +export declare const stripHexPrefix: (str: string) => string; +/** + * Parses a genesis.json exported from Geth into parameters for Common instance + * @param json representing the Geth genesis file + * @param name optional chain name + * @returns parsed params + */ +export declare function parseGethGenesis(json: any, name?: string, mergeForkIdPostMerge?: boolean): { + name: string; + chainId: number; + networkId: number; + genesis: { + timestamp: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + mixHash: string; + coinbase: string; + baseFeePerGas: string; + }; + hardfork: string | undefined; + hardforks: ConfigHardfork[]; + bootstrapNodes: never[]; + consensus: { + type: string; + algorithm: string; + clique: { + period: any; + epoch: any; + }; + ethash?: undefined; + } | { + type: string; + algorithm: string; + ethash: {}; + clique?: undefined; + }; +}; +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +export declare function padToEven(value: string): string; +/** + * Converts an `Number` to a `Uint8Array` + * @param {Number} i + * @return {Uint8Array} + */ +export declare const intToUint8Array: (i: number) => Uint8Array; +/** + * Attempts to turn a value into a `Uint8Array`. + * Inputs supported: `Uint8Array` `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toUint8Array()` method. + * @param v the value + */ +export declare const toUint8Array: (v: ToBytesInputTypes) => Uint8Array; +/** + * Converts a {@link Uint8Array} to a {@link bigint} + */ +export declare function uint8ArrayToBigInt(buf: Uint8Array): bigint; +/** + * Converts a {@link bigint} to a {@link Uint8Array} + */ +export declare function bigIntToUint8Array(num: bigint): Uint8Array; +/** + * Returns a Uint8Array filled with 0s. + * @param bytes the number of bytes the Uint8Array should be + */ +export declare const zeros: (bytes: number) => Uint8Array; +/** + * Throws if input is not a Uint8Array + * @param {Uint8Array} input value to check + */ +export declare function assertIsUint8Array(input: unknown): asserts input is Uint8Array; +/** + * Left Pads a `Uint8Array` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @return (Uint8Array) + */ +export declare const setLengthLeft: (msg: Uint8Array, length: number) => Uint8Array; +/** + * Trims leading zeros from a `Uint8Array`, `String` or `Number[]`. + * @param a (Uint8Array|Array|String) + * @return (Uint8Array|Array|String) + */ +export declare function stripZeros(a: T): T; +/** + * Trims leading zeros from a `Uint8Array`. + * @param a (Uint8Array) + * @return (Uint8Array) + */ +export declare const unpadUint8Array: (a: Uint8Array) => Uint8Array; +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +export declare const bigIntToHex: (num: bigint) => string; +/** + * Convert value from bigint to an unpadded Uint8Array + * (useful for RLP transport) + * @param value value to convert + */ +export declare function bigIntToUnpaddedUint8Array(value: bigint): Uint8Array; +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +export declare const ecrecover: (msgHash: Uint8Array, v: bigint, r: Uint8Array, s: Uint8Array, chainId?: bigint) => Uint8Array; +/** + * Convert an input to a specified type. + * Input of null/undefined returns null/undefined regardless of the output type. + * @param input value to convert + * @param outputType type to output + */ +export declare function toType(input: null, outputType: T): null; +export declare function toType(input: undefined, outputType: T): undefined; +export declare function toType(input: ToBytesInputTypes, outputType: T): TypeOutputReturnType[T]; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/utils.d.ts.map new file mode 100644 index 0000000..9768aac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/common/utils.d.ts.map @@ -0,0 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AEF;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,UAAU,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAY5E;AAED;;;;GAIG;AACH,eAAO,MAAM,eAAe,MAAgB,UAAU,KAAG,UAGxD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,QAAS,MAAM,WAA4B,CAAC;AAEpE;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAEpE;AAeD;;;;GAIG;AACH,eAAO,MAAM,SAAS,YACZ,UAAU,KAChB,MAAM,KACN,UAAU,KACV,UAAU,YACH,MAAM,KACd,UAWF,CAAC;AAEF;;;;;GAKG;AAEH,wBAAgB,MAAM,CAAC,CAAC,SAAS,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,GAAG,IAAI,CAAC;AAC/E,wBAAgB,MAAM,CAAC,CAAC,SAAS,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC,GAAG,SAAS,CAAC;AACzF,wBAAgB,MAAM,CAAC,CAAC,SAAS,UAAU,EAC1C,KAAK,EAAE,iBAAiB,EACxB,UAAU,EAAE,CAAC,GACX,oBAAoB,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/index.d.ts new file mode 100644 index 0000000..60688a6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/index.d.ts @@ -0,0 +1,28 @@ +/** + * The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data. + * + * **_NOTE:_** This package has NOT been audited and might potentially be unsafe. Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production! + * + * + * To use this package standalone and use its methods use: + * ```ts + * import { create, decrypt } from 'web3-eth-accounts'; // .... + * ``` + * + * To use this package within the web3 object use: + * + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // now you have access to the accounts class + * web3.eth.accounts.create(); + * ``` + */ +export * from './wallet.js'; +export * from './account.js'; +export * from './types.js'; +export * from './schemas.js'; +export * from './common/index.js'; +export * from './tx/index.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/index.d.ts.map new file mode 100644 index 0000000..6a224f2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/schemas.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/schemas.d.ts new file mode 100644 index 0000000..db0cc53 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/schemas.d.ts @@ -0,0 +1,43 @@ +export declare const keyStoreSchema: { + type: string; + required: string[]; + properties: { + crypto: { + type: string; + required: string[]; + properties: { + cipher: { + type: string; + }; + ciphertext: { + type: string; + }; + cipherparams: { + type: string; + }; + kdf: { + type: string; + }; + kdfparams: { + type: string; + }; + salt: { + type: string; + }; + mac: { + type: string; + }; + }; + }; + id: { + type: string; + }; + version: { + type: string; + }; + address: { + type: string; + }; + }; +}; +//# sourceMappingURL=schemas.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/schemas.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/schemas.d.ts.map new file mode 100644 index 0000000..30c1dd1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/schemas.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/schemas.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqB1B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/address.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/address.d.ts new file mode 100644 index 0000000..cd9939b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/address.d.ts @@ -0,0 +1,32 @@ +export declare class Address { + readonly buf: Uint8Array; + constructor(buf: Uint8Array); + /** + * Returns the zero address. + */ + static zero(): Address; + /** + * Is address equal to another. + */ + equals(address: Address): boolean; + /** + * Is address zero. + */ + isZero(): boolean; + /** + * Returns hex encoding of address. + */ + toString(): string; + /** + * Returns Uint8Array representation of address. + */ + toArray(): Uint8Array; + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ + static publicToAddress(_pubKey: Uint8Array, sanitize?: boolean): Uint8Array; +} +//# sourceMappingURL=address.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/address.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/address.d.ts.map new file mode 100644 index 0000000..5c77b55 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../../src/tx/address.ts"],"names":[],"mappings":"AAqBA,qBAAa,OAAO;IACnB,SAAgB,GAAG,EAAE,UAAU,CAAC;gBAEb,GAAG,EAAE,UAAU;IAOlC;;OAEG;WACW,IAAI,IAAI,OAAO;IAI7B;;OAEG;IACI,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO;IAIxC;;OAEG;IACI,MAAM,IAAI,OAAO;IAIxB;;OAEG;IACI,QAAQ,IAAI,MAAM;IAIzB;;OAEG;IACI,OAAO,IAAI,UAAU;IAI5B;;;;;OAKG;WACW,eAAe,CAAC,OAAO,EAAE,UAAU,EAAE,QAAQ,UAAQ,GAAG,UAAU;CAYhF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/baseTransaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/baseTransaction.d.ts new file mode 100644 index 0000000..36c1104 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/baseTransaction.d.ts @@ -0,0 +1,198 @@ +import { Numbers } from 'web3-types'; +import { Common } from '../common/common.js'; +import { Hardfork, Chain } from '../common/enums.js'; +import type { AccessListEIP2930TxData, AccessListEIP2930ValuesArray, FeeMarketEIP1559TxData, FeeMarketEIP1559ValuesArray, JsonTx, TxData, TxOptions, TxValuesArray } from './types.js'; +import { Capability } from './types.js'; +import { Address } from './address.js'; +interface TransactionCache { + hash: Uint8Array | undefined; + dataFee?: { + value: bigint; + hardfork: string | Hardfork; + }; +} +/** + * This base class will likely be subject to further + * refactoring along the introduction of additional tx types + * on the Ethereum network. + * + * It is therefore not recommended to use directly. + */ +export declare abstract class BaseTransaction { + private readonly _type; + readonly nonce: bigint; + readonly gasLimit: bigint; + readonly to?: Address; + readonly value: bigint; + readonly data: Uint8Array; + readonly v?: bigint; + readonly r?: bigint; + readonly s?: bigint; + readonly common: Common; + protected cache: TransactionCache; + protected readonly txOptions: TxOptions; + /** + * List of tx type defining EIPs, + * e.g. 1559 (fee market) and 2930 (access lists) + * for FeeMarketEIP1559Transaction objects + */ + protected activeCapabilities: number[]; + /** + * The default chain the tx falls back to if no Common + * is provided and if the chain can't be derived from + * a passed in chainId (only EIP-2718 typed txs) or + * EIP-155 signature (legacy txs). + * + * @hidden + */ + protected DEFAULT_CHAIN: Chain; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string | Hardfork; + constructor(txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData, opts: TxOptions); + /** + * Returns the transaction type. + * + * Note: legacy txs will return tx type `0`. + */ + get type(): number; + /** + * Checks if a tx type defining capability is active + * on a tx, for example the EIP-1559 fee market mechanism + * or the EIP-2930 access list feature. + * + * Note that this is different from the tx type itself, + * so EIP-2930 access lists can very well be active + * on an EIP-1559 tx for example. + * + * This method can be useful for feature checks if the + * tx type is unknown (e.g. when instantiated with + * the tx factory). + * + * See `Capabilites` in the `types` module for a reference + * on all supported capabilities. + */ + supports(capability: Capability): boolean; + /** + * Checks if the transaction has the minimum amount of gas required + * (DataFee + TxFee + Creation Fee). + */ + validate(): boolean; + validate(stringError: false): boolean; + validate(stringError: true): string[]; + protected _validateYParity(): void; + /** + * EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2are considered invalid. + * Reasoning: https://ethereum.stackexchange.com/a/55728 + */ + protected _validateHighS(): void; + /** + * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + */ + getBaseFee(): bigint; + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + */ + abstract getUpfrontCost(): bigint; + /** + * If the tx's `to` is to the creation address + */ + toCreationAddress(): boolean; + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of this transaction, in order. + * + * Use {@link BaseTransaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link BaseTransaction.getMessageToSign}. + */ + abstract raw(): TxValuesArray | AccessListEIP2930ValuesArray | FeeMarketEIP1559ValuesArray; + /** + * Returns the encoding of the transaction. + */ + abstract serialize(): Uint8Array; + abstract getMessageToSign(hashMessage: false): Uint8Array | Uint8Array[]; + abstract getMessageToSign(hashMessage?: true): Uint8Array; + abstract hash(): Uint8Array; + abstract getMessageToVerifySignature(): Uint8Array; + isSigned(): boolean; + /** + * Determines if the signature is valid + */ + verifySignature(): boolean; + /** + * Returns the sender's address + */ + getSenderAddress(): Address; + /** + * Returns the public key of the sender + */ + abstract getSenderPublicKey(): Uint8Array; + /** + * Signs a transaction. + * + * Note that the signed tx is returned as a new object, + * use as follows: + * ```javascript + * const signedTx = tx.sign(privateKey) + * ``` + */ + sign(privateKey: Uint8Array): TransactionObject; + /** + * Returns an object with the JSON representation of the transaction + */ + abstract toJSON(): JsonTx; + protected abstract _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): TransactionObject; + /** + * Does chain ID checks on common and returns a common + * to be used on instantiation + * @hidden + * + * @param common - {@link Common} instance from tx options + * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) + */ + protected _getCommon(common?: Common, chainId?: Numbers): Common; + /** + * Validates that an object with BigInt values cannot exceed the specified bit limit. + * @param values Object containing string keys and BigInt values + * @param bits Number of bits to check (64 or 256) + * @param cannotEqual Pass true if the number also cannot equal one less the maximum value + */ + protected _validateCannotExceedMaxInteger(values: { + [key: string]: bigint | undefined; + }, bits?: number, cannotEqual?: boolean): void; + protected static _validateNotArray(values: { + [key: string]: any; + }): void; + /** + * Return a compact error string representation of the object + */ + abstract errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected abstract _errorMsg(msg: string): string; + /** + * Returns the shared error postfix part for _error() method + * tx type implementations. + */ + protected _getSharedErrorPostfix(): string; + private _ecsign; + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): any; + static fromTxData(txData: any, opts?: TxOptions): any; +} +export {}; +//# sourceMappingURL=baseTransaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/baseTransaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/baseTransaction.d.ts.map new file mode 100644 index 0000000..c4eacac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/baseTransaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"baseTransaction.d.ts","sourceRoot":"","sources":["../../../src/tx/baseTransaction.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAIrC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EACX,uBAAuB,EACvB,4BAA4B,EAC5B,sBAAsB,EACtB,2BAA2B,EAC3B,MAAM,EACN,MAAM,EACN,SAAS,EACT,aAAa,EACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAkB,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,UAAU,gBAAgB;IACzB,IAAI,EAAE,UAAU,GAAG,SAAS,CAAC;IAC7B,OAAO,CAAC,EAAE;QACT,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC;KAC5B,CAAC;CACF;AAED;;;;;;GAMG;AACH,8BAAsB,eAAe,CAAC,iBAAiB;IACtD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAE/B,SAAgB,KAAK,EAAE,MAAM,CAAC;IAC9B,SAAgB,QAAQ,EAAE,MAAM,CAAC;IACjC,SAAgB,EAAE,CAAC,EAAE,OAAO,CAAC;IAC7B,SAAgB,KAAK,EAAE,MAAM,CAAC;IAC9B,SAAgB,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s/node_modules/web3-eth-accounts/lib/types/tx/constants.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/constants.d.ts new file mode 100644 index 0000000..b902c36 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/constants.d.ts @@ -0,0 +1,62 @@ +export declare const secp256k1: Readonly<{ + create: (hash: import("@noble/curves/abstract/utils").CHash) => import("@noble/curves/abstract/weierstrass").CurveFn; + CURVE: Readonly<{ + readonly nBitLength: number; + readonly nByteLength: number; + readonly Fp: import("@noble/curves/abstract/modular").IField; + readonly n: bigint; + readonly h: bigint; + readonly hEff?: bigint | undefined; + readonly Gx: bigint; + readonly Gy: bigint; + readonly allowInfinityPoint?: boolean | undefined; + readonly a: bigint; + readonly b: bigint; + readonly allowedPrivateKeyLengths?: readonly number[] | undefined; + readonly wrapPrivateKey?: boolean | undefined; + readonly endo?: { + beta: bigint; + splitScalar: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; + } | undefined; + readonly isTorsionFree?: ((c: import("@noble/curves/abstract/weierstrass").ProjConstructor, point: import("@noble/curves/abstract/weierstrass").ProjPointType) => boolean) | undefined; + readonly clearCofactor?: ((c: import("@noble/curves/abstract/weierstrass").ProjConstructor, point: import("@noble/curves/abstract/weierstrass").ProjPointType) => import("@noble/curves/abstract/weierstrass").ProjPointType) | undefined; + readonly hash: import("@noble/curves/abstract/utils").CHash; + readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array; + readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array; + lowS: boolean; + readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined; + readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined; + readonly p: bigint; + }>; + getPublicKey: (privateKey: import("@noble/curves/abstract/utils").PrivKey, isCompressed?: boolean | undefined) => Uint8Array; + getSharedSecret: (privateA: import("@noble/curves/abstract/utils").PrivKey, publicB: import("@noble/curves/abstract/utils").Hex, isCompressed?: boolean | undefined) => Uint8Array; + sign: (msgHash: import("@noble/curves/abstract/utils").Hex, privKey: import("@noble/curves/abstract/utils").PrivKey, opts?: import("@noble/curves/abstract/weierstrass").SignOpts | undefined) => import("@noble/curves/abstract/weierstrass").SignatureType; + verify: (signature: import("@noble/curves/abstract/utils").Hex | { + r: bigint; + s: bigint; + }, msgHash: import("@noble/curves/abstract/utils").Hex, publicKey: import("@noble/curves/abstract/utils").Hex, opts?: import("@noble/curves/abstract/weierstrass").VerOpts | undefined) => boolean; + ProjectivePoint: import("@noble/curves/abstract/weierstrass").ProjConstructor; + Signature: import("@noble/curves/abstract/weierstrass").SignatureConstructor; + utils: { + normPrivateKeyToScalar: (key: import("@noble/curves/abstract/utils").PrivKey) => bigint; + isValidPrivateKey(privateKey: import("@noble/curves/abstract/utils").PrivKey): boolean; + randomPrivateKey: () => Uint8Array; + precompute: (windowSize?: number | undefined, point?: import("@noble/curves/abstract/weierstrass").ProjPointType | undefined) => import("@noble/curves/abstract/weierstrass").ProjPointType; + }; +}>; +/** + * 2^64-1 + */ +export declare const MAX_UINT64: bigint; +/** + * The max integer that the evm can handle (2^256-1) + */ +export declare const MAX_INTEGER: bigint; +export declare const SECP256K1_ORDER: bigint; +export declare const SECP256K1_ORDER_DIV_2: bigint; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/constants.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/constants.d.ts.map new file mode 100644 index 0000000..a600316 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/tx/constants.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAyD,CAAC;AAChF;;GAEG;AACH,eAAO,MAAM,UAAU,QAA+B,CAAC;AAEvD;;GAEG;AACH,eAAO,MAAM,WAAW,QAEvB,CAAC;AAEF,eAAO,MAAM,eAAe,QAAoB,CAAC;AACjD,eAAO,MAAM,qBAAqB,QAA8B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip1559Transaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip1559Transaction.d.ts new file mode 100644 index 0000000..3102c8a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip1559Transaction.d.ts @@ -0,0 +1,137 @@ +import { BaseTransaction } from './baseTransaction.js'; +import type { AccessList, AccessListUint8Array, FeeMarketEIP1559TxData, FeeMarketEIP1559ValuesArray, JsonTx, TxOptions } from './types.js'; +import type { Common } from '../common/common.js'; +/** + * Typed transaction with a new gas fee market mechanism + * + * - TransactionType: 2 + * - EIP: [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) + */ +export declare class FeeMarketEIP1559Transaction extends BaseTransaction { + readonly chainId: bigint; + readonly accessList: AccessListUint8Array; + readonly AccessListJSON: AccessList; + readonly maxPriorityFeePerGas: bigint; + readonly maxFeePerGas: bigint; + readonly common: Common; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string; + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData: FeeMarketEIP1559TxData, opts?: TxOptions): FeeMarketEIP1559Transaction; + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + */ + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): FeeMarketEIP1559Transaction; + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + */ + static fromValuesArray(values: FeeMarketEIP1559ValuesArray, opts?: TxOptions): FeeMarketEIP1559Transaction; + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData: FeeMarketEIP1559TxData, opts?: TxOptions); + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + * @param baseFee The base fee of the block (will be set to 0 if not provided) + */ + getUpfrontCost(baseFee?: bigint): bigint; + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-1559 transaction, in order. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + * + * Use {@link FeeMarketEIP1559Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link FeeMarketEIP1559Transaction.getMessageToSign}. + */ + raw(): FeeMarketEIP1559ValuesArray; + /** + * Returns the serialized encoding of the EIP-1559 transaction. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize(): Uint8Array; + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage?: boolean): Uint8Array; + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link FeeMarketEIP1559Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash(): Uint8Array; + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature(): Uint8Array; + /** + * Returns the public key of the sender + */ + getSenderPublicKey(): Uint8Array; + _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): FeeMarketEIP1559Transaction; + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON(): JsonTx; + /** + * Return a compact error string representation of the object + */ + errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string): string; +} +//# sourceMappingURL=eip1559Transaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip1559Transaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip1559Transaction.d.ts.map new file mode 100644 index 0000000..afa9211 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip1559Transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eip1559Transaction.d.ts","sourceRoot":"","sources":["../../../src/tx/eip1559Transaction.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAcvD,OAAO,KAAK,EACX,UAAU,EACV,oBAAoB,EACpB,sBAAsB,EACtB,2BAA2B,EAC3B,MAAM,EACN,SAAS,EACT,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAKlD;;;;;GAKG;AAEH,qBAAa,2BAA4B,SAAQ,eAAe,CAAC,2BAA2B,CAAC;IAC5F,SAAgB,OAAO,EAAE,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types/tx/eip2930Transaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip2930Transaction.d.ts new file mode 100644 index 0000000..d38eb97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip2930Transaction.d.ts @@ -0,0 +1,135 @@ +import { BaseTransaction } from './baseTransaction.js'; +import type { AccessList, AccessListUint8Array, AccessListEIP2930TxData, AccessListEIP2930ValuesArray, JsonTx, TxOptions } from './types.js'; +import type { Common } from '../common/common.js'; +/** + * Typed transaction with optional access lists + * + * - TransactionType: 1 + * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) + */ +export declare class AccessListEIP2930Transaction extends BaseTransaction { + readonly chainId: bigint; + readonly accessList: AccessListUint8Array; + readonly AccessListJSON: AccessList; + readonly gasPrice: bigint; + readonly common: Common; + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string; + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData: AccessListEIP2930TxData, opts?: TxOptions): AccessListEIP2930Transaction; + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + */ + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): AccessListEIP2930Transaction; + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + */ + static fromValuesArray(values: AccessListEIP2930ValuesArray, opts?: TxOptions): AccessListEIP2930Transaction; + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData: AccessListEIP2930TxData, opts?: TxOptions); + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost(): bigint; + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-2930 transaction, in order. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + * + * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty UINT8ARRAY values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. + */ + raw(): AccessListEIP2930ValuesArray; + /** + * Returns the serialized encoding of the EIP-2930 transaction. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + serialize(): Uint8Array; + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage?: boolean): Uint8Array; + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash(): Uint8Array; + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature(): Uint8Array; + /** + * Returns the public key of the sender + */ + getSenderPublicKey(): Uint8Array; + _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): AccessListEIP2930Transaction; + /** + * Returns an object with the JSON representation of the transaction + */ + toJSON(): JsonTx; + /** + * Return a compact error string representation of the object + */ + errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string): string; +} +//# sourceMappingURL=eip2930Transaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip2930Transaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip2930Transaction.d.ts.map new file mode 100644 index 0000000..4ed9901 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/eip2930Transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eip2930Transaction.d.ts","sourceRoot":"","sources":["../../../src/tx/eip2930Transaction.ts"],"names":[],"mappings":"AAkCA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EACX,UAAU,EACV,oBAAoB,EACpB,uBAAuB,EACvB,4BAA4B,EAC5B,MAAM,EACN,SAAS,EACT,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAKlD;;;;;GAKG;AAEH,qBAAa,4BAA6B,SAAQ,eAAe,CAAC,4BAA4B,CAAC;IAC9F,SAAgB,OAAO,EAAE,MAAM,CAAC;IAChC,SAAgB,UAAU,EAAE,oBAAoB,CAAC;IACjD,SAAgB,cAAc,EAAE,UAAU,CAAC;IAC3C,SAAgB,QAAQ,EAAE,MAAM,CAAC;IAEjC,SAAgB,MAAM,EAAE,MAAM,CAAC;IAE/B;;;;;OAKG;IACH,SAAS,CAAC,gBAAgB,SAAY;IAEtC;;;;;;;;;OASG;WACW,UAAU,CAAC,MAAM,EAAE,uBAAuB,EAAE,IAAI,GAAE,SAAc;IAI9E;;;;;OAKG;WACW,gBAAgB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,GAAE,SAAc;IAiB3E;;;;;OAKG;WACW,eAAe,CAAC,MAAM,EAAE,4BAA4B,EAAE,IAAI,GAAE,SAAc;IAgCxF;;;;;;OAMG;gBACgB,MAAM,EAAE,uBAAuB,EAAE,IAAI,GAAE,SAAc;IA0CxE;;OAEG;IACI,UAAU,IAAI,MAAM;IAkB3B;;OAEG;IACI,cAAc,IAAI,MAAM;IAI/B;;;;;;;;;;;;OAYG;IACI,GAAG,IAAI,4BAA4B;IAgB1C;;;;;;;;;OASG;IACI,SAAS,IAAI,UAAU;IAK9B;;;;;;;;;;;;OAYG;IACI,gBAAgB,CAAC,WAAW,UAAO,GAAG,UAAU;IASvD;;;;;OAKG;IACI,IAAI,IAAI,UAAU;IAgBzB;;OAEG;IACI,2BAA2B,IAAI,UAAU;IAIhD;;OAEG;IACI,kBAAkB,IAAI,UAAU;IAwBhC,iBAAiB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU;IAqBhE;;OAEG;IACI,MAAM,IAAI,MAAM;IAkBvB;;OAEG;IACI,QAAQ;IAOf;;;;;OAKG;IACH,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM;CAG/B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/index.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/index.d.ts new file mode 100644 index 0000000..c407d43 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/index.d.ts @@ -0,0 +1,8 @@ +export { FeeMarketEIP1559Transaction } from './eip1559Transaction.js'; +export { AccessListEIP2930Transaction } from './eip2930Transaction.js'; +export { Transaction } from './legacyTransaction.js'; +export { TransactionFactory } from './transactionFactory.js'; +export { BaseTransaction } from './baseTransaction.js'; +export * as txUtils from './utils.js'; +export * from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/index.d.ts.map new file mode 100644 index 0000000..658e00e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/tx/index.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AACtC,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/legacyTransaction.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/legacyTransaction.d.ts new file mode 100644 index 0000000..9d17ef4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/legacyTransaction.d.ts @@ -0,0 +1,129 @@ +import { BaseTransaction } from './baseTransaction.js'; +import type { Common } from '../common/common.js'; +import type { JsonTx, TxData, TxOptions, TxValuesArray } from './types.js'; +/** + * An Ethereum non-typed (legacy) transaction + */ +export declare class Transaction extends BaseTransaction { + readonly gasPrice: bigint; + readonly common: Common; + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { nonce, gasPrice, gasLimit, to, value, data, v, r, s } + * + * Notes: + * - All parameters are optional and have some basic default values + */ + static fromTxData(txData: TxData, opts?: TxOptions): Transaction; + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + */ + static fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): Transaction; + /** + * Create a transaction from a values array. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + */ + static fromValuesArray(values: TxValuesArray, opts?: TxOptions): Transaction; + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + constructor(txData: TxData, opts?: TxOptions); + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the legacy transaction, in order. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + * + * For legacy txs this is also the correct format to add transactions + * to a block with {@link Block.fromValuesArray} (use the `serialize()` method + * for typed txs). + * + * For an unsigned tx this method returns the empty Uint8Array values + * for the signature parameters `v`, `r` and `s`. For an EIP-155 compliant + * representation have a look at {@link Transaction.getMessageToSign}. + */ + raw(): TxValuesArray; + /** + * Returns the serialized encoding of the legacy transaction. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link Transaction.getMessageToSign}. + */ + serialize(): Uint8Array; + private _getMessageToSign; + /** + * Returns the unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: the raw message message format for the legacy tx is not RLP encoded + * and you might need to do yourself with: + * + * ```javascript + * import { bufArrToArr } from '../util' + * import { RLP } from '../rlp' + * const message = tx.getMessageToSign(false) + * const serializedMessage = RLP.encode(message) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + getMessageToSign(hashMessage: false): Uint8Array[]; + getMessageToSign(hashMessage?: true): Uint8Array; + /** + * The amount of gas paid for the data in this tx + */ + getDataFee(): bigint; + /** + * The up front amount that an account must have for this transaction to be valid + */ + getUpfrontCost(): bigint; + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + hash(): Uint8Array; + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + getMessageToVerifySignature(): Uint8Array; + /** + * Returns the public key of the sender + */ + getSenderPublicKey(): Uint8Array; + /** + * Process the v, r, s values from the `sign` method of the base transaction. + */ + protected _processSignature(_v: bigint, r: Uint8Array, s: Uint8Array): Transaction; + /** + * Returns an object with the JSON representation of the transaction. + */ + toJSON(): JsonTx; + /** + * Validates tx's `v` value + */ + private _validateTxV; + /** + * Return a compact error string representation of the object + */ + errorStr(): string; + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string): string; +} +//# sourceMappingURL=legacyTransaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/legacyTransaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/legacyTransaction.d.ts.map new file mode 100644 index 0000000..3ea079a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/legacyTransaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"legacyTransaction.d.ts","sourceRoot":"","sources":["../../../src/tx/legacyTransaction.ts"],"names":[],"mappings":"AA8BA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAW3E;;GAEG;AAEH,qBAAa,WAAY,SAAQ,eAAe,CAAC,WAAW,CAAC;IAC5D,SAAgB,QAAQ,EAAE,MAAM,CAAC;IAEjC,SAAgB,MAAM,EAAE,MAAM,CAAC;IAE/B;;;;;;;OAOG;WACW,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc;IAI7D;;;;OAIG;WACW,gBAAgB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,GAAE,SAAc;IAU3E;;;;OAIG;WACW,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,SAAc;IA6BzE;;;;;;OAMG;gBACgB,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc;IAuCvD;;;;;;;;;;;;OAYG;IACI,GAAG,IAAI,aAAa;IAc3B;;;;;;;;OAQG;IACI,SAAS,IAAI,UAAU;IAI9B,OAAO,CAAC,iBAAiB;IAmBzB;;;;;;;;;;;;;;;OAeG;IACI,gBAAgB,CAAC,WAAW,EAAE,KAAK,GAAG,UAAU,EAAE;IAClD,gBAAgB,CAAC,WAAW,CAAC,EAAE,IAAI,GAAG,UAAU;IASvD;;OAEG;IACI,UAAU,IAAI,MAAM;IAe3B;;OAEG;IACI,cAAc,IAAI,MAAM;IAI/B;;;;;OAKG;IACI,IAAI,IAAI,UAAU;IAgBzB;;OAEG;IACI,2BAA2B;IASlC;;OAEG;IACI,kBAAkB,IAAI,UAAU;IAuBvC;;OAEG;IACH,SAAS,CAAC,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU;IAwBpE;;OAEG;IACI,MAAM,IAAI,MAAM;IAcvB;;OAEG;IACH,OAAO,CAAC,YAAY;IA2CpB;;OAEG;IACI,QAAQ;IAMf;;;;;OAKG;IACH,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM;CAG/B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/transactionFactory.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/transactionFactory.d.ts new file mode 100644 index 0000000..9eb6368 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/transactionFactory.d.ts @@ -0,0 +1,34 @@ +import { Numbers } from 'web3-types'; +import type { TypedTransaction } from '../types.js'; +import type { TxData, TxOptions } from './types.js'; +import { BaseTransaction } from './baseTransaction.js'; +export declare class TransactionFactory { + private constructor(); + static typeToInt(txType: Numbers): number; + static registerTransactionType>(type: Numbers, txClass: NewTxTypeClass): void; + /** + * Create a transaction from a `txData` object + * + * @param txData - The transaction data. The `type` field will determine which transaction type is returned (if undefined, creates a legacy transaction) + * @param txOptions - Options to pass on to the constructor of the transaction + */ + static fromTxData(txData: TxData | TypedTransaction, txOptions?: TxOptions): TypedTransaction; + /** + * This method tries to decode serialized data. + * + * @param data - The data Uint8Array + * @param txOptions - The transaction options + */ + static fromSerializedData(data: Uint8Array, txOptions?: TxOptions): TypedTransaction; + /** + * When decoding a BlockBody, in the transactions field, a field is either: + * A Uint8Array (a TypedTransaction - encoded as TransactionType || rlp(TransactionPayload)) + * A Uint8Array[] (Legacy Transaction) + * This method returns the right transaction. + * + * @param data - A Uint8Array or Uint8Array[] + * @param txOptions - The transaction options + */ + static fromBlockBodyData(data: Uint8Array | Uint8Array[], txOptions?: TxOptions): TypedTransaction; +} +//# sourceMappingURL=transactionFactory.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/transactionFactory.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/transactionFactory.d.ts.map new file mode 100644 index 0000000..fabd14a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/transactionFactory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transactionFactory.d.ts","sourceRoot":"","sources":["../../../src/tx/transactionFactory.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAKrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,KAAK,EAGX,MAAM,EACN,SAAS,EACT,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAKvD,qBAAa,kBAAkB;IAG9B,OAAO;WAEO,SAAS,CAAC,MAAM,EAAE,OAAO;WAIzB,uBAAuB,CAAC,cAAc,SAAS,OAAO,eAAe,CAAC,OAAO,CAAC,EAC3F,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,cAAc;IAMxB;;;;;OAKG;WACW,UAAU,CACvB,MAAM,EAAE,MAAM,GAAG,gBAAgB,EACjC,SAAS,GAAE,SAAc,GACvB,gBAAgB;IAgCnB;;;;;OAKG;WACW,kBAAkB,CAC/B,IAAI,EAAE,UAAU,EAChB,SAAS,GAAE,SAAc,GACvB,gBAAgB;IAyBnB;;;;;;;;OAQG;WACW,iBAAiB,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,EAAE,EAAE,SAAS,GAAE,SAAc;CAU1F"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/types.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/types.d.ts new file mode 100644 index 0000000..5e66441 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/types.d.ts @@ -0,0 +1,222 @@ +import type { HexString, Numbers } from 'web3-types'; +import type { Common } from '../common/common.js'; +import type { Uint8ArrayLike, PrefixedHexString } from '../common/types'; +import { Address } from './address.js'; +/** + * Can be used in conjunction with {@link Transaction.supports} + * to query on tx capabilities + */ +export declare enum Capability { + /** + * Tx supports EIP-155 replay protection + * See: [155](https://eips.ethereum.org/EIPS/eip-155) Replay Attack Protection EIP + */ + EIP155ReplayProtection = 155, + /** + * Tx supports EIP-1559 gas fee market mechanism + * See: [1559](https://eips.ethereum.org/EIPS/eip-1559) Fee Market EIP + */ + EIP1559FeeMarket = 1559, + /** + * Tx is a typed transaction as defined in EIP-2718 + * See: [2718](https://eips.ethereum.org/EIPS/eip-2718) Transaction Type EIP + */ + EIP2718TypedTransaction = 2718, + /** + * Tx supports access list generation as defined in EIP-2930 + * See: [2930](https://eips.ethereum.org/EIPS/eip-2930) Access Lists EIP + */ + EIP2930AccessLists = 2930 +} +/** + * The options for initializing a {@link Transaction}. + */ +export interface TxOptions { + /** + * A {@link Common} object defining the chain and hardfork for the transaction. + * + * Object will be internally copied so that tx behavior don't incidentally + * change on future HF changes. + * + * Default: {@link Common} object set to `mainnet` and the default hardfork as defined in the {@link Common} class. + * + * Current default hardfork: `istanbul` + */ + common?: Common; + /** + * A transaction object by default gets frozen along initialization. This gives you + * strong additional security guarantees on the consistency of the tx parameters. + * It also enables tx hash caching when the `hash()` method is called multiple times. + * + * If you need to deactivate the tx freeze - e.g. because you want to subclass tx and + * add additional properties - it is strongly encouraged that you do the freeze yourself + * within your code instead. + * + * Default: true + */ + freeze?: boolean; + /** + * Allows unlimited contract code-size init while debugging. This (partially) disables EIP-3860. + * Gas cost for initcode size analysis will still be charged. Use with caution. + */ + allowUnlimitedInitCodeSize?: boolean; +} +export declare type AccessListItem = { + address: PrefixedHexString; + storageKeys: PrefixedHexString[]; +}; +export declare type AccessListUint8ArrayItem = [Uint8Array, Uint8Array[]]; +export declare type AccessListUint8Array = AccessListUint8ArrayItem[]; +export declare type AccessList = AccessListItem[]; +export declare function isAccessListUint8Array(input: AccessListUint8Array | AccessList): input is AccessListUint8Array; +export declare function isAccessList(input: AccessListUint8Array | AccessList): input is AccessList; +export interface ECDSASignature { + v: bigint; + r: Uint8Array; + s: Uint8Array; +} +/** + * Legacy {@link Transaction} Data + */ +export declare type TxData = { + /** + * The transaction's nonce. + */ + nonce?: Numbers | Uint8Array; + /** + * The transaction's gas price. + */ + gasPrice?: Numbers | Uint8Array | null; + /** + * The transaction's gas limit. + */ + gasLimit?: Numbers | Uint8Array; + /** + * The transaction's the address is sent to. + */ + to?: Address | Uint8Array | HexString; + /** + * The amount of Ether sent. + */ + value?: Numbers | Uint8Array; + /** + * This will contain the data of the message or the init of a contract. + */ + data?: Uint8ArrayLike; + /** + * EC recovery ID. + */ + v?: Numbers | Uint8Array; + /** + * EC signature parameter. + */ + r?: Numbers | Uint8Array; + /** + * EC signature parameter. + */ + s?: Numbers | Uint8Array; + /** + * The transaction type + */ + type?: Numbers; +}; +/** + * {@link AccessListEIP2930Transaction} data. + */ +export interface AccessListEIP2930TxData extends TxData { + /** + * The transaction's chain ID + */ + chainId?: Numbers; + /** + * The access list which contains the addresses/storage slots which the transaction wishes to access + */ + accessList?: AccessListUint8Array | AccessList | null; +} +/** + * {@link FeeMarketEIP1559Transaction} data. + */ +export interface FeeMarketEIP1559TxData extends AccessListEIP2930TxData { + /** + * The transaction's gas price, inherited from {@link Transaction}. This property is not used for EIP1559 + * transactions and should always be undefined for this specific transaction type. + */ + gasPrice?: never | null; + /** + * The maximum inclusion fee per gas (this fee is given to the miner) + */ + maxPriorityFeePerGas?: Numbers | Uint8Array; + /** + * The maximum total fee + */ + maxFeePerGas?: Numbers | Uint8Array; +} +/** + * Uint8Array values array for a legacy {@link Transaction} + */ +export declare type TxValuesArray = Uint8Array[]; +/** + * Uint8Array values array for an {@link AccessListEIP2930Transaction} + */ +export declare type AccessListEIP2930ValuesArray = [ + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + AccessListUint8Array, + Uint8Array?, + Uint8Array?, + Uint8Array? +]; +/** + * Uint8Array values array for a {@link FeeMarketEIP1559Transaction} + */ +export declare type FeeMarketEIP1559ValuesArray = [ + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + AccessListUint8Array, + Uint8Array?, + Uint8Array?, + Uint8Array? +]; +declare type JsonAccessListItem = { + address: string; + storageKeys: string[]; +}; +/** + * Generic interface for all tx types with a + * JSON representation of a transaction. + * + * Note that all values are marked as optional + * and not all the values are present on all tx types + * (an EIP1559 tx e.g. lacks a `gasPrice`). + */ +export interface JsonTx { + nonce?: string; + gasPrice?: string; + gasLimit?: string; + to?: string; + data?: string; + v?: string; + r?: string; + s?: string; + value?: string; + chainId?: string; + accessList?: JsonAccessListItem[]; + type?: string; + maxPriorityFeePerGas?: string; + maxFeePerGas?: string; + maxFeePerDataGas?: string; + versionedHashes?: string[]; +} +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/types.d.ts.map new file mode 100644 index 0000000..ad7d3b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/tx/types.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC;;;GAGG;AACH,oBAAY,UAAU;IACrB;;;OAGG;IACH,sBAAsB,MAAM;IAE5B;;;OAGG;IACH,gBAAgB,OAAO;IAEvB;;;OAGG;IACH,uBAAuB,OAAO;IAE9B;;;OAGG;IACH,kBAAkB,OAAO;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;OAUG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IAEjB;;;OAGG;IACH,0BAA0B,CAAC,EAAE,OAAO,CAAC;CACrC;AAMD,oBAAY,cAAc,GAAG;IAC5B,OAAO,EAAE,iBAAiB,CAAC;IAC3B,WAAW,EAAE,iBAAiB,EAAE,CAAC;CACjC,CAAC;AAKF,oBAAY,wBAAwB,GAAG,CAAC,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;AAClE,oBAAY,oBAAoB,GAAG,wBAAwB,EAAE,CAAC;AAC9D,oBAAY,U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oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/utils.d.ts new file mode 100644 index 0000000..90f9bba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/utils.d.ts @@ -0,0 +1,15 @@ +import { HexString } from 'web3-types'; +import type { AccessList, AccessListUint8Array } from './types.js'; +import type { Common } from '../common/common.js'; +export declare const checkMaxInitCodeSize: (common: Common, length: number) => void; +export declare const getAccessListData: (accessList: AccessListUint8Array | AccessList) => { + AccessListJSON: AccessList; + accessList: AccessListUint8Array; +}; +export declare const verifyAccessList: (accessList: AccessListUint8Array) => void; +export declare const getAccessListJSON: (accessList: AccessListUint8Array) => { + address: HexString; + storageKeys: HexString[]; +}[]; +export declare const getDataFeeEIP2930: (accessList: AccessListUint8Array, common: Common) => number; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/utils.d.ts.map new file mode 100644 index 0000000..0d526b1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/tx/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/tx/utils.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,OAAO,KAAK,EAAE,UAAU,EAAE,oBAAoB,EAAkB,MAAM,YAAY,CAAC;AAGnF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,eAAO,MAAM,oBAAoB,WAAY,MAAM,UAAU,MAAM,SAUlE,CAAC;AAEF,eAAO,MAAM,iBAAiB,eAAgB,oBAAoB,GAAG,UAAU;;;CA4C9E,CAAC;AAEF,eAAO,MAAM,gBAAgB,4CAwB5B,CAAC;AAEF,eAAO,MAAM,iBAAiB,wCAE3B;IACF,OAAO,EAAE,SAAS,CAAC;IACnB,WAAW,EAAE,SAAS,EAAE,CAAC;CACzB,EAoBA,CAAC;AAEF,eAAO,MAAM,iBAAiB,6CAA8C,MAAM,KAAG,MAcpF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/types.d.ts new file mode 100644 index 0000000..daee36b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/types.d.ts @@ -0,0 +1,55 @@ +import { Web3BaseWalletAccount, HexString } from 'web3-types'; +import { FeeMarketEIP1559TxData, AccessListEIP2930TxData, TxData } from './tx/types.js'; +import { AccessListEIP2930Transaction, FeeMarketEIP1559Transaction, Transaction } from './tx'; +export declare type SignatureObject = { + messageHash: string; + r: string; + s: string; + v: string; +}; +export declare type SignTransactionResult = SignatureObject & { + rawTransaction: string; + transactionHash: string; +}; +export declare type SignTransactionFunction = (transaction: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData | Record) => SignTransactionResult; +export declare type SignResult = SignatureObject & { + message?: string; + signature: string; +}; +export declare type SignFunction = (data: string, privateKey: string) => SignResult; +export interface Web3Account extends Web3BaseWalletAccount { + address: HexString; + privateKey: HexString; +} +/** This Web Storage API interface provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items. */ +export interface WebStorage { + /** Returns the number of key/value pairs. */ + readonly length: number; + /** + * Removes all key/value pairs, if there are any. + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + clear(): void; + /** Returns the current value associated with the given key, or null if the given key does not exist. */ + getItem(key: string): string | null; + /** Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs. */ + key(index: number): string | null; + /** + * Removes the key/value pair with the given key, if a key/value pair with the given key exists. + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + removeItem(key: string): void; + /** + * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. + * + * Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + setItem(key: string, value: string): void; + [name: string]: any; +} +export declare type TypedTransaction = Transaction | AccessListEIP2930Transaction | FeeMarketEIP1559Transaction; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/types.d.ts.map new file mode 100644 index 0000000..7fd1550 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACxF,OAAO,EAAE,4BAA4B,EAAE,2BAA2B,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AAE9F,oBAAY,eAAe,GAAG;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACV,CAAC;AAEF,oBAAY,qBAAqB,GAAG,eAAe,GAAG;IACrD,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,oBAAY,uBAAuB,GAAG,CACrC,WAAW,EACR,MAAM,GACN,uBAAuB,GACvB,sBAAsB,GACtB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACtB,qBAAqB,CAAC;AAE3B,oBAAY,UAAU,GAAG,eAAe,GAAG;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,oBAAY,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,UAAU,CAAC;AAI5E,MAAM,WAAW,WAAY,SAAQ,qBAAqB;IACzD,OAAO,EAAE,SAAS,CAAC;IACnB,UAAU,EAAE,SAAS,CAAC;CACtB;AAGD,8LAA8L;AAC9L,MAAM,WAAW,UAAU;IAC1B,6CAA6C;IAC7C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,KAAK,IAAI,IAAI,CAAC;IACd,wGAAwG;IAExG,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IACpC,+GAA+G;IAE/G,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAClC;;;;OAIG;IACH,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B;;;;;;OAMG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1C,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,oBAAY,gBAAgB,GACzB,WAAW,GACX,4BAA4B,GAC5B,2BAA2B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/wallet.d.ts b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/wallet.d.ts new file mode 100644 index 0000000..9a9b6ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/wallet.d.ts @@ -0,0 +1,278 @@ +import { Web3BaseWallet, Web3BaseWalletAccount, KeyStore } from 'web3-types'; +import { WebStorage } from './types.js'; +/** + * Wallet is an in memory `wallet` that can hold multiple accounts. + * These accounts can be used when using web3.eth.sendTransaction(). + * + * ### Parameters + * Web3AccountProvider - AccountProvider for the wallet + * + * ```ts + * import Web3 from 'web3'; + * const web3 = new Web3("https://localhost:8454") + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ +export declare class Wallet extends Web3BaseWallet { + private readonly _addressMap; + private readonly _defaultKeyName; + /** + * Get the storage object of the browser + * + * @returns the storage + */ + static getStorage(): WebStorage | undefined; + /** + * Generates one or more accounts in the wallet. If wallets already exist they will not be overridden. + * + * @param numberOfAccounts - Number of accounts to create. Leave empty to create an empty wallet. + * @returns The wallet + * ```ts + * web3.eth.accounts.wallet.create(2) + * > Wallet(2) [ + * { + * address: '0xde38310a42B751AE57d30cFFF4a0A3c52A442fCE', + * privateKey: '0x6422c9d28efdcbee93c1d32a5fc6fd6fa081b985487885296cf8c9bbb5872600', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * { + * address: '0x766BF755246d924B1d017Fdb5390f38a60166691', + * privateKey: '0x756530f13c0eb636ebdda655335f5dea9921e3362e2e588b0ad59e556f7751f0', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(2) { + * '0xde38310a42b751ae57d30cfff4a0a3c52a442fce' => 0, + * '0x766bf755246d924b1d017fdb5390f38a60166691' => 1 + * }, + * _defaultKeyName: 'web3js_wallet' + * ] + * + * ``` + */ + create(numberOfAccounts: number): this; + /** + * Adds an account using a private key or account object to the wallet. + * + * @param account - A private key or account object + * @returns The wallet + * + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * > Wallet(1) [ + * { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(1) { '0x85d70633b90e03e0276b98880286d0d055685ed7' => 0 }, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + add(account: T | string): this; + /** + * Get the account of the wallet with either the index or public address. + * + * @param addressOrIndex - A string of the address or number index within the wallet. + * @returns The account object or undefined if the account doesn't exist + */ + get(addressOrIndex: string | number): T | undefined; + /** + * Removes an account from the wallet. + * + * @param addressOrIndex - The account address, or index in the wallet. + * @returns true if the wallet was removed. false if it couldn't be found. + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * + * web3.eth.accounts.wallet.remove('0x85D70633b90e03e0276B98880286D0D055685ed7'); + * > true + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + remove(addressOrIndex: string | number): boolean; + /** + * Securely empties the wallet and removes all its accounts. + * Use this with *caution as it will remove all accounts stored in local wallet. + * + * @returns The wallet object + * ```ts + * + * web3.eth.accounts.wallet.clear(); + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + clear(): this; + /** + * Encrypts all wallet accounts to an array of encrypted keystore v3 objects. + * + * @param password - The password which will be used for encryption + * @param options - encryption options + * @returns An array of the encrypted keystore v3. + * + * ```ts + * web3.eth.accounts.wallet.create(1) + * web3.eth.accounts.wallet.encrypt("abc").then(console.log); + * > [ + * '{"version":3,"id":"fa46e213-a7c3-4844-b903-dd14d39cc7db", + * "address":"fa3e41a401609103c241431cbdee8623ae2a321a","crypto": + * {"ciphertext":"8d179a911d6146ad2924e86bf493ed89b8ff3596ffec0816e761c542016ab13c", + * "cipherparams":{"iv":"acc888c6cf4a19b86846cef0185a7164"},"cipher":"aes-128-ctr", + * "kdf":"scrypt","kdfparams":{"n":8192,"r":8,"p":1,"dklen":32,"salt":"6a743c9b367d15f4758e4f3f3378ff0fd443708d1c64854e07588ea5331823ae"}, + * "mac":"410544c8307e3691fda305eb3722d82c3431f212a87daa119a21587d96698b57"}}' + * ] + * ``` + */ + encrypt(password: string, options?: Record | undefined): Promise; + /** + * Decrypts keystore v3 objects. + * + * @param encryptedWallets - An array of encrypted keystore v3 objects to decrypt + * @param password - The password to encrypt with + * @param options - decrypt options for the wallets + * @returns The decrypted wallet object + * + * ```ts + * web3.eth.accounts.wallet.decrypt([ + * { version: 3, + * id: '83191a81-aaca-451f-b63d-0c5f3b849289', + * address: '06f702337909c06c82b09b7a22f0a2f0855d1f68', + * crypto: + * { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d', + * cipherparams: { iv: '497f4d26997a84d570778eae874b2333' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } }, + * { version: 3, + * id: '7d6b91fa-3611-407b-b16b-396efb28f97e', + * address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf', + * crypto: + * { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43', + * cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } } + * ], 'test').then(console.log) + * > Wallet { + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _defaultKeyName: 'web3js_wallet', + * _accounts: { + * '0x85d70633b90e03e0276b98880286d0d055685ed7': { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0x06f702337909c06c82b09b7a22f0a2f0855d1f68': { + * address: '0x06F702337909C06C82B09B7A22F0a2f0855d1F68', + * privateKey: '87a51da18900da7398b3bab03996833138f269f8f66dd1237b98df6b9ce14573', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0xb5d89661b59a9af0b34f58d19138baa2de48baaf': { + * address: '0xB5d89661B59a9aF0b34f58D19138bAa2de48BAaf', + * privateKey: '7ee61c5282979aae9dd795bb6a54e8bdc2bfe009acb64eb9a67322eec3b3da6e', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * } + * } + * } + * ``` + */ + decrypt(encryptedWallets: KeyStore[], password: string, options?: Record | undefined): Promise; + /** + * Stores the wallet encrypted and as string in local storage. + * **__NOTE:__** Browser only + * + * @param password - The password to encrypt the wallet + * @param keyName - (optional) The key used for the local storage position, defaults to `"web3js_wallet"`. + * @returns Will return boolean value true if saved properly + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * >true + * ``` + */ + save(password: string, keyName?: string): Promise; + /** + * Loads a wallet from local storage and decrypts it. + * **__NOTE:__** Browser only + * + * @param password - The password to decrypt the wallet. + * @param keyName - (optional)The key used for local storage position, defaults to `web3js_wallet"` + * @returns Returns the wallet object + * + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * > true + * web3.eth.accounts.wallet.load('test#!$'); + * { defaultKeyName: "web3js_wallet", + * length: 0, + * _accounts: Accounts {_requestManager: RequestManager, givenProvider: Proxy, providers: {…}, _provider: WebsocketProvider, …}, + * [[Prototype]]: Object + * } + * ``` + */ + load(password: string, keyName?: string): Promise; +} +//# sourceMappingURL=wallet.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/wallet.d.ts.map b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/wallet.d.ts.map new file mode 100644 index 0000000..403aad3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/lib/types/wallet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["../../src/wallet.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE7E,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAIxC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,MAAM,CAClB,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,CACtD,SAAQ,cAAc,CAAC,CAAC,CAAC;IAC1B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA6B;IACzD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAmB;IAEnD;;;;OAIG;WACW,UAAU,IAAI,UAAU,GAAG,SAAS;IA4BlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IAEI,MAAM,CAAC,gBAAgB,EAAE,MAAM;IAQtC;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACI,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,MAAM,GAAG,IAAI;IAerC;;;;;OAKG;IAEI,GAAG,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,GAAG,CAAC,GAAG,SAAS;IAc1D;;;;;;;;;;;;;;;;;;;;;OAqBG;IACI,MAAM,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO;IAoBvD;;;;;;;;;;;;;;;;;;OAkBG;IACI,KAAK;IASZ;;;;;;;;;;;;;;;;;;;OAmBG;IACU,OAAO,CACnB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GAC3C,OAAO,CAAC,QAAQ,EAAE,CAAC;IAItB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAyEG;IACU,OAAO,CACnB,gBAAgB,EAAE,QAAQ,EAAE,EAC5B,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS;IAa9C;;;;;;;;;;;OAWG;IACU,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;IAepD;;;;;;;;;;;;;;;;;;OAkBG;IACU,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;CAepD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/node_modules/.bin/crc32 b/test/merkletreejs/node_modules/web3-eth-accounts/node_modules/.bin/crc32 new file mode 120000 index 0000000..aa1fc22 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/node_modules/.bin/crc32 @@ -0,0 +1 @@ +../../../crc-32/bin/crc32.njs \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/node_modules/.bin/rlp b/test/merkletreejs/node_modules/web3-eth-accounts/node_modules/.bin/rlp new file mode 120000 index 0000000..a260f56 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/node_modules/.bin/rlp @@ -0,0 +1 @@ +../../../@ethereumjs/rlp/bin/rlp \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/package.json b/test/merkletreejs/node_modules/web3-eth-accounts/package.json new file mode 100644 index 0000000..2694b73 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/package.json @@ -0,0 +1,70 @@ +{ + "name": "web3-eth-accounts", + "version": "4.1.0", + "description": "Package for managing Ethereum accounts and signing", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "jest-when": "^3.5.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4", + "web3-providers-ipc": "^4.0.7" + }, + "dependencies": { + "@ethereumjs/rlp": "^4.0.1", + "crc-32": "^1.2.2", + "ethereum-cryptography": "^2.0.0", + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "web3-validator": "^2.0.3" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/account.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/account.ts new file mode 100644 index 0000000..793f1f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/account.ts @@ -0,0 +1,742 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + decrypt as createDecipheriv, + encrypt as createCipheriv, +} from 'ethereum-cryptography/aes.js'; +import { pbkdf2Sync } from 'ethereum-cryptography/pbkdf2.js'; +import { scryptSync } from 'ethereum-cryptography/scrypt.js'; +import { + InvalidKdfError, + InvalidPasswordError, + InvalidPrivateKeyError, + InvalidSignatureError, + IVLengthError, + KeyDerivationError, + KeyStoreVersionError, + PBKDF2IterationsError, + PrivateKeyLengthError, + TransactionSigningError, + UndefinedRawTransactionError, +} from 'web3-errors'; +import { + Address, + Bytes, + CipherOptions, + HexString, + KeyStore, + PBKDF2SHA256Params, + ScryptParams, + Transaction, +} from 'web3-types'; +import { + bytesToUint8Array, + bytesToHex, + fromUtf8, + hexToBytes, + numberToHex, + randomBytes, + sha3Raw, + toChecksumAddress, + uint8ArrayConcat, + utf8ToHex, + uuidV4, +} from 'web3-utils'; + +import { isHexStrict, isNullish, isString, validator } from 'web3-validator'; +import { secp256k1 } from './tx/constants.js'; +import { keyStoreSchema } from './schemas.js'; +import { TransactionFactory } from './tx/transactionFactory.js'; +import type { + SignatureObject, + SignTransactionResult, + TypedTransaction, + Web3Account, + SignResult, +} from './types.js'; + +/** + * Get the private key Uint8Array after the validation + */ +export const parseAndValidatePrivateKey = (data: Bytes, ignoreLength?: boolean): Uint8Array => { + let privateKeyUint8Array: Uint8Array; + + // To avoid the case of 1 character less in a hex string which is prefixed with '0' by using 'bytesToUint8Array' + if (!ignoreLength && typeof data === 'string' && isHexStrict(data) && data.length !== 66) { + throw new PrivateKeyLengthError(); + } + + try { + privateKeyUint8Array = data instanceof Uint8Array ? data : bytesToUint8Array(data); + } catch { + throw new InvalidPrivateKeyError(); + } + + if (!ignoreLength && privateKeyUint8Array.byteLength !== 32) { + throw new PrivateKeyLengthError(); + } + + return privateKeyUint8Array; +}; + +/** + * + * Hashes the given message. The data will be UTF-8 HEX decoded and enveloped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message and hashed using keccak256. + * + * @param message - A message to hash, if its HEX it will be UTF8 decoded. + * @returns The hashed message + * + * ```ts + * hashMessage("Hello world") + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * hashMessage(utf8ToHex("Hello world")) // Will be hex decoded in hashMessage + * > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede" + * ``` + */ +export const hashMessage = (message: string): string => { + const messageHex = isHexStrict(message) ? message : utf8ToHex(message); + + const messageBytes = hexToBytes(messageHex); + + const preamble = hexToBytes( + fromUtf8(`\x19Ethereum Signed Message:\n${messageBytes.byteLength}`), + ); + + const ethMessage = uint8ArrayConcat(preamble, messageBytes); + + return sha3Raw(ethMessage); // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different +}; + +/** + * Signs arbitrary data with a given private key. + * **_NOTE:_** The value passed as the data parameter will be UTF-8 HEX decoded and wrapped as follows: "\\x19Ethereum Signed Message:\\n" + message.length + message + * + * @param data - The data to sign + * @param privateKey - The 32 byte private key to sign with + * @returns The signature Object containing the message, messageHash, signature r, s, v + * + * ```ts + * web3.eth.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318') + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1c', + * r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', + * s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029', + * signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c' + * } + * ``` + */ +export const sign = (data: string, privateKey: Bytes): SignResult => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + + const hash = hashMessage(data); + + const signature = secp256k1.sign(hash.substring(2), privateKeyUint8Array); + const signatureBytes = signature.toCompactRawBytes(); + const r = signature.r.toString(16).padStart(64, '0'); + const s = signature.s.toString(16).padStart(64, '0'); + const v = signature.recovery! + 27; + + return { + message: data, + messageHash: hash, + v: numberToHex(v), + r: `0x${r}`, + s: `0x${s}`, + signature: `${bytesToHex(signatureBytes)}${v.toString(16)}`, + }; +}; + +/** + * Signs an Ethereum transaction with a given private key. + * + * @param transaction - The transaction, must be a legacy, EIP2930 or EIP 1559 transaction type + * @param privateKey - The private key to import. This is 32 bytes of random data. + * @returns A signTransactionResult object that contains message hash, r, s, v, transaction hash and raw transaction. + * + * This function is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * This function will rely on user to provide the full transaction to be signed. If you want to sign a partial transaction object + * Use {@link Web3.eth.accounts.sign} instead. + * + * Signing a legacy transaction + * ```ts + * signTransaction({ + * to: '0x118C2E5F57FD62C2B5b46a5ae9216F4FF4011a07', + * value: '0x186A0', + * gasLimit: '0x520812', + * gasPrice: '0x09184e72a000', + * data: '', + * chainId: 1, + * nonce: 0, + * }, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')) + * } + * > { + * messageHash: '0x28b7b75f7ba48d588a902c1ff4d5d13cc0ca9ac0aaa39562368146923fb853bf', + * v: '0x25', + * r: '0x601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5', + * s: '0x690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * rawTransaction: '0xf869808609184e72a0008352081294118c2e5f57fd62c2b5b46a5ae9216f4ff4011a07830186a08025a00601b0017b0e20dd0eeda4b895fbc1a9e8968990953482214f880bae593e71b5a0690d984493560552e3ebdcc19a65b9c301ea9ddc82d3ab8cfde60485fd5722ce', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * ``` + * Signing an eip 1559 transaction + * ```ts + * signTransaction({ + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * maxPriorityFeePerGas: '0x3B9ACA00', + * maxFeePerGas: '0xB2D05E00', + * gasLimit: '0x6A4012', + * value: '0x186A0', + * data: '', + * chainId: 1, + * nonce: 0, + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0x5744f24d5f0aff6c70487c8e85adf07d8564e50b08558788f00479611d7bae5f', + * v: '0x25', + * r: '0x78a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347', + * s: '0x9cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * rawTransaction: '0xf8638080836a401294f0109fc8df283027b6285cc889f5aa624eac1f55830186a08025a078a5a6b2876c3985f90f82073d18d57ac299b608cc76a4ba697b8bb085048347a009cfcb40cc7d505ed17ff2d3337b51b066648f10c6b7e746117de69b2eb6358d', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + * Signing an eip 2930 transaction + * ```ts + * signTransaction({ + * chainId: 1, + * nonce: 0, + * gasPrice: '0x09184e72a000', + * gasLimit: '0x2710321', + * to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', + * value: '0x186A0', + * data: '', + * accessList: [ + * { + * address: '0x0000000000000000000000000000000000000101', + * storageKeys: [ + * '0x0000000000000000000000000000000000000000000000000000000000000000', + * '0x00000000000000000000000000000000000000000000000000000000000060a7', + * ], + * }, + * ], + * },"0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318") + * > { + * messageHash: '0xc55ea24bdb4c379550a7c9a6818ac39ca33e75bc78ddb862bd82c31cc1c7a073', + * v: '0x26', + * r: '0x27344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098e', + * s: '0x519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * rawTransaction: '0xf86a808609184e72a000840271032194f0109fc8df283027b6285cc889f5aa624eac1f55830186a08026a027344e77871c8b2068bc998bf28e0b5f9920867a69c455b2ed0c1c150fec098ea0519f0130a1d662841d4a28082e9c9bb0a15e0e59bb46cfc39a52f0e285dec6b9', + * transactionHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + * } + * ``` + */ +export const signTransaction = async ( + transaction: TypedTransaction, + privateKey: HexString, + // To make it compatible with rest of the API, have to keep it async + // eslint-disable-next-line @typescript-eslint/require-await +): Promise => { + const signedTx = transaction.sign(hexToBytes(privateKey)); + if (isNullish(signedTx.v) || isNullish(signedTx.r) || isNullish(signedTx.s)) + throw new TransactionSigningError('Signer Error'); + + const validationErrors = signedTx.validate(true); + + if (validationErrors.length > 0) { + let errorString = 'Signer Error '; + for (const validationError of validationErrors) { + errorString += `${errorString} ${validationError}.`; + } + throw new TransactionSigningError(errorString); + } + + const rawTx = bytesToHex(signedTx.serialize()); + const txHash = sha3Raw(rawTx); // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different + + return { + messageHash: bytesToHex(signedTx.getMessageToSign(true)), + v: `0x${signedTx.v.toString(16)}`, + r: `0x${signedTx.r.toString(16).padStart(64, '0')}`, + s: `0x${signedTx.s.toString(16).padStart(64, '0')}`, + rawTransaction: rawTx, + transactionHash: bytesToHex(txHash), + }; +}; + +/** + * Recovers the Ethereum address which was used to sign the given RLP encoded transaction. + * + * @param rawTransaction - The hex string having RLP encoded transaction + * @returns The Ethereum address used to sign this transaction + * ```ts + * recoverTransaction('0xf869808504e3b29200831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a0c9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895a0727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68'); + * > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23" + * ``` + */ +export const recoverTransaction = (rawTransaction: HexString): Address => { + if (isNullish(rawTransaction)) throw new UndefinedRawTransactionError(); + + const tx = TransactionFactory.fromSerializedData(hexToBytes(rawTransaction)); + + return toChecksumAddress(tx.getSenderAddress().toString()); +}; + +/** + * Recovers the Ethereum address which was used to sign the given data + * + * @param data - Either a signed message, hash, or the {@link signatureObject} + * @param signature - The raw RLP encoded signature + * @param signatureOrV - signatureOrV + * @param prefixedOrR - prefixedOrR + * @param s - s + * @param prefixed - (default: false) If the last parameter is true, the given message will NOT automatically be prefixed with "\\x19Ethereum Signed Message:\\n" + message.length + message, and assumed to be already prefixed. + * @returns The Ethereum address used to sign this data + * ```ts + * sign('Some data', '0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728'); + * > { + * message: 'Some data', + * messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655', + * v: '0x1b', + * r: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f9', + * s: '0x53e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb150', + * signature: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b' + * } + * recover('0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f953e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb1501b'); + * > '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0' + * ``` + */ +export const recover = ( + data: string | SignatureObject, + signatureOrV?: string, + prefixedOrR?: boolean | string, + s?: string, + prefixed?: boolean, +): Address => { + if (typeof data === 'object') { + const signatureStr = `${data.r}${data.s.slice(2)}${data.v.slice(2)}`; + return recover(data.messageHash, signatureStr, prefixedOrR); + } + if (typeof signatureOrV === 'string' && typeof prefixedOrR === 'string' && !isNullish(s)) { + const signatureStr = `${prefixedOrR}${s.slice(2)}${signatureOrV.slice(2)}`; + return recover(data, signatureStr, prefixed); + } + + if (isNullish(signatureOrV)) throw new InvalidSignatureError('signature string undefined'); + + const V_INDEX = 130; // r = first 32 bytes, s = second 32 bytes, v = last byte of signature + const hashedMessage = prefixedOrR ? data : hashMessage(data); + + let v = parseInt(signatureOrV.substring(V_INDEX),16); // 0x + r + s + v + if (v > 26) { + v -= 27; + } + + const ecPublicKey = secp256k1.Signature.fromCompact(signatureOrV.slice(2, V_INDEX)) + .addRecoveryBit(v) + .recoverPublicKey(hashedMessage.replace('0x', '')) + .toRawBytes(false); + + const publicHash = sha3Raw(ecPublicKey.subarray(1)); + + const address = toChecksumAddress(`0x${publicHash.slice(-40)}`); + + return address; +}; + +/** + * Get the ethereum Address from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns The Ethereum address + * @example + * ```ts + * privateKeyToAddress("0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728") + * > "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0" + * ``` + */ +export const privateKeyToAddress = (privateKey: Bytes): string => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + + // Get public key from private key in compressed format + const publicKey = secp256k1.getPublicKey(privateKeyUint8Array, false); + + // Uncompressed ECDSA public key contains the prefix `0x04` which is not used in the Ethereum public key + const publicKeyHash = sha3Raw(publicKey.slice(1)); + + // The hash is returned as 256 bits (32 bytes) or 64 hex characters + // To get the address, take the last 20 bytes of the public hash + const address = publicKeyHash.slice(-40); + + return toChecksumAddress(`0x${address}`); +}; + +/** + * Get the public key from a private key + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param isCompressed - if true, will generate a 33 byte compressed public key instead of a 65 byte public key + * @returns The public key + * @example + * ```ts + * privateKeyToAddress("0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", true) + * > "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a" // uncompressed public key + * ``` + */ + export const privateKeyToPublicKey = (privateKey: Bytes, isCompressed: boolean): string => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + + // Get public key from private key in compressed format + return `0x${bytesToHex(secp256k1.getPublicKey(privateKeyUint8Array, isCompressed)).slice(4)}`; // 0x and removing compression byte +}; + +/** + * encrypt a private key with a password, returns a V3 JSON Keystore + * + * Read more: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + * + * @param privateKey - The private key to encrypt, 32 bytes. + * @param password - The password used for encryption. + * @param options - Options to configure to encrypt the keystore either scrypt or pbkdf2 + * @returns Returns a V3 JSON Keystore + * + * + * Encrypt using scrypt options + * ```ts + * encrypt('0x67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * '123', + * { + * n: 8192, + * iv: web3.utils.hexToBytes('0xbfb43120ae00e9de110f8325143a2709'), + * salt: web3.utils.hexToBytes('0x210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'), + * ), + * }).then(console.log) + * > { + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + *} + *``` + * Encrypting using pbkdf2 options + * ```ts + * encrypt('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + *'123', + *{ + * iv: 'bfb43120ae00e9de110f8325143a2709', + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * kdf: 'pbkdf2', + *}).then(console.log) + * > + * { + * version: 3, + * id: '77381417-0973-4e4b-b590-8eb3ace0fe2d', + * address: 'b8ce9ab6943e0eced004cde8e3bbed6568b2fa01', + * crypto: { + * ciphertext: '76512156a34105fa6473ad040c666ae7b917d14c06543accc0d2dc28e6073b12', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'pbkdf2', + * kdfparams: { + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd', + * c: 262144, + * prf: 'hmac-sha256' + * }, + * mac: '46eb4884e82dc43b5aa415faba53cc653b7038e9d61cc32fd643cf8c396189b7' + * } + * } + *``` + */ +export const encrypt = async ( + privateKey: Bytes, + password: string | Uint8Array, + options?: CipherOptions, +): Promise => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey); + + // if given salt or iv is a string, convert it to a Uint8Array + let salt; + if (options?.salt) { + salt = typeof options.salt === 'string' ? hexToBytes(options.salt) : options.salt; + } else { + salt = randomBytes(32); + } + + if (!(isString(password) || password instanceof Uint8Array)) { + throw new InvalidPasswordError(); + } + + const uint8ArrayPassword = + typeof password === 'string' ? hexToBytes(utf8ToHex(password)) : password; + + let initializationVector; + if (options?.iv) { + initializationVector = typeof options.iv === 'string' ? hexToBytes(options.iv) : options.iv; + if (initializationVector.length !== 16) { + throw new IVLengthError(); + } + } else { + initializationVector = randomBytes(16); + } + + const kdf = options?.kdf ?? 'scrypt'; + + let derivedKey; + let kdfparams: ScryptParams | PBKDF2SHA256Params; + + // derive key from key derivation function + if (kdf === 'pbkdf2') { + kdfparams = { + dklen: options?.dklen ?? 32, + salt: bytesToHex(salt).replace('0x', ''), + c: options?.c ?? 262144, + prf: 'hmac-sha256', + }; + + if (kdfparams.c < 1000) { + // error when c < 1000, pbkdf2 is less secure with less iterations + throw new PBKDF2IterationsError(); + } + derivedKey = pbkdf2Sync(uint8ArrayPassword, salt, kdfparams.c, kdfparams.dklen, 'sha256'); + } else if (kdf === 'scrypt') { + kdfparams = { + n: options?.n ?? 8192, + r: options?.r ?? 8, + p: options?.p ?? 1, + dklen: options?.dklen ?? 32, + salt: bytesToHex(salt).replace('0x', ''), + }; + derivedKey = scryptSync( + uint8ArrayPassword, + salt, + kdfparams.n, + kdfparams.p, + kdfparams.r, + kdfparams.dklen, + ); + } else { + throw new InvalidKdfError(); + } + + const cipher = await createCipheriv( + privateKeyUint8Array, + derivedKey.slice(0, 16), + initializationVector, + 'aes-128-ctr', + ); + + const ciphertext = bytesToHex(cipher).slice(2); + + const mac = sha3Raw(uint8ArrayConcat(derivedKey.slice(16, 32), cipher)).replace('0x', ''); + return { + version: 3, + id: uuidV4(), + address: privateKeyToAddress(privateKeyUint8Array).toLowerCase().replace('0x', ''), + crypto: { + ciphertext, + cipherparams: { + iv: bytesToHex(initializationVector).replace('0x', ''), + }, + cipher: 'aes-128-ctr', + kdf, + kdfparams, + mac, + }, + }; +}; + +/** + * Get an Account object from the privateKey + * + * @param privateKey - String or Uint8Array of 32 bytes + * @param ignoreLength - if true, will not error check length + * @returns A Web3Account object + * + * The `Web3Account.signTransaction` is not stateful here. We need network access to get the account `nonce` and `chainId` to sign the transaction. + * Use {@link Web3.eth.accounts.signTransaction} instead. + * + * ```ts + * privateKeyToAccount("0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709"); + * > { + * address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01', + * privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', + * sign, + * signTransaction, + * encrypt, + * } + * ``` + */ +export const privateKeyToAccount = (privateKey: Bytes, ignoreLength?: boolean): Web3Account => { + const privateKeyUint8Array = parseAndValidatePrivateKey(privateKey, ignoreLength); + + return { + address: privateKeyToAddress(privateKeyUint8Array), + privateKey: bytesToHex(privateKeyUint8Array), + // eslint-disable-next-line @typescript-eslint/no-unused-vars + signTransaction: (_tx: Transaction) => { + throw new TransactionSigningError('Do not have network access to sign the transaction'); + }, + sign: (data: Record | string) => + sign(typeof data === 'string' ? data : JSON.stringify(data), privateKeyUint8Array), + encrypt: async (password: string, options?: Record) => + encrypt(privateKeyUint8Array, password, options), + }; +}; + +/** + * + * Generates and returns a Web3Account object that includes the private and public key + * For creation of private key, it uses an audited package ethereum-cryptography/secp256k1 + * that is cryptographically secure random number with certain characteristics. + * Read more: https://www.npmjs.com/package/ethereum-cryptography#secp256k1-curve + * + * @returns A Web3Account object + * ```ts + * web3.eth.accounts.create(); + * { + * address: '0xbD504f977021b5E5DdccD8741A368b147B3B38bB', + * privateKey: '0x964ced1c69ad27a311c432fdc0d8211e987595f7eb34ab405a5f16bdc9563ec5', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export const create = (): Web3Account => { + const privateKey = secp256k1.utils.randomPrivateKey(); + + return privateKeyToAccount(`${bytesToHex(privateKey)}`); +}; + +/** + * Decrypts a v3 keystore JSON, and creates the account. + * + * @param keystore - the encrypted Keystore object or string to decrypt + * @param password - The password that was used for encryption + * @param nonStrict - if true and given a json string, the keystore will be parsed as lowercase. + * @returns Returns the decrypted Web3Account object + * Decrypting scrypt + * + * ```ts + * decrypt({ + * version: 3, + * id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a', + * address: 'cda9a91875fc35c8ac1320e098e584495d66e47c', + * crypto: { + * ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f', + * cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: { + * n: 8192, + * r: 8, + * p: 1, + * dklen: 32, + * salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd' + * }, + * mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd' + * } + * }, '123').then(console.log) + * > { + * address: '0xcdA9A91875fc35c8Ac1320E098e584495d66e47c', + * privateKey: '67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [AsyncFunction: encrypt] + * } + * ``` + */ +export const decrypt = async ( + keystore: KeyStore | string, + password: string | Uint8Array, + nonStrict?: boolean, +): Promise => { + const json = + typeof keystore === 'object' + ? keystore + : (JSON.parse(nonStrict ? keystore.toLowerCase() : keystore) as KeyStore); + + validator.validateJSONSchema(keyStoreSchema, json); + + if (json.version !== 3) throw new KeyStoreVersionError(); + + const uint8ArrayPassword = + typeof password === 'string' ? hexToBytes(utf8ToHex(password)) : password; + + validator.validate(['bytes'], [uint8ArrayPassword]); + + let derivedKey; + if (json.crypto.kdf === 'scrypt') { + const kdfparams = json.crypto.kdfparams as ScryptParams; + const uint8ArraySalt = + typeof kdfparams.salt === 'string' ? hexToBytes(kdfparams.salt) : kdfparams.salt; + derivedKey = scryptSync( + uint8ArrayPassword, + uint8ArraySalt, + kdfparams.n, + kdfparams.p, + kdfparams.r, + kdfparams.dklen, + ); + } else if (json.crypto.kdf === 'pbkdf2') { + const kdfparams: PBKDF2SHA256Params = json.crypto.kdfparams as PBKDF2SHA256Params; + + const uint8ArraySalt = + typeof kdfparams.salt === 'string' ? hexToBytes(kdfparams.salt) : kdfparams.salt; + + derivedKey = pbkdf2Sync( + uint8ArrayPassword, + uint8ArraySalt, + kdfparams.c, + kdfparams.dklen, + 'sha256', + ); + } else { + throw new InvalidKdfError(); + } + + const ciphertext = hexToBytes(json.crypto.ciphertext); + const mac = sha3Raw(uint8ArrayConcat(derivedKey.slice(16, 32), ciphertext)).replace('0x', ''); + + if (mac !== json.crypto.mac) { + throw new KeyDerivationError(); + } + + const seed = await createDecipheriv( + hexToBytes(json.crypto.ciphertext), + derivedKey.slice(0, 16), + hexToBytes(json.crypto.cipherparams.iv), + ); + + return privateKeyToAccount(seed); +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/goerli.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/goerli.ts new file mode 100644 index 0000000..d09be79 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/goerli.ts @@ -0,0 +1,97 @@ +export default { + "name": "goerli", + "chainId": 5, + "networkId": 5, + "defaultHardfork": "merge", + "consensus": { + "type": "poa", + "algorithm": "clique", + "clique": { + "period": 15, + "epoch": 30000 + } + }, + "comment": "Cross-client PoA test network", + "url": "https://github.com/goerli/testnet", + "genesis": { + "timestamp": "0x5c51a607", + "gasLimit": 10485760, + "difficulty": 1, + "nonce": "0x0000000000000000", + "extraData": "0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "homestead", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "tangerineWhistle", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "spuriousDragon", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "byzantium", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "constantinople", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "petersburg", + "block": 0, + "forkHash": "0xa3f5ab08" + }, + { + "name": "istanbul", + "block": 1561651, + "forkHash": "0xc25efa5c" + }, + { + "name": "berlin", + "block": 4460644, + "forkHash": "0x757a1c47" + }, + { + "name": "london", + "block": 5062605, + "forkHash": "0xb8c6299d" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://goerli.etherscan.io/block/7382818", + "name": "merge", + "ttd": "10790000", + "block": 7382819, + "forkHash": "0xb8c6299d" + }, + { + "name": "mergeForkIdTransition", + "block": null, + "forkHash": null + }, + { + "name": "shanghai", + "block": null, + "forkHash": null + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.goerli.ethdisco.net" + ] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/mainnet.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/mainnet.ts new file mode 100644 index 0000000..d18bc73 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/mainnet.ts @@ -0,0 +1,113 @@ +export default { + "name": "mainnet", + "chainId": 1, + "networkId": 1, + "defaultHardfork": "merge", + "consensus": { + "type": "pow", + "algorithm": "ethash", + "ethash": {} + }, + "comment": "The Ethereum main chain", + "url": "https://ethstats.net/", + "genesis": { + "gasLimit": 5000, + "difficulty": 17179869184, + "nonce": "0x0000000000000042", + "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xfc64ec04" + }, + { + "name": "homestead", + "block": 1150000, + "forkHash": "0x97c2c34c" + }, + { + "name": "dao", + "block": 1920000, + "forkHash": "0x91d1f948" + }, + { + "name": "tangerineWhistle", + "block": 2463000, + "forkHash": "0x7a64da13" + }, + { + "name": "spuriousDragon", + "block": 2675000, + "forkHash": "0x3edd5b10" + }, + { + "name": "byzantium", + "block": 4370000, + "forkHash": "0xa00bc324" + }, + { + "name": "constantinople", + "block": 7280000, + "forkHash": "0x668db0af" + }, + { + "name": "petersburg", + "block": 7280000, + "forkHash": "0x668db0af" + }, + { + "name": "istanbul", + "block": 9069000, + "forkHash": "0x879d6e30" + }, + { + "name": "muirGlacier", + "block": 9200000, + "forkHash": "0xe029e991" + }, + { + "name": "berlin", + "block": 12244000, + "forkHash": "0x0eb440f6" + }, + { + "name": "london", + "block": 12965000, + "forkHash": "0xb715077d" + }, + { + "name": "arrowGlacier", + "block": 13773000, + "forkHash": "0x20c327fc" + }, + { + "name": "grayGlacier", + "block": 15050000, + "forkHash": "0xf0afd0e3" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://etherscan.io/block/15537393", + "name": "merge", + "ttd": "58750000000000000000000", + "block": 15537394, + "forkHash": "0xf0afd0e3" + }, + { + "name": "mergeForkIdTransition", + "block": null, + "forkHash": null + }, + { + "name": "shanghai", + "block": null, + "forkHash": null + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.mainnet.ethdisco.net" + ] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/sepolia.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/sepolia.ts new file mode 100644 index 0000000..1de20e4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/chains/sepolia.ts @@ -0,0 +1,100 @@ +export default { + "name": "sepolia", + "chainId": 11155111, + "networkId": 11155111, + "defaultHardfork": "merge", + "consensus": { + "type": "pow", + "algorithm": "ethash", + "ethash": {} + }, + "comment": "PoW test network to replace Ropsten", + "url": "https://github.com/ethereum/go-ethereum/pull/23730", + "genesis": { + "timestamp": "0x6159af19", + "gasLimit": 30000000, + "difficulty": 131072, + "nonce": "0x0000000000000000", + "extraData": "0x5365706f6c69612c20417468656e732c204174746963612c2047726565636521" + }, + "hardforks": [ + { + "name": "chainstart", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "homestead", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "tangerineWhistle", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "spuriousDragon", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "byzantium", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "constantinople", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "petersburg", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "istanbul", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "muirGlacier", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "berlin", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "name": "london", + "block": 0, + "forkHash": "0xfe3366e7" + }, + { + "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://sepolia.etherscan.io/block/1450408", + "name": "merge", + "ttd": "17000000000000000", + "block": 1450409, + "forkHash": "0xfe3366e7" + }, + { + "name": "mergeForkIdTransition", + "block": 1735371, + "forkHash": "0xb96cbd13" + }, + { + "name": "shanghai", + "block": null, + "timestamp": "1677557088", + "forkHash": "0xf7f9bc08" + } + ], + "bootstrapNodes": [], + "dnsNetworks": [ + "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.sepolia.ethdisco.net" + ] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/common.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/common.ts new file mode 100644 index 0000000..e941338 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/common.ts @@ -0,0 +1,1207 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import pkg from 'crc-32'; +import { EventEmitter, bytesToHex, hexToBytes, uint8ArrayConcat } from 'web3-utils'; +import type { Numbers } from 'web3-types'; +import { TypeOutput } from './types.js'; +import { intToUint8Array, toType, parseGethGenesis } from './utils.js'; +import goerli from './chains/goerli.js'; +import mainnet from './chains/mainnet.js'; +import sepolia from './chains/sepolia.js'; +import { EIPs } from './eips/index.js'; +import type { ConsensusAlgorithm, ConsensusType } from './enums.js'; +import { Chain, CustomChain, Hardfork } from './enums.js'; +import { hardforks as HARDFORK_SPECS } from './hardforks/index.js'; + +import type { + BootstrapNodeConfig, + CasperConfig, + ChainConfig, + ChainName, + ChainsConfig, + CliqueConfig, + CommonOpts, + CustomCommonOpts, + EthashConfig, + GenesisBlockConfig, + GethConfigOpts, + HardforkConfig, +} from './types.js'; + +const { buf: crc32Uint8Array } = pkg; + +type HardforkSpecKeys = keyof typeof HARDFORK_SPECS; +type HardforkSpecValues = typeof HARDFORK_SPECS[HardforkSpecKeys]; +/** + * Common class to access chain and hardfork parameters and to provide + * a unified and shared view on the network and hardfork state. + * + * Use the {@link Common.custom} static constructor for creating simple + * custom chain {@link Common} objects (more complete custom chain setups + * can be created via the main constructor and the {@link CommonOpts.customChains} parameter). + */ +export class Common extends EventEmitter { + public readonly DEFAULT_HARDFORK: string | Hardfork; + + private _chainParams: ChainConfig; + private _hardfork: string | Hardfork; + private _eips: number[] = []; + private readonly _customChains: ChainConfig[]; + + private readonly HARDFORK_CHANGES: [HardforkSpecKeys, HardforkSpecValues][]; + + /** + * Creates a {@link Common} object for a custom chain, based on a standard one. + * + * It uses all the {@link Chain} parameters from the {@link baseChain} option except the ones overridden + * in a provided {@link chainParamsOrName} dictionary. Some usage example: + * + * ```javascript + * Common.custom({chainId: 123}) + * ``` + * + * There are also selected supported custom chains which can be initialized by using one of the + * {@link CustomChains} for {@link chainParamsOrName}, e.g.: + * + * ```javascript + * Common.custom(CustomChains.MaticMumbai) + * ``` + * + * Note that these supported custom chains only provide some base parameters (usually the chain and + * network ID and a name) and can only be used for selected use cases (e.g. sending a tx with + * the `web3-utils/tx` library to a Layer-2 chain). + * + * @param chainParamsOrName Custom parameter dict (`name` will default to `custom-chain`) or string with name of a supported custom chain + * @param opts Custom chain options to set the {@link CustomCommonOpts.baseChain}, selected {@link CustomCommonOpts.hardfork} and others + */ + public static custom( + chainParamsOrName: Partial | CustomChain, + opts: CustomCommonOpts = {}, + ): Common { + const baseChain = opts.baseChain ?? 'mainnet'; + const standardChainParams = { ...Common._getChainParams(baseChain) }; + standardChainParams.name = 'custom-chain'; + + if (typeof chainParamsOrName !== 'string') { + return new Common({ + chain: { + ...standardChainParams, + ...chainParamsOrName, + }, + ...opts, + }); + } + if (chainParamsOrName === CustomChain.PolygonMainnet) { + return Common.custom( + { + name: CustomChain.PolygonMainnet, + chainId: 137, + networkId: 137, + }, + opts, + ); + } + if (chainParamsOrName === CustomChain.PolygonMumbai) { + return Common.custom( + { + name: CustomChain.PolygonMumbai, + chainId: 80001, + networkId: 80001, + }, + opts, + ); + } + if (chainParamsOrName === CustomChain.ArbitrumRinkebyTestnet) { + return Common.custom( + { + name: CustomChain.ArbitrumRinkebyTestnet, + chainId: 421611, + networkId: 421611, + }, + opts, + ); + } + if (chainParamsOrName === CustomChain.ArbitrumOne) { + return Common.custom( + { + name: CustomChain.ArbitrumOne, + chainId: 42161, + networkId: 42161, + }, + opts, + ); + } + if (chainParamsOrName === CustomChain.xDaiChain) { + return Common.custom( + { + name: CustomChain.xDaiChain, + chainId: 100, + networkId: 100, + }, + opts, + ); + } + + if (chainParamsOrName === CustomChain.OptimisticKovan) { + return Common.custom( + { + name: CustomChain.OptimisticKovan, + chainId: 69, + networkId: 69, + }, + // Optimism has not implemented the London hardfork yet (targeting Q1.22) + { hardfork: Hardfork.Berlin, ...opts }, + ); + } + + if (chainParamsOrName === CustomChain.OptimisticEthereum) { + return Common.custom( + { + name: CustomChain.OptimisticEthereum, + chainId: 10, + networkId: 10, + }, + // Optimism has not implemented the London hardfork yet (targeting Q1.22) + { hardfork: Hardfork.Berlin, ...opts }, + ); + } + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + throw new Error(`Custom chain ${chainParamsOrName} not supported`); + } + + /** + * Static method to load and set common from a geth genesis json + * @param genesisJson json of geth configuration + * @param { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge } to further configure the common instance + * @returns Common + */ + public static fromGethGenesis( + genesisJson: any, + { chain, eips, genesisHash, hardfork, mergeForkIdPostMerge }: GethConfigOpts, + ): Common { + const genesisParams = parseGethGenesis(genesisJson, chain, mergeForkIdPostMerge); + const common = new Common({ + chain: genesisParams.name ?? 'custom', + customChains: [genesisParams], + eips, + hardfork: hardfork ?? genesisParams.hardfork, + }); + if (genesisHash !== undefined) { + common.setForkHashes(genesisHash); + } + return common; + } + + /** + * Static method to determine if a {@link chainId} is supported as a standard chain + * @param chainId bigint id (`1`) of a standard chain + * @returns boolean + */ + public static isSupportedChainId(chainId: bigint): boolean { + const initializedChains = this._getInitializedChains(); + return Boolean((initializedChains.names as ChainName)[chainId.toString()]); + } + + private static _getChainParams( + _chain: string | number | Chain | bigint, + customChains?: ChainConfig[], + ): ChainConfig { + let chain = _chain; + const initializedChains = this._getInitializedChains(customChains); + if (typeof chain === 'number' || typeof chain === 'bigint') { + chain = chain.toString(); + + if ((initializedChains.names as ChainName)[chain]) { + const name: string = (initializedChains.names as ChainName)[chain]; + return initializedChains[name] as ChainConfig; + } + + throw new Error(`Chain with ID ${chain} not supported`); + } + + if (initializedChains[chain] !== undefined) { + return initializedChains[chain] as ChainConfig; + } + + throw new Error(`Chain with name ${chain} not supported`); + } + + public constructor(opts: CommonOpts) { + super(); + this._customChains = opts.customChains ?? []; + this._chainParams = this.setChain(opts.chain); + this.DEFAULT_HARDFORK = this._chainParams.defaultHardfork ?? Hardfork.Merge; + // Assign hardfork changes in the sequence of the applied hardforks + this.HARDFORK_CHANGES = this.hardforks().map(hf => [ + hf.name as HardforkSpecKeys, + HARDFORK_SPECS[hf.name as HardforkSpecKeys], + ]); + this._hardfork = this.DEFAULT_HARDFORK; + if (opts.hardfork !== undefined) { + this.setHardfork(opts.hardfork); + } + if (opts.eips) { + this.setEIPs(opts.eips); + } + } + + /** + * Sets the chain + * @param chain String ('mainnet') or Number (1) chain representation. + * Or, a Dictionary of chain parameters for a private network. + * @returns The dictionary with parameters set as chain + */ + public setChain(chain: string | number | Chain | bigint | object): ChainConfig { + if (typeof chain === 'number' || typeof chain === 'bigint' || typeof chain === 'string') { + this._chainParams = Common._getChainParams(chain, this._customChains); + } else if (typeof chain === 'object') { + if (this._customChains.length > 0) { + throw new Error( + 'Chain must be a string, number, or bigint when initialized with customChains passed in', + ); + } + const required = ['networkId', 'genesis', 'hardforks', 'bootstrapNodes']; + for (const param of required) { + if (!(param in chain)) { + throw new Error(`Missing required chain parameter: ${param}`); + } + } + this._chainParams = chain as ChainConfig; + } else { + throw new Error('Wrong input format'); + } + for (const hf of this.hardforks()) { + if (hf.block === undefined) { + throw new Error(`Hardfork cannot have undefined block number`); + } + } + return this._chainParams; + } + + /** + * Sets the hardfork to get params for + * @param hardfork String identifier (e.g. 'byzantium') or {@link Hardfork} enum + */ + public setHardfork(hardfork: string | Hardfork): void { + let existing = false; + for (const hfChanges of this.HARDFORK_CHANGES) { + if (hfChanges[0] === hardfork) { + if (this._hardfork !== hardfork) { + this._hardfork = hardfork; + this.emit('hardforkChanged', hardfork); + } + existing = true; + } + } + if (!existing) { + throw new Error(`Hardfork with name ${hardfork} not supported`); + } + } + + /** + * Returns the hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td : total difficulty of the parent block (for block hf) OR of the chain latest (for chain hf) + * @param timestamp: timestamp in seconds at which block was/is to be minted + * @returns The name of the HF + */ + public getHardforkByBlockNumber( + _blockNumber: Numbers, + _td?: Numbers, + _timestamp?: Numbers, + ): string { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const td = toType(_td, TypeOutput.BigInt); + const timestamp = toType(_timestamp, TypeOutput.Number); + + // Filter out hardforks with no block number, no ttd or no timestamp (i.e. unapplied hardforks) + const hfs = this.hardforks().filter( + hf => + // eslint-disable-next-line no-null/no-null + hf.block !== null || + // eslint-disable-next-line no-null/no-null + (hf.ttd !== null && hf.ttd !== undefined) || + hf.timestamp !== undefined, + ); + // eslint-disable-next-line no-null/no-null + const mergeIndex = hfs.findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + const doubleTTDHF = hfs + .slice(mergeIndex + 1) + // eslint-disable-next-line no-null/no-null + .findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + if (doubleTTDHF >= 0) { + throw Error(`More than one merge hardforks found with ttd specified`); + } + + // Find the first hardfork that has a block number greater than `blockNumber` + // (skips the merge hardfork since it cannot have a block number specified). + // If timestamp is not provided, it also skips timestamps hardforks to continue + // discovering/checking number hardforks. + let hfIndex = hfs.findIndex( + hf => + // eslint-disable-next-line no-null/no-null + (hf.block !== null && hf.block > blockNumber) || + (timestamp !== undefined && Number(hf.timestamp) > timestamp), + ); + + if (hfIndex === -1) { + // all hardforks apply, set hfIndex to the last one as that's the candidate + hfIndex = hfs.length; + } else if (hfIndex === 0) { + // cannot have a case where a block number is before all applied hardforks + // since the chain has to start with a hardfork + throw Error('Must have at least one hardfork at block 0'); + } + + // If timestamp is not provided, we need to rollback to the last hf with block or ttd + if (timestamp === undefined) { + const stepBack = hfs + .slice(0, hfIndex) + .reverse() + // eslint-disable-next-line no-null/no-null + .findIndex(hf => hf.block !== null || hf.ttd !== undefined); + hfIndex -= stepBack; + } + // Move hfIndex one back to arrive at candidate hardfork + hfIndex -= 1; + + // If the timestamp was not provided, we could have skipped timestamp hardforks to look for number + // hardforks. so it will now be needed to rollback + // eslint-disable-next-line no-null/no-null + if (hfs[hfIndex].block === null && hfs[hfIndex].timestamp === undefined) { + // We're on the merge hardfork. Let's check the TTD + // eslint-disable-next-line no-null/no-null + if (td === undefined || td === null || BigInt(hfs[hfIndex].ttd!) > td) { + // Merge ttd greater than current td so we're on hardfork before merge + hfIndex -= 1; + } + // eslint-disable-next-line no-null/no-null + } else if (mergeIndex >= 0 && td !== undefined && td !== null) { + if (hfIndex >= mergeIndex && BigInt(hfs[mergeIndex].ttd!) > td) { + throw Error( + 'Maximum HF determined by total difficulty is lower than the block number HF', + ); + } else if (hfIndex < mergeIndex && BigInt(hfs[mergeIndex].ttd!) <= td) { + throw Error( + 'HF determined by block number is lower than the minimum total difficulty HF', + ); + } + } + + const hfStartIndex = hfIndex; + // Move the hfIndex to the end of the hardforks that might be scheduled on the same block/timestamp + // This won't anyway be the case with Merge hfs + for (; hfIndex < hfs.length - 1; hfIndex += 1) { + // break out if hfIndex + 1 is not scheduled at hfIndex + if ( + hfs[hfIndex].block !== hfs[hfIndex + 1].block || + hfs[hfIndex].timestamp !== hfs[hfIndex + 1].timestamp + ) { + break; + } + } + + if (timestamp) { + const minTimeStamp = hfs + .slice(0, hfStartIndex) + .reduce( + (acc: number, hf: HardforkConfig) => Math.max(Number(hf.timestamp ?? '0'), acc), + 0, + ); + if (minTimeStamp > timestamp) { + throw Error( + `Maximum HF determined by timestamp is lower than the block number/ttd HF`, + ); + } + + const maxTimeStamp = hfs + .slice(hfIndex + 1) + .reduce( + (acc: number, hf: HardforkConfig) => + Math.min(Number(hf.timestamp ?? timestamp), acc), + timestamp, + ); + if (maxTimeStamp < timestamp) { + throw Error(`Maximum HF determined by block number/ttd is lower than timestamp HF`); + } + } + const hardfork = hfs[hfIndex]; + return hardfork.name; + } + + /** + * Sets a new hardfork based on the block number or an optional + * total difficulty (Merge HF) provided. + * + * An optional TD takes precedence in case the corresponding HF block + * is set to `null` or otherwise needs to match (if not an error + * will be thrown). + * + * @param blockNumber + * @param td + * @param timestamp + * @returns The name of the HF set + */ + public setHardforkByBlockNumber( + blockNumber: Numbers, + td?: Numbers, + timestamp?: Numbers, + ): string { + const hardfork = this.getHardforkByBlockNumber(blockNumber, td, timestamp); + this.setHardfork(hardfork); + return hardfork; + } + + /** + * Internal helper function, returns the params for the given hardfork for the chain set + * @param hardfork Hardfork name + * @returns Dictionary with hardfork params or null if hardfork not on chain + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public _getHardfork(hardfork: string | Hardfork): HardforkConfig | null { + const hfs = this.hardforks(); + for (const hf of hfs) { + if (hf.name === hardfork) return hf; + } + // eslint-disable-next-line no-null/no-null + return null; + } + + /** + * Sets the active EIPs + * @param eips + */ + public setEIPs(eips: number[] = []) { + for (const eip of eips) { + if (!(eip in EIPs)) { + throw new Error(`${eip} not supported`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument + const minHF = this.gteHardfork(EIPs[eip].minimumHardfork); + if (!minHF) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${eip} cannot be activated on hardfork ${this.hardfork()}, minimumHardfork: ${minHF}`, + ); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (EIPs[eip].requiredEIPs !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + for (const elem of EIPs[eip].requiredEIPs) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + if (!(eips.includes(elem) || this.isActivatedEIP(elem))) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${eip} requires EIP ${elem}, but is not included in the EIP list`, + ); + } + } + } + } + this._eips = eips; + } + + /** + * Returns a parameter for the current chain setup + * + * If the parameter is present in an EIP, the EIP always takes precedence. + * Otherwise the parameter if taken from the latest applied HF with + * a change on the respective parameter. + * + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @returns The value requested or `BigInt(0)` if not found + */ + public param(topic: string, name: string): bigint { + // TODO: consider the case that different active EIPs + // can change the same parameter + let value; + for (const eip of this._eips) { + value = this.paramByEIP(topic, name, eip); + if (value !== undefined) return value; + } + return this.paramByHardfork(topic, name, this._hardfork); + } + + /** + * Returns the parameter corresponding to a hardfork + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param hardfork Hardfork name + * @returns The value requested or `BigInt(0)` if not found + */ + public paramByHardfork(topic: string, name: string, hardfork: string | Hardfork): bigint { + // eslint-disable-next-line no-null/no-null + let value = null; + for (const hfChanges of this.HARDFORK_CHANGES) { + // EIP-referencing HF file (e.g. berlin.json) + if ('eips' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + const hfEIPs = hfChanges[1].eips; + for (const eip of hfEIPs) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const valueEIP = this.paramByEIP(topic, name, eip); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + value = typeof valueEIP === 'bigint' ? valueEIP : value; + } + // Parameter-inlining HF file (e.g. istanbul.json) + } else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hfChanges[1][topic] === undefined) { + throw new Error(`Topic ${topic} not defined`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (hfChanges[1][topic][name] !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1][topic][name].v; + } + } + if (hfChanges[0] === hardfork) break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return BigInt(value ?? 0); + } + + /** + * Returns a parameter corresponding to an EIP + * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow') + * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) + * @param eip Number of the EIP + * @returns The value requested or `undefined` if not found + */ + // eslint-disable-next-line class-methods-use-this + public paramByEIP(topic: string, name: string, eip: number): bigint | undefined { + if (!(eip in EIPs)) { + throw new Error(`${eip} not supported`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const eipParams = EIPs[eip]; + if (!(topic in eipParams)) { + throw new Error(`Topic ${topic} not defined`); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (eipParams[topic][name] === undefined) { + return undefined; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + const value = eipParams[topic][name].v; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return BigInt(value); + } + + /** + * Returns a parameter for the hardfork active on block number or + * optional provided total difficulty (Merge HF) + * @param topic Parameter topic + * @param name Parameter name + * @param blockNumber Block number + * @param td Total difficulty + * * @returns The value requested or `BigInt(0)` if not found + */ + public paramByBlock( + topic: string, + name: string, + blockNumber: Numbers, + td?: Numbers, + timestamp?: Numbers, + ): bigint { + const hardfork = this.getHardforkByBlockNumber(blockNumber, td, timestamp); + return this.paramByHardfork(topic, name, hardfork); + } + + /** + * Checks if an EIP is activated by either being included in the EIPs + * manually passed in with the {@link CommonOpts.eips} or in a + * hardfork currently being active + * + * Note: this method only works for EIPs being supported + * by the {@link CommonOpts.eips} constructor option + * @param eip + */ + public isActivatedEIP(eip: number): boolean { + if (this.eips().includes(eip)) { + return true; + } + for (const hfChanges of this.HARDFORK_CHANGES) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const hf = hfChanges[1]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument + if (this.gteHardfork(hf.name) && 'eips' in hf) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if ((hf.eips as number[]).includes(eip)) { + return true; + } + } + } + return false; + } + + /** + * Checks if set or provided hardfork is active on block number + * @param hardfork Hardfork name or null (for HF set) + * @param blockNumber + * @returns True if HF is active on block number + */ + public hardforkIsActiveOnBlock( + // eslint-disable-next-line @typescript-eslint/ban-types + _hardfork: string | Hardfork | null, + _blockNumber: Numbers, + ): boolean { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const hardfork = _hardfork ?? this._hardfork; + const hfBlock = this.hardforkBlock(hardfork); + if (typeof hfBlock === 'bigint' && hfBlock !== BigInt(0) && blockNumber >= hfBlock) { + return true; + } + return false; + } + + /** + * Alias to hardforkIsActiveOnBlock when hardfork is set + * @param blockNumber + * @returns True if HF is active on block number + */ + public activeOnBlock(blockNumber: Numbers): boolean { + // eslint-disable-next-line no-null/no-null + return this.hardforkIsActiveOnBlock(null, blockNumber); + } + + /** + * Sequence based check if given or set HF1 is greater than or equal HF2 + * @param hardfork1 Hardfork name or null (if set) + * @param hardfork2 Hardfork name + * @param opts Hardfork options + * @returns True if HF1 gte HF2 + */ + public hardforkGteHardfork( + // eslint-disable-next-line @typescript-eslint/ban-types + _hardfork1: string | Hardfork | null, + hardfork2: string | Hardfork, + ): boolean { + const hardfork1 = _hardfork1 ?? this._hardfork; + const hardforks = this.hardforks(); + + let posHf1 = -1; + let posHf2 = -1; + let index = 0; + for (const hf of hardforks) { + if (hf.name === hardfork1) posHf1 = index; + if (hf.name === hardfork2) posHf2 = index; + index += 1; + } + return posHf1 >= posHf2 && posHf2 !== -1; + } + + /** + * Alias to hardforkGteHardfork when hardfork is set + * @param hardfork Hardfork name + * @returns True if hardfork set is greater than hardfork provided + */ + public gteHardfork(hardfork: string | Hardfork): boolean { + // eslint-disable-next-line no-null/no-null + return this.hardforkGteHardfork(null, hardfork); + } + + /** + * Returns the hardfork change block for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if unscheduled + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public hardforkBlock(_hardfork?: string | Hardfork): bigint | null { + const hardfork = _hardfork ?? this._hardfork; + const block = this._getHardfork(hardfork)?.block; + // eslint-disable-next-line no-null/no-null + if (block === undefined || block === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(block); + } + // eslint-disable-next-line @typescript-eslint/ban-types + public hardforkTimestamp(_hardfork?: string | Hardfork): bigint | null { + const hardfork = _hardfork ?? this._hardfork; + const timestamp = this._getHardfork(hardfork)?.timestamp; + // eslint-disable-next-line no-null/no-null + if (timestamp === undefined || timestamp === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(timestamp); + } + + /** + * Returns the hardfork change block for eip + * @param eip EIP number + * @returns Block number or null if unscheduled + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public eipBlock(eip: number): bigint | null { + for (const hfChanges of this.HARDFORK_CHANGES) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const hf = hfChanges[1]; + if ('eips' in hf) { + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + if (hf.eips.includes(eip)) { + return this.hardforkBlock( + typeof hfChanges[0] === 'number' ? String(hfChanges[0]) : hfChanges[0], + ); + } + } + } + // eslint-disable-next-line no-null/no-null + return null; + } + + /** + * Returns the hardfork change total difficulty (Merge HF) for hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Total difficulty or null if no set + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public hardforkTTD(_hardfork?: string | Hardfork): bigint | null { + const hardfork = _hardfork ?? this._hardfork; + const ttd = this._getHardfork(hardfork)?.ttd; + // eslint-disable-next-line no-null/no-null + if (ttd === undefined || ttd === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + return BigInt(ttd); + } + + /** + * True if block number provided is the hardfork (given or set) change block + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + public isHardforkBlock(_blockNumber: Numbers, _hardfork?: string | Hardfork): boolean { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const hardfork = _hardfork ?? this._hardfork; + const block = this.hardforkBlock(hardfork); + return typeof block === 'bigint' && block !== BigInt(0) ? block === blockNumber : false; + } + + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block timestamp, number or null if not available + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public nextHardforkBlockOrTimestamp(_hardfork?: string | Hardfork): bigint | null { + const hardfork = _hardfork ?? this._hardfork; + const hfs = this.hardforks(); + let hfIndex = hfs.findIndex(hf => hf.name === hardfork); + // If the current hardfork is merge, go one behind as merge hf is not part of these + // calcs even if the merge hf block is set + if (hardfork === Hardfork.Merge) { + hfIndex -= 1; + } + // Hardfork not found + if (hfIndex < 0) { + // eslint-disable-next-line no-null/no-null + return null; + } + + let currHfTimeOrBlock = hfs[hfIndex].timestamp ?? hfs[hfIndex].block; + currHfTimeOrBlock = + // eslint-disable-next-line no-null/no-null + currHfTimeOrBlock !== null && currHfTimeOrBlock !== undefined + ? Number(currHfTimeOrBlock) + : // eslint-disable-next-line no-null/no-null + null; + + const nextHf = hfs.slice(hfIndex + 1).find(hf => { + let hfTimeOrBlock = hf.timestamp ?? hf.block; + hfTimeOrBlock = + // eslint-disable-next-line no-null/no-null + hfTimeOrBlock !== null && hfTimeOrBlock !== undefined + ? Number(hfTimeOrBlock) + : // eslint-disable-next-line no-null/no-null + null; + return ( + hf.name !== Hardfork.Merge && + // eslint-disable-next-line no-null/no-null + hfTimeOrBlock !== null && + hfTimeOrBlock !== undefined && + hfTimeOrBlock !== currHfTimeOrBlock + ); + }); + // If no next hf found with valid block or timestamp return null + if (nextHf === undefined) { + // eslint-disable-next-line no-null/no-null + return null; + } + + const nextHfBlock = nextHf.timestamp ?? nextHf.block; + // eslint-disable-next-line no-null/no-null + if (nextHfBlock === null || nextHfBlock === undefined) { + // eslint-disable-next-line no-null/no-null + return null; + } + + return BigInt(nextHfBlock); + } + + /** + * Returns the change block for the next hardfork after the hardfork provided or set + * @param hardfork Hardfork name, optional if HF set + * @returns Block number or null if not available + * @deprecated + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public nextHardforkBlock(_hardfork?: string | Hardfork): bigint | null { + const hardfork = _hardfork ?? this._hardfork; + let hfBlock = this.hardforkBlock(hardfork); + // If this is a merge hardfork with block not set, then we fallback to previous hardfork + // to find the nextHardforkBlock + // eslint-disable-next-line no-null/no-null + if (hfBlock === null && hardfork === Hardfork.Merge) { + const hfs = this.hardforks(); + // eslint-disable-next-line no-null/no-null + const mergeIndex = hfs.findIndex(hf => hf.ttd !== null && hf.ttd !== undefined); + if (mergeIndex < 0) { + throw Error(`Merge hardfork should have been found`); + } + hfBlock = this.hardforkBlock(hfs[mergeIndex - 1].name); + } + // eslint-disable-next-line no-null/no-null + if (hfBlock === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + // Next fork block number or null if none available + // Logic: if accumulator is still null and on the first occurrence of + // a block greater than the current hfBlock set the accumulator, + // pass on the accumulator as the final result from this time on + // eslint-disable-next-line no-null/no-null, @typescript-eslint/ban-types + const nextHfBlock = this.hardforks().reduce((acc: bigint | null, hf: HardforkConfig) => { + // We need to ignore the merge block in our next hardfork calc + const block = BigInt( + // eslint-disable-next-line no-null/no-null + hf.block === null || (hf.ttd !== undefined && hf.ttd !== null) ? 0 : hf.block, + ); + // Typescript can't seem to follow that the hfBlock is not null at this point + // eslint-disable-next-line no-null/no-null + return block > hfBlock! && acc === null ? block : acc; + // eslint-disable-next-line no-null/no-null + }, null); + return nextHfBlock; + } + + /** + * True if block number provided is the hardfork change block following the hardfork given or set + * @param blockNumber Number of the block to check + * @param hardfork Hardfork name, optional if HF set + * @returns True if blockNumber is HF block + * @deprecated + */ + public isNextHardforkBlock(_blockNumber: Numbers, _hardfork?: string | Hardfork): boolean { + const blockNumber = toType(_blockNumber, TypeOutput.BigInt); + const hardfork = _hardfork ?? this._hardfork; + // eslint-disable-next-line deprecation/deprecation + const nextHardforkBlock = this.nextHardforkBlock(hardfork); + // eslint-disable-next-line no-null/no-null + return nextHardforkBlock === null ? false : nextHardforkBlock === blockNumber; + } + + /** + * Internal helper function to calculate a fork hash + * @param hardfork Hardfork name + * @param genesisHash Genesis block hash of the chain + * @returns Fork hash as hex string + */ + public _calcForkHash(hardfork: string | Hardfork, genesisHash: Uint8Array) { + let hfUint8Array = new Uint8Array(); + let prevBlockOrTime = 0; + for (const hf of this.hardforks()) { + const { block, timestamp, name } = hf; + // Timestamp to be used for timestamp based hfs even if we may bundle + // block number with them retrospectively + let blockOrTime = timestamp ?? block; + // eslint-disable-next-line no-null/no-null + blockOrTime = blockOrTime !== null ? Number(blockOrTime) : null; + + // Skip for chainstart (0), not applied HFs (null) and + // when already applied on same blockOrTime HFs + // and on the merge since forkhash doesn't change on merge hf + if ( + typeof blockOrTime === 'number' && + blockOrTime !== 0 && + blockOrTime !== prevBlockOrTime && + name !== Hardfork.Merge + ) { + const hfBlockUint8Array = hexToBytes(blockOrTime.toString(16).padStart(16, '0')); + hfUint8Array = uint8ArrayConcat(hfUint8Array, hfBlockUint8Array); + prevBlockOrTime = blockOrTime; + } + + if (hf.name === hardfork) break; + } + const inputUint8Array = uint8ArrayConcat(genesisHash, hfUint8Array); + + // CRC32 delivers result as signed (negative) 32-bit integer, + // convert to hex string + // eslint-disable-next-line no-bitwise + const forkhash = bytesToHex(intToUint8Array(crc32Uint8Array(inputUint8Array) >>> 0)); + return forkhash; + } + + /** + * Returns an eth/64 compliant fork hash (EIP-2124) + * @param hardfork Hardfork name, optional if HF set + * @param genesisHash Genesis block hash of the chain, optional if already defined and not needed to be calculated + */ + public forkHash(_hardfork?: string | Hardfork, genesisHash?: Uint8Array): string { + const hardfork = _hardfork ?? this._hardfork; + const data = this._getHardfork(hardfork); + if ( + // eslint-disable-next-line no-null/no-null + data === null || + // eslint-disable-next-line no-null/no-null + (data?.block === null && data?.timestamp === undefined && data?.ttd === undefined) + ) { + const msg = 'No fork hash calculation possible for future hardfork'; + throw new Error(msg); + } + // eslint-disable-next-line no-null/no-null + if (data?.forkHash !== null && data?.forkHash !== undefined) { + return data.forkHash; + } + if (!genesisHash) throw new Error('genesisHash required for forkHash calculation'); + return this._calcForkHash(hardfork, genesisHash); + } + + /** + * + * @param forkHash Fork hash as a hex string + * @returns Array with hardfork data (name, block, forkHash) + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public hardforkForForkHash(forkHash: string): HardforkConfig | null { + const resArray = this.hardforks().filter((hf: HardforkConfig) => hf.forkHash === forkHash); + // eslint-disable-next-line no-null/no-null + return resArray.length >= 1 ? resArray[resArray.length - 1] : null; + } + + /** + * Sets any missing forkHashes on the passed-in {@link Common} instance + * @param common The {@link Common} to set the forkHashes for + * @param genesisHash The genesis block hash + */ + public setForkHashes(genesisHash: Uint8Array) { + for (const hf of this.hardforks()) { + const blockOrTime = hf.timestamp ?? hf.block; + if ( + // eslint-disable-next-line no-null/no-null + (hf.forkHash === null || hf.forkHash === undefined) && + // eslint-disable-next-line no-null/no-null + ((blockOrTime !== null && blockOrTime !== undefined) || + typeof hf.ttd !== 'undefined') + ) { + hf.forkHash = this.forkHash(hf.name, genesisHash); + } + } + } + + /** + * Returns the Genesis parameters of the current chain + * @returns Genesis dictionary + */ + public genesis(): GenesisBlockConfig { + return this._chainParams.genesis; + } + + /** + * Returns the hardforks for current chain + * @returns {Array} Array with arrays of hardforks + */ + public hardforks(): HardforkConfig[] { + return this._chainParams.hardforks; + } + + /** + * Returns bootstrap nodes for the current chain + * @returns {Dictionary} Dict with bootstrap nodes + */ + public bootstrapNodes(): BootstrapNodeConfig[] | undefined { + return this._chainParams.bootstrapNodes; + } + + /** + * Returns DNS networks for the current chain + * @returns {String[]} Array of DNS ENR urls + */ + public dnsNetworks(): string[] { + return this._chainParams.dnsNetworks!; + } + + /** + * Returns the hardfork set + * @returns Hardfork name + */ + public hardfork(): string | Hardfork { + return this._hardfork; + } + + /** + * Returns the Id of current chain + * @returns chain Id + */ + public chainId(): bigint { + return BigInt(this._chainParams.chainId); + } + + /** + * Returns the name of current chain + * @returns chain name (lower case) + */ + public chainName(): string { + return this._chainParams.name; + } + + /** + * Returns the Id of current network + * @returns network Id + */ + public networkId(): bigint { + return BigInt(this._chainParams.networkId); + } + + /** + * Returns the active EIPs + * @returns List of EIPs + */ + public eips(): number[] { + return this._eips; + } + + /** + * Returns the consensus type of the network + * Possible values: "pow"|"poa"|"pos" + * + * Note: This value can update along a Hardfork. + */ + public consensusType(): string | ConsensusType { + const hardfork = this.hardfork(); + + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus.type; + } + if (hfChanges[0] === hardfork) break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value ?? this._chainParams.consensus.type; + } + + /** + * Returns the concrete consensus implementation + * algorithm or protocol for the network + * e.g. "ethash" for "pow" consensus type, + * "clique" for "poa" consensus type or + * "casper" for "pos" consensus type. + * + * Note: This value can update along a Hardfork. + */ + public consensusAlgorithm(): string | ConsensusAlgorithm { + const hardfork = this.hardfork(); + + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus.algorithm; + } + if (hfChanges[0] === hardfork) break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value ?? (this._chainParams.consensus.algorithm as ConsensusAlgorithm); + } + + /** + * Returns a dictionary with consensus configuration + * parameters based on the consensus algorithm + * + * Expected returns (parameters must be present in + * the respective chain json files): + * + * ethash: empty object + * clique: period, epoch + * casper: empty object + * + * Note: This value can update along a Hardfork. + */ + public consensusConfig(): { [key: string]: CliqueConfig | EthashConfig | CasperConfig } { + const hardfork = this.hardfork(); + + let value; + for (const hfChanges of this.HARDFORK_CHANGES) { + if ('consensus' in hfChanges[1]) { + // The config parameter is named after the respective consensus algorithm + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + value = hfChanges[1].consensus[hfChanges[1].consensus.algorithm]; + } + if (hfChanges[0] === hardfork) break; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return ( + value ?? + this._chainParams.consensus[this.consensusAlgorithm() as ConsensusAlgorithm] ?? + {} + ); + } + + /** + * Returns a deep copy of this {@link Common} instance. + */ + public copy(): Common { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment + const copy = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + copy.removeAllListeners(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return copy; + } + + public static _getInitializedChains(customChains?: ChainConfig[]): ChainsConfig { + const names: ChainName = {}; + for (const [name, id] of Object.entries(Chain)) { + names[id] = name.toLowerCase(); + } + const chains = { mainnet, goerli, sepolia } as ChainsConfig; + if (customChains) { + for (const chain of customChains) { + const { name } = chain; + names[chain.chainId.toString()] = name; + chains[name] = chain; + } + } + chains.names = names; + return chains; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/1153.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/1153.ts new file mode 100644 index 0000000..a7440d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/1153.ts @@ -0,0 +1,23 @@ +export default { + "name": "EIP-1153", + "number": 1153, + "comment": "Transient Storage", + "url": "https://eips.ethereum.org/EIPS/eip-1153", + "status": "Review", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "tstore": { + "v": 100, + "d": "Base fee of the TSTORE opcode" + }, + "tload": { + "v": 100, + "d": "Base fee of the TLOAD opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/1559.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/1559.ts new file mode 100644 index 0000000..ef3f044 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/1559.ts @@ -0,0 +1,27 @@ +export default { + "name": "EIP-1559", + "number": 1559, + "comment": "Fee market change for ETH 1.0 chain", + "url": "https://eips.ethereum.org/EIPS/eip-1559", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [2930], + "gasConfig": { + "baseFeeMaxChangeDenominator": { + "v": 8, + "d": "Maximum base fee change denominator" + }, + "elasticityMultiplier": { + "v": 2, + "d": "Maximum block gas target elasticity" + }, + "initialBaseFee": { + "v": 1000000000, + "d": "Initial base fee on first EIP1559 block" + } + }, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2315.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2315.ts new file mode 100644 index 0000000..d29efa3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2315.ts @@ -0,0 +1,26 @@ +export default { + "name": "EIP-2315", + "number": 2315, + "comment": "Simple subroutines for the EVM", + "url": "https://eips.ethereum.org/EIPS/eip-2315", + "status": "Draft", + "minimumHardfork": "istanbul", + "gasConfig": {}, + "gasPrices": { + "beginsub": { + "v": 2, + "d": "Base fee of the BEGINSUB opcode" + }, + "returnsub": { + "v": 5, + "d": "Base fee of the RETURNSUB opcode" + }, + "jumpsub": { + "v": 10, + "d": "Base fee of the JUMPSUB opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2537.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2537.ts new file mode 100644 index 0000000..14fa62a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2537.ts @@ -0,0 +1,179 @@ +export default { + "name": "EIP-2537", + "number": 2537, + "comment": "BLS12-381 precompiles", + "url": "https://eips.ethereum.org/EIPS/eip-2537", + "status": "Draft", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": { + "Bls12381G1AddGas": { + "v": 600, + "d": "Gas cost of a single BLS12-381 G1 addition precompile-call" + }, + "Bls12381G1MulGas": { + "v": 12000, + "d": "Gas cost of a single BLS12-381 G1 multiplication precompile-call" + }, + "Bls12381G2AddGas": { + "v": 4500, + "d": "Gas cost of a single BLS12-381 G2 addition precompile-call" + }, + "Bls12381G2MulGas": { + "v": 55000, + "d": "Gas cost of a single BLS12-381 G2 multiplication precompile-call" + }, + "Bls12381PairingBaseGas": { + "v": 115000, + "d": "Base gas cost of BLS12-381 pairing check" + }, + "Bls12381PairingPerPairGas": { + "v": 23000, + "d": "Per-pair gas cost of BLS12-381 pairing check" + }, + "Bls12381MapG1Gas": { + "v": 5500, + "d": "Gas cost of BLS12-381 map field element to G1" + }, + "Bls12381MapG2Gas": { + "v": 110000, + "d": "Gas cost of BLS12-381 map field element to G2" + }, + "Bls12381MultiExpGasDiscount": { + "v": [ + [1, 1200], + [2, 888], + [3, 764], + [4, 641], + [5, 594], + [6, 547], + [7, 500], + [8, 453], + [9, 438], + [10, 423], + [11, 408], + [12, 394], + [13, 379], + [14, 364], + [15, 349], + [16, 334], + [17, 330], + [18, 326], + [19, 322], + [20, 318], + [21, 314], + [22, 310], + [23, 306], + [24, 302], + [25, 298], + [26, 294], + [27, 289], + [28, 285], + [29, 281], + [30, 277], + [31, 273], + [32, 269], + [33, 268], + [34, 266], + [35, 265], + [36, 263], + [37, 262], + [38, 260], + [39, 259], + [40, 257], + [41, 256], + [42, 254], + [43, 253], + [44, 251], + [45, 250], + [46, 248], + [47, 247], + [48, 245], + [49, 244], + [50, 242], + [51, 241], + [52, 239], + [53, 238], + [54, 236], + [55, 235], + [56, 233], + [57, 232], + [58, 231], + [59, 229], + [60, 228], + [61, 226], + [62, 225], + [63, 223], + [64, 222], + [65, 221], + [66, 220], + [67, 219], + [68, 219], + [69, 218], + [70, 217], + [71, 216], + [72, 216], + [73, 215], + [74, 214], + [75, 213], + [76, 213], + [77, 212], + [78, 211], + [79, 211], + [80, 210], + [81, 209], + [82, 208], + [83, 208], + [84, 207], + [85, 206], + [86, 205], + [87, 205], + [88, 204], + [89, 203], + [90, 202], + [91, 202], + [92, 201], + [93, 200], + [94, 199], + [95, 199], + [96, 198], + [97, 197], + [98, 196], + [99, 196], + [100, 195], + [101, 194], + [102, 193], + [103, 193], + [104, 192], + [105, 191], + [106, 191], + [107, 190], + [108, 189], + [109, 188], + [110, 188], + [111, 187], + [112, 186], + [113, 185], + [114, 185], + [115, 184], + [116, 183], + [117, 182], + [118, 182], + [119, 181], + [120, 180], + [121, 179], + [122, 179], + [123, 178], + [124, 177], + [125, 176], + [126, 176], + [127, 175], + [128, 174] + ], + "d": "Discount gas costs of calls to the MultiExp precompiles with `k` (point, scalar) pair" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2565.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2565.ts new file mode 100644 index 0000000..1c1743e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2565.ts @@ -0,0 +1,18 @@ +export default { + "name": "EIP-2565", + "number": 2565, + "comment": "ModExp gas cost", + "url": "https://eips.ethereum.org/EIPS/eip-2565", + "status": "Final", + "minimumHardfork": "byzantium", + "gasConfig": {}, + "gasPrices": { + "modexpGquaddivisor": { + "v": 3, + "d": "Gquaddivisor from modexp precompile for gas calculation" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2718.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2718.ts new file mode 100644 index 0000000..f8815c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2718.ts @@ -0,0 +1,12 @@ +export default { + "name": "EIP-2718", + "comment": "Typed Transaction Envelope", + "url": "https://eips.ethereum.org/EIPS/eip-2718", + "status": "Final", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2929.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2929.ts new file mode 100644 index 0000000..f52dc21 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2929.ts @@ -0,0 +1,85 @@ +export default { + "name": "EIP-2929", + "comment": "Gas cost increases for state access opcodes", + "url": "https://eips.ethereum.org/EIPS/eip-2929", + "status": "Final", + "minimumHardfork": "chainstart", + "gasConfig": {}, + "gasPrices": { + "coldsload": { + "v": 2100, + "d": "Gas cost of the first read of storage from a given location (per transaction)" + }, + "coldaccountaccess": { + "v": 2600, + "d": "Gas cost of the first read of a given address (per transaction)" + }, + "warmstorageread": { + "v": 100, + "d": "Gas cost of reading storage locations which have already loaded 'cold'" + }, + "sstoreCleanGasEIP2200": { + "v": 2900, + "d": "Once per SSTORE operation from clean non-zero to something else" + }, + "sstoreNoopGasEIP2200": { + "v": 100, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "sstoreDirtyGasEIP2200": { + "v": 100, + "d": "Once per SSTORE operation if a dirty value is changed" + }, + "sstoreInitRefundEIP2200": { + "v": 19900, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "sstoreCleanRefundEIP2200": { + "v": 4900, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "call": { + "v": 0, + "d": "Base fee of the CALL opcode" + }, + "callcode": { + "v": 0, + "d": "Base fee of the CALLCODE opcode" + }, + "delegatecall": { + "v": 0, + "d": "Base fee of the DELEGATECALL opcode" + }, + "staticcall": { + "v": 0, + "d": "Base fee of the STATICCALL opcode" + }, + "balance": { + "v": 0, + "d": "Base fee of the BALANCE opcode" + }, + "extcodesize": { + "v": 0, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 0, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "extcodehash": { + "v": 0, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "sload": { + "v": 0, + "d": "Base fee of the SLOAD opcode" + }, + "sstore": { + "v": 0, + "d": "Base fee of the SSTORE opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2930.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2930.ts new file mode 100644 index 0000000..52500d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/2930.ts @@ -0,0 +1,22 @@ +export default { + "name": "EIP-2930", + "comment": "Optional access lists", + "url": "https://eips.ethereum.org/EIPS/eip-2930", + "status": "Final", + "minimumHardfork": "istanbul", + "requiredEIPs": [2718, 2929], + "gasConfig": {}, + "gasPrices": { + "accessListStorageKeyCost": { + "v": 1900, + "d": "Gas cost per storage key in an Access List transaction" + }, + "accessListAddressCost": { + "v": 2400, + "d": "Gas cost per storage key in an Access List transaction" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3074.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3074.ts new file mode 100644 index 0000000..538b056 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3074.ts @@ -0,0 +1,26 @@ +export default { + "name": "EIP-3074", + "number": 3074, + "comment": "AUTH and AUTHCALL opcodes", + "url": "https://eips.ethereum.org/EIPS/eip-3074", + "status": "Review", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": { + "auth": { + "v": 3100, + "d": "Gas cost of the AUTH opcode" + }, + "authcall": { + "v": 0, + "d": "Gas cost of the AUTHCALL opcode" + }, + "authcallValueTransfer": { + "v": 6700, + "d": "Paid for CALL when the value transfer is non-zero" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3198.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3198.ts new file mode 100644 index 0000000..d949d97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3198.ts @@ -0,0 +1,18 @@ +export default { + "name": "EIP-3198", + "number": 3198, + "comment": "BASEFEE opcode", + "url": "https://eips.ethereum.org/EIPS/eip-3198", + "status": "Final", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": { + "basefee": { + "v": 2, + "d": "Gas cost of the BASEFEE opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3529.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3529.ts new file mode 100644 index 0000000..2e8b0e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3529.ts @@ -0,0 +1,27 @@ +export default { + "name": "EIP-3529", + "comment": "Reduction in refunds", + "url": "https://eips.ethereum.org/EIPS/eip-3529", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [2929], + "gasConfig": { + "maxRefundQuotient": { + "v": 5, + "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" + } + }, + "gasPrices": { + "selfdestructRefund": { + "v": 0, + "d": "Refunded following a selfdestruct operation" + }, + "sstoreClearRefundEIP2200": { + "v": 4800, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3540.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3540.ts new file mode 100644 index 0000000..39fdb91 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3540.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3540", + "number": 3540, + "comment": "EVM Object Format (EOF) v1", + "url": "https://eips.ethereum.org/EIPS/eip-3540", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [3541], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3541.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3541.ts new file mode 100644 index 0000000..b3e7a0c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3541.ts @@ -0,0 +1,13 @@ +export default { + "name": "EIP-3541", + "comment": "Reject new contracts starting with the 0xEF byte", + "url": "https://eips.ethereum.org/EIPS/eip-3541", + "status": "Final", + "minimumHardfork": "berlin", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3554.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3554.ts new file mode 100644 index 0000000..36a9d16 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3554.ts @@ -0,0 +1,18 @@ +export default { + "name": "EIP-3554", + "comment": "Reduction in refunds", + "url": "Difficulty Bomb Delay to December 1st 2021", + "status": "Final", + "minimumHardfork": "muirGlacier", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 9500000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3607.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3607.ts new file mode 100644 index 0000000..6c12272 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3607.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3607", + "number": 3607, + "comment": "Reject transactions from senders with deployed code", + "url": "https://eips.ethereum.org/EIPS/eip-3607", + "status": "Final", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3651.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3651.ts new file mode 100644 index 0000000..c6ebe81 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3651.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3651", + "number": 3198, + "comment": "Warm COINBASE", + "url": "https://eips.ethereum.org/EIPS/eip-3651", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [2929], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3670.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3670.ts new file mode 100644 index 0000000..5b36d99 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3670.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3670", + "number": 3670, + "comment": "EOF - Code Validation", + "url": "https://eips.ethereum.org/EIPS/eip-3670", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [3540], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3675.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3675.ts new file mode 100644 index 0000000..a803503 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3675.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-3675", + "number": 3675, + "comment": "Upgrade consensus to Proof-of-Stake", + "url": "https://eips.ethereum.org/EIPS/eip-3675", + "status": "Final", + "minimumHardfork": "london", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3855.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3855.ts new file mode 100644 index 0000000..2f5ac06 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3855.ts @@ -0,0 +1,19 @@ +export default { + "name": "EIP-3855", + "number": 3855, + "comment": "PUSH0 instruction", + "url": "https://eips.ethereum.org/EIPS/eip-3855", + "status": "Review", + "minimumHardfork": "chainstart", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "push0": { + "v": 2, + "d": "Base fee of the PUSH0 opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3860.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3860.ts new file mode 100644 index 0000000..0e1aeb9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/3860.ts @@ -0,0 +1,24 @@ +export default { + "name": "EIP-3860", + "number": 3860, + "comment": "Limit and meter initcode", + "url": "https://eips.ethereum.org/EIPS/eip-3860", + "status": "Review", + "minimumHardfork": "spuriousDragon", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": { + "initCodeWordCost": { + "v": 2, + "d": "Gas to pay for each word (32 bytes) of initcode when creating a contract" + } + }, + "vm": { + "maxInitCodeSize": { + "v": 49152, + "d": "Maximum length of initialization code when creating a contract" + } + }, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4345.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4345.ts new file mode 100644 index 0000000..0e571b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4345.ts @@ -0,0 +1,18 @@ +export default { + "name": "EIP-4345", + "number": 4345, + "comment": "Difficulty Bomb Delay to June 2022", + "url": "https://eips.ethereum.org/EIPS/eip-4345", + "status": "Final", + "minimumHardfork": "london", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 10700000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4399.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4399.ts new file mode 100644 index 0000000..ed948d6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4399.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-4399", + "number": 4399, + "comment": "Supplant DIFFICULTY opcode with PREVRANDAO", + "url": "https://eips.ethereum.org/EIPS/eip-4399", + "status": "Review", + "minimumHardfork": "london", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4844.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4844.ts new file mode 100644 index 0000000..2795067 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4844.ts @@ -0,0 +1,58 @@ +export default { + "name": "EIP-4844", + "number": 4844, + "comment": "Shard Blob Transactions", + "url": "https://eips.ethereum.org/EIPS/eip-4844", + "status": "Draft", + "minimumHardfork": "merge", + "requiredEIPs": [1559, 2718, 2930, 4895], + "gasConfig": { + "dataGasPerBlob": { + "v": 131072, + "d": "The base fee for data gas per blob" + }, + "targetDataGasPerBlock": { + "v": 262144, + "d": "The target data gas consumed per block" + }, + "maxDataGasPerBlock": { + "v": 524288, + "d": "The max data gas allowable per block" + }, + "dataGasPriceUpdateFraction": { + "v": 2225652, + "d": "The denominator used in the exponential when calculating a data gas price" + } + }, + "gasPrices": { + "simpleGasPerBlob": { + "v": 12000, + "d": "The basic gas fee for each blob" + }, + "minDataGasPrice": { + "v": 1, + "d": "The minimum fee per data gas" + }, + "kzgPointEvaluationGasPrecompilePrice": { + "v": 50000, + "d": "The fee associated with the point evaluation precompile" + }, + "datahash": { + "v": 3, + "d": "Base fee of the DATAHASH opcode" + } + }, + "sharding": { + "blobCommitmentVersionKzg": { + "v": 1, + "d": "The number indicated a versioned hash is a KZG commitment" + }, + "fieldElementsPerBlob": { + "v": 4096, + "d": "The number of field elements allowed per blob" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4895.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4895.ts new file mode 100644 index 0000000..f70f2ec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/4895.ts @@ -0,0 +1,14 @@ +export default { + "name": "EIP-4895", + "number": 4895, + "comment": "Beacon chain push withdrawals as operations", + "url": "https://eips.ethereum.org/EIPS/eip-4895", + "status": "Review", + "minimumHardfork": "merge", + "requiredEIPs": [], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/5133.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/5133.ts new file mode 100644 index 0000000..de3b55c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/5133.ts @@ -0,0 +1,18 @@ +export default { + "name": "EIP-5133", + "number": 5133, + "comment": "Delaying Difficulty Bomb to mid-September 2022", + "url": "https://eips.ethereum.org/EIPS/eip-5133", + "status": "Draft", + "minimumHardfork": "grayGlacier", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 11400000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/index.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/index.ts new file mode 100644 index 0000000..eeb5d95 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/eips/index.ts @@ -0,0 +1,63 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import e1153 from './1153.js'; +import e1559 from './1559.js'; +import e2315 from './2315.js'; +import e2537 from './2537.js'; +import e2565 from './2565.js'; +import e2718 from './2718.js'; +import e2929 from './2929.js'; +import e2930 from './2930.js'; +import e3198 from './3198.js'; +import e3529 from './3529.js'; +import e3540 from './3540.js'; +import e3541 from './3541.js'; +import e3554 from './3554.js'; +import e3607 from './3607.js'; +import e3651 from './3651.js'; +import e3670 from './3670.js'; +import e3675 from './3675.js'; +import e3855 from './3855.js'; +import e3860 from './3860.js'; +import e4345 from './4345.js'; +import e4399 from './4399.js'; +import e5133 from './5133.js'; + +export const EIPs: { [key: number]: any } = { + 1153: e1153, + 1559: e1559, + 2315: e2315, + 2537: e2537, + 2565: e2565, + 2718: e2718, + 2929: e2929, + 2930: e2930, + 3198: e3198, + 3529: e3529, + 3540: e3540, + 3541: e3541, + 3554: e3554, + 3607: e3607, + 3651: e3651, + 3670: e3670, + 3675: e3675, + 3855: e3855, + 3860: e3860, + 4345: e4345, + 4399: e4399, + 5133: e5133, +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/enums.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/enums.ts new file mode 100644 index 0000000..0661dd0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/enums.ts @@ -0,0 +1,105 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export enum Chain { + Mainnet = 1, + Goerli = 5, + Sepolia = 11155111, +} + +export enum Hardfork { + Chainstart = 'chainstart', + Homestead = 'homestead', + Dao = 'dao', + TangerineWhistle = 'tangerineWhistle', + SpuriousDragon = 'spuriousDragon', + Byzantium = 'byzantium', + Constantinople = 'constantinople', + Petersburg = 'petersburg', + Istanbul = 'istanbul', + MuirGlacier = 'muirGlacier', + Berlin = 'berlin', + London = 'london', + ArrowGlacier = 'arrowGlacier', + GrayGlacier = 'grayGlacier', + MergeForkIdTransition = 'mergeForkIdTransition', + Merge = 'merge', + Shanghai = 'shanghai', + ShardingForkDev = 'shardingFork', +} + +export enum ConsensusType { + ProofOfStake = 'pos', + ProofOfWork = 'pow', + ProofOfAuthority = 'poa', +} + +export enum ConsensusAlgorithm { + Ethash = 'ethash', + Clique = 'clique', + Casper = 'casper', +} + +export enum CustomChain { + /** + * Polygon (Matic) Mainnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + PolygonMainnet = 'polygon-mainnet', + + /** + * Polygon (Matic) Mumbai Testnet + * + * - [Documentation](https://docs.matic.network/docs/develop/network-details/network) + */ + PolygonMumbai = 'polygon-mumbai', + + /** + * Arbitrum Rinkeby Testnet + * + * - [Documentation](https://developer.offchainlabs.com/docs/public_testnet) + */ + ArbitrumRinkebyTestnet = 'arbitrum-rinkeby-testnet', + + /** + * Arbitrum One - mainnet for Arbitrum roll-up + * + * - [Documentation](https://developer.offchainlabs.com/public-chains) + */ + ArbitrumOne = 'arbitrum-one', + + /** + * xDai EVM sidechain with a native stable token + * + * - [Documentation](https://www.xdaichain.com/) + */ + xDaiChain = 'x-dai-chain', + + /** + * Optimistic Kovan - testnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + OptimisticKovan = 'optimistic-kovan', + + /** + * Optimistic Ethereum - mainnet for Optimism roll-up + * + * - [Documentation](https://community.optimism.io/docs/developers/tutorials.html) + */ + OptimisticEthereum = 'optimistic-ethereum', +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts new file mode 100644 index 0000000..e38f178 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts @@ -0,0 +1,12 @@ +export default { + "name": "arrowGlacier", + "comment": "HF to delay the difficulty bomb", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/arrow-glacier.md", + "status": "Final", + "eips": [4345], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/berlin.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/berlin.ts new file mode 100644 index 0000000..df30229 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/berlin.ts @@ -0,0 +1,8 @@ +export default { + "name": "berlin", + "comment": "HF targeted for July 2020 following the Muir Glacier HF", + "url": "https://eips.ethereum.org/EIPS/eip-2070", + "status": "Final", + "eips": [2565, 2929, 2718, 2930] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/byzantium.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/byzantium.ts new file mode 100644 index 0000000..2c358c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/byzantium.ts @@ -0,0 +1,57 @@ +export default { + "name": "byzantium", + "comment": "Hardfork with new precompiles, instructions and other protocol changes", + "url": "https://eips.ethereum.org/EIPS/eip-609", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "modexpGquaddivisor": { + "v": 20, + "d": "Gquaddivisor from modexp precompile for gas calculation" + }, + "ecAdd": { + "v": 500, + "d": "Gas costs for curve addition precompile" + }, + "ecMul": { + "v": 40000, + "d": "Gas costs for curve multiplication precompile" + }, + "ecPairing": { + "v": 100000, + "d": "Base gas costs for curve pairing precompile" + }, + "ecPairingWord": { + "v": 80000, + "d": "Gas costs regarding curve pairing precompile input length" + }, + "revert": { + "v": 0, + "d": "Base fee of the REVERT opcode" + }, + "staticcall": { + "v": 700, + "d": "Base fee of the STATICCALL opcode" + }, + "returndatasize": { + "v": 2, + "d": "Base fee of the RETURNDATASIZE opcode" + }, + "returndatacopy": { + "v": 3, + "d": "Base fee of the RETURNDATACOPY opcode" + } + }, + "vm": {}, + "pow": { + "minerReward": { + "v": "3000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 3000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/chainstart.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/chainstart.ts new file mode 100644 index 0000000..32f5630 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/chainstart.ts @@ -0,0 +1,439 @@ +export default { + "name": "chainstart", + "comment": "Start of the Ethereum main chain", + "url": "", + "status": "", + "gasConfig": { + "minGasLimit": { + "v": 5000, + "d": "Minimum the gas limit may ever be" + }, + "gasLimitBoundDivisor": { + "v": 1024, + "d": "The bound divisor of the gas limit, used in update calculations" + }, + "maxRefundQuotient": { + "v": 2, + "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" + } + }, + "gasPrices": { + "base": { + "v": 2, + "d": "Gas base cost, used e.g. for ChainID opcode (Istanbul)" + }, + "tierStep": { + "v": [0, 2, 3, 5, 8, 10, 20], + "d": "Once per operation, for a selection of them" + }, + "exp": { + "v": 10, + "d": "Base fee of the EXP opcode" + }, + "expByte": { + "v": 10, + "d": "Times ceil(log256(exponent)) for the EXP instruction" + }, + "sha3": { + "v": 30, + "d": "Base fee of the SHA3 opcode" + }, + "sha3Word": { + "v": 6, + "d": "Once per word of the SHA3 operation's data" + }, + "sload": { + "v": 50, + "d": "Base fee of the SLOAD opcode" + }, + "sstoreSet": { + "v": 20000, + "d": "Once per SSTORE operation if the zeroness changes from zero" + }, + "sstoreReset": { + "v": 5000, + "d": "Once per SSTORE operation if the zeroness does not change from zero" + }, + "sstoreRefund": { + "v": 15000, + "d": "Once per SSTORE operation if the zeroness changes to zero" + }, + "jumpdest": { + "v": 1, + "d": "Base fee of the JUMPDEST opcode" + }, + "log": { + "v": 375, + "d": "Base fee of the LOG opcode" + }, + "logData": { + "v": 8, + "d": "Per byte in a LOG* operation's data" + }, + "logTopic": { + "v": 375, + "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas" + }, + "create": { + "v": 32000, + "d": "Base fee of the CREATE opcode" + }, + "call": { + "v": 40, + "d": "Base fee of the CALL opcode" + }, + "callStipend": { + "v": 2300, + "d": "Free gas given at beginning of call" + }, + "callValueTransfer": { + "v": 9000, + "d": "Paid for CALL when the value transfor is non-zero" + }, + "callNewAccount": { + "v": 25000, + "d": "Paid for CALL when the destination address didn't exist prior" + }, + "selfdestructRefund": { + "v": 24000, + "d": "Refunded following a selfdestruct operation" + }, + "memory": { + "v": 3, + "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL" + }, + "quadCoeffDiv": { + "v": 512, + "d": "Divisor for the quadratic particle of the memory cost equation" + }, + "createData": { + "v": 200, + "d": "" + }, + "tx": { + "v": 21000, + "d": "Per transaction. NOTE: Not payable on data of calls between transactions" + }, + "txCreation": { + "v": 32000, + "d": "The cost of creating a contract via tx" + }, + "txDataZero": { + "v": 4, + "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions" + }, + "txDataNonZero": { + "v": 68, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + }, + "copy": { + "v": 3, + "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added" + }, + "ecRecover": { + "v": 3000, + "d": "" + }, + "sha256": { + "v": 60, + "d": "" + }, + "sha256Word": { + "v": 12, + "d": "" + }, + "ripemd160": { + "v": 600, + "d": "" + }, + "ripemd160Word": { + "v": 120, + "d": "" + }, + "identity": { + "v": 15, + "d": "" + }, + "identityWord": { + "v": 3, + "d": "" + }, + "stop": { + "v": 0, + "d": "Base fee of the STOP opcode" + }, + "add": { + "v": 3, + "d": "Base fee of the ADD opcode" + }, + "mul": { + "v": 5, + "d": "Base fee of the MUL opcode" + }, + "sub": { + "v": 3, + "d": "Base fee of the SUB opcode" + }, + "div": { + "v": 5, + "d": "Base fee of the DIV opcode" + }, + "sdiv": { + "v": 5, + "d": "Base fee of the SDIV opcode" + }, + "mod": { + "v": 5, + "d": "Base fee of the MOD opcode" + }, + "smod": { + "v": 5, + "d": "Base fee of the SMOD opcode" + }, + "addmod": { + "v": 8, + "d": "Base fee of the ADDMOD opcode" + }, + "mulmod": { + "v": 8, + "d": "Base fee of the MULMOD opcode" + }, + "signextend": { + "v": 5, + "d": "Base fee of the SIGNEXTEND opcode" + }, + "lt": { + "v": 3, + "d": "Base fee of the LT opcode" + }, + "gt": { + "v": 3, + "d": "Base fee of the GT opcode" + }, + "slt": { + "v": 3, + "d": "Base fee of the SLT opcode" + }, + "sgt": { + "v": 3, + "d": "Base fee of the SGT opcode" + }, + "eq": { + "v": 3, + "d": "Base fee of the EQ opcode" + }, + "iszero": { + "v": 3, + "d": "Base fee of the ISZERO opcode" + }, + "and": { + "v": 3, + "d": "Base fee of the AND opcode" + }, + "or": { + "v": 3, + "d": "Base fee of the OR opcode" + }, + "xor": { + "v": 3, + "d": "Base fee of the XOR opcode" + }, + "not": { + "v": 3, + "d": "Base fee of the NOT opcode" + }, + "byte": { + "v": 3, + "d": "Base fee of the BYTE opcode" + }, + "address": { + "v": 2, + "d": "Base fee of the ADDRESS opcode" + }, + "balance": { + "v": 20, + "d": "Base fee of the BALANCE opcode" + }, + "origin": { + "v": 2, + "d": "Base fee of the ORIGIN opcode" + }, + "caller": { + "v": 2, + "d": "Base fee of the CALLER opcode" + }, + "callvalue": { + "v": 2, + "d": "Base fee of the CALLVALUE opcode" + }, + "calldataload": { + "v": 3, + "d": "Base fee of the CALLDATALOAD opcode" + }, + "calldatasize": { + "v": 2, + "d": "Base fee of the CALLDATASIZE opcode" + }, + "calldatacopy": { + "v": 3, + "d": "Base fee of the CALLDATACOPY opcode" + }, + "codesize": { + "v": 2, + "d": "Base fee of the CODESIZE opcode" + }, + "codecopy": { + "v": 3, + "d": "Base fee of the CODECOPY opcode" + }, + "gasprice": { + "v": 2, + "d": "Base fee of the GASPRICE opcode" + }, + "extcodesize": { + "v": 20, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 20, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "blockhash": { + "v": 20, + "d": "Base fee of the BLOCKHASH opcode" + }, + "coinbase": { + "v": 2, + "d": "Base fee of the COINBASE opcode" + }, + "timestamp": { + "v": 2, + "d": "Base fee of the TIMESTAMP opcode" + }, + "number": { + "v": 2, + "d": "Base fee of the NUMBER opcode" + }, + "difficulty": { + "v": 2, + "d": "Base fee of the DIFFICULTY opcode" + }, + "gaslimit": { + "v": 2, + "d": "Base fee of the GASLIMIT opcode" + }, + "pop": { + "v": 2, + "d": "Base fee of the POP opcode" + }, + "mload": { + "v": 3, + "d": "Base fee of the MLOAD opcode" + }, + "mstore": { + "v": 3, + "d": "Base fee of the MSTORE opcode" + }, + "mstore8": { + "v": 3, + "d": "Base fee of the MSTORE8 opcode" + }, + "sstore": { + "v": 0, + "d": "Base fee of the SSTORE opcode" + }, + "jump": { + "v": 8, + "d": "Base fee of the JUMP opcode" + }, + "jumpi": { + "v": 10, + "d": "Base fee of the JUMPI opcode" + }, + "pc": { + "v": 2, + "d": "Base fee of the PC opcode" + }, + "msize": { + "v": 2, + "d": "Base fee of the MSIZE opcode" + }, + "gas": { + "v": 2, + "d": "Base fee of the GAS opcode" + }, + "push": { + "v": 3, + "d": "Base fee of the PUSH opcode" + }, + "dup": { + "v": 3, + "d": "Base fee of the DUP opcode" + }, + "swap": { + "v": 3, + "d": "Base fee of the SWAP opcode" + }, + "callcode": { + "v": 40, + "d": "Base fee of the CALLCODE opcode" + }, + "return": { + "v": 0, + "d": "Base fee of the RETURN opcode" + }, + "invalid": { + "v": 0, + "d": "Base fee of the INVALID opcode" + }, + "selfdestruct": { + "v": 0, + "d": "Base fee of the SELFDESTRUCT opcode" + } + }, + "vm": { + "stackLimit": { + "v": 1024, + "d": "Maximum size of VM stack allowed" + }, + "callCreateDepth": { + "v": 1024, + "d": "Maximum depth of call/create stack" + }, + "maxExtraDataSize": { + "v": 32, + "d": "Maximum size extra data may be after Genesis" + } + }, + "pow": { + "minimumDifficulty": { + "v": 131072, + "d": "The minimum that the difficulty may ever be" + }, + "difficultyBoundDivisor": { + "v": 2048, + "d": "The bound divisor of the difficulty, used in the update calculations" + }, + "durationLimit": { + "v": 13, + "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not" + }, + "epochDuration": { + "v": 30000, + "d": "Duration between proof-of-work epochs" + }, + "timebombPeriod": { + "v": 100000, + "d": "Exponential difficulty timebomb period" + }, + "minerReward": { + "v": "5000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 0, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/constantinople.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/constantinople.ts new file mode 100644 index 0000000..dd576fe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/constantinople.ts @@ -0,0 +1,69 @@ +export default { + "name": "constantinople", + "comment": "Postponed hardfork including EIP-1283 (SSTORE gas metering changes)", + "url": "https://eips.ethereum.org/EIPS/eip-1013", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "netSstoreNoopGas": { + "v": 200, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "netSstoreInitGas": { + "v": 20000, + "d": "Once per SSTORE operation from clean zero" + }, + "netSstoreCleanGas": { + "v": 5000, + "d": "Once per SSTORE operation from clean non-zero" + }, + "netSstoreDirtyGas": { + "v": 200, + "d": "Once per SSTORE operation from dirty" + }, + "netSstoreClearRefund": { + "v": 15000, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + }, + "netSstoreResetRefund": { + "v": 4800, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "netSstoreResetClearRefund": { + "v": 19800, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "shl": { + "v": 3, + "d": "Base fee of the SHL opcode" + }, + "shr": { + "v": 3, + "d": "Base fee of the SHR opcode" + }, + "sar": { + "v": 3, + "d": "Base fee of the SAR opcode" + }, + "extcodehash": { + "v": 400, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "create2": { + "v": 32000, + "d": "Base fee of the CREATE2 opcode" + } + }, + "vm": {}, + "pow": { + "minerReward": { + "v": "2000000000000000000", + "d": "The amount a miner gets rewarded for mining a block" + }, + "difficultyBombDelay": { + "v": 5000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/dao.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/dao.ts new file mode 100644 index 0000000..a565ec8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/dao.ts @@ -0,0 +1,11 @@ +export default { + "name": "dao", + "comment": "DAO rescue hardfork", + "url": "https://eips.ethereum.org/EIPS/eip-779", + "status": "Final", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/grayGlacier.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/grayGlacier.ts new file mode 100644 index 0000000..3c67d73 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/grayGlacier.ts @@ -0,0 +1,12 @@ +export default { + "name": "grayGlacier", + "comment": "Delaying the difficulty bomb to Mid September 2022", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md", + "status": "Draft", + "eips": [5133], + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/homestead.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/homestead.ts new file mode 100644 index 0000000..e6521fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/homestead.ts @@ -0,0 +1,16 @@ +export default { + "name": "homestead", + "comment": "Homestead hardfork with protocol and network changes", + "url": "https://eips.ethereum.org/EIPS/eip-606", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "delegatecall": { + "v": 40, + "d": "Base fee of the DELEGATECALL opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/index.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/index.ts new file mode 100644 index 0000000..6f646d1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/index.ts @@ -0,0 +1,53 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import chainstart from './chainstart.js'; +import dao from './dao.js'; +import homestead from './homestead.js'; +import tangerineWhistle from './tangerineWhistle.js'; +import spuriousDragon from './spuriousDragon.js'; +import byzantium from './byzantium.js'; +import constantinople from './constantinople.js'; +import petersburg from './petersburg.js'; +import istanbul from './istanbul.js'; +import muirGlacier from './muirGlacier.js'; +import berlin from './berlin.js'; +import london from './london.js'; +import shanghai from './shanghai.js'; +import arrowGlacier from './arrowGlacier.js'; +import grayGlacier from './grayGlacier.js'; +import mergeForkIdTransition from './mergeForkIdTransition.js'; +import merge from './merge.js'; + +export const hardforks: { [key: string]: any } = { + chainstart, + homestead, + dao, + tangerineWhistle, + spuriousDragon, + byzantium, + constantinople, + petersburg, + istanbul, + muirGlacier, + berlin, + london, + shanghai, + arrowGlacier, + grayGlacier, + mergeForkIdTransition, + merge, +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/istanbul.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/istanbul.ts new file mode 100644 index 0000000..96f3a66 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/istanbul.ts @@ -0,0 +1,88 @@ +export default { + "name": "istanbul", + "comment": "HF targeted for December 2019 following the Constantinople/Petersburg HF", + "url": "https://eips.ethereum.org/EIPS/eip-1679", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "blake2Round": { + "v": 1, + "d": "Gas cost per round for the Blake2 F precompile" + }, + "ecAdd": { + "v": 150, + "d": "Gas costs for curve addition precompile" + }, + "ecMul": { + "v": 6000, + "d": "Gas costs for curve multiplication precompile" + }, + "ecPairing": { + "v": 45000, + "d": "Base gas costs for curve pairing precompile" + }, + "ecPairingWord": { + "v": 34000, + "d": "Gas costs regarding curve pairing precompile input length" + }, + "txDataNonZero": { + "v": 16, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + }, + "sstoreSentryGasEIP2200": { + "v": 2300, + "d": "Minimum gas required to be present for an SSTORE call, not consumed" + }, + "sstoreNoopGasEIP2200": { + "v": 800, + "d": "Once per SSTORE operation if the value doesn't change" + }, + "sstoreDirtyGasEIP2200": { + "v": 800, + "d": "Once per SSTORE operation if a dirty value is changed" + }, + "sstoreInitGasEIP2200": { + "v": 20000, + "d": "Once per SSTORE operation from clean zero to non-zero" + }, + "sstoreInitRefundEIP2200": { + "v": 19200, + "d": "Once per SSTORE operation for resetting to the original zero value" + }, + "sstoreCleanGasEIP2200": { + "v": 5000, + "d": "Once per SSTORE operation from clean non-zero to something else" + }, + "sstoreCleanRefundEIP2200": { + "v": 4200, + "d": "Once per SSTORE operation for resetting to the original non-zero value" + }, + "sstoreClearRefundEIP2200": { + "v": 15000, + "d": "Once per SSTORE operation for clearing an originally existing storage slot" + }, + "balance": { + "v": 700, + "d": "Base fee of the BALANCE opcode" + }, + "extcodehash": { + "v": 700, + "d": "Base fee of the EXTCODEHASH opcode" + }, + "chainid": { + "v": 2, + "d": "Base fee of the CHAINID opcode" + }, + "selfbalance": { + "v": 5, + "d": "Base fee of the SELFBALANCE opcode" + }, + "sload": { + "v": 800, + "d": "Base fee of the SLOAD opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/london.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/london.ts new file mode 100644 index 0000000..6d0ec4a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/london.ts @@ -0,0 +1,8 @@ +export default { + "name": "london", + "comment": "HF targeted for July 2021 following the Berlin fork", + "url": "https://github.com/ethereum/eth1.0-specs/blob/master/network-upgrades/mainnet-upgrades/london.md", + "status": "Final", + "eips": [1559, 3198, 3529, 3541] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/merge.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/merge.ts new file mode 100644 index 0000000..db48aa3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/merge.ts @@ -0,0 +1,13 @@ +export default { + "name": "merge", + "comment": "Hardfork to upgrade the consensus mechanism to Proof-of-Stake", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/merge.md", + "status": "Final", + "consensus": { + "type": "pos", + "algorithm": "casper", + "casper": {} + }, + "eips": [3675, 4399] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts new file mode 100644 index 0000000..f4df67b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts @@ -0,0 +1,8 @@ +export default { + "name": "mergeForkIdTransition", + "comment": "Pre-merge hardfork to fork off non-upgraded clients", + "url": "https://eips.ethereum.org/EIPS/eip-3675", + "status": "Draft", + "eips": [] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/muirGlacier.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/muirGlacier.ts new file mode 100644 index 0000000..a7d02c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/muirGlacier.ts @@ -0,0 +1,16 @@ +export default { + "name": "muirGlacier", + "comment": "HF to delay the difficulty bomb", + "url": "https://eips.ethereum.org/EIPS/eip-2384", + "status": "Final", + "gasConfig": {}, + "gasPrices": {}, + "vm": {}, + "pow": { + "difficultyBombDelay": { + "v": 9000000, + "d": "the amount of blocks to delay the difficulty bomb with" + } + } +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/petersburg.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/petersburg.ts new file mode 100644 index 0000000..cca4005 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/petersburg.ts @@ -0,0 +1,40 @@ +export default { + "name": "petersburg", + "comment": "Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople", + "url": "https://eips.ethereum.org/EIPS/eip-1716", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "netSstoreNoopGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreInitGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreCleanGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreDirtyGas": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreClearRefund": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreResetRefund": { + "v": null, + "d": "Removed along EIP-1283" + }, + "netSstoreResetClearRefund": { + "v": null, + "d": "Removed along EIP-1283" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/shanghai.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/shanghai.ts new file mode 100644 index 0000000..736e331 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/shanghai.ts @@ -0,0 +1,8 @@ +export default { + "name": "shanghai", + "comment": "Next feature hardfork after the merge hardfork having withdrawals, warm coinbase, push0, limit/meter initcode", + "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md", + "status": "Final", + "eips": [3651, 3855, 3860, 4895] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/sharding.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/sharding.ts new file mode 100644 index 0000000..e164e5f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/sharding.ts @@ -0,0 +1,8 @@ +export default { + "name": "shardingFork", + "comment": "Internal hardfork to test proto-danksharding (do not use in production)", + "url": "https://eips.ethereum.org/EIPS/eip-4844", + "status": "Experimental", + "eips": [4844] +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts new file mode 100644 index 0000000..e1ed0ed --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts @@ -0,0 +1,21 @@ +export default { + "name": "spuriousDragon", + "comment": "HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit", + "url": "https://eips.ethereum.org/EIPS/eip-607", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "expByte": { + "v": 50, + "d": "Times ceil(log256(exponent)) for the EXP instruction" + } + }, + "vm": { + "maxCodeSize": { + "v": 24576, + "d": "Maximum length of contract code" + } + }, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts new file mode 100644 index 0000000..ffb2bf4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts @@ -0,0 +1,44 @@ +export default { + "name": "tangerineWhistle", + "comment": "Hardfork with gas cost changes for IO-heavy operations", + "url": "https://eips.ethereum.org/EIPS/eip-608", + "status": "Final", + "gasConfig": {}, + "gasPrices": { + "sload": { + "v": 200, + "d": "Once per SLOAD operation" + }, + "call": { + "v": 700, + "d": "Once per CALL operation & message call transaction" + }, + "extcodesize": { + "v": 700, + "d": "Base fee of the EXTCODESIZE opcode" + }, + "extcodecopy": { + "v": 700, + "d": "Base fee of the EXTCODECOPY opcode" + }, + "balance": { + "v": 400, + "d": "Base fee of the BALANCE opcode" + }, + "delegatecall": { + "v": 700, + "d": "Base fee of the DELEGATECALL opcode" + }, + "callcode": { + "v": 700, + "d": "Base fee of the CALLCODE opcode" + }, + "selfdestruct": { + "v": 5000, + "d": "Base fee of the SELFDESTRUCT opcode" + } + }, + "vm": {}, + "pow": {} +} + ; \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/index.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/index.ts new file mode 100644 index 0000000..3602a0f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/index.ts @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// @ethereumjs/common version 3.1.1 +export * from './common.js'; +export * from './enums.js'; +export * from './types.js'; +export * from './utils.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/types.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/types.ts new file mode 100644 index 0000000..9d5c0bb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/types.ts @@ -0,0 +1,191 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import type { Chain, ConsensusAlgorithm, ConsensusType, Hardfork } from './enums.js'; + +export interface ChainName { + [chainId: string]: string; +} + +export type CliqueConfig = { + period: number; + epoch: number; +}; + +export type EthashConfig = Record; + +export type CasperConfig = Record; + +export interface GenesisBlockConfig { + timestamp?: string; + gasLimit: number; + difficulty: number; + nonce: string; + extraData: string; + baseFeePerGas?: string; +} + +export interface HardforkConfig { + name: Hardfork | string; + // eslint-disable-next-line @typescript-eslint/ban-types + block: number | null; // null is used for hardforks that should not be applied -- since `undefined` isn't a valid value in JSON + ttd?: bigint | string; + timestamp?: number | string; + // eslint-disable-next-line @typescript-eslint/ban-types + forkHash?: string | null; +} + +export interface BootstrapNodeConfig { + ip: string; + port: number | string; + network?: string; + chainId?: number; + id: string; + location: string; + comment: string; +} + +export interface ChainConfig { + name: string; + chainId: number | bigint; + networkId: number | bigint; + defaultHardfork?: string; + comment?: string; + url?: string; + genesis: GenesisBlockConfig; + hardforks: HardforkConfig[]; + bootstrapNodes?: BootstrapNodeConfig[]; + dnsNetworks?: string[]; + consensus: { + type: ConsensusType | string; + algorithm: ConsensusAlgorithm | string; + clique?: CliqueConfig; + ethash?: EthashConfig; + casper?: CasperConfig; + }; +} +export interface ChainsConfig { + [key: string]: ChainConfig | ChainName; +} + +interface BaseOpts { + /** + * String identifier ('byzantium') for hardfork or {@link Hardfork} enum. + * + * Default: Hardfork.London + */ + hardfork?: string | Hardfork; + /** + * Selected EIPs which can be activated, please use an array for instantiation + * (e.g. `eips: [ 2537, ]`) + * + * Currently supported: + * + * - [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537) - BLS12-381 precompiles + */ + eips?: number[]; +} + +/** + * Options for instantiating a {@link Common} instance. + */ +export interface CommonOpts extends BaseOpts { + /** + * Chain name ('mainnet'), id (1), or {@link Chain} enum, + * either from a chain directly supported or a custom chain + * passed in via {@link CommonOpts.customChains}. + */ + chain: string | number | Chain | bigint | object; + /** + * Initialize (in addition to the supported chains) with the selected + * custom chains. Custom genesis state should be passed to the Blockchain class if used. + * + * Usage (directly with the respective chain initialization via the {@link CommonOpts.chain} option): + * + * ```javascript + * import myCustomChain1 from '[PATH_TO_MY_CHAINS]/myCustomChain1.json' + * const common = new Common({ chain: 'myCustomChain1', customChains: [ myCustomChain1 ]}) + * ``` + */ + customChains?: ChainConfig[]; +} + +/** + * Options to be used with the {@link Common.custom} static constructor. + */ +export interface CustomCommonOpts extends BaseOpts { + /** + * The name (`mainnet`), id (`1`), or {@link Chain} enum of + * a standard chain used to base the custom chain params on. + */ + baseChain?: string | number | Chain | bigint; +} + +export interface GethConfigOpts extends BaseOpts { + chain?: string; + genesisHash?: Uint8Array; + mergeForkIdPostMerge?: boolean; +} + +/* + * A type that represents a `0x`-prefixed hex string. + */ +export type PrefixedHexString = string; + +/* + * A type that represents an input that can be converted to a Buffer. + */ +export type Uint8ArrayLike = Uint8Array | number[] | number | bigint | PrefixedHexString; + +/* + * A type that represents an input that can be converted to a BigInt. + */ +export type BigIntLike = bigint | PrefixedHexString | number | Uint8Array; + +/* + * A type that represents an object that has a `toArray()` method. + */ +export interface TransformableToArray { + toArray(): Uint8Array; +} + +export type NestedUint8Array = Array; +/** + * Type output options + */ +export enum TypeOutput { + Number, + BigInt, + Uint8Array, + PrefixedHexString, +} + +export type TypeOutputReturnType = { + [TypeOutput.Number]: number; + [TypeOutput.BigInt]: bigint; + [TypeOutput.Uint8Array]: Uint8Array; + [TypeOutput.PrefixedHexString]: PrefixedHexString; +}; +export type ToBytesInputTypes = + | PrefixedHexString + | number + | bigint + | Uint8Array + | number[] + | TransformableToArray + // eslint-disable-next-line @typescript-eslint/ban-types + | null + | undefined; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/common/utils.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/utils.ts new file mode 100644 index 0000000..f243ede --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/common/utils.ts @@ -0,0 +1,577 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isHexPrefixed, isHexString } from 'web3-validator'; +import { bytesToHex, hexToBytes, numberToHex } from 'web3-utils'; +import { secp256k1 } from '../tx/constants.js'; +import { Hardfork } from './enums.js'; +import { ToBytesInputTypes, TypeOutput, TypeOutputReturnType } from './types.js'; + +type ConfigHardfork = + // eslint-disable-next-line @typescript-eslint/ban-types + | { name: string; block: null; timestamp: number } + | { name: string; block: number; timestamp?: number }; + +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +export const stripHexPrefix = (str: string): string => { + if (typeof str !== 'string') + throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`); + + return isHexPrefixed(str) ? str.slice(2) : str; +}; +/** + * Transforms Geth formatted nonce (i.e. hex string) to 8 byte 0x-prefixed string used internally + * @param nonce string parsed from the Geth genesis file + * @returns nonce as a 0x-prefixed 8 byte string + */ +function formatNonce(nonce: string): string { + if (!nonce || nonce === '0x0') { + return '0x0000000000000000'; + } + if (isHexPrefixed(nonce)) { + return `0x${stripHexPrefix(nonce).padStart(16, '0')}`; + } + return `0x${nonce.padStart(16, '0')}`; +} + +/** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ +const intToHex = function (i: number) { + if (!Number.isSafeInteger(i) || i < 0) { + throw new Error(`Received an invalid integer type: ${i}`); + } + return `0x${i.toString(16)}`; +}; + +/** + * Converts Geth genesis parameters to an EthereumJS compatible `CommonOpts` object + * @param json object representing the Geth genesis file + * @param optional mergeForkIdPostMerge which clarifies the placement of MergeForkIdTransition + * hardfork, which by default is post merge as with the merged eth networks but could also come + * before merge like in kiln genesis + * @returns genesis parameters in a `CommonOpts` compliant object + */ +function parseGethParams(json: any, mergeForkIdPostMerge = true) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { + name, + config, + difficulty, + mixHash, + gasLimit, + coinbase, + baseFeePerGas, + }: { + name: string; + config: any; + difficulty: string; + mixHash: string; + gasLimit: string; + coinbase: string; + baseFeePerGas: string; + } = json; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + let { extraData, timestamp, nonce }: { extraData: string; timestamp: string; nonce: string } = + json; + const genesisTimestamp = Number(timestamp); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { chainId }: { chainId: number } = config; + + // geth is not strictly putting empty fields with a 0x prefix + if (extraData === '') { + extraData = '0x'; + } + // geth may use number for timestamp + if (!isHexPrefixed(timestamp)) { + // eslint-disable-next-line radix + timestamp = intToHex(parseInt(timestamp)); + } + // geth may not give us a nonce strictly formatted to an 8 byte hex string + if (nonce.length !== 18) { + nonce = formatNonce(nonce); + } + + // EIP155 and EIP158 are both part of Spurious Dragon hardfork and must occur at the same time + // but have different configuration parameters in geth genesis parameters + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (config.eip155Block !== config.eip158Block) { + throw new Error( + 'EIP155 block number must equal EIP 158 block number since both are part of SpuriousDragon hardfork and the client only supports activating the full hardfork', + ); + } + + const params = { + name, + chainId, + networkId: chainId, + genesis: { + timestamp, + // eslint-disable-next-line radix + gasLimit: parseInt(gasLimit), // geth gasLimit and difficulty are hex strings while ours are `number`s + // eslint-disable-next-line radix + difficulty: parseInt(difficulty), + nonce, + extraData, + mixHash, + coinbase, + baseFeePerGas, + }, + hardfork: undefined as string | undefined, + hardforks: [] as ConfigHardfork[], + bootstrapNodes: [], + consensus: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config.clique !== undefined + ? { + type: 'poa', + algorithm: 'clique', + clique: { + // The recent geth genesis seems to be using blockperiodseconds + // and epochlength for clique specification + // see: https://hackmd.io/PqZgMpnkSWCWv5joJoFymQ + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + period: config.clique.period ?? config.clique.blockperiodseconds, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + epoch: config.clique.epoch ?? config.clique.epochlength, + }, + } + : { + type: 'pow', + algorithm: 'ethash', + ethash: {}, + }, + }; + + const forkMap: { [key: string]: { name: string; postMerge?: boolean; isTimestamp?: boolean } } = + { + [Hardfork.Homestead]: { name: 'homesteadBlock' }, + [Hardfork.Dao]: { name: 'daoForkBlock' }, + [Hardfork.TangerineWhistle]: { name: 'eip150Block' }, + [Hardfork.SpuriousDragon]: { name: 'eip155Block' }, + [Hardfork.Byzantium]: { name: 'byzantiumBlock' }, + [Hardfork.Constantinople]: { name: 'constantinopleBlock' }, + [Hardfork.Petersburg]: { name: 'petersburgBlock' }, + [Hardfork.Istanbul]: { name: 'istanbulBlock' }, + [Hardfork.MuirGlacier]: { name: 'muirGlacierBlock' }, + [Hardfork.Berlin]: { name: 'berlinBlock' }, + [Hardfork.London]: { name: 'londonBlock' }, + [Hardfork.MergeForkIdTransition]: { + name: 'mergeForkBlock', + postMerge: mergeForkIdPostMerge, + }, + [Hardfork.Shanghai]: { name: 'shanghaiTime', postMerge: true, isTimestamp: true }, + [Hardfork.ShardingForkDev]: { + name: 'shardingForkTime', + postMerge: true, + isTimestamp: true, + }, + }; + + // forkMapRev is the map from config field name to Hardfork + const forkMapRev = Object.keys(forkMap).reduce<{ [key: string]: string }>((acc, elem) => { + acc[forkMap[elem].name] = elem; + return acc; + }, {}); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const configHardforkNames = Object.keys(config).filter( + // eslint-disable-next-line no-null/no-null, @typescript-eslint/no-unsafe-member-access + key => forkMapRev[key] !== undefined && config[key] !== undefined && config[key] !== null, + ); + + params.hardforks = configHardforkNames + .map(nameBlock => ({ + name: forkMapRev[nameBlock], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + block: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + forkMap[forkMapRev[nameBlock]].isTimestamp === true || + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof config[nameBlock] !== 'number' + ? // eslint-disable-next-line no-null/no-null + null + : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config[nameBlock], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + timestamp: + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + forkMap[forkMapRev[nameBlock]].isTimestamp === true && + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof config[nameBlock] === 'number' + ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + config[nameBlock] + : undefined, + })) + // eslint-disable-next-line no-null/no-null + .filter(fork => fork.block !== null || fork.timestamp !== undefined) as ConfigHardfork[]; + + params.hardforks.sort( + (a: ConfigHardfork, b: ConfigHardfork) => (a.block ?? Infinity) - (b.block ?? Infinity), + ); + + params.hardforks.sort( + (a: ConfigHardfork, b: ConfigHardfork) => + (a.timestamp ?? genesisTimestamp) - (b.timestamp ?? genesisTimestamp), + ); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (config.terminalTotalDifficulty !== undefined) { + // Following points need to be considered for placement of merge hf + // - Merge hardfork can't be placed at genesis + // - Place merge hf before any hardforks that require CL participation for e.g. withdrawals + // - Merge hardfork has to be placed just after genesis if any of the genesis hardforks make CL + // necessary for e.g. withdrawals + const mergeConfig = { + name: Hardfork.Merge, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + ttd: config.terminalTotalDifficulty, + // eslint-disable-next-line no-null/no-null + block: null, + }; + + // Merge hardfork has to be placed before first hardfork that is dependent on merge + const postMergeIndex = params.hardforks.findIndex( + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (hf: any) => forkMap[hf.name]?.postMerge === true, + ); + if (postMergeIndex !== -1) { + params.hardforks.splice(postMergeIndex, 0, mergeConfig as unknown as ConfigHardfork); + } else { + params.hardforks.push(mergeConfig as unknown as ConfigHardfork); + } + } + + const latestHardfork = params.hardforks.length > 0 ? params.hardforks.slice(-1)[0] : undefined; + params.hardfork = latestHardfork?.name; + params.hardforks.unshift({ name: Hardfork.Chainstart, block: 0 }); + + return params; +} + +/** + * Parses a genesis.json exported from Geth into parameters for Common instance + * @param json representing the Geth genesis file + * @param name optional chain name + * @returns parsed params + */ +export function parseGethGenesis(json: any, name?: string, mergeForkIdPostMerge?: boolean) { + try { + if (['config', 'difficulty', 'gasLimit', 'alloc'].some(field => !(field in json))) { + throw new Error('Invalid format, expected geth genesis fields missing'); + } + if (name !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-param-reassign + json.name = name; + } + return parseGethParams(json, mergeForkIdPostMerge); + } catch (e: any) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-template-expressions + throw new Error(`Error parsing parameters file: ${e.message}`); + } +} + +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +export function padToEven(value: string): string { + let a = value; + + if (typeof a !== 'string') { + throw new Error(`[padToEven] value must be type 'string', received ${typeof a}`); + } + + if (a.length % 2) a = `0${a}`; + + return a; +} + +/** + * Converts an `Number` to a `Uint8Array` + * @param {Number} i + * @return {Uint8Array} + */ +export const intToUint8Array = function (i: number) { + const hex = intToHex(i); + return hexToBytes(`0x${padToEven(hex.slice(2))}`); +}; + +/** + * Attempts to turn a value into a `Uint8Array`. + * Inputs supported: `Uint8Array` `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toUint8Array()` method. + * @param v the value + */ +export const toUint8Array = function (v: ToBytesInputTypes): Uint8Array { + // eslint-disable-next-line no-null/no-null + if (v === null || v === undefined) { + return new Uint8Array(); + } + + if (v instanceof Uint8Array) { + return v; + } + + if (Array.isArray(v)) { + return Uint8Array.from(v); + } + + if (typeof v === 'string') { + if (!isHexString(v)) { + throw new Error( + `Cannot convert string to Uint8Array. only supports 0x-prefixed hex strings and this string was given: ${v}`, + ); + } + return hexToBytes(padToEven(stripHexPrefix(v))); + } + + if (typeof v === 'number') { + return toUint8Array(numberToHex(v)); + } + + if (typeof v === 'bigint') { + if (v < BigInt(0)) { + throw new Error(`Cannot convert negative bigint to Uint8Array. Given: ${v}`); + } + let n = v.toString(16); + if (n.length % 2) n = `0${n}`; + return toUint8Array(`0x${n}`); + } + + if (v.toArray) { + // converts a BN to a Uint8Array + return Uint8Array.from(v.toArray()); + } + + throw new Error('invalid type'); +}; + +/** + * Converts a {@link Uint8Array} to a {@link bigint} + */ +export function uint8ArrayToBigInt(buf: Uint8Array) { + const hex = bytesToHex(buf); + if (hex === '0x') { + return BigInt(0); + } + return BigInt(hex); +} + +/** + * Converts a {@link bigint} to a {@link Uint8Array} + */ +export function bigIntToUint8Array(num: bigint) { + return toUint8Array(`0x${num.toString(16)}`); +} + +/** + * Returns a Uint8Array filled with 0s. + * @param bytes the number of bytes the Uint8Array should be + */ +export const zeros = function (bytes: number): Uint8Array { + return new Uint8Array(bytes).fill(0); +}; + +/** + * Pads a `Uint8Array` with zeros till it has `length` bytes. + * Truncates the beginning or end of input if its length exceeds `length`. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @param right whether to start padding form the left or right + * @return (Uint8Array) + */ +const setLength = function (msg: Uint8Array, length: number, right: boolean) { + const buf = zeros(length); + if (right) { + if (msg.length < length) { + buf.set(msg); + return buf; + } + return msg.subarray(0, length); + } + if (msg.length < length) { + buf.set(msg, length - msg.length); + return buf; + } + return msg.subarray(-length); +}; + +/** + * Throws if input is not a Uint8Array + * @param {Uint8Array} input value to check + */ +export function assertIsUint8Array(input: unknown): asserts input is Uint8Array { + if (!(input instanceof Uint8Array)) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + const msg = `This method only supports Uint8Array but input was: ${input}`; + throw new Error(msg); + } +} +/** + * Left Pads a `Uint8Array` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Uint8Array) + * @param length the number of bytes the output should be + * @return (Uint8Array) + */ +export const setLengthLeft = function (msg: Uint8Array, length: number) { + assertIsUint8Array(msg); + return setLength(msg, length, false); +}; + +/** + * Trims leading zeros from a `Uint8Array`, `String` or `Number[]`. + * @param a (Uint8Array|Array|String) + * @return (Uint8Array|Array|String) + */ +export function stripZeros(a: T): T { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment + let first = a[0]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + while (a.length > 0 && first.toString() === '0') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, prefer-destructuring, @typescript-eslint/no-unsafe-call, no-param-reassign + a = a.slice(1) as T; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, prefer-destructuring, @typescript-eslint/no-unsafe-member-access + first = a[0]; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return a; +} + +/** + * Trims leading zeros from a `Uint8Array`. + * @param a (Uint8Array) + * @return (Uint8Array) + */ +export const unpadUint8Array = function (a: Uint8Array): Uint8Array { + assertIsUint8Array(a); + return stripZeros(a); +}; + +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +export const bigIntToHex = (num: bigint) => `0x${num.toString(16)}`; + +/** + * Convert value from bigint to an unpadded Uint8Array + * (useful for RLP transport) + * @param value value to convert + */ +export function bigIntToUnpaddedUint8Array(value: bigint): Uint8Array { + return unpadUint8Array(bigIntToUint8Array(value)); +} + +function calculateSigRecovery(v: bigint, chainId?: bigint): bigint { + if (v === BigInt(0) || v === BigInt(1)) return v; + + if (chainId === undefined) { + return v - BigInt(27); + } + return v - (chainId * BigInt(2) + BigInt(35)); +} + +function isValidSigRecovery(recovery: bigint): boolean { + return recovery === BigInt(0) || recovery === BigInt(1); +} + +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +export const ecrecover = function ( + msgHash: Uint8Array, + v: bigint, + r: Uint8Array, + s: Uint8Array, + chainId?: bigint, +): Uint8Array { + const recovery = calculateSigRecovery(v, chainId); + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value'); + } + + const senderPubKey = new secp256k1.Signature(uint8ArrayToBigInt(r), uint8ArrayToBigInt(s)) + .addRecoveryBit(Number(recovery)) + .recoverPublicKey(msgHash) + .toRawBytes(false); + return senderPubKey.slice(1); +}; + +/** + * Convert an input to a specified type. + * Input of null/undefined returns null/undefined regardless of the output type. + * @param input value to convert + * @param outputType type to output + */ +// eslint-disable-next-line @typescript-eslint/ban-types +export function toType(input: null, outputType: T): null; +export function toType(input: undefined, outputType: T): undefined; +export function toType( + input: ToBytesInputTypes, + outputType: T, +): TypeOutputReturnType[T]; +export function toType( + input: ToBytesInputTypes, + outputType: T, + // eslint-disable-next-line @typescript-eslint/ban-types +): TypeOutputReturnType[T] | undefined | null { + // eslint-disable-next-line no-null/no-null + if (input === null) { + // eslint-disable-next-line no-null/no-null + return null; + } + if (input === undefined) { + return undefined; + } + + if (typeof input === 'string' && !isHexString(input)) { + throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`); + } else if (typeof input === 'number' && !Number.isSafeInteger(input)) { + throw new Error( + 'The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)', + ); + } + + const output = toUint8Array(input); + + switch (outputType) { + case TypeOutput.Uint8Array: + return output as TypeOutputReturnType[T]; + case TypeOutput.BigInt: + return uint8ArrayToBigInt(output) as TypeOutputReturnType[T]; + case TypeOutput.Number: { + const bigInt = uint8ArrayToBigInt(output); + if (bigInt > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error( + 'The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)', + ); + } + return Number(bigInt) as TypeOutputReturnType[T]; + } + case TypeOutput.PrefixedHexString: + return bytesToHex(output) as TypeOutputReturnType[T]; + default: + throw new Error('unknown outputType'); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/index.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/index.ts new file mode 100644 index 0000000..3d128c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/index.ts @@ -0,0 +1,45 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The web3.eth.accounts contains functions to generate Ethereum accounts and sign transactions and data. + * + * **_NOTE:_** This package has NOT been audited and might potentially be unsafe. Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production! + * + * + * To use this package standalone and use its methods use: + * ```ts + * import { create, decrypt } from 'web3-eth-accounts'; // .... + * ``` + * + * To use this package within the web3 object use: + * + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // now you have access to the accounts class + * web3.eth.accounts.create(); + * ``` + */ + +export * from './wallet.js'; +export * from './account.js'; +export * from './types.js'; +export * from './schemas.js'; +export * from './common/index.js'; +export * from './tx/index.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/schemas.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/schemas.ts new file mode 100644 index 0000000..3c88da7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/schemas.ts @@ -0,0 +1,39 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export const keyStoreSchema = { + type: 'object', + required: ['crypto', 'id', 'version', 'address'], + properties: { + crypto: { + type: 'object', + required: ['cipher', 'ciphertext', 'cipherparams', 'kdf', 'kdfparams', 'mac'], + properties: { + cipher: { type: 'string' }, + ciphertext: { type: 'string' }, + cipherparams: { type: 'object' }, + kdf: { type: 'string' }, + kdfparams: { type: 'object' }, + salt: { type: 'string' }, + mac: { type: 'string' }, + }, + }, + id: { type: 'string' }, + version: { type: 'number' }, + address: { type: 'string' }, + }, +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/address.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/address.ts new file mode 100644 index 0000000..7d6f1ac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/address.ts @@ -0,0 +1,85 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { bytesToHex, uint8ArrayEquals } from 'web3-utils'; +import { secp256k1 } from './constants.js'; +import { assertIsUint8Array, zeros } from '../common/utils.js'; + +export class Address { + public readonly buf: Uint8Array; + + public constructor(buf: Uint8Array) { + if (buf.length !== 20) { + throw new Error('Invalid address length'); + } + this.buf = buf; + } + + /** + * Returns the zero address. + */ + public static zero(): Address { + return new Address(zeros(20)); + } + + /** + * Is address equal to another. + */ + public equals(address: Address): boolean { + return uint8ArrayEquals(this.buf, address.buf); + } + + /** + * Is address zero. + */ + public isZero(): boolean { + return this.equals(Address.zero()); + } + + /** + * Returns hex encoding of address. + */ + public toString(): string { + return bytesToHex(this.buf); + } + + /** + * Returns Uint8Array representation of address. + */ + public toArray(): Uint8Array { + return this.buf; + } + + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ + public static publicToAddress(_pubKey: Uint8Array, sanitize = false): Uint8Array { + let pubKey = _pubKey; + assertIsUint8Array(pubKey); + if (sanitize && pubKey.length !== 64) { + pubKey = secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1); + } + if (pubKey.length !== 64) { + throw new Error('Expected pubKey to be of length 64'); + } + // Only take the lower 160bits of the hash + return keccak256(pubKey).slice(-20); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/baseTransaction.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/baseTransaction.ts new file mode 100644 index 0000000..f0cace3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/baseTransaction.ts @@ -0,0 +1,581 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Numbers } from 'web3-types'; +import { bytesToHex } from 'web3-utils'; +import { MAX_INTEGER, MAX_UINT64, SECP256K1_ORDER_DIV_2, secp256k1 } from './constants.js'; +import { toUint8Array, uint8ArrayToBigInt, unpadUint8Array } from '../common/utils.js'; +import { Common } from '../common/common.js'; +import { Hardfork, Chain } from '../common/enums.js'; +import type { + AccessListEIP2930TxData, + AccessListEIP2930ValuesArray, + FeeMarketEIP1559TxData, + FeeMarketEIP1559ValuesArray, + JsonTx, + TxData, + TxOptions, + TxValuesArray, +} from './types.js'; +import { Capability, ECDSASignature } from './types.js'; +import { Address } from './address.js'; +import { checkMaxInitCodeSize } from './utils.js'; + +interface TransactionCache { + hash: Uint8Array | undefined; + dataFee?: { + value: bigint; + hardfork: string | Hardfork; + }; +} + +/** + * This base class will likely be subject to further + * refactoring along the introduction of additional tx types + * on the Ethereum network. + * + * It is therefore not recommended to use directly. + */ +export abstract class BaseTransaction { + private readonly _type: number; + + public readonly nonce: bigint; + public readonly gasLimit: bigint; + public readonly to?: Address; + public readonly value: bigint; + public readonly data: Uint8Array; + + public readonly v?: bigint; + public readonly r?: bigint; + public readonly s?: bigint; + + public readonly common!: Common; + + protected cache: TransactionCache = { + hash: undefined, + dataFee: undefined, + }; + + protected readonly txOptions: TxOptions; + + /** + * List of tx type defining EIPs, + * e.g. 1559 (fee market) and 2930 (access lists) + * for FeeMarketEIP1559Transaction objects + */ + protected activeCapabilities: number[] = []; + + /** + * The default chain the tx falls back to if no Common + * is provided and if the chain can't be derived from + * a passed in chainId (only EIP-2718 typed txs) or + * EIP-155 signature (legacy txs). + * + * @hidden + */ + protected DEFAULT_CHAIN = Chain.Mainnet; + + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK: string | Hardfork = Hardfork.Merge; + + public constructor( + txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData, + opts: TxOptions, + ) { + const { nonce, gasLimit, to, value, data, v, r, s, type } = txData; + this._type = Number(uint8ArrayToBigInt(toUint8Array(type))); + + this.txOptions = opts; + + const toB = toUint8Array(to === '' ? '0x' : to); + const vB = toUint8Array(v === '' ? '0x' : v); + const rB = toUint8Array(r === '' ? '0x' : r); + const sB = toUint8Array(s === '' ? '0x' : s); + + this.nonce = uint8ArrayToBigInt(toUint8Array(nonce === '' ? '0x' : nonce)); + this.gasLimit = uint8ArrayToBigInt(toUint8Array(gasLimit === '' ? '0x' : gasLimit)); + this.to = toB.length > 0 ? new Address(toB) : undefined; + this.value = uint8ArrayToBigInt(toUint8Array(value === '' ? '0x' : value)); + this.data = toUint8Array(data === '' ? '0x' : data); + + this.v = vB.length > 0 ? uint8ArrayToBigInt(vB) : undefined; + this.r = rB.length > 0 ? uint8ArrayToBigInt(rB) : undefined; + this.s = sB.length > 0 ? uint8ArrayToBigInt(sB) : undefined; + + this._validateCannotExceedMaxInteger({ value: this.value, r: this.r, s: this.s }); + + // geth limits gasLimit to 2^64-1 + this._validateCannotExceedMaxInteger({ gasLimit: this.gasLimit }, 64); + + // EIP-2681 limits nonce to 2^64-1 (cannot equal 2^64-1) + this._validateCannotExceedMaxInteger({ nonce: this.nonce }, 64, true); + // eslint-disable-next-line no-null/no-null + const createContract = this.to === undefined || this.to === null; + const allowUnlimitedInitCodeSize = opts.allowUnlimitedInitCodeSize ?? false; + const common = opts.common ?? this._getCommon(); + if (createContract && common.isActivatedEIP(3860) && !allowUnlimitedInitCodeSize) { + checkMaxInitCodeSize(common, this.data.length); + } + } + + /** + * Returns the transaction type. + * + * Note: legacy txs will return tx type `0`. + */ + public get type() { + return this._type; + } + + /** + * Checks if a tx type defining capability is active + * on a tx, for example the EIP-1559 fee market mechanism + * or the EIP-2930 access list feature. + * + * Note that this is different from the tx type itself, + * so EIP-2930 access lists can very well be active + * on an EIP-1559 tx for example. + * + * This method can be useful for feature checks if the + * tx type is unknown (e.g. when instantiated with + * the tx factory). + * + * See `Capabilites` in the `types` module for a reference + * on all supported capabilities. + */ + public supports(capability: Capability) { + return this.activeCapabilities.includes(capability); + } + + /** + * Checks if the transaction has the minimum amount of gas required + * (DataFee + TxFee + Creation Fee). + */ + public validate(): boolean; + public validate(stringError: false): boolean; + public validate(stringError: true): string[]; + public validate(stringError = false): boolean | string[] { + const errors = []; + + if (this.getBaseFee() > this.gasLimit) { + errors.push( + `gasLimit is too low. given ${this.gasLimit}, need at least ${this.getBaseFee()}`, + ); + } + + if (this.isSigned() && !this.verifySignature()) { + errors.push('Invalid Signature'); + } + + return stringError ? errors : errors.length === 0; + } + + protected _validateYParity() { + const { v } = this; + if (v !== undefined && v !== BigInt(0) && v !== BigInt(1)) { + const msg = this._errorMsg('The y-parity of the transaction should either be 0 or 1'); + throw new Error(msg); + } + } + + /** + * EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2are considered invalid. + * Reasoning: https://ethereum.stackexchange.com/a/55728 + */ + protected _validateHighS() { + const { s } = this; + if (this.common.gteHardfork('homestead') && s !== undefined && s > SECP256K1_ORDER_DIV_2) { + const msg = this._errorMsg( + 'Invalid Signature: s-values greater than secp256k1n/2 are considered invalid', + ); + throw new Error(msg); + } + } + + /** + * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + */ + public getBaseFee(): bigint { + const txFee = this.common.param('gasPrices', 'tx'); + let fee = this.getDataFee(); + if (txFee) fee += txFee; + if (this.common.gteHardfork('homestead') && this.toCreationAddress()) { + const txCreationFee = this.common.param('gasPrices', 'txCreation'); + if (txCreationFee) fee += txCreationFee; + } + return fee; + } + + /** + * The amount of gas paid for the data in this tx + */ + public getDataFee(): bigint { + const txDataZero = this.common.param('gasPrices', 'txDataZero'); + const txDataNonZero = this.common.param('gasPrices', 'txDataNonZero'); + + let cost = BigInt(0); + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < this.data.length; i += 1) { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-unused-expressions + this.data[i] === 0 ? (cost += txDataZero) : (cost += txDataNonZero); + } + // eslint-disable-next-line no-null/no-null + if ((this.to === undefined || this.to === null) && this.common.isActivatedEIP(3860)) { + const dataLength = BigInt(Math.ceil(this.data.length / 32)); + const initCodeCost = this.common.param('gasPrices', 'initCodeWordCost') * dataLength; + cost += initCodeCost; + } + + return cost; + } + + /** + * The up front amount that an account must have for this transaction to be valid + */ + public abstract getUpfrontCost(): bigint; + + /** + * If the tx's `to` is to the creation address + */ + public toCreationAddress(): boolean { + return this.to === undefined || this.to.buf.length === 0; + } + + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of this transaction, in order. + * + * Use {@link BaseTransaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link BaseTransaction.getMessageToSign}. + */ + public abstract raw(): + | TxValuesArray + | AccessListEIP2930ValuesArray + | FeeMarketEIP1559ValuesArray; + + /** + * Returns the encoding of the transaction. + */ + public abstract serialize(): Uint8Array; + + // Returns the unsigned tx (hashed or raw), which is used to sign the transaction. + // + // Note: do not use code docs here since VS Studio is then not able to detect the + // comments from the inherited methods + public abstract getMessageToSign(hashMessage: false): Uint8Array | Uint8Array[]; + public abstract getMessageToSign(hashMessage?: true): Uint8Array; + + public abstract hash(): Uint8Array; + + public abstract getMessageToVerifySignature(): Uint8Array; + + public isSigned(): boolean { + const { v, r, s } = this; + if (v === undefined || r === undefined || s === undefined) { + return false; + } + return true; + } + + /** + * Determines if the signature is valid + */ + public verifySignature(): boolean { + try { + // Main signature verification is done in `getSenderPublicKey()` + const publicKey = this.getSenderPublicKey(); + return unpadUint8Array(publicKey).length !== 0; + } catch (e: any) { + return false; + } + } + + /** + * Returns the sender's address + */ + public getSenderAddress(): Address { + return new Address(Address.publicToAddress(this.getSenderPublicKey())); + } + + /** + * Returns the public key of the sender + */ + public abstract getSenderPublicKey(): Uint8Array; + + /** + * Signs a transaction. + * + * Note that the signed tx is returned as a new object, + * use as follows: + * ```javascript + * const signedTx = tx.sign(privateKey) + * ``` + */ + public sign(privateKey: Uint8Array): TransactionObject { + if (privateKey.length !== 32) { + const msg = this._errorMsg('Private key must be 32 bytes in length.'); + throw new Error(msg); + } + + // Hack for the constellation that we have got a legacy tx after spuriousDragon with a non-EIP155 conforming signature + // and want to recreate a signature (where EIP155 should be applied) + // Leaving this hack lets the legacy.spec.ts -> sign(), verifySignature() test fail + // 2021-06-23 + let hackApplied = false; + if ( + this.type === 0 && + this.common.gteHardfork('spuriousDragon') && + !this.supports(Capability.EIP155ReplayProtection) + ) { + this.activeCapabilities.push(Capability.EIP155ReplayProtection); + hackApplied = true; + } + + const msgHash = this.getMessageToSign(true); + const { v, r, s } = this._ecsign(msgHash, privateKey); + const tx = this._processSignature(v, r, s); + + // Hack part 2 + if (hackApplied) { + const index = this.activeCapabilities.indexOf(Capability.EIP155ReplayProtection); + if (index > -1) { + this.activeCapabilities.splice(index, 1); + } + } + + return tx; + } + + /** + * Returns an object with the JSON representation of the transaction + */ + public abstract toJSON(): JsonTx; + + // Accept the v,r,s values from the `sign` method, and convert this into a TransactionObject + protected abstract _processSignature( + v: bigint, + r: Uint8Array, + s: Uint8Array, + ): TransactionObject; + + /** + * Does chain ID checks on common and returns a common + * to be used on instantiation + * @hidden + * + * @param common - {@link Common} instance from tx options + * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) + */ + protected _getCommon(common?: Common, chainId?: Numbers) { + // Chain ID provided + if (chainId !== undefined) { + const chainIdBigInt = uint8ArrayToBigInt(toUint8Array(chainId)); + if (common) { + if (common.chainId() !== chainIdBigInt) { + const msg = this._errorMsg( + 'The chain ID does not match the chain ID of Common', + ); + throw new Error(msg); + } + // Common provided, chain ID does match + // -> Return provided Common + return common.copy(); + } + if (Common.isSupportedChainId(chainIdBigInt)) { + // No Common, chain ID supported by Common + // -> Instantiate Common with chain ID + return new Common({ chain: chainIdBigInt, hardfork: this.DEFAULT_HARDFORK }); + } + // No Common, chain ID not supported by Common + // -> Instantiate custom Common derived from DEFAULT_CHAIN + return Common.custom( + { + name: 'custom-chain', + networkId: chainIdBigInt, + chainId: chainIdBigInt, + }, + { baseChain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK }, + ); + } + // No chain ID provided + // -> return Common provided or create new default Common + return ( + common?.copy() ?? + new Common({ chain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK }) + ); + } + + /** + * Validates that an object with BigInt values cannot exceed the specified bit limit. + * @param values Object containing string keys and BigInt values + * @param bits Number of bits to check (64 or 256) + * @param cannotEqual Pass true if the number also cannot equal one less the maximum value + */ + protected _validateCannotExceedMaxInteger( + values: { [key: string]: bigint | undefined }, + bits = 256, + cannotEqual = false, + ) { + for (const [key, value] of Object.entries(values)) { + switch (bits) { + case 64: + if (cannotEqual) { + if (value !== undefined && value >= MAX_UINT64) { + const msg = this._errorMsg( + `${key} cannot equal or exceed MAX_UINT64 (2^64-1), given ${value}`, + ); + throw new Error(msg); + } + } else if (value !== undefined && value > MAX_UINT64) { + const msg = this._errorMsg( + `${key} cannot exceed MAX_UINT64 (2^64-1), given ${value}`, + ); + throw new Error(msg); + } + break; + case 256: + if (cannotEqual) { + if (value !== undefined && value >= MAX_INTEGER) { + const msg = this._errorMsg( + `${key} cannot equal or exceed MAX_INTEGER (2^256-1), given ${value}`, + ); + throw new Error(msg); + } + } else if (value !== undefined && value > MAX_INTEGER) { + const msg = this._errorMsg( + `${key} cannot exceed MAX_INTEGER (2^256-1), given ${value}`, + ); + throw new Error(msg); + } + break; + default: { + const msg = this._errorMsg('unimplemented bits value'); + throw new Error(msg); + } + } + } + } + + protected static _validateNotArray(values: { [key: string]: any }) { + const txDataKeys = [ + 'nonce', + 'gasPrice', + 'gasLimit', + 'to', + 'value', + 'data', + 'v', + 'r', + 's', + 'type', + 'baseFee', + 'maxFeePerGas', + 'chainId', + ]; + for (const [key, value] of Object.entries(values)) { + if (txDataKeys.includes(key)) { + if (Array.isArray(value)) { + throw new Error(`${key} cannot be an array`); + } + } + } + } + + /** + * Return a compact error string representation of the object + */ + public abstract errorStr(): string; + + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected abstract _errorMsg(msg: string): string; + + /** + * Returns the shared error postfix part for _error() method + * tx type implementations. + */ + protected _getSharedErrorPostfix() { + let hash = ''; + try { + hash = this.isSigned() ? bytesToHex(this.hash()) : 'not available (unsigned)'; + } catch (e: any) { + hash = 'error'; + } + let isSigned = ''; + try { + isSigned = this.isSigned().toString(); + } catch (e: any) { + hash = 'error'; + } + let hf = ''; + try { + hf = this.common.hardfork(); + } catch (e: any) { + hf = 'error'; + } + + let postfix = `tx type=${this.type} hash=${hash} nonce=${this.nonce} value=${this.value} `; + postfix += `signed=${isSigned} hf=${hf}`; + + return postfix; + } + // eslint-disable-next-line class-methods-use-this + private _ecsign(msgHash: Uint8Array, privateKey: Uint8Array, chainId?: bigint): ECDSASignature { + const signature = secp256k1.sign(msgHash, privateKey); + const signatureBytes = signature.toCompactRawBytes(); + + const r = signatureBytes.subarray(0, 32); + const s = signatureBytes.subarray(32, 64); + + const v = + chainId === undefined + ? BigInt(signature.recovery! + 27) + : BigInt(signature.recovery! + 35) + BigInt(chainId) * BigInt(2); + + return { r, s, v }; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public static fromSerializedTx( + // @ts-expect-error unused variable + serialized: Uint8Array, + // @ts-expect-error unused variable + opts: TxOptions = {}, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): any {} + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public static fromTxData( + // @ts-expect-error unused variable + txData: any, + // @ts-expect-error unused variable + opts: TxOptions = {}, + // eslint-disable-next-line @typescript-eslint/no-empty-function + ): any {} +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/constants.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/constants.ts new file mode 100644 index 0000000..3ef47cd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/constants.ts @@ -0,0 +1,34 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line import/extensions +import * as ethereumCryptography from 'ethereum-cryptography/secp256k1.js'; + +export const secp256k1 = ethereumCryptography.secp256k1 ?? ethereumCryptography; +/** + * 2^64-1 + */ +export const MAX_UINT64 = BigInt('0xffffffffffffffff'); + +/** + * The max integer that the evm can handle (2^256-1) + */ +export const MAX_INTEGER = BigInt( + '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', +); + +export const SECP256K1_ORDER = secp256k1.CURVE.n; +export const SECP256K1_ORDER_DIV_2 = SECP256K1_ORDER / BigInt(2); diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/eip1559Transaction.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/eip1559Transaction.ts new file mode 100644 index 0000000..eafb889 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/eip1559Transaction.ts @@ -0,0 +1,450 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { validateNoLeadingZeroes } from 'web3-validator'; +import { RLP } from '@ethereumjs/rlp'; +import { bytesToHex, hexToBytes, uint8ArrayConcat, uint8ArrayEquals } from 'web3-utils'; +import { MAX_INTEGER } from './constants.js'; +import { BaseTransaction } from './baseTransaction.js'; +import { + getAccessListData, + getAccessListJSON, + getDataFeeEIP2930, + verifyAccessList, +} from './utils.js'; +import { + bigIntToHex, + toUint8Array, + ecrecover, + uint8ArrayToBigInt, + bigIntToUnpaddedUint8Array, +} from '../common/utils.js'; +import type { + AccessList, + AccessListUint8Array, + FeeMarketEIP1559TxData, + FeeMarketEIP1559ValuesArray, + JsonTx, + TxOptions, +} from './types.js'; +import type { Common } from '../common/common.js'; + +const TRANSACTION_TYPE = 2; +const TRANSACTION_TYPE_UINT8ARRAY = hexToBytes(TRANSACTION_TYPE.toString(16).padStart(2, '0')); + +/** + * Typed transaction with a new gas fee market mechanism + * + * - TransactionType: 2 + * - EIP: [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) + */ +// eslint-disable-next-line no-use-before-define +export class FeeMarketEIP1559Transaction extends BaseTransaction { + public readonly chainId: bigint; + public readonly accessList: AccessListUint8Array; + public readonly AccessListJSON: AccessList; + public readonly maxPriorityFeePerGas: bigint; + public readonly maxFeePerGas: bigint; + + public readonly common: Common; + + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK = 'london'; + + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + public static fromTxData(txData: FeeMarketEIP1559TxData, opts: TxOptions = {}) { + return new FeeMarketEIP1559Transaction(txData, opts); + } + + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + */ + public static fromSerializedTx(serialized: Uint8Array, opts: TxOptions = {}) { + if (!uint8ArrayEquals(serialized.subarray(0, 1), TRANSACTION_TYPE_UINT8ARRAY)) { + throw new Error( + `Invalid serialized tx input: not an EIP-1559 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${bytesToHex( + serialized.subarray(0, 1), + )}`, + ); + } + const values = RLP.decode(serialized.subarray(1)); + + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input: must be array'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return FeeMarketEIP1559Transaction.fromValuesArray(values as any, opts); + } + + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + */ + public static fromValuesArray(values: FeeMarketEIP1559ValuesArray, opts: TxOptions = {}) { + if (values.length !== 9 && values.length !== 12) { + throw new Error( + 'Invalid EIP-1559 transaction. Only expecting 9 values (for unsigned tx) or 12 values (for signed tx).', + ); + } + + const [ + chainId, + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + to, + value, + data, + accessList, + v, + r, + s, + ] = values; + + this._validateNotArray({ chainId, v }); + validateNoLeadingZeroes({ + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + value, + v, + r, + s, + }); + + return new FeeMarketEIP1559Transaction( + { + chainId: uint8ArrayToBigInt(chainId), + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + to, + value, + data, + accessList: accessList ?? [], + v: v !== undefined ? uint8ArrayToBigInt(v) : undefined, // EIP2930 supports v's with value 0 (empty Uint8Array) + r, + s, + }, + opts, + ); + } + + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + public constructor(txData: FeeMarketEIP1559TxData, opts: TxOptions = {}) { + super({ ...txData, type: TRANSACTION_TYPE }, opts); + const { chainId, accessList, maxFeePerGas, maxPriorityFeePerGas } = txData; + + this.common = this._getCommon(opts.common, chainId); + this.chainId = this.common.chainId(); + + if (!this.common.isActivatedEIP(1559)) { + throw new Error('EIP-1559 not enabled on Common'); + } + this.activeCapabilities = this.activeCapabilities.concat([1559, 2718, 2930]); + + // Populate the access list fields + const accessListData = getAccessListData(accessList ?? []); + this.accessList = accessListData.accessList; + this.AccessListJSON = accessListData.AccessListJSON; + // Verify the access list format. + verifyAccessList(this.accessList); + + this.maxFeePerGas = uint8ArrayToBigInt( + toUint8Array(maxFeePerGas === '' ? '0x' : maxFeePerGas), + ); + this.maxPriorityFeePerGas = uint8ArrayToBigInt( + toUint8Array(maxPriorityFeePerGas === '' ? '0x' : maxPriorityFeePerGas), + ); + + this._validateCannotExceedMaxInteger({ + maxFeePerGas: this.maxFeePerGas, + maxPriorityFeePerGas: this.maxPriorityFeePerGas, + }); + + BaseTransaction._validateNotArray(txData); + + if (this.gasLimit * this.maxFeePerGas > MAX_INTEGER) { + const msg = this._errorMsg( + 'gasLimit * maxFeePerGas cannot exceed MAX_INTEGER (2^256-1)', + ); + throw new Error(msg); + } + + if (this.maxFeePerGas < this.maxPriorityFeePerGas) { + const msg = this._errorMsg( + 'maxFeePerGas cannot be less than maxPriorityFeePerGas (The total must be the larger of the two)', + ); + throw new Error(msg); + } + + this._validateYParity(); + this._validateHighS(); + + const freeze = opts?.freeze ?? true; + if (freeze) { + Object.freeze(this); + } + } + + /** + * The amount of gas paid for the data in this tx + */ + public getDataFee(): bigint { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + + let cost = super.getDataFee(); + cost += BigInt(getDataFeeEIP2930(this.accessList, this.common)); + + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: cost, + hardfork: this.common.hardfork(), + }; + } + + return cost; + } + + /** + * The up front amount that an account must have for this transaction to be valid + * @param baseFee The base fee of the block (will be set to 0 if not provided) + */ + public getUpfrontCost(baseFee = BigInt(0)): bigint { + const prio = this.maxPriorityFeePerGas; + const maxBase = this.maxFeePerGas - baseFee; + const inclusionFeePerGas = prio < maxBase ? prio : maxBase; + const gasPrice = inclusionFeePerGas + baseFee; + return this.gasLimit * gasPrice + this.value; + } + + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-1559 transaction, in order. + * + * Format: `[chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS]` + * + * Use {@link FeeMarketEIP1559Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link FeeMarketEIP1559Transaction.getMessageToSign}. + */ + public raw(): FeeMarketEIP1559ValuesArray { + return [ + bigIntToUnpaddedUint8Array(this.chainId), + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.maxPriorityFeePerGas), + bigIntToUnpaddedUint8Array(this.maxFeePerGas), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + this.accessList, + this.v !== undefined ? bigIntToUnpaddedUint8Array(this.v) : Uint8Array.from([]), + this.r !== undefined ? bigIntToUnpaddedUint8Array(this.r) : Uint8Array.from([]), + this.s !== undefined ? bigIntToUnpaddedUint8Array(this.s) : Uint8Array.from([]), + ]; + } + + /** + * Returns the serialized encoding of the EIP-1559 transaction. + * + * Format: `0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, + * accessList, signatureYParity, signatureR, signatureS])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + public serialize(): Uint8Array { + const base = this.raw(); + return uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + } + + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + public getMessageToSign(hashMessage = true): Uint8Array { + const base = this.raw().slice(0, 9); + const message = uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + if (hashMessage) { + return keccak256(message); + } + return message; + } + + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link FeeMarketEIP1559Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + public hash(): Uint8Array { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = keccak256(this.serialize()); + } + return this.cache.hash; + } + + return keccak256(this.serialize()); + } + + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + public getMessageToVerifySignature(): Uint8Array { + return this.getMessageToSign(); + } + + /** + * Returns the public key of the sender + */ + public getSenderPublicKey(): Uint8Array { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call this method if transaction is not signed'); + throw new Error(msg); + } + + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + + this._validateHighS(); + + try { + return ecrecover( + msgHash, + v! + BigInt(27), // Recover the 27 which was stripped from ecsign + bigIntToUnpaddedUint8Array(r!), + bigIntToUnpaddedUint8Array(s!), + ); + } catch (e: any) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + + public _processSignature(v: bigint, r: Uint8Array, s: Uint8Array) { + const opts = { ...this.txOptions, common: this.common }; + + return FeeMarketEIP1559Transaction.fromTxData( + { + chainId: this.chainId, + nonce: this.nonce, + maxPriorityFeePerGas: this.maxPriorityFeePerGas, + maxFeePerGas: this.maxFeePerGas, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + accessList: this.accessList, + v: v - BigInt(27), // This looks extremely hacky: /util actually adds 27 to the value, the recovery bit is either 0 or 1. + r: uint8ArrayToBigInt(r), + s: uint8ArrayToBigInt(s), + }, + opts, + ); + } + + /** + * Returns an object with the JSON representation of the transaction + */ + public toJSON(): JsonTx { + const accessListJSON = getAccessListJSON(this.accessList); + + return { + chainId: bigIntToHex(this.chainId), + nonce: bigIntToHex(this.nonce), + maxPriorityFeePerGas: bigIntToHex(this.maxPriorityFeePerGas), + maxFeePerGas: bigIntToHex(this.maxFeePerGas), + gasLimit: bigIntToHex(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: bigIntToHex(this.value), + data: bytesToHex(this.data), + accessList: accessListJSON, + v: this.v !== undefined ? bigIntToHex(this.v) : undefined, + r: this.r !== undefined ? bigIntToHex(this.r) : undefined, + s: this.s !== undefined ? bigIntToHex(this.s) : undefined, + }; + } + + /** + * Return a compact error string representation of the object + */ + public errorStr() { + let errorStr = this._getSharedErrorPostfix(); + errorStr += ` maxFeePerGas=${this.maxFeePerGas} maxPriorityFeePerGas=${this.maxPriorityFeePerGas}`; + return errorStr; + } + + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string) { + return `${msg} (${this.errorStr()})`; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/eip2930Transaction.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/eip2930Transaction.ts new file mode 100644 index 0000000..7152fbe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/eip2930Transaction.ts @@ -0,0 +1,407 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { validateNoLeadingZeroes } from 'web3-validator'; +import { RLP } from '@ethereumjs/rlp'; +import { bytesToHex, hexToBytes, uint8ArrayConcat, uint8ArrayEquals } from 'web3-utils'; +import { MAX_INTEGER } from './constants.js'; +import { + getAccessListData, + verifyAccessList, + getAccessListJSON, + getDataFeeEIP2930, +} from './utils.js'; +import { + bigIntToHex, + toUint8Array, + ecrecover, + uint8ArrayToBigInt, + bigIntToUnpaddedUint8Array, +} from '../common/utils.js'; +import { BaseTransaction } from './baseTransaction.js'; +import type { + AccessList, + AccessListUint8Array, + AccessListEIP2930TxData, + AccessListEIP2930ValuesArray, + JsonTx, + TxOptions, +} from './types.js'; +import type { Common } from '../common/common.js'; + +const TRANSACTION_TYPE = 1; +const TRANSACTION_TYPE_UINT8ARRAY = hexToBytes(TRANSACTION_TYPE.toString(16).padStart(2, '0')); + +/** + * Typed transaction with optional access lists + * + * - TransactionType: 1 + * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) + */ +// eslint-disable-next-line no-use-before-define +export class AccessListEIP2930Transaction extends BaseTransaction { + public readonly chainId: bigint; + public readonly accessList: AccessListUint8Array; + public readonly AccessListJSON: AccessList; + public readonly gasPrice: bigint; + + public readonly common: Common; + + /** + * The default HF if the tx type is active on that HF + * or the first greater HF where the tx is active. + * + * @hidden + */ + protected DEFAULT_HARDFORK = 'berlin'; + + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * v, r, s } + * + * Notes: + * - `chainId` will be set automatically if not provided + * - All parameters are optional and have some basic default values + */ + public static fromTxData(txData: AccessListEIP2930TxData, opts: TxOptions = {}) { + return new AccessListEIP2930Transaction(txData, opts); + } + + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + */ + public static fromSerializedTx(serialized: Uint8Array, opts: TxOptions = {}) { + if (!uint8ArrayEquals(serialized.subarray(0, 1), TRANSACTION_TYPE_UINT8ARRAY)) { + throw new Error( + `Invalid serialized tx input: not an EIP-2930 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${bytesToHex( + serialized.subarray(0, 1), + )}`, + ); + } + const values = RLP.decode(Uint8Array.from(serialized.subarray(1))); + + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input: must be array'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return AccessListEIP2930Transaction.fromValuesArray(values as any, opts); + } + + /** + * Create a transaction from a values array. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + */ + public static fromValuesArray(values: AccessListEIP2930ValuesArray, opts: TxOptions = {}) { + if (values.length !== 8 && values.length !== 11) { + throw new Error( + 'Invalid EIP-2930 transaction. Only expecting 8 values (for unsigned tx) or 11 values (for signed tx).', + ); + } + + const [chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, v, r, s] = values; + + this._validateNotArray({ chainId, v }); + validateNoLeadingZeroes({ nonce, gasPrice, gasLimit, value, v, r, s }); + + const emptyAccessList: AccessList = []; + + return new AccessListEIP2930Transaction( + { + chainId: uint8ArrayToBigInt(chainId), + nonce, + gasPrice, + gasLimit, + to, + value, + data, + accessList: accessList ?? emptyAccessList, + v: v !== undefined ? uint8ArrayToBigInt(v) : undefined, // EIP2930 supports v's with value 0 (empty Uint8Array) + r, + s, + }, + opts, + ); + } + + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + public constructor(txData: AccessListEIP2930TxData, opts: TxOptions = {}) { + super({ ...txData, type: TRANSACTION_TYPE }, opts); + const { chainId, accessList, gasPrice } = txData; + + this.common = this._getCommon(opts.common, chainId); + this.chainId = this.common.chainId(); + + // EIP-2718 check is done in Common + if (!this.common.isActivatedEIP(2930)) { + throw new Error('EIP-2930 not enabled on Common'); + } + this.activeCapabilities = this.activeCapabilities.concat([2718, 2930]); + + // Populate the access list fields + const accessListData = getAccessListData(accessList ?? []); + this.accessList = accessListData.accessList; + this.AccessListJSON = accessListData.AccessListJSON; + // Verify the access list format. + verifyAccessList(this.accessList); + + this.gasPrice = uint8ArrayToBigInt(toUint8Array(gasPrice === '' ? '0x' : gasPrice)); + + this._validateCannotExceedMaxInteger({ + gasPrice: this.gasPrice, + }); + + BaseTransaction._validateNotArray(txData); + + if (this.gasPrice * this.gasLimit > MAX_INTEGER) { + const msg = this._errorMsg('gasLimit * gasPrice cannot exceed MAX_INTEGER'); + throw new Error(msg); + } + + this._validateYParity(); + this._validateHighS(); + + const freeze = opts?.freeze ?? true; + if (freeze) { + Object.freeze(this); + } + } + + /** + * The amount of gas paid for the data in this tx + */ + public getDataFee(): bigint { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + + let cost = super.getDataFee(); + cost += BigInt(getDataFeeEIP2930(this.accessList, this.common)); + + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: cost, + hardfork: this.common.hardfork(), + }; + } + + return cost; + } + + /** + * The up front amount that an account must have for this transaction to be valid + */ + public getUpfrontCost(): bigint { + return this.gasLimit * this.gasPrice + this.value; + } + + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-2930 transaction, in order. + * + * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)]` + * + * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block + * with {@link Block.fromValuesArray}. + * + * For an unsigned tx this method uses the empty UINT8ARRAY values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. + */ + public raw(): AccessListEIP2930ValuesArray { + return [ + bigIntToUnpaddedUint8Array(this.chainId), + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.gasPrice), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + this.accessList, + this.v !== undefined ? bigIntToUnpaddedUint8Array(this.v) : Uint8Array.from([]), + this.r !== undefined ? bigIntToUnpaddedUint8Array(this.r) : Uint8Array.from([]), + this.s !== undefined ? bigIntToUnpaddedUint8Array(this.s) : Uint8Array.from([]), + ]; + } + + /** + * Returns the serialized encoding of the EIP-2930 transaction. + * + * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, + * signatureYParity (v), signatureR (r), signatureS (s)])` + * + * Note that in contrast to the legacy tx serialization format this is not + * valid RLP any more due to the raw tx type preceding and concatenated to + * the RLP encoding of the values. + */ + public serialize(): Uint8Array { + const base = this.raw(); + return uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + } + + /** + * Returns the serialized unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: in contrast to the legacy tx the raw message format is already + * serialized and doesn't need to be RLP encoded any more. + * + * ```javascript + * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + public getMessageToSign(hashMessage = true): Uint8Array { + const base = this.raw().slice(0, 8); + const message = uint8ArrayConcat(TRANSACTION_TYPE_UINT8ARRAY, RLP.encode(base)); + if (hashMessage) { + return keccak256(message); + } + return message; + } + + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + public hash(): Uint8Array { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = keccak256(this.serialize()); + } + return this.cache.hash; + } + + return keccak256(this.serialize()); + } + + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + public getMessageToVerifySignature(): Uint8Array { + return this.getMessageToSign(); + } + + /** + * Returns the public key of the sender + */ + public getSenderPublicKey(): Uint8Array { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call this method if transaction is not signed'); + throw new Error(msg); + } + + const msgHash = this.getMessageToVerifySignature(); + const { v, r, s } = this; + + this._validateHighS(); + + try { + return ecrecover( + msgHash, + v! + BigInt(27), // Recover the 27 which was stripped from ecsign + bigIntToUnpaddedUint8Array(r!), + bigIntToUnpaddedUint8Array(s!), + ); + } catch (e: any) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + + public _processSignature(v: bigint, r: Uint8Array, s: Uint8Array) { + const opts = { ...this.txOptions, common: this.common }; + + return AccessListEIP2930Transaction.fromTxData( + { + chainId: this.chainId, + nonce: this.nonce, + gasPrice: this.gasPrice, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + accessList: this.accessList, + v: v - BigInt(27), // This looks extremely hacky: /util actually adds 27 to the value, the recovery bit is either 0 or 1. + r: uint8ArrayToBigInt(r), + s: uint8ArrayToBigInt(s), + }, + opts, + ); + } + + /** + * Returns an object with the JSON representation of the transaction + */ + public toJSON(): JsonTx { + const accessListJSON = getAccessListJSON(this.accessList); + + return { + chainId: bigIntToHex(this.chainId), + nonce: bigIntToHex(this.nonce), + gasPrice: bigIntToHex(this.gasPrice), + gasLimit: bigIntToHex(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: bigIntToHex(this.value), + data: bytesToHex(this.data), + accessList: accessListJSON, + v: this.v !== undefined ? bigIntToHex(this.v) : undefined, + r: this.r !== undefined ? bigIntToHex(this.r) : undefined, + s: this.s !== undefined ? bigIntToHex(this.s) : undefined, + }; + } + + /** + * Return a compact error string representation of the object + */ + public errorStr() { + let errorStr = this._getSharedErrorPostfix(); + // Keep ? for this.accessList since this otherwise causes Hardhat E2E tests to fail + errorStr += ` gasPrice=${this.gasPrice} accessListCount=${this.accessList?.length ?? 0}`; + return errorStr; + } + + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string) { + return `${msg} (${this.errorStr()})`; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/index.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/index.ts new file mode 100644 index 0000000..26ead20 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/index.ts @@ -0,0 +1,25 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// @ethereumjs/tx version 4.1.1 +export { FeeMarketEIP1559Transaction } from './eip1559Transaction.js'; +export { AccessListEIP2930Transaction } from './eip2930Transaction.js'; +export { Transaction } from './legacyTransaction.js'; +export { TransactionFactory } from './transactionFactory.js'; +export { BaseTransaction } from './baseTransaction.js'; +export * as txUtils from './utils.js'; +export * from './types.js'; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/legacyTransaction.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/legacyTransaction.ts new file mode 100644 index 0000000..a7b05b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/legacyTransaction.ts @@ -0,0 +1,439 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { RLP } from '@ethereumjs/rlp'; +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { bytesToHex } from 'web3-utils'; +import { validateNoLeadingZeroes } from 'web3-validator'; +import { + bigIntToHex, + bigIntToUnpaddedUint8Array, + ecrecover, + toUint8Array, + uint8ArrayToBigInt, + unpadUint8Array, +} from '../common/utils.js'; +import { MAX_INTEGER } from './constants.js'; + +import { BaseTransaction } from './baseTransaction.js'; + +import type { Common } from '../common/common.js'; +import type { JsonTx, TxData, TxOptions, TxValuesArray } from './types.js'; +import { Capability } from './types.js'; + +const TRANSACTION_TYPE = 0; + +function meetsEIP155(_v: bigint, chainId: bigint) { + const v = Number(_v); + const chainIdDoubled = Number(chainId) * 2; + return v === chainIdDoubled + 35 || v === chainIdDoubled + 36; +} + +/** + * An Ethereum non-typed (legacy) transaction + */ +// eslint-disable-next-line no-use-before-define +export class Transaction extends BaseTransaction { + public readonly gasPrice: bigint; + + public readonly common: Common; + + /** + * Instantiate a transaction from a data dictionary. + * + * Format: { nonce, gasPrice, gasLimit, to, value, data, v, r, s } + * + * Notes: + * - All parameters are optional and have some basic default values + */ + public static fromTxData(txData: TxData, opts: TxOptions = {}) { + return new Transaction(txData, opts); + } + + /** + * Instantiate a transaction from the serialized tx. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + */ + public static fromSerializedTx(serialized: Uint8Array, opts: TxOptions = {}) { + const values = RLP.decode(serialized); + + if (!Array.isArray(values)) { + throw new Error('Invalid serialized tx input. Must be array'); + } + + return this.fromValuesArray(values as Uint8Array[], opts); + } + + /** + * Create a transaction from a values array. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + */ + public static fromValuesArray(values: TxValuesArray, opts: TxOptions = {}) { + // If length is not 6, it has length 9. If v/r/s are empty Uint8Array, it is still an unsigned transaction + // This happens if you get the RLP data from `raw()` + if (values.length !== 6 && values.length !== 9) { + throw new Error( + 'Invalid transaction. Only expecting 6 values (for unsigned tx) or 9 values (for signed tx).', + ); + } + + const [nonce, gasPrice, gasLimit, to, value, data, v, r, s] = values; + + validateNoLeadingZeroes({ nonce, gasPrice, gasLimit, value, v, r, s }); + + return new Transaction( + { + nonce, + gasPrice, + gasLimit, + to, + value, + data, + v, + r, + s, + }, + opts, + ); + } + + /** + * This constructor takes the values, validates them, assigns them and freezes the object. + * + * It is not recommended to use this constructor directly. Instead use + * the static factory methods to assist in creating a Transaction object from + * varying data types. + */ + public constructor(txData: TxData, opts: TxOptions = {}) { + super({ ...txData, type: TRANSACTION_TYPE }, opts); + + this.common = this._validateTxV(this.v, opts.common); + + this.gasPrice = uint8ArrayToBigInt( + toUint8Array(txData.gasPrice === '' ? '0x' : txData.gasPrice), + ); + + if (this.gasPrice * this.gasLimit > MAX_INTEGER) { + const msg = this._errorMsg('gas limit * gasPrice cannot exceed MAX_INTEGER (2^256-1)'); + throw new Error(msg); + } + this._validateCannotExceedMaxInteger({ gasPrice: this.gasPrice }); + BaseTransaction._validateNotArray(txData); + + if (this.common.gteHardfork('spuriousDragon')) { + if (!this.isSigned()) { + this.activeCapabilities.push(Capability.EIP155ReplayProtection); + } else { + // EIP155 spec: + // If block.number >= 2,675,000 and v = CHAIN_ID * 2 + 35 or v = CHAIN_ID * 2 + 36 + // then when computing the hash of a transaction for purposes of signing or recovering + // instead of hashing only the first six elements (i.e. nonce, gasprice, startgas, to, value, data) + // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0. + // v and chain ID meet EIP-155 conditions + // eslint-disable-next-line no-lonely-if + if (meetsEIP155(this.v!, this.common.chainId())) { + this.activeCapabilities.push(Capability.EIP155ReplayProtection); + } + } + } + + const freeze = opts?.freeze ?? true; + if (freeze) { + Object.freeze(this); + } + } + + /** + * Returns a Uint8Array Array of the raw Uint8Arrays of the legacy transaction, in order. + * + * Format: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` + * + * For legacy txs this is also the correct format to add transactions + * to a block with {@link Block.fromValuesArray} (use the `serialize()` method + * for typed txs). + * + * For an unsigned tx this method returns the empty Uint8Array values + * for the signature parameters `v`, `r` and `s`. For an EIP-155 compliant + * representation have a look at {@link Transaction.getMessageToSign}. + */ + public raw(): TxValuesArray { + return [ + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.gasPrice), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + this.v !== undefined ? bigIntToUnpaddedUint8Array(this.v) : Uint8Array.from([]), + this.r !== undefined ? bigIntToUnpaddedUint8Array(this.r) : Uint8Array.from([]), + this.s !== undefined ? bigIntToUnpaddedUint8Array(this.s) : Uint8Array.from([]), + ]; + } + + /** + * Returns the serialized encoding of the legacy transaction. + * + * Format: `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + * + * For an unsigned tx this method uses the empty Uint8Array values for the + * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant + * representation for external signing use {@link Transaction.getMessageToSign}. + */ + public serialize(): Uint8Array { + return RLP.encode(this.raw()); + } + + private _getMessageToSign() { + const values = [ + bigIntToUnpaddedUint8Array(this.nonce), + bigIntToUnpaddedUint8Array(this.gasPrice), + bigIntToUnpaddedUint8Array(this.gasLimit), + this.to !== undefined ? this.to.buf : Uint8Array.from([]), + bigIntToUnpaddedUint8Array(this.value), + this.data, + ]; + + if (this.supports(Capability.EIP155ReplayProtection)) { + values.push(toUint8Array(this.common.chainId())); + values.push(unpadUint8Array(toUint8Array(0))); + values.push(unpadUint8Array(toUint8Array(0))); + } + + return values; + } + + /** + * Returns the unsigned tx (hashed or raw), which can be used + * to sign the transaction (e.g. for sending to a hardware wallet). + * + * Note: the raw message message format for the legacy tx is not RLP encoded + * and you might need to do yourself with: + * + * ```javascript + * import { bufArrToArr } from '../util' + * import { RLP } from '../rlp' + * const message = tx.getMessageToSign(false) + * const serializedMessage = RLP.encode(message) // use this for the HW wallet input + * ``` + * + * @param hashMessage - Return hashed message if set to true (default: true) + */ + public getMessageToSign(hashMessage: false): Uint8Array[]; + public getMessageToSign(hashMessage?: true): Uint8Array; + public getMessageToSign(hashMessage = true) { + const message = this._getMessageToSign(); + if (hashMessage) { + return keccak256(RLP.encode(message)); + } + return message; + } + + /** + * The amount of gas paid for the data in this tx + */ + public getDataFee(): bigint { + if (this.cache.dataFee && this.cache.dataFee.hardfork === this.common.hardfork()) { + return this.cache.dataFee.value; + } + + if (Object.isFrozen(this)) { + this.cache.dataFee = { + value: super.getDataFee(), + hardfork: this.common.hardfork(), + }; + } + + return super.getDataFee(); + } + + /** + * The up front amount that an account must have for this transaction to be valid + */ + public getUpfrontCost(): bigint { + return this.gasLimit * this.gasPrice + this.value; + } + + /** + * Computes a sha3-256 hash of the serialized tx. + * + * This method can only be used for signed txs (it throws otherwise). + * Use {@link Transaction.getMessageToSign} to get a tx hash for the purpose of signing. + */ + public hash(): Uint8Array { + if (!this.isSigned()) { + const msg = this._errorMsg('Cannot call hash method if transaction is not signed'); + throw new Error(msg); + } + + if (Object.isFrozen(this)) { + if (!this.cache.hash) { + this.cache.hash = keccak256(RLP.encode(this.raw())); + } + return this.cache.hash; + } + + return keccak256(RLP.encode(this.raw())); + } + + /** + * Computes a sha3-256 hash which can be used to verify the signature + */ + public getMessageToVerifySignature() { + if (!this.isSigned()) { + const msg = this._errorMsg('This transaction is not signed'); + throw new Error(msg); + } + const message = this._getMessageToSign(); + return keccak256(RLP.encode(message)); + } + + /** + * Returns the public key of the sender + */ + public getSenderPublicKey(): Uint8Array { + const msgHash = this.getMessageToVerifySignature(); + + const { v, r, s } = this; + + this._validateHighS(); + + try { + return ecrecover( + msgHash, + v!, + bigIntToUnpaddedUint8Array(r!), + bigIntToUnpaddedUint8Array(s!), + this.supports(Capability.EIP155ReplayProtection) + ? this.common.chainId() + : undefined, + ); + } catch (e: any) { + const msg = this._errorMsg('Invalid Signature'); + throw new Error(msg); + } + } + + /** + * Process the v, r, s values from the `sign` method of the base transaction. + */ + protected _processSignature(_v: bigint, r: Uint8Array, s: Uint8Array) { + let v = _v; + if (this.supports(Capability.EIP155ReplayProtection)) { + v += this.common.chainId() * BigInt(2) + BigInt(8); + } + + const opts = { ...this.txOptions, common: this.common }; + + return Transaction.fromTxData( + { + nonce: this.nonce, + gasPrice: this.gasPrice, + gasLimit: this.gasLimit, + to: this.to, + value: this.value, + data: this.data, + v, + r: uint8ArrayToBigInt(r), + s: uint8ArrayToBigInt(s), + }, + opts, + ); + } + + /** + * Returns an object with the JSON representation of the transaction. + */ + public toJSON(): JsonTx { + return { + nonce: bigIntToHex(this.nonce), + gasPrice: bigIntToHex(this.gasPrice), + gasLimit: bigIntToHex(this.gasLimit), + to: this.to !== undefined ? this.to.toString() : undefined, + value: bigIntToHex(this.value), + data: bytesToHex(this.data), + v: this.v !== undefined ? bigIntToHex(this.v) : undefined, + r: this.r !== undefined ? bigIntToHex(this.r) : undefined, + s: this.s !== undefined ? bigIntToHex(this.s) : undefined, + }; + } + + /** + * Validates tx's `v` value + */ + private _validateTxV(_v?: bigint, common?: Common): Common { + let chainIdBigInt; + const v = _v !== undefined ? Number(_v) : undefined; + // Check for valid v values in the scope of a signed legacy tx + if (v !== undefined) { + // v is 1. not matching the EIP-155 chainId included case and... + // v is 2. not matching the classic v=27 or v=28 case + if (v < 37 && v !== 27 && v !== 28) { + throw new Error( + `Legacy txs need either v = 27/28 or v >= 37 (EIP-155 replay protection), got v = ${v}`, + ); + } + } + + // No unsigned tx and EIP-155 activated and chain ID included + if ( + v !== undefined && + v !== 0 && + (!common || common.gteHardfork('spuriousDragon')) && + v !== 27 && + v !== 28 + ) { + if (common) { + if (!meetsEIP155(BigInt(v), common.chainId())) { + throw new Error( + `Incompatible EIP155-based V ${v} and chain id ${common.chainId()}. See the Common parameter of the Transaction constructor to set the chain id.`, + ); + } + } else { + // Derive the original chain ID + let numSub; + if ((v - 35) % 2 === 0) { + numSub = 35; + } else { + numSub = 36; + } + // Use derived chain ID to create a proper Common + chainIdBigInt = BigInt(v - numSub) / BigInt(2); + } + } + return this._getCommon(common, chainIdBigInt); + } + + /** + * Return a compact error string representation of the object + */ + public errorStr() { + let errorStr = this._getSharedErrorPostfix(); + errorStr += ` gasPrice=${this.gasPrice}`; + return errorStr; + } + + /** + * Internal helper function to create an annotated error message + * + * @param msg Base error message + * @hidden + */ + protected _errorMsg(msg: string) { + return `${msg} (${this.errorStr()})`; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/transactionFactory.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/transactionFactory.ts new file mode 100644 index 0000000..e4da9fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/transactionFactory.ts @@ -0,0 +1,146 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Numbers } from 'web3-types'; +import { toUint8Array, uint8ArrayToBigInt } from '../common/utils.js'; +import { FeeMarketEIP1559Transaction } from './eip1559Transaction.js'; +import { AccessListEIP2930Transaction } from './eip2930Transaction.js'; +import { Transaction } from './legacyTransaction.js'; +import type { TypedTransaction } from '../types.js'; + +import type { + AccessListEIP2930TxData, + FeeMarketEIP1559TxData, + TxData, + TxOptions, +} from './types.js'; +import { BaseTransaction } from './baseTransaction.js'; + +const extraTxTypes: Map> = new Map(); + +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export class TransactionFactory { + // It is not possible to instantiate a TransactionFactory object. + // eslint-disable-next-line @typescript-eslint/no-empty-function, no-useless-constructor + private constructor() {} + + public static typeToInt(txType: Numbers) { + return Number(uint8ArrayToBigInt(toUint8Array(txType))); + } + + public static registerTransactionType>( + type: Numbers, + txClass: NewTxTypeClass, + ) { + const txType = TransactionFactory.typeToInt(type); + extraTxTypes.set(txType, txClass); + } + + /** + * Create a transaction from a `txData` object + * + * @param txData - The transaction data. The `type` field will determine which transaction type is returned (if undefined, creates a legacy transaction) + * @param txOptions - Options to pass on to the constructor of the transaction + */ + public static fromTxData( + txData: TxData | TypedTransaction, + txOptions: TxOptions = {}, + ): TypedTransaction { + if (!('type' in txData) || txData.type === undefined) { + // Assume legacy transaction + return Transaction.fromTxData(txData as TxData, txOptions); + } + const txType = TransactionFactory.typeToInt(txData.type); + if (txType === 0) { + return Transaction.fromTxData(txData as TxData, txOptions); + } + if (txType === 1) { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return AccessListEIP2930Transaction.fromTxData( + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + txData, + txOptions, + ); + } + if (txType === 2) { + return FeeMarketEIP1559Transaction.fromTxData( + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + txData, + txOptions, + ); + } + const ExtraTransaction = extraTxTypes.get(txType); + if (ExtraTransaction?.fromTxData) { + return ExtraTransaction.fromTxData(txData, txOptions) as TypedTransaction; + } + + throw new Error(`Tx instantiation with type ${txType} not supported`); + } + + /** + * This method tries to decode serialized data. + * + * @param data - The data Uint8Array + * @param txOptions - The transaction options + */ + public static fromSerializedData( + data: Uint8Array, + txOptions: TxOptions = {}, + ): TypedTransaction { + if (data[0] <= 0x7f) { + // Determine the type. + switch (data[0]) { + case 1: + return AccessListEIP2930Transaction.fromSerializedTx(data, txOptions); + case 2: + return FeeMarketEIP1559Transaction.fromSerializedTx(data, txOptions); + default: { + const ExtraTransaction = extraTxTypes.get(Number(data[0])); + if (ExtraTransaction?.fromSerializedTx) { + return ExtraTransaction.fromSerializedTx( + data, + txOptions, + ) as TypedTransaction; + } + + throw new Error(`TypedTransaction with ID ${data[0]} unknown`); + } + } + } else { + return Transaction.fromSerializedTx(data, txOptions); + } + } + + /** + * When decoding a BlockBody, in the transactions field, a field is either: + * A Uint8Array (a TypedTransaction - encoded as TransactionType || rlp(TransactionPayload)) + * A Uint8Array[] (Legacy Transaction) + * This method returns the right transaction. + * + * @param data - A Uint8Array or Uint8Array[] + * @param txOptions - The transaction options + */ + public static fromBlockBodyData(data: Uint8Array | Uint8Array[], txOptions: TxOptions = {}) { + if (data instanceof Uint8Array) { + return this.fromSerializedData(data, txOptions); + } + if (Array.isArray(data)) { + // It is a legacy transaction + return Transaction.fromValuesArray(data, txOptions); + } + throw new Error('Cannot decode transaction: unknown type input'); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/types.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/types.ts new file mode 100644 index 0000000..830c9e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/types.ts @@ -0,0 +1,288 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import type { HexString, Numbers } from 'web3-types'; + +import type { Common } from '../common/common.js'; +// eslint-disable-next-line require-extensions/require-extensions +import type { Uint8ArrayLike, PrefixedHexString } from '../common/types'; +import { Address } from './address.js'; + +/** + * Can be used in conjunction with {@link Transaction.supports} + * to query on tx capabilities + */ +export enum Capability { + /** + * Tx supports EIP-155 replay protection + * See: [155](https://eips.ethereum.org/EIPS/eip-155) Replay Attack Protection EIP + */ + EIP155ReplayProtection = 155, + + /** + * Tx supports EIP-1559 gas fee market mechanism + * See: [1559](https://eips.ethereum.org/EIPS/eip-1559) Fee Market EIP + */ + EIP1559FeeMarket = 1559, + + /** + * Tx is a typed transaction as defined in EIP-2718 + * See: [2718](https://eips.ethereum.org/EIPS/eip-2718) Transaction Type EIP + */ + EIP2718TypedTransaction = 2718, + + /** + * Tx supports access list generation as defined in EIP-2930 + * See: [2930](https://eips.ethereum.org/EIPS/eip-2930) Access Lists EIP + */ + EIP2930AccessLists = 2930, +} + +/** + * The options for initializing a {@link Transaction}. + */ +export interface TxOptions { + /** + * A {@link Common} object defining the chain and hardfork for the transaction. + * + * Object will be internally copied so that tx behavior don't incidentally + * change on future HF changes. + * + * Default: {@link Common} object set to `mainnet` and the default hardfork as defined in the {@link Common} class. + * + * Current default hardfork: `istanbul` + */ + common?: Common; + /** + * A transaction object by default gets frozen along initialization. This gives you + * strong additional security guarantees on the consistency of the tx parameters. + * It also enables tx hash caching when the `hash()` method is called multiple times. + * + * If you need to deactivate the tx freeze - e.g. because you want to subclass tx and + * add additional properties - it is strongly encouraged that you do the freeze yourself + * within your code instead. + * + * Default: true + */ + freeze?: boolean; + + /** + * Allows unlimited contract code-size init while debugging. This (partially) disables EIP-3860. + * Gas cost for initcode size analysis will still be charged. Use with caution. + */ + allowUnlimitedInitCodeSize?: boolean; +} + +/* + * Access List types + */ + +export type AccessListItem = { + address: PrefixedHexString; + storageKeys: PrefixedHexString[]; +}; + +/* + * An Access List as a tuple of [address: Uint8Array, storageKeys: Uint8Array[]] + */ +export type AccessListUint8ArrayItem = [Uint8Array, Uint8Array[]]; +export type AccessListUint8Array = AccessListUint8ArrayItem[]; +export type AccessList = AccessListItem[]; + +export function isAccessListUint8Array( + input: AccessListUint8Array | AccessList, +): input is AccessListUint8Array { + if (input.length === 0) { + return true; + } + const firstItem = input[0]; + if (Array.isArray(firstItem)) { + return true; + } + return false; +} + +export function isAccessList(input: AccessListUint8Array | AccessList): input is AccessList { + return !isAccessListUint8Array(input); // This is exactly the same method, except the output is negated. +} + +export interface ECDSASignature { + v: bigint; + r: Uint8Array; + s: Uint8Array; +} + +/** + * Legacy {@link Transaction} Data + */ +export type TxData = { + /** + * The transaction's nonce. + */ + nonce?: Numbers | Uint8Array; + + /** + * The transaction's gas price. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + gasPrice?: Numbers | Uint8Array | null; + + /** + * The transaction's gas limit. + */ + gasLimit?: Numbers | Uint8Array; + + /** + * The transaction's the address is sent to. + */ + to?: Address | Uint8Array | HexString; + + /** + * The amount of Ether sent. + */ + value?: Numbers | Uint8Array; + + /** + * This will contain the data of the message or the init of a contract. + */ + data?: Uint8ArrayLike; + + /** + * EC recovery ID. + */ + v?: Numbers | Uint8Array; + + /** + * EC signature parameter. + */ + r?: Numbers | Uint8Array; + + /** + * EC signature parameter. + */ + s?: Numbers | Uint8Array; + + /** + * The transaction type + */ + + type?: Numbers; +}; + +/** + * {@link AccessListEIP2930Transaction} data. + */ +export interface AccessListEIP2930TxData extends TxData { + /** + * The transaction's chain ID + */ + chainId?: Numbers; + + /** + * The access list which contains the addresses/storage slots which the transaction wishes to access + */ + // eslint-disable-next-line @typescript-eslint/ban-types + accessList?: AccessListUint8Array | AccessList | null; +} + +/** + * {@link FeeMarketEIP1559Transaction} data. + */ +export interface FeeMarketEIP1559TxData extends AccessListEIP2930TxData { + /** + * The transaction's gas price, inherited from {@link Transaction}. This property is not used for EIP1559 + * transactions and should always be undefined for this specific transaction type. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + gasPrice?: never | null; + /** + * The maximum inclusion fee per gas (this fee is given to the miner) + */ + maxPriorityFeePerGas?: Numbers | Uint8Array; + /** + * The maximum total fee + */ + maxFeePerGas?: Numbers | Uint8Array; +} + +/** + * Uint8Array values array for a legacy {@link Transaction} + */ +export type TxValuesArray = Uint8Array[]; + +/** + * Uint8Array values array for an {@link AccessListEIP2930Transaction} + */ +export type AccessListEIP2930ValuesArray = [ + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + AccessListUint8Array, + Uint8Array?, + Uint8Array?, + Uint8Array?, +]; + +/** + * Uint8Array values array for a {@link FeeMarketEIP1559Transaction} + */ +export type FeeMarketEIP1559ValuesArray = [ + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + Uint8Array, + AccessListUint8Array, + Uint8Array?, + Uint8Array?, + Uint8Array?, +]; + +type JsonAccessListItem = { address: string; storageKeys: string[] }; + +/** + * Generic interface for all tx types with a + * JSON representation of a transaction. + * + * Note that all values are marked as optional + * and not all the values are present on all tx types + * (an EIP1559 tx e.g. lacks a `gasPrice`). + */ +export interface JsonTx { + nonce?: string; + gasPrice?: string; + gasLimit?: string; + to?: string; + data?: string; + v?: string; + r?: string; + s?: string; + value?: string; + chainId?: string; + accessList?: JsonAccessListItem[]; + type?: string; + maxPriorityFeePerGas?: string; + maxFeePerGas?: string; + maxFeePerDataGas?: string; + versionedHashes?: string[]; +} diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/utils.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/utils.ts new file mode 100644 index 0000000..3b2fabb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/tx/utils.ts @@ -0,0 +1,150 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { HexString } from 'web3-types'; +import { bytesToHex } from 'web3-utils'; +import { setLengthLeft, toUint8Array } from '../common/utils.js'; +import type { AccessList, AccessListUint8Array, AccessListItem } from './types.js'; +import { isAccessList } from './types.js'; + +import type { Common } from '../common/common.js'; + +export const checkMaxInitCodeSize = (common: Common, length: number) => { + const maxInitCodeSize = common.param('vm', 'maxInitCodeSize'); + if (maxInitCodeSize && BigInt(length) > maxInitCodeSize) { + throw new Error( + `the initcode size of this transaction is too large: it is ${length} while the max is ${common.param( + 'vm', + 'maxInitCodeSize', + )}`, + ); + } +}; + +export const getAccessListData = (accessList: AccessListUint8Array | AccessList) => { + let AccessListJSON; + let uint8arrayAccessList; + if (isAccessList(accessList)) { + AccessListJSON = accessList; + const newAccessList: AccessListUint8Array = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < accessList.length; i += 1) { + const item: AccessListItem = accessList[i]; + const addressBytes = toUint8Array(item.address); + const storageItems: Uint8Array[] = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < item.storageKeys.length; index += 1) { + storageItems.push(toUint8Array(item.storageKeys[index])); + } + newAccessList.push([addressBytes, storageItems]); + } + uint8arrayAccessList = newAccessList; + } else { + uint8arrayAccessList = accessList ?? []; + // build the JSON + const json: AccessList = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < uint8arrayAccessList.length; i += 1) { + const data = uint8arrayAccessList[i]; + const address = bytesToHex(data[0]); + const storageKeys: string[] = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let item = 0; item < data[1].length; item += 1) { + storageKeys.push(bytesToHex(data[1][item])); + } + const jsonItem: AccessListItem = { + address, + storageKeys, + }; + json.push(jsonItem); + } + AccessListJSON = json; + } + + return { + AccessListJSON, + accessList: uint8arrayAccessList, + }; +}; + +export const verifyAccessList = (accessList: AccessListUint8Array) => { + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let key = 0; key < accessList.length; key += 1) { + const accessListItem = accessList[key]; + const address = accessListItem[0]; + const storageSlots = accessListItem[1]; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions + if ((accessListItem)[2] !== undefined) { + throw new Error( + 'Access list item cannot have 3 elements. It can only have an address, and an array of storage slots.', + ); + } + if (address.length !== 20) { + throw new Error('Invalid EIP-2930 transaction: address length should be 20 bytes'); + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let storageSlot = 0; storageSlot < storageSlots.length; storageSlot += 1) { + if (storageSlots[storageSlot].length !== 32) { + throw new Error( + 'Invalid EIP-2930 transaction: storage slot length should be 32 bytes', + ); + } + } + } +}; + +export const getAccessListJSON = ( + accessList: AccessListUint8Array, +): { + address: HexString; + storageKeys: HexString[]; +}[] => { + const accessListJSON: { address: HexString; storageKeys: HexString[] }[] = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < accessList.length; index += 1) { + const item: any = accessList[index]; + const JSONItem: { address: HexString; storageKeys: HexString[] } = { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions + address: bytesToHex(setLengthLeft(item[0], 20)), + storageKeys: [], + }; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/prefer-optional-chain + const storageSlots: Uint8Array[] = item && item[1]; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let slot = 0; slot < storageSlots.length; slot += 1) { + const storageSlot = storageSlots[slot]; + JSONItem.storageKeys.push(bytesToHex(setLengthLeft(storageSlot, 32))); + } + accessListJSON.push(JSONItem); + } + return accessListJSON; +}; + +export const getDataFeeEIP2930 = (accessList: AccessListUint8Array, common: Common): number => { + const accessListStorageKeyCost = common.param('gasPrices', 'accessListStorageKeyCost'); + const accessListAddressCost = common.param('gasPrices', 'accessListAddressCost'); + + let slots = 0; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let index = 0; index < accessList.length; index += 1) { + const item = accessList[index]; + const storageSlots = item[1]; + slots += storageSlots.length; + } + + const addresses = accessList.length; + return addresses * Number(accessListAddressCost) + slots * Number(accessListStorageKeyCost); +}; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/types.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/types.ts new file mode 100644 index 0000000..ed45ad9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/types.ts @@ -0,0 +1,94 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3BaseWalletAccount, HexString } from 'web3-types'; +import { FeeMarketEIP1559TxData, AccessListEIP2930TxData, TxData } from './tx/types.js'; +import { AccessListEIP2930Transaction, FeeMarketEIP1559Transaction, Transaction } from './tx'; + +export type SignatureObject = { + messageHash: string; + r: string; + s: string; + v: string; +}; + +export type SignTransactionResult = SignatureObject & { + rawTransaction: string; + transactionHash: string; +}; + +export type SignTransactionFunction = ( + transaction: + | TxData + | AccessListEIP2930TxData + | FeeMarketEIP1559TxData + | Record, +) => SignTransactionResult; + +export type SignResult = SignatureObject & { + message?: string; + signature: string; +}; + +export type SignFunction = (data: string, privateKey: string) => SignResult; + +// https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + +export interface Web3Account extends Web3BaseWalletAccount { + address: HexString; + privateKey: HexString; +} + +// To avoid dependency of "dom" library for TS, copying this interface within project +/** This Web Storage API interface provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items. */ +export interface WebStorage { + /** Returns the number of key/value pairs. */ + readonly length: number; + /** + * Removes all key/value pairs, if there are any. + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + clear(): void; + /** Returns the current value associated with the given key, or null if the given key does not exist. */ + // eslint-disable-next-line @typescript-eslint/ban-types + getItem(key: string): string | null; + /** Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs. */ + // eslint-disable-next-line @typescript-eslint/ban-types + key(index: number): string | null; + /** + * Removes the key/value pair with the given key, if a key/value pair with the given key exists. + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + removeItem(key: string): void; + /** + * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. + * + * Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) + * + * Dispatches a storage event on Window objects holding an equivalent Storage object. + */ + setItem(key: string, value: string): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [name: string]: any; +} + +export type TypedTransaction = + | Transaction + | AccessListEIP2930Transaction + | FeeMarketEIP1559Transaction; diff --git a/test/merkletreejs/node_modules/web3-eth-accounts/src/wallet.ts b/test/merkletreejs/node_modules/web3-eth-accounts/src/wallet.ts new file mode 100644 index 0000000..8d50efd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-accounts/src/wallet.ts @@ -0,0 +1,440 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3BaseWallet, Web3BaseWalletAccount, KeyStore } from 'web3-types'; +import { isNullish } from 'web3-validator'; +import { WebStorage } from './types.js'; + +type BrowserError = { code: number; name: string }; + +/** + * Wallet is an in memory `wallet` that can hold multiple accounts. + * These accounts can be used when using web3.eth.sendTransaction(). + * + * ### Parameters + * Web3AccountProvider - AccountProvider for the wallet + * + * ```ts + * import Web3 from 'web3'; + * const web3 = new Web3("https://localhost:8454") + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ +export class Wallet< + T extends Web3BaseWalletAccount = Web3BaseWalletAccount, +> extends Web3BaseWallet { + private readonly _addressMap = new Map(); + private readonly _defaultKeyName = 'web3js_wallet'; + + /** + * Get the storage object of the browser + * + * @returns the storage + */ + public static getStorage(): WebStorage | undefined { + let storage: WebStorage | undefined; + + try { + storage = window.localStorage; + const x = '__storage_test__'; + storage.setItem(x, x); + storage.removeItem(x); + + return storage; + } catch (e: unknown) { + return (e as BrowserError) && + // everything except Firefox + ((e as BrowserError).code === 22 || + // Firefox + (e as BrowserError).code === 1014 || + // test name field too, because code might not be present + // everything except Firefox + (e as BrowserError).name === 'QuotaExceededError' || + // Firefox + (e as BrowserError).name === 'NS_ERROR_DOM_QUOTA_REACHED') && + // acknowledge QuotaExceededError only if there's something already stored + !isNullish(storage) && + storage.length !== 0 + ? storage + : undefined; + } + } + /** + * Generates one or more accounts in the wallet. If wallets already exist they will not be overridden. + * + * @param numberOfAccounts - Number of accounts to create. Leave empty to create an empty wallet. + * @returns The wallet + * ```ts + * web3.eth.accounts.wallet.create(2) + * > Wallet(2) [ + * { + * address: '0xde38310a42B751AE57d30cFFF4a0A3c52A442fCE', + * privateKey: '0x6422c9d28efdcbee93c1d32a5fc6fd6fa081b985487885296cf8c9bbb5872600', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * { + * address: '0x766BF755246d924B1d017Fdb5390f38a60166691', + * privateKey: '0x756530f13c0eb636ebdda655335f5dea9921e3362e2e588b0ad59e556f7751f0', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(2) { + * '0xde38310a42b751ae57d30cfff4a0a3c52a442fce' => 0, + * '0x766bf755246d924b1d017fdb5390f38a60166691' => 1 + * }, + * _defaultKeyName: 'web3js_wallet' + * ] + * + * ``` + */ + + public create(numberOfAccounts: number) { + for (let i = 0; i < numberOfAccounts; i += 1) { + this.add(this._accountProvider.create()); + } + + return this; + } + + /** + * Adds an account using a private key or account object to the wallet. + * + * @param account - A private key or account object + * @returns The wallet + * + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * > Wallet(1) [ + * { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(1) { '0x85d70633b90e03e0276b98880286d0d055685ed7' => 0 }, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + public add(account: T | string): this { + if (typeof account === 'string') { + return this.add(this._accountProvider.privateKeyToAccount(account)); + } + let index = this.length; + const existAccount = this.get(account.address); + if (existAccount) { + console.warn(`Account ${account.address.toLowerCase()} already exists.`); + index = this._addressMap.get(account.address.toLowerCase()) ?? index; + } + this._addressMap.set(account.address.toLowerCase(), index); + this[index] = account; + + return this; + } + /** + * Get the account of the wallet with either the index or public address. + * + * @param addressOrIndex - A string of the address or number index within the wallet. + * @returns The account object or undefined if the account doesn't exist + */ + + public get(addressOrIndex: string | number): T | undefined { + if (typeof addressOrIndex === 'string') { + const index = this._addressMap.get(addressOrIndex.toLowerCase()); + + if (!isNullish(index)) { + return this[index]; + } + + return undefined; + } + + return this[addressOrIndex]; + } + + /** + * Removes an account from the wallet. + * + * @param addressOrIndex - The account address, or index in the wallet. + * @returns true if the wallet was removed. false if it couldn't be found. + * ```ts + * web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387'); + * + * web3.eth.accounts.wallet.remove('0x85D70633b90e03e0276B98880286D0D055685ed7'); + * > true + * web3.eth.accounts.wallet + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + public remove(addressOrIndex: string | number): boolean { + if (typeof addressOrIndex === 'string') { + const index = this._addressMap.get(addressOrIndex.toLowerCase()); + if (isNullish(index)) { + return false; + } + this._addressMap.delete(addressOrIndex.toLowerCase()); + this.splice(index, 1); + + return true; + } + + if (this[addressOrIndex]) { + this.splice(addressOrIndex, 1); + return true; + } + + return false; + } + + /** + * Securely empties the wallet and removes all its accounts. + * Use this with *caution as it will remove all accounts stored in local wallet. + * + * @returns The wallet object + * ```ts + * + * web3.eth.accounts.wallet.clear(); + * > Wallet(0) [ + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _addressMap: Map(0) {}, + * _defaultKeyName: 'web3js_wallet' + * ] + * ``` + */ + public clear() { + this._addressMap.clear(); + + // Setting length clears the Array in JS. + this.length = 0; + + return this; + } + + /** + * Encrypts all wallet accounts to an array of encrypted keystore v3 objects. + * + * @param password - The password which will be used for encryption + * @param options - encryption options + * @returns An array of the encrypted keystore v3. + * + * ```ts + * web3.eth.accounts.wallet.create(1) + * web3.eth.accounts.wallet.encrypt("abc").then(console.log); + * > [ + * '{"version":3,"id":"fa46e213-a7c3-4844-b903-dd14d39cc7db", + * "address":"fa3e41a401609103c241431cbdee8623ae2a321a","crypto": + * {"ciphertext":"8d179a911d6146ad2924e86bf493ed89b8ff3596ffec0816e761c542016ab13c", + * "cipherparams":{"iv":"acc888c6cf4a19b86846cef0185a7164"},"cipher":"aes-128-ctr", + * "kdf":"scrypt","kdfparams":{"n":8192,"r":8,"p":1,"dklen":32,"salt":"6a743c9b367d15f4758e4f3f3378ff0fd443708d1c64854e07588ea5331823ae"}, + * "mac":"410544c8307e3691fda305eb3722d82c3431f212a87daa119a21587d96698b57"}}' + * ] + * ``` + */ + public async encrypt( + password: string, + options?: Record | undefined, + ): Promise { + return Promise.all(this.map(async (account: T) => account.encrypt(password, options))); + } + + /** + * Decrypts keystore v3 objects. + * + * @param encryptedWallets - An array of encrypted keystore v3 objects to decrypt + * @param password - The password to encrypt with + * @param options - decrypt options for the wallets + * @returns The decrypted wallet object + * + * ```ts + * web3.eth.accounts.wallet.decrypt([ + * { version: 3, + * id: '83191a81-aaca-451f-b63d-0c5f3b849289', + * address: '06f702337909c06c82b09b7a22f0a2f0855d1f68', + * crypto: + * { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d', + * cipherparams: { iv: '497f4d26997a84d570778eae874b2333' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } }, + * { version: 3, + * id: '7d6b91fa-3611-407b-b16b-396efb28f97e', + * address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf', + * crypto: + * { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43', + * cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' }, + * cipher: 'aes-128-ctr', + * kdf: 'scrypt', + * kdfparams: + * { dklen: 32, + * salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8', + * n: 262144, + * r: 8, + * p: 1 }, + * mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } } + * ], 'test').then(console.log) + * > Wallet { + * _accountProvider: { + * create: [Function: create], + * privateKeyToAccount: [Function: privateKeyToAccount], + * decrypt: [Function: decrypt] + * }, + * _defaultKeyName: 'web3js_wallet', + * _accounts: { + * '0x85d70633b90e03e0276b98880286d0d055685ed7': { + * address: '0x85D70633b90e03e0276B98880286D0D055685ed7', + * privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0x06f702337909c06c82b09b7a22f0a2f0855d1f68': { + * address: '0x06F702337909C06C82B09B7A22F0a2f0855d1F68', + * privateKey: '87a51da18900da7398b3bab03996833138f269f8f66dd1237b98df6b9ce14573', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * }, + * '0xb5d89661b59a9af0b34f58d19138baa2de48baaf': { + * address: '0xB5d89661B59a9aF0b34f58D19138bAa2de48BAaf', + * privateKey: '7ee61c5282979aae9dd795bb6a54e8bdc2bfe009acb64eb9a67322eec3b3da6e', + * signTransaction: [Function: signTransaction], + * sign: [Function: sign], + * encrypt: [Function: encrypt] + * } + * } + * } + * ``` + */ + public async decrypt( + encryptedWallets: KeyStore[], + password: string, + options?: Record | undefined, + ) { + const results = await Promise.all( + encryptedWallets.map(async (wallet: KeyStore) => + this._accountProvider.decrypt(wallet, password, options), + ), + ); + for (const res of results) { + this.add(res); + } + return this; + } + + /** + * Stores the wallet encrypted and as string in local storage. + * **__NOTE:__** Browser only + * + * @param password - The password to encrypt the wallet + * @param keyName - (optional) The key used for the local storage position, defaults to `"web3js_wallet"`. + * @returns Will return boolean value true if saved properly + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * >true + * ``` + */ + public async save(password: string, keyName?: string) { + const storage = Wallet.getStorage(); + + if (!storage) { + throw new Error('Local storage not available.'); + } + + storage.setItem( + keyName ?? this._defaultKeyName, + JSON.stringify(await this.encrypt(password)), + ); + + return true; + } + + /** + * Loads a wallet from local storage and decrypts it. + * **__NOTE:__** Browser only + * + * @param password - The password to decrypt the wallet. + * @param keyName - (optional)The key used for local storage position, defaults to `web3js_wallet"` + * @returns Returns the wallet object + * + * ```ts + * web3.eth.accounts.wallet.save('test#!$'); + * > true + * web3.eth.accounts.wallet.load('test#!$'); + * { defaultKeyName: "web3js_wallet", + * length: 0, + * _accounts: Accounts {_requestManager: RequestManager, givenProvider: Proxy, providers: {…}, _provider: WebsocketProvider, …}, + * [[Prototype]]: Object + * } + * ``` + */ + public async load(password: string, keyName?: string) { + const storage = Wallet.getStorage(); + + if (!storage) { + throw new Error('Local storage not available.'); + } + + const keystore = storage.getItem(keyName ?? this._defaultKeyName); + + if (keystore) { + await this.decrypt((JSON.parse(keystore) as KeyStore[]) || [], password); + } + + return this; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/LICENSE b/test/merkletreejs/node_modules/web3-eth-contract/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth-contract/README.md b/test/merkletreejs/node_modules/web3-eth-contract/README.md new file mode 100644 index 0000000..9de73d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/README.md @@ -0,0 +1,82 @@ +

+ web3.js +

+ +# web3.js - Eth Contract Package + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth-contract` contains the contract package used in `web3-eth`. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth-contract) or using [Yarn](https://yarnpkg.com/package/web3-eth-contract) + +### Using NPM + +```bash +npm install web3-eth-contract +``` + +### Using Yarn + +```bash +yarn add web3-eth-contract +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Usage + +You can initialize the typesafe Contract API instance with the following. + +```ts +import { Contract } from 'web3-eth-contract'; + +const abi = [...] as const; + +const contract = new Contract(abi); +``` + +- We prefer that you use `web3.eth.Contract` API in normal usage. +- The use of `as const` is necessary to have fully type-safe interface for the contract. +- As the ABIs are not extensive in size, we suggest declaring them `as const` in your TS project. +- This approach is more flexible and seamless compared to other approaches of off-line compiling ABIs to TS interfaces (such as [TypeChain](https://github.com/dethcrypto/TypeChain). + +## Compatibility + +We have tested the Typescript interface support for the ABIs compiled with solidity version `v0.4.x` and above. If you face any issue regarding the contract typing, please create an issue to report to us. + +The Typescript support for fixed length array types are supported up 30 elements. See more details [here](https://github.com/ChainSafe/web3.js/blob/nh%2F4562-contract-typing/packages/web3-eth-abi/src/number_map_type.ts#L1). This limitation is only to provide more performant developer experience in IDEs. In future we may come up with a workaround to avoid this limitation. If you have any idea feel free to share. + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth-contract +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-contract%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth-contract +[downloads-image]: https://img.shields.io/npm/dm/web3-eth-contract?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.d.ts new file mode 100644 index 0000000..b9be6cc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.d.ts @@ -0,0 +1 @@ +export { ALL_EVENTS, ALL_EVENTS_ABI } from 'web3-eth'; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.js new file mode 100644 index 0000000..ae23677 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ALL_EVENTS_ABI = exports.ALL_EVENTS = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var web3_eth_1 = require("web3-eth"); +Object.defineProperty(exports, "ALL_EVENTS", { enumerable: true, get: function () { return web3_eth_1.ALL_EVENTS; } }); +Object.defineProperty(exports, "ALL_EVENTS_ABI", { enumerable: true, get: function () { return web3_eth_1.ALL_EVENTS_ABI; } }); +//# sourceMappingURL=constant.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.js.map new file mode 100644 index 0000000..c901859 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/constant.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constant.js","sourceRoot":"","sources":["../../src/constant.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,qCAAsD;AAA7C,sGAAA,UAAU,OAAA;AAAE,0GAAA,cAAc,OAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.d.ts new file mode 100644 index 0000000..db7df57 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.d.ts @@ -0,0 +1,321 @@ +import { Web3Context, Web3EventEmitter, Web3PromiEvent } from 'web3-core'; +import { NewHeadsSubscription, SendTransactionEvents } from 'web3-eth'; +import { AbiFunctionFragment, ContractAbi, ContractConstructorArgs, ContractEvent, ContractEvents, ContractMethod, ContractMethodInputParameters, ContractMethodOutputParameters, Address, EthExecutionAPI, Filter, FilterAbis, HexString, ContractInitOptions, PayableCallOptions, DataFormat, DEFAULT_RETURN_FORMAT, EventLog, ContractOptions } from 'web3-types'; +import { LogsSubscription } from './log_subscription.js'; +import { ContractEventOptions, NonPayableMethodObject, PayableMethodObject, PayableTxOptions, Web3ContractContext } from './types.js'; +declare type ContractBoundMethod = ContractMethod> = (...args: Method['Inputs']) => Method['Abi']['stateMutability'] extends 'payable' | 'pure' ? PayableMethodObject : NonPayableMethodObject; +export declare type ContractOverloadedMethodInputs> = NonNullable | ContractOverloadedMethodInputs : undefined : undefined>; +export declare type ContractOverloadedMethodOutputs> = NonNullable | ContractOverloadedMethodOutputs : undefined : undefined>; +export declare type ContractMethodsInterface = { + [MethodAbi in FilterAbis as MethodAbi['name']]: ContractBoundMethod; +} & { + [key: string]: ContractBoundMethod; +}; +/** + * @hidden + * The event object can be accessed from `myContract.events.myEvent`. + * + * \> Remember: To subscribe to an event, your provider must have support for subscriptions. + * + * ```ts + * const subscription = await myContract.events.MyEvent([options]) + * ``` + * + * @param options - The options used to subscribe for the event + * @returns - A Promise resolved with {@link LogsSubscription} object + */ +export declare type ContractBoundEvent = (options?: ContractEventOptions) => LogsSubscription; +export declare type ContractEventsInterface = ContractEvents> = { + [Name in keyof Events | 'allEvents']: ContractBoundEvent; +} & { + [key: string]: ContractBoundEvent; +}; +export declare type ContractEventEmitterInterface = { + [EventAbi in FilterAbis as EventAbi['name']]: ContractEvent['Inputs']; +}; +declare const contractSubscriptions: { + logs: typeof LogsSubscription; + newHeads: typeof NewHeadsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; +}; +/** + * The class designed to interact with smart contracts on the Ethereum blockchain. + */ +export declare class Contract extends Web3Context implements Web3EventEmitter> { + /** + * The options `object` for the contract instance. `from`, `gas` and `gasPrice` are used as fallback values when sending transactions. + * + * ```ts + * myContract.options; + * > { + * address: '0x1234567890123456789012345678901234567891', + * jsonInterface: [...], + * from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', + * gasPrice: '10000000000000', + * gas: 1000000 + * } + * + * myContract.options.from = '0x1234567890123456789012345678901234567891'; // default from address + * myContract.options.gasPrice = '20000000000000'; // default gas price in wei + * myContract.options.gas = 5000000; // provide as fallback always 5M gas + * ``` + */ + readonly options: ContractOptions; + /** + * Set to true if you want contracts' defaults to sync with global defaults. + */ + syncWithContext: boolean; + private _errorsInterface; + private _jsonInterface; + private _address?; + private _functions; + private readonly _overloadedMethodAbis; + private _methods; + private _events; + /** + * Set property to `data`, `input`, or `both` to change the property of the contract being sent to the + * RPC provider when using contract methods. + * Default is `input` + */ + private context?; + /** + * Creates a new contract instance with all its methods and events defined in its ABI provided. + * + * ```ts + * new web3.eth.Contract(jsonInterface[, address][, options]) + * ``` + * + * @param jsonInterface - The JSON interface for the contract to instantiate. + * @param address - The address of the smart contract to call. + * @param options - The options of the contract. Some are used as fallbacks for calls and transactions. + * @param context - The context of the contract used for customizing the behavior of the contract. + * @returns - The contract instance with all its methods and events. + * + * ```ts title="Example" + * var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', { + * from: '0x1234567890123456789012345678901234567891', // default from address + * gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case + * }); + * ``` + * + * To use the type safe interface for these contracts you have to include the ABI definitions in your Typescript project and then declare these as `const`. + * + * ```ts title="Example" + * const myContractAbi = [....] as const; // ABI definitions + * const myContract = new web3.eth.Contract(myContractAbi, '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'); + * ``` + */ + constructor(jsonInterface: Abi, context?: Web3ContractContext | Web3Context, returnFormat?: DataFormat); + constructor(jsonInterface: Abi, address?: Address, contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, returnFormat?: DataFormat); + constructor(jsonInterface: Abi, options?: ContractInitOptions, contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, returnFormat?: DataFormat); + constructor(jsonInterface: Abi, address: Address | undefined, options: ContractInitOptions, contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, returnFormat?: DataFormat); + /** + * Subscribe to an event. + * + * ```ts + * await myContract.events.MyEvent([options]) + * ``` + * + * There is a special event `allEvents` that can be used to subscribe all events. + * + * ```ts + * await myContract.events.allEvents([options]) + * ``` + * + * @returns - When individual event is accessed will returns {@link ContractBoundEvent} object + */ + get events(): ContractEventsInterface>; + /** + * Creates a transaction object for that method, which then can be `called`, `send`, `estimated`, `createAccessList` , or `ABI encoded`. + * + * The methods of this smart contract are available through: + * + * The name: `myContract.methods.myMethod(123)` + * The name with parameters: `myContract.methods['myMethod(uint256)'](123)` + * The signature `myContract.methods['0x58cf5f10'](123)` + * + * This allows calling functions with same name but different parameters from the JavaScript contract object. + * + * \> The method signature does not provide a type safe interface, so we recommend to use method `name` instead. + * + * ```ts + * // calling a method + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using a promise + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using the events + * const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * sendObject.on('transactionHash', function(hash){ + * ... + * }); + * sendObject.on('receipt', function(receipt){ + * ... + * }); + * sendObject.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * sendObject.on('error', function(error, receipt) { + * ... + * }); + * ``` + * + * @returns - Either returns {@link PayableMethodObject} or {@link NonPayableMethodObject} based on the definitions of the ABI of that contract. + */ + get methods(): ContractMethodsInterface; + /** + * Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone. + * + * @returns - The new contract instance. + * + * ```ts + * const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress}); + * + * const contract2 = contract1.clone(); + * contract2.options.address = address2; + * + * (contract1.options.address !== contract2.options.address); + * > true + * ``` + */ + clone(): Contract; + /** + * Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance. + * + * ```ts + * myContract.deploy({ + * input: '0x12345...', // data keyword can be used, too. If input is used, data will be ignored. + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }, function(error, transactionHash){ ... }) + * .on('error', function(error){ ... }) + * .on('transactionHash', function(transactionHash){ ... }) + * .on('receipt', function(receipt){ + * console.log(receipt.contractAddress) // contains the new contract address + * }) + * .on('confirmation', function(confirmationNumber, receipt){ ... }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // When the data is already set as an option to the contract itself + * myContract.options.data = '0x12345...'; + * + * myContract.deploy({ + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // Simply encoding + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .encodeABI(); + * > '0x12345...0000012345678765432' + * + * + * // Gas estimation + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .estimateGas(function(err, gas){ + * console.log(gas); + * }); + * ``` + * + * @returns - The transaction object + */ + deploy(deployOptions?: { + /** + * The byte code of the contract. + */ + data?: HexString; + input?: HexString; + /** + * The arguments which get passed to the constructor on deployment. + */ + arguments?: ContractConstructorArgs; + }): { + arguments: never[] | NonNullable>; + send: (options?: PayableTxOptions) => Web3PromiEvent, SendTransactionEvents>; + estimateGas: (options?: PayableCallOptions, returnFormat?: ReturnFormat) => Promise; + encodeABI: () => string; + }; + /** + * Gets past events for this contract. + * + * ```ts + * const events = await myContract.getPastEvents('MyEvent', { + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0, + * toBlock: 'latest' + * }); + * + * > [{ + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * },{ + * ... + * }] + * ``` + * + * @param eventName - The name of the event in the contract, or `allEvents` to get all events. + * @param filter - The filter options used to get events. + * @param returnFormat - Return format + * @returns - An array with the past event `Objects`, matching the given event name and filter. + */ + getPastEvents(returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + getPastEvents(eventName: keyof ContractEvents | 'allEvents' | 'ALLEVENTS', returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + getPastEvents(filter: Omit, returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + getPastEvents(eventName: keyof ContractEvents | 'allEvents' | 'ALLEVENTS', filter: Omit, returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + private _parseAndSetAddress; + private _parseAndSetJsonInterface; + private _getAbiParams; + private _createContractMethod; + private _contractMethodCall; + private _contractMethodCreateAccessList; + private _contractMethodSend; + private _contractMethodDeploySend; + private _contractMethodEstimateGas; + private _createContractEvent; + protected subscribeToContextEvents(context: T): void; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.js new file mode 100644 index 0000000..34d0ddb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.js @@ -0,0 +1,667 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Contract = void 0; +const web3_core_1 = require("web3-core"); +const web3_errors_1 = require("web3-errors"); +const web3_eth_1 = require("web3-eth"); +const web3_eth_abi_1 = require("web3-eth-abi"); +const web3_types_1 = require("web3-types"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const encoding_js_1 = require("./encoding.js"); +const log_subscription_js_1 = require("./log_subscription.js"); +const utils_js_1 = require("./utils.js"); +const contractSubscriptions = { + logs: log_subscription_js_1.LogsSubscription, + newHeads: web3_eth_1.NewHeadsSubscription, + newBlockHeaders: web3_eth_1.NewHeadsSubscription, +}; +/** + * The class designed to interact with smart contracts on the Ethereum blockchain. + */ +class Contract extends web3_core_1.Web3Context { + constructor(jsonInterface, addressOrOptionsOrContext, optionsOrContextOrReturnFormat, contextOrReturnFormat, returnFormat) { + var _a, _b, _c; + // eslint-disable-next-line no-nested-ternary + const options = (0, utils_js_1.isContractInitOptions)(addressOrOptionsOrContext) + ? addressOrOptionsOrContext + : (0, utils_js_1.isContractInitOptions)(optionsOrContextOrReturnFormat) + ? optionsOrContextOrReturnFormat + : undefined; + let contractContext; + if ((0, utils_js_1.isWeb3ContractContext)(addressOrOptionsOrContext)) { + contractContext = addressOrOptionsOrContext; + } + else if ((0, utils_js_1.isWeb3ContractContext)(optionsOrContextOrReturnFormat)) { + contractContext = optionsOrContextOrReturnFormat; + } + else { + contractContext = contextOrReturnFormat; + } + let provider; + if (typeof addressOrOptionsOrContext === 'object' && + 'provider' in addressOrOptionsOrContext) { + provider = addressOrOptionsOrContext.provider; + } + else if (typeof optionsOrContextOrReturnFormat === 'object' && + 'provider' in optionsOrContextOrReturnFormat) { + provider = optionsOrContextOrReturnFormat.provider; + } + else if (typeof contextOrReturnFormat === 'object' && + 'provider' in contextOrReturnFormat) { + provider = contextOrReturnFormat.provider; + } + else { + provider = Contract.givenProvider; + } + super(Object.assign(Object.assign({}, contractContext), { provider, registeredSubscriptions: contractSubscriptions })); + /** + * Set to true if you want contracts' defaults to sync with global defaults. + */ + this.syncWithContext = false; + this._functions = {}; + if (!(0, web3_validator_1.isNullish)(options) && + !(0, web3_validator_1.isNullish)(options.data) && + !(0, web3_validator_1.isNullish)(options.input) && + this.config.contractDataInputFill !== 'both') + throw new web3_errors_1.ContractTransactionDataAndInputError({ + data: options.data, + input: options.input, + }); + this._overloadedMethodAbis = new Map(); + // eslint-disable-next-line no-nested-ternary + const returnDataFormat = (0, web3_utils_1.isDataFormat)(contextOrReturnFormat) + ? contextOrReturnFormat + : (0, web3_utils_1.isDataFormat)(optionsOrContextOrReturnFormat) + ? optionsOrContextOrReturnFormat + : returnFormat !== null && returnFormat !== void 0 ? returnFormat : web3_types_1.DEFAULT_RETURN_FORMAT; + const address = typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined; + this.config.contractDataInputFill = + (_a = options === null || options === void 0 ? void 0 : options.dataInputFill) !== null && _a !== void 0 ? _a : this.config.contractDataInputFill; + this._parseAndSetJsonInterface(jsonInterface, returnDataFormat); + if (!(0, web3_validator_1.isNullish)(address)) { + this._parseAndSetAddress(address, returnDataFormat); + } + this.options = { + address, + jsonInterface: this._jsonInterface, + gas: (_b = options === null || options === void 0 ? void 0 : options.gas) !== null && _b !== void 0 ? _b : options === null || options === void 0 ? void 0 : options.gasLimit, + gasPrice: options === null || options === void 0 ? void 0 : options.gasPrice, + from: options === null || options === void 0 ? void 0 : options.from, + input: options === null || options === void 0 ? void 0 : options.input, + data: options === null || options === void 0 ? void 0 : options.data, + }; + this.syncWithContext = (_c = options === null || options === void 0 ? void 0 : options.syncWithContext) !== null && _c !== void 0 ? _c : false; + if (contractContext instanceof web3_core_1.Web3Context) { + this.subscribeToContextEvents(contractContext); + } + Object.defineProperty(this.options, 'address', { + set: (value) => this._parseAndSetAddress(value, returnDataFormat), + get: () => this._address, + }); + Object.defineProperty(this.options, 'jsonInterface', { + set: (value) => this._parseAndSetJsonInterface(value, returnDataFormat), + get: () => this._jsonInterface, + }); + if (contractContext instanceof web3_core_1.Web3Context) { + contractContext.on(web3_core_1.Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.setConfig({ [event.name]: event.newValue }); + }); + } + } + /** + * Subscribe to an event. + * + * ```ts + * await myContract.events.MyEvent([options]) + * ``` + * + * There is a special event `allEvents` that can be used to subscribe all events. + * + * ```ts + * await myContract.events.allEvents([options]) + * ``` + * + * @returns - When individual event is accessed will returns {@link ContractBoundEvent} object + */ + get events() { + return this._events; + } + /** + * Creates a transaction object for that method, which then can be `called`, `send`, `estimated`, `createAccessList` , or `ABI encoded`. + * + * The methods of this smart contract are available through: + * + * The name: `myContract.methods.myMethod(123)` + * The name with parameters: `myContract.methods['myMethod(uint256)'](123)` + * The signature `myContract.methods['0x58cf5f10'](123)` + * + * This allows calling functions with same name but different parameters from the JavaScript contract object. + * + * \> The method signature does not provide a type safe interface, so we recommend to use method `name` instead. + * + * ```ts + * // calling a method + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using a promise + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using the events + * const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * sendObject.on('transactionHash', function(hash){ + * ... + * }); + * sendObject.on('receipt', function(receipt){ + * ... + * }); + * sendObject.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * sendObject.on('error', function(error, receipt) { + * ... + * }); + * ``` + * + * @returns - Either returns {@link PayableMethodObject} or {@link NonPayableMethodObject} based on the definitions of the ABI of that contract. + */ + get methods() { + return this._methods; + } + /** + * Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone. + * + * @returns - The new contract instance. + * + * ```ts + * const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress}); + * + * const contract2 = contract1.clone(); + * contract2.options.address = address2; + * + * (contract1.options.address !== contract2.options.address); + * > true + * ``` + */ + clone() { + let newContract; + if (this.options.address) { + newContract = new Contract([...this._jsonInterface, ...this._errorsInterface], this.options.address, { + gas: this.options.gas, + gasPrice: this.options.gasPrice, + from: this.options.from, + input: this.options.input, + data: this.options.data, + provider: this.currentProvider, + syncWithContext: this.syncWithContext, + dataInputFill: this.config.contractDataInputFill, + }, this.getContextObject()); + } + else { + newContract = new Contract([...this._jsonInterface, ...this._errorsInterface], { + gas: this.options.gas, + gasPrice: this.options.gasPrice, + from: this.options.from, + input: this.options.input, + data: this.options.data, + provider: this.currentProvider, + syncWithContext: this.syncWithContext, + dataInputFill: this.config.contractDataInputFill, + }, this.getContextObject()); + } + if (this.context) + newContract.subscribeToContextEvents(this.context); + return newContract; + } + /** + * Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance. + * + * ```ts + * myContract.deploy({ + * input: '0x12345...', // data keyword can be used, too. If input is used, data will be ignored. + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }, function(error, transactionHash){ ... }) + * .on('error', function(error){ ... }) + * .on('transactionHash', function(transactionHash){ ... }) + * .on('receipt', function(receipt){ + * console.log(receipt.contractAddress) // contains the new contract address + * }) + * .on('confirmation', function(confirmationNumber, receipt){ ... }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // When the data is already set as an option to the contract itself + * myContract.options.data = '0x12345...'; + * + * myContract.deploy({ + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // Simply encoding + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .encodeABI(); + * > '0x12345...0000012345678765432' + * + * + * // Gas estimation + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .estimateGas(function(err, gas){ + * console.log(gas); + * }); + * ``` + * + * @returns - The transaction object + */ + deploy(deployOptions) { + var _a, _b, _c; + let abi = this._jsonInterface.find(j => j.type === 'constructor'); + if (!abi) { + abi = { + type: 'constructor', + inputs: [], + stateMutability: '', + }; + } + const _input = (0, web3_utils_1.format)({ format: 'bytes' }, (_a = deployOptions === null || deployOptions === void 0 ? void 0 : deployOptions.input) !== null && _a !== void 0 ? _a : this.options.input, web3_types_1.DEFAULT_RETURN_FORMAT); + const _data = (0, web3_utils_1.format)({ format: 'bytes' }, (_b = deployOptions === null || deployOptions === void 0 ? void 0 : deployOptions.data) !== null && _b !== void 0 ? _b : this.options.data, web3_types_1.DEFAULT_RETURN_FORMAT); + if ((!_input || _input.trim() === '0x') && (!_data || _data.trim() === '0x')) { + throw new web3_errors_1.Web3ContractError('contract creation without any data provided.'); + } + const args = (_c = deployOptions === null || deployOptions === void 0 ? void 0 : deployOptions.arguments) !== null && _c !== void 0 ? _c : []; + const contractOptions = Object.assign(Object.assign({}, this.options), { input: _input, data: _data }); + const deployData = _input !== null && _input !== void 0 ? _input : _data; + return { + arguments: args, + send: (options) => { + const modifiedOptions = Object.assign({}, options); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._contractMethodDeploySend(abi, args, modifiedOptions, contractOptions); + }, + estimateGas: (options, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) => __awaiter(this, void 0, void 0, function* () { + const modifiedOptions = Object.assign({}, options); + return this._contractMethodEstimateGas({ + abi: abi, + params: args, + returnFormat, + options: modifiedOptions, + contractOptions, + }); + }), + encodeABI: () => (0, encoding_js_1.encodeMethodABI)(abi, args, (0, web3_utils_1.format)({ format: 'bytes' }, deployData, web3_types_1.DEFAULT_RETURN_FORMAT)), + }; + } + getPastEvents(param1, param2, param3) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const eventName = typeof param1 === 'string' ? param1 : web3_eth_1.ALL_EVENTS; + const options = + // eslint-disable-next-line no-nested-ternary + typeof param1 !== 'string' && !(0, web3_utils_1.isDataFormat)(param1) + ? param1 + : !(0, web3_utils_1.isDataFormat)(param2) + ? param2 + : {}; + // eslint-disable-next-line no-nested-ternary + const returnFormat = (0, web3_utils_1.isDataFormat)(param1) + ? param1 + : (0, web3_utils_1.isDataFormat)(param2) + ? param2 + : param3 !== null && param3 !== void 0 ? param3 : web3_types_1.DEFAULT_RETURN_FORMAT; + const abi = eventName === 'allEvents' || eventName === web3_eth_1.ALL_EVENTS + ? web3_eth_1.ALL_EVENTS_ABI + : this._jsonInterface.find(j => 'name' in j && j.name === eventName); + if (!abi) { + throw new web3_errors_1.Web3ContractError(`Event ${eventName} not found.`); + } + const { fromBlock, toBlock, topics, address } = (0, encoding_js_1.encodeEventABI)(this.options, abi, options !== null && options !== void 0 ? options : {}); + const logs = yield (0, web3_eth_1.getLogs)(this, { fromBlock, toBlock, topics, address }, returnFormat); + const decodedLogs = logs.map(log => typeof log === 'string' + ? log + : (0, web3_eth_1.decodeEventABI)(abi, log, this._jsonInterface, returnFormat)); + const filter = (_a = options === null || options === void 0 ? void 0 : options.filter) !== null && _a !== void 0 ? _a : {}; + const filterKeys = Object.keys(filter); + if (filterKeys.length > 0) { + return decodedLogs.filter(log => { + if (typeof log === 'string') + return true; + return filterKeys.every((key) => { + var _a; + if (Array.isArray(filter[key])) { + return filter[key].some((v) => String(log.returnValues[key]).toUpperCase() === + String(v).toUpperCase()); + } + const inputAbi = (_a = abi.inputs) === null || _a === void 0 ? void 0 : _a.filter(input => input.name === key)[0]; + if ((inputAbi === null || inputAbi === void 0 ? void 0 : inputAbi.indexed) && inputAbi.type === 'string') { + const hashedIndexedString = (0, web3_utils_1.keccak256)(filter[key]); + if (hashedIndexedString === String(log.returnValues[key])) + return true; + } + return (String(log.returnValues[key]).toUpperCase() === + String(filter[key]).toUpperCase()); + }); + }); + } + return decodedLogs; + }); + } + _parseAndSetAddress(value, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + this._address = value + ? (0, web3_utils_1.toChecksumAddress)((0, web3_utils_1.format)({ format: 'address' }, value, returnFormat)) + : value; + } + _parseAndSetJsonInterface(abis, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + var _a, _b, _c, _d, _e; + this._functions = {}; + this._methods = {}; + this._events = {}; + let result = []; + const functionsAbi = abis.filter(abi => abi.type !== 'error'); + const errorsAbi = abis.filter(abi => (0, web3_eth_abi_1.isAbiErrorFragment)(abi)); + for (const a of functionsAbi) { + const abi = Object.assign(Object.assign({}, a), { signature: '' }); + if ((0, web3_eth_abi_1.isAbiFunctionFragment)(abi)) { + const methodName = (0, web3_eth_abi_1.jsonInterfaceMethodToString)(abi); + const methodSignature = (0, web3_eth_abi_1.encodeFunctionSignature)(methodName); + abi.signature = methodSignature; + // make constant and payable backwards compatible + abi.constant = + (_b = (_a = abi.stateMutability === 'view') !== null && _a !== void 0 ? _a : abi.stateMutability === 'pure') !== null && _b !== void 0 ? _b : abi.constant; + abi.payable = (_c = abi.stateMutability === 'payable') !== null && _c !== void 0 ? _c : abi.payable; + this._overloadedMethodAbis.set(abi.name, [ + ...((_d = this._overloadedMethodAbis.get(abi.name)) !== null && _d !== void 0 ? _d : []), + abi, + ]); + const abiFragment = (_e = this._overloadedMethodAbis.get(abi.name)) !== null && _e !== void 0 ? _e : []; + const contractMethod = this._createContractMethod(abiFragment, errorsAbi); + this._functions[methodName] = { + signature: methodSignature, + method: contractMethod, + }; + // We don't know a particular type of the Abi method so can't type check + this._methods[abi.name] = this._functions[methodName].method; + // We don't know a particular type of the Abi method so can't type check + this._methods[methodName] = this._functions[methodName].method; + // We don't know a particular type of the Abi method so can't type check + this._methods[methodSignature] = this + ._functions[methodName].method; + } + else if ((0, web3_eth_abi_1.isAbiEventFragment)(abi)) { + const eventName = (0, web3_eth_abi_1.jsonInterfaceMethodToString)(abi); + const eventSignature = (0, web3_eth_abi_1.encodeEventSignature)(eventName); + const event = this._createContractEvent(abi, returnFormat); + abi.signature = eventSignature; + if (!(eventName in this._events) || abi.name === 'bound') { + // It's a private type and we don't want to expose it and no need to check + this._events[eventName] = event; + } + // It's a private type and we don't want to expose it and no need to check + this._events[abi.name] = event; + // It's a private type and we don't want to expose it and no need to check + this._events[eventSignature] = event; + } + result = [...result, abi]; + } + this._events.allEvents = this._createContractEvent(web3_eth_1.ALL_EVENTS_ABI, returnFormat); + this._jsonInterface = [...result]; + this._errorsInterface = errorsAbi; + } + // eslint-disable-next-line class-methods-use-this + _getAbiParams(abi, params) { + var _a; + try { + return web3_validator_1.utils.transformJsonDataToAbiFormat((_a = abi.inputs) !== null && _a !== void 0 ? _a : [], params); + } + catch (error) { + throw new web3_errors_1.Web3ContractError(`Invalid parameters for method ${abi.name}: ${error.message}`); + } + } + _createContractMethod(abiArr, errorsAbis) { + const abi = abiArr[abiArr.length - 1]; + return (...params) => { + var _a, _b; + let abiParams; + const abis = (_a = this._overloadedMethodAbis.get(abi.name)) !== null && _a !== void 0 ? _a : []; + let methodAbi = abis[0]; + const internalErrorsAbis = errorsAbis; + const arrayOfAbis = abis.filter(_abi => { var _a; return ((_a = _abi.inputs) !== null && _a !== void 0 ? _a : []).length === params.length; }); + if (abis.length === 1 || arrayOfAbis.length === 0) { + abiParams = this._getAbiParams(methodAbi, params); + web3_validator_1.validator.validate((_b = abi.inputs) !== null && _b !== void 0 ? _b : [], abiParams); + } + else { + const errors = []; + for (const _abi of arrayOfAbis) { + try { + abiParams = this._getAbiParams(_abi, params); + web3_validator_1.validator.validate(_abi.inputs, abiParams); + methodAbi = _abi; + break; + } + catch (e) { + errors.push(e); + } + } + if (errors.length === arrayOfAbis.length) { + throw new web3_validator_1.Web3ValidatorError(errors); + } + } + const methods = { + arguments: abiParams, + call: (options, block) => __awaiter(this, void 0, void 0, function* () { + return this._contractMethodCall(methodAbi, abiParams, internalErrorsAbis, options, block); + }), + send: (options) => this._contractMethodSend(methodAbi, abiParams, internalErrorsAbis, options), + estimateGas: (options, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) => __awaiter(this, void 0, void 0, function* () { + return this._contractMethodEstimateGas({ + abi: methodAbi, + params: abiParams, + returnFormat, + options, + }); + }), + encodeABI: () => (0, encoding_js_1.encodeMethodABI)(methodAbi, abiParams), + createAccessList: (options, block) => __awaiter(this, void 0, void 0, function* () { + return this._contractMethodCreateAccessList(methodAbi, abiParams, internalErrorsAbis, options, block); + }), + }; + if (methodAbi.stateMutability === 'payable') { + return methods; + } + return methods; + }; + } + _contractMethodCall(abi, params, errorsAbi, options, block) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const tx = (0, utils_js_1.getEthTxCallParams)({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: Object.assign(Object.assign({}, this.options), { from: (_a = this.options.from) !== null && _a !== void 0 ? _a : this.config.defaultAccount }), + }); + try { + const result = yield (0, web3_eth_1.call)(this, tx, block, web3_types_1.DEFAULT_RETURN_FORMAT); + return (0, encoding_js_1.decodeMethodReturn)(abi, result); + } + catch (error) { + if (error instanceof web3_errors_1.ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + (0, web3_eth_abi_1.decodeContractErrorData)(errorsAbi, error.innerError); + } + throw error; + } + }); + } + _contractMethodCreateAccessList(abi, params, errorsAbi, options, block) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const tx = (0, utils_js_1.getCreateAccessListParams)({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: Object.assign(Object.assign({}, this.options), { from: (_a = this.options.from) !== null && _a !== void 0 ? _a : this.config.defaultAccount }), + }); + try { + return (0, web3_eth_1.createAccessList)(this, tx, block, web3_types_1.DEFAULT_RETURN_FORMAT); + } + catch (error) { + if (error instanceof web3_errors_1.ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + (0, web3_eth_abi_1.decodeContractErrorData)(errorsAbi, error.innerError); + } + throw error; + } + }); + } + _contractMethodSend(abi, params, errorsAbi, options, contractOptions) { + var _a, _b; + let modifiedContractOptions = contractOptions !== null && contractOptions !== void 0 ? contractOptions : this.options; + modifiedContractOptions = Object.assign(Object.assign({}, modifiedContractOptions), { input: undefined, from: (_b = (_a = modifiedContractOptions.from) !== null && _a !== void 0 ? _a : this.defaultAccount) !== null && _b !== void 0 ? _b : undefined }); + const tx = (0, utils_js_1.getSendTxParams)({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: modifiedContractOptions, + }); + const transactionToSend = (0, web3_eth_1.sendTransaction)(this, tx, web3_types_1.DEFAULT_RETURN_FORMAT, { + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + contractAbi: this._jsonInterface, + }); + // eslint-disable-next-line no-void + void transactionToSend.on('error', (error) => { + if (error instanceof web3_errors_1.ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + (0, web3_eth_abi_1.decodeContractErrorData)(errorsAbi, error.innerError); + } + }); + return transactionToSend; + } + _contractMethodDeploySend(abi, params, options, contractOptions) { + var _a, _b; + let modifiedContractOptions = contractOptions !== null && contractOptions !== void 0 ? contractOptions : this.options; + modifiedContractOptions = Object.assign(Object.assign({}, modifiedContractOptions), { from: (_b = (_a = modifiedContractOptions.from) !== null && _a !== void 0 ? _a : this.defaultAccount) !== null && _b !== void 0 ? _b : undefined }); + const tx = (0, utils_js_1.getSendTxParams)({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: modifiedContractOptions, + }); + return (0, web3_eth_1.sendTransaction)(this, tx, web3_types_1.DEFAULT_RETURN_FORMAT, { + transactionResolver: receipt => { + if (receipt.status === BigInt(0)) { + throw new web3_errors_1.Web3ContractError("code couldn't be stored", receipt); + } + const newContract = this.clone(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + newContract.options.address = receipt.contractAddress; + return newContract; + }, + contractAbi: this._jsonInterface, + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + }); + } + _contractMethodEstimateGas({ abi, params, returnFormat, options, contractOptions, }) { + return __awaiter(this, void 0, void 0, function* () { + const tx = (0, utils_js_1.getEstimateGasParams)({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: contractOptions !== null && contractOptions !== void 0 ? contractOptions : this.options, + }); + return (0, web3_eth_1.estimateGas)(this, tx, web3_types_1.BlockTags.LATEST, returnFormat); + }); + } + // eslint-disable-next-line class-methods-use-this + _createContractEvent(abi, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return (...params) => { + var _a; + const { topics, fromBlock } = (0, encoding_js_1.encodeEventABI)(this.options, abi, params[0]); + const sub = new log_subscription_js_1.LogsSubscription({ + address: this.options.address, + topics, + abi, + jsonInterface: this._jsonInterface, + }, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + subscriptionManager: this.subscriptionManager, + returnFormat, + }); + if (!(0, web3_validator_1.isNullish)(fromBlock)) { + // emit past events when fromBlock is defined + this.getPastEvents(abi.name, { fromBlock, topics }, returnFormat) + .then(logs => { + logs.forEach(log => sub.emit('data', log)); + }) + .catch((error) => { + sub.emit('error', new web3_errors_1.SubscriptionError('Failed to get past events.', error)); + }); + } + (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.addSubscription(sub).catch((error) => { + sub.emit('error', new web3_errors_1.SubscriptionError('Failed to subscribe.', error)); + }); + return sub; + }; + } + subscribeToContextEvents(context) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const contractThis = this; + this.context = context; + if (contractThis.syncWithContext) { + context.on(web3_core_1.Web3ConfigEvent.CONFIG_CHANGE, event => { + contractThis.setConfig({ [event.name]: event.newValue }); + }); + } + } +} +exports.Contract = Contract; +//# sourceMappingURL=contract.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.js.map new file mode 100644 index 0000000..6387833 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/contract.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,yCAMmB;AACnB,6CAKqB;AACrB,uCAWkB;AAClB,+CAQsB;AACtB,2CAiCoB;AACpB,2CAAgF;AAChF,mDAMwB;AACxB,+CAAoF;AACpF,+DAAyD;AASzD,yCAOoB;AA4EpB,MAAM,qBAAqB,GAAG;IAC7B,IAAI,EAAE,sCAAgB;IACtB,QAAQ,EAAE,+BAAoB;IAC9B,eAAe,EAAE,+BAAoB;CACrC,CAAC;AAEF;;GAEG;AACH,MAAa,QACZ,SAAQ,uBAA0D;IAqGlE,YACC,aAAkB,EAClB,yBAIc,EACd,8BAIa,EACb,qBAAsE,EACtE,YAAyB;;QAEzB,6CAA6C;QAC7C,MAAM,OAAO,GAAG,IAAA,gCAAqB,EAAC,yBAAyB,CAAC;YAC/D,CAAC,CAAC,yBAAyB;YAC3B,CAAC,CAAC,IAAA,gCAAqB,EAAC,8BAA8B,CAAC;gBACvD,CAAC,CAAC,8BAA8B;gBAChC,CAAC,CAAC,SAAS,CAAC;QAEb,IAAI,eAAe,CAAC;QACpB,IAAI,IAAA,gCAAqB,EAAC,yBAAyB,CAAC,EAAE;YACrD,eAAe,GAAG,yBAAyB,CAAC;SAC5C;aAAM,IAAI,IAAA,gCAAqB,EAAC,8BAA8B,CAAC,EAAE;YACjE,eAAe,GAAG,8BAA8B,CAAC;SACjD;aAAM;YACN,eAAe,GAAG,qBAAqB,CAAC;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;YAC1D,CAAC,CAAC,CAAC;SACH;IACF,CAAC;CACD;AAlgCD,4BAkgCC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.d.ts new file mode 100644 index 0000000..f017d3a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.d.ts @@ -0,0 +1,10 @@ +import { AbiConstructorFragment, AbiEventFragment, AbiFunctionFragment, Filter, HexString, ContractOptions } from 'web3-types'; +export { decodeEventABI } from 'web3-eth'; +declare type Writeable = { + -readonly [P in keyof T]: T[P]; +}; +export declare const encodeEventABI: ({ address }: ContractOptions, event: AbiEventFragment & { + signature: string; +}, options?: Filter) => Writeable; +export declare const encodeMethodABI: (abi: AbiFunctionFragment | AbiConstructorFragment, args: unknown[], deployData?: HexString) => string; +export declare const decodeMethodReturn: (abi: AbiFunctionFragment, returnValues?: HexString) => unknown; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.js new file mode 100644 index 0000000..aa88daf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.js @@ -0,0 +1,126 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeMethodReturn = exports.encodeMethodABI = exports.encodeEventABI = exports.decodeEventABI = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_types_1 = require("web3-types"); +const web3_eth_abi_1 = require("web3-eth-abi"); +const web3_eth_1 = require("web3-eth"); +const web3_errors_1 = require("web3-errors"); +var web3_eth_2 = require("web3-eth"); +Object.defineProperty(exports, "decodeEventABI", { enumerable: true, get: function () { return web3_eth_2.decodeEventABI; } }); +const encodeEventABI = ({ address }, event, options) => { + var _a, _b; + const topics = options === null || options === void 0 ? void 0 : options.topics; + const filter = (_a = options === null || options === void 0 ? void 0 : options.filter) !== null && _a !== void 0 ? _a : {}; + const opts = {}; + if (!(0, web3_utils_1.isNullish)(options === null || options === void 0 ? void 0 : options.fromBlock)) { + opts.fromBlock = (0, web3_utils_1.format)(web3_eth_1.blockSchema.properties.number, options === null || options === void 0 ? void 0 : options.fromBlock, { + number: web3_types_1.FMT_NUMBER.HEX, + bytes: web3_types_1.FMT_BYTES.HEX, + }); + } + if (!(0, web3_utils_1.isNullish)(options === null || options === void 0 ? void 0 : options.toBlock)) { + opts.toBlock = (0, web3_utils_1.format)(web3_eth_1.blockSchema.properties.number, options === null || options === void 0 ? void 0 : options.toBlock, { + number: web3_types_1.FMT_NUMBER.HEX, + bytes: web3_types_1.FMT_BYTES.HEX, + }); + } + if (topics && Array.isArray(topics)) { + opts.topics = [...topics]; + } + else { + opts.topics = []; + // add event signature + if (event && !event.anonymous && ![web3_eth_1.ALL_EVENTS, 'allEvents'].includes(event.name)) { + opts.topics.push((_b = event.signature) !== null && _b !== void 0 ? _b : (0, web3_eth_abi_1.encodeEventSignature)((0, web3_eth_abi_1.jsonInterfaceMethodToString)(event))); + } + // add event topics (indexed arguments) + if (![web3_eth_1.ALL_EVENTS, 'allEvents'].includes(event.name) && event.inputs) { + for (const input of event.inputs) { + if (!input.indexed) { + continue; + } + const value = filter[input.name]; + if (!value) { + // eslint-disable-next-line no-null/no-null + opts.topics.push(null); + continue; + } + // TODO: https://github.com/ethereum/web3.js/issues/344 + // TODO: deal properly with components + if (Array.isArray(value)) { + opts.topics.push(value.map(v => (0, web3_eth_abi_1.encodeParameter)(input.type, v))); + } + else if (input.type === 'string') { + opts.topics.push((0, web3_utils_1.keccak256)(value)); + } + else { + opts.topics.push((0, web3_eth_abi_1.encodeParameter)(input.type, value)); + } + } + } + } + if (!opts.topics.length) + delete opts.topics; + if (address) { + opts.address = address.toLowerCase(); + } + return opts; +}; +exports.encodeEventABI = encodeEventABI; +const encodeMethodABI = (abi, args, deployData) => { + const inputLength = Array.isArray(abi.inputs) ? abi.inputs.length : 0; + if (inputLength !== args.length) { + throw new web3_errors_1.Web3ContractError(`The number of arguments is not matching the methods required number. You need to pass ${inputLength} arguments.`); + } + const params = (0, web3_eth_abi_1.encodeParameters)(Array.isArray(abi.inputs) ? abi.inputs : [], args).replace('0x', ''); + if ((0, web3_eth_abi_1.isAbiConstructorFragment)(abi)) { + if (!deployData) + throw new web3_errors_1.Web3ContractError('The contract has no contract data option set. This is necessary to append the constructor parameters.'); + if (!deployData.startsWith('0x')) { + return `0x${deployData}${params}`; + } + return `${deployData}${params}`; + } + return `${(0, web3_eth_abi_1.encodeFunctionSignature)(abi)}${params}`; +}; +exports.encodeMethodABI = encodeMethodABI; +const decodeMethodReturn = (abi, returnValues) => { + // If it was constructor then we need to return contract address + if (abi.type === 'constructor') { + return returnValues; + } + if (!returnValues) { + // Using "null" value intentionally to match legacy behavior + // eslint-disable-next-line no-null/no-null + return null; + } + const value = returnValues.length >= 2 ? returnValues.slice(2) : returnValues; + if (!abi.outputs) { + // eslint-disable-next-line no-null/no-null + return null; + } + const result = (0, web3_eth_abi_1.decodeParameters)([...abi.outputs], value); + if (result.__length__ === 1) { + return result[0]; + } + return result; +}; +exports.decodeMethodReturn = decodeMethodReturn; +//# sourceMappingURL=encoding.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.js.map new file mode 100644 index 0000000..b877f36 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/encoding.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;QAED,OAAO,GAAG,UAAU,GAAG,MAAM,EAAE,CAAC;KAChC;IAED,OAAO,GAAG,IAAA,sCAAuB,EAAC,GAAG,CAAC,GAAG,MAAM,EAAE,CAAC;AACnD,CAAC,CAAC;AA/BW,QAAA,eAAe,mBA+B1B;AAEK,MAAM,kBAAkB,GAAG,CAAC,GAAwB,EAAE,YAAwB,EAAE,EAAE;IACxF,gEAAgE;IAChE,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,EAAE;QAC/B,OAAO,YAAY,CAAC;KACpB;IAED,IAAI,CAAC,YAAY,EAAE;QAClB,4DAA4D;QAC5D,2CAA2C;QAC3C,OAAO,IAAI,CAAC;KACZ;IAED,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;IAC9E,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE;QACjB,2CAA2C;QAC3C,OAAO,IAAI,CAAC;KACZ;IACD,MAAM,MAAM,GAAG,IAAA,+BAAgB,EAAC,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC;IAEzD,IAAI,MAAM,CAAC,UAAU,KAAK,CAAC,EAAE;QAC5B,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;KACjB;IAED,OAAO,MAAM,CAAC;AACf,CAAC,CAAC;AAxBW,QAAA,kBAAkB,sBAwB7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.d.ts new file mode 100644 index 0000000..26ed803 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.d.ts @@ -0,0 +1,31 @@ +/** + * The `web3.eth.Contract` object makes it easy to interact with smart contracts on the Ethereum blockchain. + * When you create a new contract object you give it the JSON interface of the respective smart contract and + * web3 will auto convert all calls into low level ABI calls over RPC for you. + * This allows you to interact with smart contracts as if they were JavaScript objects. + * + * To use it standalone: + * + * ```ts + * const Contract = require('web3-eth-contract'); + * + * // set provider for all later instances to use + * Contract.setProvider('ws://localhost:8546'); + * + * const contract = new Contract(jsonInterface, address); + * + * contract.methods.somFunc().send({from: ....}) + * .on('receipt', function(){ + * ... + * }); + * ``` + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Contract } from './contract.js'; +export * from './encoding.js'; +export * from './contract.js'; +export * from './log_subscription.js'; +export * from './types.js'; +export default Contract; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.js new file mode 100644 index 0000000..a707ace --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.js @@ -0,0 +1,64 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * The `web3.eth.Contract` object makes it easy to interact with smart contracts on the Ethereum blockchain. + * When you create a new contract object you give it the JSON interface of the respective smart contract and + * web3 will auto convert all calls into low level ABI calls over RPC for you. + * This allows you to interact with smart contracts as if they were JavaScript objects. + * + * To use it standalone: + * + * ```ts + * const Contract = require('web3-eth-contract'); + * + * // set provider for all later instances to use + * Contract.setProvider('ws://localhost:8546'); + * + * const contract = new Contract(jsonInterface, address); + * + * contract.methods.somFunc().send({from: ....}) + * .on('receipt', function(){ + * ... + * }); + * ``` + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +const contract_js_1 = require("./contract.js"); +__exportStar(require("./encoding.js"), exports); +__exportStar(require("./contract.js"), exports); +__exportStar(require("./log_subscription.js"), exports); +__exportStar(require("./types.js"), exports); +exports.default = contract_js_1.Contract; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.js.map new file mode 100644 index 0000000..e841b2b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH;;GAEG;AACH,+CAAyC;AAEzC,gDAA8B;AAE9B,gDAA8B;AAC9B,wDAAsC;AACtC,6CAA2B;AAE3B,kBAAe,sBAAQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.d.ts new file mode 100644 index 0000000..07fe258 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.d.ts @@ -0,0 +1,112 @@ +import { AbiEventFragment, HexString, Topic, DataFormat, EventLog, ContractAbiWithSignature } from 'web3-types'; +import { Web3RequestManager, Web3Subscription, Web3SubscriptionManager } from 'web3-core'; +/** + * LogSubscription to be used to subscribe to events logs. + * + * Following events are supported and can be accessed with either {@link LogsSubscription.once} or ${@link LogsSubscription.on} methods. + * + * - **connected**: Emitted when the subscription is connected. + * - **data**: Fires on each incoming event with the event object as argument. + * - **changed**: Fires on each event which was removed from the blockchain. The event will have the additional property `removed: true`. + * - **error**: Fires on each error. + * + * ```ts + * const subscription = await myContract.events.MyEvent({ + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0 + * }); + * + * subscription.on("connected", function(subscriptionId){ + * console.log(subscriptionId); + * }); + * + * subscription.on('data', function(event){ + * console.log(event); // same results as the optional callback above + * }); + * + * subscription.on('changed', function(event){ + * // remove event from local database + * }) + * + * subscription.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * + * // event output example + * > { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * } + * ``` + */ +export declare class LogsSubscription extends Web3Subscription<{ + data: EventLog; + changed: EventLog & { + removed: true; + }; +}, { + address?: HexString; + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment; +}> { + /** + * Address of tye contract + */ + readonly address?: HexString; + /** + * The list of topics subscribed + */ + readonly topics?: (Topic | Topic[] | null)[]; + /** + * The {@doclink glossary/json_interface | JSON Interface} of the event. + */ + readonly abi: AbiEventFragment & { + signature: HexString; + }; + readonly jsonInterface: ContractAbiWithSignature; + constructor(args: { + address?: HexString; + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { + signature: HexString; + }; + jsonInterface: ContractAbiWithSignature; + }, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; + }); + /** + * @deprecated This constructor overloading should not be used + */ + constructor(args: { + address?: HexString; + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { + signature: HexString; + }; + jsonInterface: ContractAbiWithSignature; + }, options: { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; + }); + protected _buildSubscriptionParams(): (string | { + address: string | undefined; + topics: (string | string[] | null)[] | undefined; + })[]; + protected formatSubscriptionResult(data: EventLog): EventLog; +} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.js new file mode 100644 index 0000000..3634fae --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.js @@ -0,0 +1,93 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LogsSubscription = void 0; +const web3_core_1 = require("web3-core"); +const web3_eth_1 = require("web3-eth"); +/** + * LogSubscription to be used to subscribe to events logs. + * + * Following events are supported and can be accessed with either {@link LogsSubscription.once} or ${@link LogsSubscription.on} methods. + * + * - **connected**: Emitted when the subscription is connected. + * - **data**: Fires on each incoming event with the event object as argument. + * - **changed**: Fires on each event which was removed from the blockchain. The event will have the additional property `removed: true`. + * - **error**: Fires on each error. + * + * ```ts + * const subscription = await myContract.events.MyEvent({ + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0 + * }); + * + * subscription.on("connected", function(subscriptionId){ + * console.log(subscriptionId); + * }); + * + * subscription.on('data', function(event){ + * console.log(event); // same results as the optional callback above + * }); + * + * subscription.on('changed', function(event){ + * // remove event from local database + * }) + * + * subscription.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * + * // event output example + * > { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * } + * ``` + */ +class LogsSubscription extends web3_core_1.Web3Subscription { + constructor(args, options) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + super(args, options); + this.address = args.address; + this.topics = args.topics; + this.abi = args.abi; + this.jsonInterface = args.jsonInterface; + } + _buildSubscriptionParams() { + return ['logs', { address: this.address, topics: this.topics }]; + } + formatSubscriptionResult(data) { + return (0, web3_eth_1.decodeEventABI)(this.abi, data, this.jsonInterface, super.returnFormat); + } +} +exports.LogsSubscription = LogsSubscription; +//# sourceMappingURL=log_subscription.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.js.map new file mode 100644 index 0000000..47ca1fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/log_subscription.js.map @@ -0,0 +1 @@ +{"version":3,"file":"log_subscription.js","sourceRoot":"","sources":["../../src/log_subscription.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAWF,yCAA0F;AAC1F,uCAA0C;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,MAAa,gBAAiB,SAAQ,4BAOrC;IA0CA,YACC,IAMC,EACD,OAKC;QAED,iEAAiE;QACjE,KAAK,CAAC,IAAI,EAAE,OAAc,CAAC,CAAC;QAE5B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACpB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC;IACzC,CAAC;IAES,wBAAwB;QACjC,OAAO,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACjE,CAAC;IAES,wBAAwB,CAAC,IAAc;QAChD,OAAO,IAAA,yBAAc,EAAC,IAAI,CAAC,GAAG,EAAE,IAAiB,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5F,CAAC;CACD;AAhFD,4CAgFC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.d.ts new file mode 100644 index 0000000..72c2750 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.d.ts @@ -0,0 +1,366 @@ +import { Web3ContextInitOptions, Web3PromiEvent } from 'web3-core'; +import { AccessListResult, BlockNumberOrTag, EthExecutionAPI, HexString, Numbers, TransactionReceipt, NonPayableCallOptions, PayableCallOptions, DataFormat, DEFAULT_RETURN_FORMAT, FormatType } from 'web3-types'; +import { NewHeadsSubscription, SendTransactionEvents } from 'web3-eth'; +import { LogsSubscription } from './log_subscription.js'; +export declare type NonPayableTxOptions = NonPayableCallOptions; +export declare type PayableTxOptions = PayableCallOptions; +export { ContractAbiWithSignature, EventLog, ContractOptions } from 'web3-types'; +export interface ContractEventOptions { + /** + * Let you filter events by indexed parameters, e.g. `{filter: {myNumber: [12,13]}}` means all events where `myNumber` is `12` or `13`. + */ + filter?: Record; + /** + * The block number (greater than or equal to) from which to get events on. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized` can also be used. For specific range use {@link Contract.getPastEvents}. + */ + fromBlock?: BlockNumberOrTag; + /** + * This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically. Each topic can also be a nested array of topics that behaves as `or` operation between the given nested topics. + */ + topics?: string[]; +} +export interface NonPayableMethodObject { + arguments: Inputs; + /** + * This will call a method and execute its smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state. + * + * ```ts + * // using the promise + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // MULTI-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(uint256 myNumber, string myString) { + * return (23456, "Hello!%"); + * } + * } + * + * // web3.js + * var MyContract = new web3.eth.Contract(abi, address); + * const result = MyContract.methods.myFunction().call() + * console.log(result) + * > Result { + * myNumber: '23456', + * myString: 'Hello!%', + * 0: '23456', // these are here as fallbacks if the name is not know or given + * 1: 'Hello!%' + * } + * + * + * // SINGLE-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(string myString) { + * return "Hello!%"; + * } + * } + * + * // web3.js + * const MyContract = new web3.eth.Contract(abi, address); + * const result = await MyContract.methods.myFunction().call(); + * console.log(result); + * > "Hello!%" + * ``` + * + * @param tx - The options used for calling. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns - The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices. + */ + call(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise; + /** + * This will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state. + * + * ```ts + * await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * + * // using the event emitter + * const sendObj = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}) + * sendObj.on('transactionHash', function(hash){ + * ... + * }); + * + * sendObj.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * + * sendObj.on('receipt', function(receipt){ + * // receipt example + * console.log(receipt); + * > { + * "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", + * "transactionIndex": 0, + * "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", + * "blockNumber": 3, + * "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * "cumulativeGasUsed": 314159, + * "gasUsed": 30234, + * "events": { + * "MyEvent": { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * "MyOtherEvent": { + * ... + * }, + * "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array + * } + * } + * }); + * + * sendObj.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * ``` + * + * @param tx - The options used for sending. + * @returns - Returns a {@link PromiEvent} resolved with transaction receipt. + */ + send(tx?: NonPayableTxOptions): Web3PromiEvent, SendTransactionEvents>; + /** + * Returns the amount of gas consumed by executing the method locally without creating a new transaction on the blockchain. + * The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be + * different when sending the transaction later, as the state of the smart contract can be different at that time. + * + * ```ts + * const gasAmount = await myContract.methods.myMethod(123).estimateGas({gas: 5000000}); + * if(gasAmount == 5000000) { + * console.log('Method ran out of gas'); + * } + * ``` + * + * @param options - The options used for calling + * @param returnFormat - The data format you want the output in. + * @returns - The gas amount estimated. + */ + estimateGas(options?: NonPayableCallOptions, returnFormat?: ReturnFormat): Promise>; + /** + * Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. + * This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. + * Set the data field on `web3.eth.sendTransaction` options as the encodeABI() result and it is the same as calling the contract method with `contract.myMethod.send()`. + * + * Some use cases for encodeABI() include: preparing a smart contract transaction for a multi signature wallet, + * working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls. + * + * @returns - The encoded ABI byte code to send via a transaction or call. + */ + encodeABI(): string; + /** + * This method generates an access list for a transaction. You must specify a `from` address and `gas` if it’s not specified in options. + * + * @param options - The options used for createAccessList. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * + * ```ts + * const result = await MyContract.methods.myFunction().createAccessList(); + * console.log(result); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise; +} +export interface PayableMethodObject { + arguments: Inputs; + /** + * Will call a method and execute its smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state. + * + * ```ts + * // using the promise + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // MULTI-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(uint256 myNumber, string myString) { + * return (23456, "Hello!%"); + * } + * } + * + * // web3.js + * var MyContract = new web3.eth.Contract(abi, address); + * const result = MyContract.methods.myFunction().call() + * console.log(result) + * > Result { + * myNumber: '23456', + * myString: 'Hello!%', + * 0: '23456', // these are here as fallbacks if the name is not know or given + * 1: 'Hello!%' + * } + * + * + * // SINGLE-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(string myString) { + * return "Hello!%"; + * } + * } + * + * // web3.js + * const MyContract = new web3.eth.Contract(abi, address); + * const result = await MyContract.methods.myFunction().call(); + * console.log(result); + * > "Hello!%" + * ``` + * + * @param tx - The options used for calling. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns - The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices. + */ + call(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise; + /** + * Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state. + * + * ```ts + * await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * + * // using the event emitter + * const sendObj = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}) + * sendObj.on('transactionHash', function(hash){ + * ... + * }); + * + * sendObj.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * + * sendObj.on('receipt', function(receipt){ + * // receipt example + * console.log(receipt); + * > { + * "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", + * "transactionIndex": 0, + * "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", + * "blockNumber": 3, + * "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * "cumulativeGasUsed": 314159, + * "gasUsed": 30234, + * "events": { + * "MyEvent": { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * "MyOtherEvent": { + * ... + * }, + * "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array + * } + * } + * }); + * + * sendObj.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * ``` + * + * @param tx - The options used for sending. + * @returns - Returns a {@link PromiEvent} object resolved with transaction receipt. + */ + send(tx?: PayableTxOptions): Web3PromiEvent, SendTransactionEvents>; + /** + * Returns the amount of gas consumed by executing the method locally without creating a new transaction on the blockchain. + * The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be + * different when sending the transaction later, as the state of the smart contract can be different at that time. + * + * ```ts + * const gasAmount = await myContract.methods.myMethod(123).estimateGas({gas: 5000000}); + * if(gasAmount == 5000000) { + * console.log('Method ran out of gas'); + * } + * ``` + * + * @param options - The options used for calling + * @param returnFormat - The data format you want the output in. + * @returns - The gas amount estimated. + */ + estimateGas(options?: PayableCallOptions, returnFormat?: ReturnFormat): Promise>; + /** + * Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. + * This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. + * Set the data field on `web3.eth.sendTransaction` options as the encodeABI() result and it is the same as calling the contract method with `contract.myMethod.send()`. + * + * Some use cases for encodeABI() include: preparing a smart contract transaction for a multi signature wallet, + * working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls. + * + * @returns - The encoded ABI byte code to send via a transaction or call. + */ + encodeABI(): HexString; + /** + * This method generates an access list for a transaction. You must specify a `from` address and `gas` if it’s not specified in options. + * + * @param options - The options used for createAccessList. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * + * ```ts + * const result = await MyContract.methods.myFunction().createAccessList(); + * console.log(result); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + *``` + */ + createAccessList(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise; +} +export declare type Web3ContractContext = Partial>; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.d.ts new file mode 100644 index 0000000..bdd63dd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.d.ts @@ -0,0 +1,44 @@ +import { TransactionForAccessList, AbiFunctionFragment, TransactionWithSenderAPI, TransactionCall, HexString, Address, NonPayableCallOptions, PayableCallOptions, ContractOptions } from 'web3-types'; +export declare const getSendTxParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + input?: string | undefined; + data?: string | undefined; + to?: string | undefined; + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => TransactionCall; +export declare const getEthTxCallParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + to?: string | undefined; + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => TransactionCall; +export declare const getEstimateGasParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => Partial; +export { isContractInitOptions } from 'web3-utils'; +export declare const isWeb3ContractContext: (options: unknown) => options is Partial>; +export declare const getCreateAccessListParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + to?: string | undefined; + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => TransactionForAccessList; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.js new file mode 100644 index 0000000..2cb3f2b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.js @@ -0,0 +1,122 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getCreateAccessListParams = exports.isWeb3ContractContext = exports.isContractInitOptions = exports.getEstimateGasParams = exports.getEthTxCallParams = exports.getSendTxParams = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const encoding_js_1 = require("./encoding.js"); +const dataInputEncodeMethodHelper = (txParams, abi, params, dataInputFill) => { + var _a, _b; + const tx = {}; + if (!(0, web3_utils_1.isNullish)(txParams.data) || dataInputFill === 'both') { + tx.data = (0, encoding_js_1.encodeMethodABI)(abi, params, ((_a = txParams.data) !== null && _a !== void 0 ? _a : txParams.input)); + } + if (!(0, web3_utils_1.isNullish)(txParams.input) || dataInputFill === 'both') { + tx.input = (0, encoding_js_1.encodeMethodABI)(abi, params, ((_b = txParams.input) !== null && _b !== void 0 ? _b : txParams.data)); + } + // if input and data is empty, use web3config default + if ((0, web3_utils_1.isNullish)(tx.input) && (0, web3_utils_1.isNullish)(tx.data)) { + tx[dataInputFill] = (0, encoding_js_1.encodeMethodABI)(abi, params); + } + return { data: tx.data, input: tx.input }; +}; +const getSendTxParams = ({ abi, params, options, contractOptions, }) => { + var _a, _b, _c; + const deploymentCall = (_c = (_b = (_a = options === null || options === void 0 ? void 0 : options.input) !== null && _a !== void 0 ? _a : options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : contractOptions.input) !== null && _c !== void 0 ? _c : contractOptions.data; + if (!deploymentCall && !(options === null || options === void 0 ? void 0 : options.to) && !contractOptions.address) { + throw new web3_errors_1.Web3ContractError('Contract address not specified'); + } + if (!(options === null || options === void 0 ? void 0 : options.from) && !contractOptions.from) { + throw new web3_errors_1.Web3ContractError('Contract "from" address not specified'); + } + let txParams = (0, web3_utils_1.mergeDeep)({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +exports.getSendTxParams = getSendTxParams; +const getEthTxCallParams = ({ abi, params, options, contractOptions, }) => { + if (!(options === null || options === void 0 ? void 0 : options.to) && !contractOptions.address) { + throw new web3_errors_1.Web3ContractError('Contract address not specified'); + } + let txParams = (0, web3_utils_1.mergeDeep)({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +exports.getEthTxCallParams = getEthTxCallParams; +const getEstimateGasParams = ({ abi, params, options, contractOptions, }) => { + let txParams = (0, web3_utils_1.mergeDeep)({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +exports.getEstimateGasParams = getEstimateGasParams; +var web3_utils_2 = require("web3-utils"); +Object.defineProperty(exports, "isContractInitOptions", { enumerable: true, get: function () { return web3_utils_2.isContractInitOptions; } }); +const isWeb3ContractContext = (options) => typeof options === 'object' && !(0, web3_utils_1.isNullish)(options) && + Object.keys(options).length !== 0 && !(0, web3_utils_1.isContractInitOptions)(options); +exports.isWeb3ContractContext = isWeb3ContractContext; +const getCreateAccessListParams = ({ abi, params, options, contractOptions, }) => { + if (!(options === null || options === void 0 ? void 0 : options.to) && !contractOptions.address) { + throw new web3_errors_1.Web3ContractError('Contract address not specified'); + } + if (!(options === null || options === void 0 ? void 0 : options.from) && !contractOptions.from) { + throw new web3_errors_1.Web3ContractError('Contract "from" address not specified'); + } + let txParams = (0, web3_utils_1.mergeDeep)({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +exports.getCreateAccessListParams = getCreateAccessListParams; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.js.map new file mode 100644 index 0000000..332f9c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/commonjs/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAAgD;AAYhD,2CAAyE;AACzE,+CAAgD;AAGhD,MAAM,2BAA2B,GAAG,CACnC,QAAoD,EACpD,GAAwB,EACxB,MAAiB,EACjB,aAAyC,EACC,EAAE;;IAC5C,MAAM,EAAE,GAA4C,EAAE,CAAC;IACvD,IAAI,CAAC,IAAA,sBAAS,EAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,aAAa,KAAK,MAAM,EAAE;QAC1D,EAAE,CAAC,IAAI,GAAG,IAAA,6BAAe,EAAC,GAAG,EAAE,MAAM,EAAE,CAAC,MAAA,QAAQ,CAAC,IAAI,mCAAI,QAAQ,CAAC,KAAK,CAAc,CAAC,CAAC;K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I,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,GAAE,CAAC;IAEzE,OAAO,QAAQ,CAAC;AACjB,CAAC,CAAC;AAxCW,QAAA,yBAAyB,6BAwCpC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/constant.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/constant.js new file mode 100644 index 0000000..7acbc4c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/constant.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export { ALL_EVENTS, ALL_EVENTS_ABI } from 'web3-eth'; +//# sourceMappingURL=constant.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/constant.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/constant.js.map new file mode 100644 index 0000000..4d656d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/constant.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constant.js","sourceRoot":"","sources":["../../src/constant.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/contract.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/contract.js new file mode 100644 index 0000000..bf5be8b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/contract.js @@ -0,0 +1,663 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { Web3Context, Web3ConfigEvent, } from 'web3-core'; +import { ContractExecutionError, ContractTransactionDataAndInputError, SubscriptionError, Web3ContractError, } from 'web3-errors'; +import { createAccessList, call, estimateGas, getLogs, sendTransaction, decodeEventABI, NewHeadsSubscription, ALL_EVENTS, ALL_EVENTS_ABI, } from 'web3-eth'; +import { encodeEventSignature, encodeFunctionSignature, decodeContractErrorData, isAbiErrorFragment, isAbiEventFragment, isAbiFunctionFragment, jsonInterfaceMethodToString, } from 'web3-eth-abi'; +import { BlockTags, DEFAULT_RETURN_FORMAT, } from 'web3-types'; +import { format, isDataFormat, keccak256, toChecksumAddress } from 'web3-utils'; +import { isNullish, validator, utils as validatorUtils, Web3ValidatorError, } from 'web3-validator'; +import { decodeMethodReturn, encodeEventABI, encodeMethodABI } from './encoding.js'; +import { LogsSubscription } from './log_subscription.js'; +import { getCreateAccessListParams, getEstimateGasParams, getEthTxCallParams, getSendTxParams, isContractInitOptions, isWeb3ContractContext, } from './utils.js'; +const contractSubscriptions = { + logs: LogsSubscription, + newHeads: NewHeadsSubscription, + newBlockHeaders: NewHeadsSubscription, +}; +/** + * The class designed to interact with smart contracts on the Ethereum blockchain. + */ +export class Contract extends Web3Context { + constructor(jsonInterface, addressOrOptionsOrContext, optionsOrContextOrReturnFormat, contextOrReturnFormat, returnFormat) { + var _a, _b, _c; + // eslint-disable-next-line no-nested-ternary + const options = isContractInitOptions(addressOrOptionsOrContext) + ? addressOrOptionsOrContext + : isContractInitOptions(optionsOrContextOrReturnFormat) + ? optionsOrContextOrReturnFormat + : undefined; + let contractContext; + if (isWeb3ContractContext(addressOrOptionsOrContext)) { + contractContext = addressOrOptionsOrContext; + } + else if (isWeb3ContractContext(optionsOrContextOrReturnFormat)) { + contractContext = optionsOrContextOrReturnFormat; + } + else { + contractContext = contextOrReturnFormat; + } + let provider; + if (typeof addressOrOptionsOrContext === 'object' && + 'provider' in addressOrOptionsOrContext) { + provider = addressOrOptionsOrContext.provider; + } + else if (typeof optionsOrContextOrReturnFormat === 'object' && + 'provider' in optionsOrContextOrReturnFormat) { + provider = optionsOrContextOrReturnFormat.provider; + } + else if (typeof contextOrReturnFormat === 'object' && + 'provider' in contextOrReturnFormat) { + provider = contextOrReturnFormat.provider; + } + else { + provider = Contract.givenProvider; + } + super(Object.assign(Object.assign({}, contractContext), { provider, registeredSubscriptions: contractSubscriptions })); + /** + * Set to true if you want contracts' defaults to sync with global defaults. + */ + this.syncWithContext = false; + this._functions = {}; + if (!isNullish(options) && + !isNullish(options.data) && + !isNullish(options.input) && + this.config.contractDataInputFill !== 'both') + throw new ContractTransactionDataAndInputError({ + data: options.data, + input: options.input, + }); + this._overloadedMethodAbis = new Map(); + // eslint-disable-next-line no-nested-ternary + const returnDataFormat = isDataFormat(contextOrReturnFormat) + ? contextOrReturnFormat + : isDataFormat(optionsOrContextOrReturnFormat) + ? optionsOrContextOrReturnFormat + : returnFormat !== null && returnFormat !== void 0 ? returnFormat : DEFAULT_RETURN_FORMAT; + const address = typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined; + this.config.contractDataInputFill = + (_a = options === null || options === void 0 ? void 0 : options.dataInputFill) !== null && _a !== void 0 ? _a : this.config.contractDataInputFill; + this._parseAndSetJsonInterface(jsonInterface, returnDataFormat); + if (!isNullish(address)) { + this._parseAndSetAddress(address, returnDataFormat); + } + this.options = { + address, + jsonInterface: this._jsonInterface, + gas: (_b = options === null || options === void 0 ? void 0 : options.gas) !== null && _b !== void 0 ? _b : options === null || options === void 0 ? void 0 : options.gasLimit, + gasPrice: options === null || options === void 0 ? void 0 : options.gasPrice, + from: options === null || options === void 0 ? void 0 : options.from, + input: options === null || options === void 0 ? void 0 : options.input, + data: options === null || options === void 0 ? void 0 : options.data, + }; + this.syncWithContext = (_c = options === null || options === void 0 ? void 0 : options.syncWithContext) !== null && _c !== void 0 ? _c : false; + if (contractContext instanceof Web3Context) { + this.subscribeToContextEvents(contractContext); + } + Object.defineProperty(this.options, 'address', { + set: (value) => this._parseAndSetAddress(value, returnDataFormat), + get: () => this._address, + }); + Object.defineProperty(this.options, 'jsonInterface', { + set: (value) => this._parseAndSetJsonInterface(value, returnDataFormat), + get: () => this._jsonInterface, + }); + if (contractContext instanceof Web3Context) { + contractContext.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.setConfig({ [event.name]: event.newValue }); + }); + } + } + /** + * Subscribe to an event. + * + * ```ts + * await myContract.events.MyEvent([options]) + * ``` + * + * There is a special event `allEvents` that can be used to subscribe all events. + * + * ```ts + * await myContract.events.allEvents([options]) + * ``` + * + * @returns - When individual event is accessed will returns {@link ContractBoundEvent} object + */ + get events() { + return this._events; + } + /** + * Creates a transaction object for that method, which then can be `called`, `send`, `estimated`, `createAccessList` , or `ABI encoded`. + * + * The methods of this smart contract are available through: + * + * The name: `myContract.methods.myMethod(123)` + * The name with parameters: `myContract.methods['myMethod(uint256)'](123)` + * The signature `myContract.methods['0x58cf5f10'](123)` + * + * This allows calling functions with same name but different parameters from the JavaScript contract object. + * + * \> The method signature does not provide a type safe interface, so we recommend to use method `name` instead. + * + * ```ts + * // calling a method + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using a promise + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using the events + * const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * sendObject.on('transactionHash', function(hash){ + * ... + * }); + * sendObject.on('receipt', function(receipt){ + * ... + * }); + * sendObject.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * sendObject.on('error', function(error, receipt) { + * ... + * }); + * ``` + * + * @returns - Either returns {@link PayableMethodObject} or {@link NonPayableMethodObject} based on the definitions of the ABI of that contract. + */ + get methods() { + return this._methods; + } + /** + * Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone. + * + * @returns - The new contract instance. + * + * ```ts + * const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress}); + * + * const contract2 = contract1.clone(); + * contract2.options.address = address2; + * + * (contract1.options.address !== contract2.options.address); + * > true + * ``` + */ + clone() { + let newContract; + if (this.options.address) { + newContract = new Contract([...this._jsonInterface, ...this._errorsInterface], this.options.address, { + gas: this.options.gas, + gasPrice: this.options.gasPrice, + from: this.options.from, + input: this.options.input, + data: this.options.data, + provider: this.currentProvider, + syncWithContext: this.syncWithContext, + dataInputFill: this.config.contractDataInputFill, + }, this.getContextObject()); + } + else { + newContract = new Contract([...this._jsonInterface, ...this._errorsInterface], { + gas: this.options.gas, + gasPrice: this.options.gasPrice, + from: this.options.from, + input: this.options.input, + data: this.options.data, + provider: this.currentProvider, + syncWithContext: this.syncWithContext, + dataInputFill: this.config.contractDataInputFill, + }, this.getContextObject()); + } + if (this.context) + newContract.subscribeToContextEvents(this.context); + return newContract; + } + /** + * Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance. + * + * ```ts + * myContract.deploy({ + * input: '0x12345...', // data keyword can be used, too. If input is used, data will be ignored. + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }, function(error, transactionHash){ ... }) + * .on('error', function(error){ ... }) + * .on('transactionHash', function(transactionHash){ ... }) + * .on('receipt', function(receipt){ + * console.log(receipt.contractAddress) // contains the new contract address + * }) + * .on('confirmation', function(confirmationNumber, receipt){ ... }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // When the data is already set as an option to the contract itself + * myContract.options.data = '0x12345...'; + * + * myContract.deploy({ + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // Simply encoding + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .encodeABI(); + * > '0x12345...0000012345678765432' + * + * + * // Gas estimation + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .estimateGas(function(err, gas){ + * console.log(gas); + * }); + * ``` + * + * @returns - The transaction object + */ + deploy(deployOptions) { + var _a, _b, _c; + let abi = this._jsonInterface.find(j => j.type === 'constructor'); + if (!abi) { + abi = { + type: 'constructor', + inputs: [], + stateMutability: '', + }; + } + const _input = format({ format: 'bytes' }, (_a = deployOptions === null || deployOptions === void 0 ? void 0 : deployOptions.input) !== null && _a !== void 0 ? _a : this.options.input, DEFAULT_RETURN_FORMAT); + const _data = format({ format: 'bytes' }, (_b = deployOptions === null || deployOptions === void 0 ? void 0 : deployOptions.data) !== null && _b !== void 0 ? _b : this.options.data, DEFAULT_RETURN_FORMAT); + if ((!_input || _input.trim() === '0x') && (!_data || _data.trim() === '0x')) { + throw new Web3ContractError('contract creation without any data provided.'); + } + const args = (_c = deployOptions === null || deployOptions === void 0 ? void 0 : deployOptions.arguments) !== null && _c !== void 0 ? _c : []; + const contractOptions = Object.assign(Object.assign({}, this.options), { input: _input, data: _data }); + const deployData = _input !== null && _input !== void 0 ? _input : _data; + return { + arguments: args, + send: (options) => { + const modifiedOptions = Object.assign({}, options); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._contractMethodDeploySend(abi, args, modifiedOptions, contractOptions); + }, + estimateGas: (options, returnFormat = DEFAULT_RETURN_FORMAT) => __awaiter(this, void 0, void 0, function* () { + const modifiedOptions = Object.assign({}, options); + return this._contractMethodEstimateGas({ + abi: abi, + params: args, + returnFormat, + options: modifiedOptions, + contractOptions, + }); + }), + encodeABI: () => encodeMethodABI(abi, args, format({ format: 'bytes' }, deployData, DEFAULT_RETURN_FORMAT)), + }; + } + getPastEvents(param1, param2, param3) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const eventName = typeof param1 === 'string' ? param1 : ALL_EVENTS; + const options = + // eslint-disable-next-line no-nested-ternary + typeof param1 !== 'string' && !isDataFormat(param1) + ? param1 + : !isDataFormat(param2) + ? param2 + : {}; + // eslint-disable-next-line no-nested-ternary + const returnFormat = isDataFormat(param1) + ? param1 + : isDataFormat(param2) + ? param2 + : param3 !== null && param3 !== void 0 ? param3 : DEFAULT_RETURN_FORMAT; + const abi = eventName === 'allEvents' || eventName === ALL_EVENTS + ? ALL_EVENTS_ABI + : this._jsonInterface.find(j => 'name' in j && j.name === eventName); + if (!abi) { + throw new Web3ContractError(`Event ${eventName} not found.`); + } + const { fromBlock, toBlock, topics, address } = encodeEventABI(this.options, abi, options !== null && options !== void 0 ? options : {}); + const logs = yield getLogs(this, { fromBlock, toBlock, topics, address }, returnFormat); + const decodedLogs = logs.map(log => typeof log === 'string' + ? log + : decodeEventABI(abi, log, this._jsonInterface, returnFormat)); + const filter = (_a = options === null || options === void 0 ? void 0 : options.filter) !== null && _a !== void 0 ? _a : {}; + const filterKeys = Object.keys(filter); + if (filterKeys.length > 0) { + return decodedLogs.filter(log => { + if (typeof log === 'string') + return true; + return filterKeys.every((key) => { + var _a; + if (Array.isArray(filter[key])) { + return filter[key].some((v) => String(log.returnValues[key]).toUpperCase() === + String(v).toUpperCase()); + } + const inputAbi = (_a = abi.inputs) === null || _a === void 0 ? void 0 : _a.filter(input => input.name === key)[0]; + if ((inputAbi === null || inputAbi === void 0 ? void 0 : inputAbi.indexed) && inputAbi.type === 'string') { + const hashedIndexedString = keccak256(filter[key]); + if (hashedIndexedString === String(log.returnValues[key])) + return true; + } + return (String(log.returnValues[key]).toUpperCase() === + String(filter[key]).toUpperCase()); + }); + }); + } + return decodedLogs; + }); + } + _parseAndSetAddress(value, returnFormat = DEFAULT_RETURN_FORMAT) { + this._address = value + ? toChecksumAddress(format({ format: 'address' }, value, returnFormat)) + : value; + } + _parseAndSetJsonInterface(abis, returnFormat = DEFAULT_RETURN_FORMAT) { + var _a, _b, _c, _d, _e; + this._functions = {}; + this._methods = {}; + this._events = {}; + let result = []; + const functionsAbi = abis.filter(abi => abi.type !== 'error'); + const errorsAbi = abis.filter(abi => isAbiErrorFragment(abi)); + for (const a of functionsAbi) { + const abi = Object.assign(Object.assign({}, a), { signature: '' }); + if (isAbiFunctionFragment(abi)) { + const methodName = jsonInterfaceMethodToString(abi); + const methodSignature = encodeFunctionSignature(methodName); + abi.signature = methodSignature; + // make constant and payable backwards compatible + abi.constant = + (_b = (_a = abi.stateMutability === 'view') !== null && _a !== void 0 ? _a : abi.stateMutability === 'pure') !== null && _b !== void 0 ? _b : abi.constant; + abi.payable = (_c = abi.stateMutability === 'payable') !== null && _c !== void 0 ? _c : abi.payable; + this._overloadedMethodAbis.set(abi.name, [ + ...((_d = this._overloadedMethodAbis.get(abi.name)) !== null && _d !== void 0 ? _d : []), + abi, + ]); + const abiFragment = (_e = this._overloadedMethodAbis.get(abi.name)) !== null && _e !== void 0 ? _e : []; + const contractMethod = this._createContractMethod(abiFragment, errorsAbi); + this._functions[methodName] = { + signature: methodSignature, + method: contractMethod, + }; + // We don't know a particular type of the Abi method so can't type check + this._methods[abi.name] = this._functions[methodName].method; + // We don't know a particular type of the Abi method so can't type check + this._methods[methodName] = this._functions[methodName].method; + // We don't know a particular type of the Abi method so can't type check + this._methods[methodSignature] = this + ._functions[methodName].method; + } + else if (isAbiEventFragment(abi)) { + const eventName = jsonInterfaceMethodToString(abi); + const eventSignature = encodeEventSignature(eventName); + const event = this._createContractEvent(abi, returnFormat); + abi.signature = eventSignature; + if (!(eventName in this._events) || abi.name === 'bound') { + // It's a private type and we don't want to expose it and no need to check + this._events[eventName] = event; + } + // It's a private type and we don't want to expose it and no need to check + this._events[abi.name] = event; + // It's a private type and we don't want to expose it and no need to check + this._events[eventSignature] = event; + } + result = [...result, abi]; + } + this._events.allEvents = this._createContractEvent(ALL_EVENTS_ABI, returnFormat); + this._jsonInterface = [...result]; + this._errorsInterface = errorsAbi; + } + // eslint-disable-next-line class-methods-use-this + _getAbiParams(abi, params) { + var _a; + try { + return validatorUtils.transformJsonDataToAbiFormat((_a = abi.inputs) !== null && _a !== void 0 ? _a : [], params); + } + catch (error) { + throw new Web3ContractError(`Invalid parameters for method ${abi.name}: ${error.message}`); + } + } + _createContractMethod(abiArr, errorsAbis) { + const abi = abiArr[abiArr.length - 1]; + return (...params) => { + var _a, _b; + let abiParams; + const abis = (_a = this._overloadedMethodAbis.get(abi.name)) !== null && _a !== void 0 ? _a : []; + let methodAbi = abis[0]; + const internalErrorsAbis = errorsAbis; + const arrayOfAbis = abis.filter(_abi => { var _a; return ((_a = _abi.inputs) !== null && _a !== void 0 ? _a : []).length === params.length; }); + if (abis.length === 1 || arrayOfAbis.length === 0) { + abiParams = this._getAbiParams(methodAbi, params); + validator.validate((_b = abi.inputs) !== null && _b !== void 0 ? _b : [], abiParams); + } + else { + const errors = []; + for (const _abi of arrayOfAbis) { + try { + abiParams = this._getAbiParams(_abi, params); + validator.validate(_abi.inputs, abiParams); + methodAbi = _abi; + break; + } + catch (e) { + errors.push(e); + } + } + if (errors.length === arrayOfAbis.length) { + throw new Web3ValidatorError(errors); + } + } + const methods = { + arguments: abiParams, + call: (options, block) => __awaiter(this, void 0, void 0, function* () { + return this._contractMethodCall(methodAbi, abiParams, internalErrorsAbis, options, block); + }), + send: (options) => this._contractMethodSend(methodAbi, abiParams, internalErrorsAbis, options), + estimateGas: (options, returnFormat = DEFAULT_RETURN_FORMAT) => __awaiter(this, void 0, void 0, function* () { + return this._contractMethodEstimateGas({ + abi: methodAbi, + params: abiParams, + returnFormat, + options, + }); + }), + encodeABI: () => encodeMethodABI(methodAbi, abiParams), + createAccessList: (options, block) => __awaiter(this, void 0, void 0, function* () { + return this._contractMethodCreateAccessList(methodAbi, abiParams, internalErrorsAbis, options, block); + }), + }; + if (methodAbi.stateMutability === 'payable') { + return methods; + } + return methods; + }; + } + _contractMethodCall(abi, params, errorsAbi, options, block) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const tx = getEthTxCallParams({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: Object.assign(Object.assign({}, this.options), { from: (_a = this.options.from) !== null && _a !== void 0 ? _a : this.config.defaultAccount }), + }); + try { + const result = yield call(this, tx, block, DEFAULT_RETURN_FORMAT); + return decodeMethodReturn(abi, result); + } + catch (error) { + if (error instanceof ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + decodeContractErrorData(errorsAbi, error.innerError); + } + throw error; + } + }); + } + _contractMethodCreateAccessList(abi, params, errorsAbi, options, block) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const tx = getCreateAccessListParams({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: Object.assign(Object.assign({}, this.options), { from: (_a = this.options.from) !== null && _a !== void 0 ? _a : this.config.defaultAccount }), + }); + try { + return createAccessList(this, tx, block, DEFAULT_RETURN_FORMAT); + } + catch (error) { + if (error instanceof ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + decodeContractErrorData(errorsAbi, error.innerError); + } + throw error; + } + }); + } + _contractMethodSend(abi, params, errorsAbi, options, contractOptions) { + var _a, _b; + let modifiedContractOptions = contractOptions !== null && contractOptions !== void 0 ? contractOptions : this.options; + modifiedContractOptions = Object.assign(Object.assign({}, modifiedContractOptions), { input: undefined, from: (_b = (_a = modifiedContractOptions.from) !== null && _a !== void 0 ? _a : this.defaultAccount) !== null && _b !== void 0 ? _b : undefined }); + const tx = getSendTxParams({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: modifiedContractOptions, + }); + const transactionToSend = sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + contractAbi: this._jsonInterface, + }); + // eslint-disable-next-line no-void + void transactionToSend.on('error', (error) => { + if (error instanceof ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + decodeContractErrorData(errorsAbi, error.innerError); + } + }); + return transactionToSend; + } + _contractMethodDeploySend(abi, params, options, contractOptions) { + var _a, _b; + let modifiedContractOptions = contractOptions !== null && contractOptions !== void 0 ? contractOptions : this.options; + modifiedContractOptions = Object.assign(Object.assign({}, modifiedContractOptions), { from: (_b = (_a = modifiedContractOptions.from) !== null && _a !== void 0 ? _a : this.defaultAccount) !== null && _b !== void 0 ? _b : undefined }); + const tx = getSendTxParams({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: modifiedContractOptions, + }); + return sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { + transactionResolver: receipt => { + if (receipt.status === BigInt(0)) { + throw new Web3ContractError("code couldn't be stored", receipt); + } + const newContract = this.clone(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + newContract.options.address = receipt.contractAddress; + return newContract; + }, + contractAbi: this._jsonInterface, + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + }); + } + _contractMethodEstimateGas({ abi, params, returnFormat, options, contractOptions, }) { + return __awaiter(this, void 0, void 0, function* () { + const tx = getEstimateGasParams({ + abi, + params, + options: Object.assign(Object.assign({}, options), { dataInputFill: this.config.contractDataInputFill }), + contractOptions: contractOptions !== null && contractOptions !== void 0 ? contractOptions : this.options, + }); + return estimateGas(this, tx, BlockTags.LATEST, returnFormat); + }); + } + // eslint-disable-next-line class-methods-use-this + _createContractEvent(abi, returnFormat = DEFAULT_RETURN_FORMAT) { + return (...params) => { + var _a; + const { topics, fromBlock } = encodeEventABI(this.options, abi, params[0]); + const sub = new LogsSubscription({ + address: this.options.address, + topics, + abi, + jsonInterface: this._jsonInterface, + }, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + subscriptionManager: this.subscriptionManager, + returnFormat, + }); + if (!isNullish(fromBlock)) { + // emit past events when fromBlock is defined + this.getPastEvents(abi.name, { fromBlock, topics }, returnFormat) + .then(logs => { + logs.forEach(log => sub.emit('data', log)); + }) + .catch((error) => { + sub.emit('error', new SubscriptionError('Failed to get past events.', error)); + }); + } + (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.addSubscription(sub).catch((error) => { + sub.emit('error', new SubscriptionError('Failed to subscribe.', error)); + }); + return sub; + }; + } + subscribeToContextEvents(context) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const contractThis = this; + this.context = context; + if (contractThis.syncWithContext) { + context.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + contractThis.setConfig({ [event.name]: event.newValue }); + }); + } + } +} +//# sourceMappingURL=contract.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/contract.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/contract.js.map new file mode 100644 index 0000000..31d237c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/contract.ts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,CAAC,EAAE;gBACjD,YAAY,CAAC,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;YAC1D,CAAC,CAAC,CAAC;SACH;IACF,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/encoding.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/encoding.js new file mode 100644 index 0000000..2142fa1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/encoding.js @@ -0,0 +1,119 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { format, isNullish, keccak256 } from 'web3-utils'; +import { FMT_NUMBER, FMT_BYTES, } from 'web3-types'; +import { decodeParameters, encodeEventSignature, encodeFunctionSignature, encodeParameter, encodeParameters, isAbiConstructorFragment, jsonInterfaceMethodToString, } from 'web3-eth-abi'; +import { blockSchema, ALL_EVENTS } from 'web3-eth'; +import { Web3ContractError } from 'web3-errors'; +export { decodeEventABI } from 'web3-eth'; +export const encodeEventABI = ({ address }, event, options) => { + var _a, _b; + const topics = options === null || options === void 0 ? void 0 : options.topics; + const filter = (_a = options === null || options === void 0 ? void 0 : options.filter) !== null && _a !== void 0 ? _a : {}; + const opts = {}; + if (!isNullish(options === null || options === void 0 ? void 0 : options.fromBlock)) { + opts.fromBlock = format(blockSchema.properties.number, options === null || options === void 0 ? void 0 : options.fromBlock, { + number: FMT_NUMBER.HEX, + bytes: FMT_BYTES.HEX, + }); + } + if (!isNullish(options === null || options === void 0 ? void 0 : options.toBlock)) { + opts.toBlock = format(blockSchema.properties.number, options === null || options === void 0 ? void 0 : options.toBlock, { + number: FMT_NUMBER.HEX, + bytes: FMT_BYTES.HEX, + }); + } + if (topics && Array.isArray(topics)) { + opts.topics = [...topics]; + } + else { + opts.topics = []; + // add event signature + if (event && !event.anonymous && ![ALL_EVENTS, 'allEvents'].includes(event.name)) { + opts.topics.push((_b = event.signature) !== null && _b !== void 0 ? _b : encodeEventSignature(jsonInterfaceMethodToString(event))); + } + // add event topics (indexed arguments) + if (![ALL_EVENTS, 'allEvents'].includes(event.name) && event.inputs) { + for (const input of event.inputs) { + if (!input.indexed) { + continue; + } + const value = filter[input.name]; + if (!value) { + // eslint-disable-next-line no-null/no-null + opts.topics.push(null); + continue; + } + // TODO: https://github.com/ethereum/web3.js/issues/344 + // TODO: deal properly with components + if (Array.isArray(value)) { + opts.topics.push(value.map(v => encodeParameter(input.type, v))); + } + else if (input.type === 'string') { + opts.topics.push(keccak256(value)); + } + else { + opts.topics.push(encodeParameter(input.type, value)); + } + } + } + } + if (!opts.topics.length) + delete opts.topics; + if (address) { + opts.address = address.toLowerCase(); + } + return opts; +}; +export const encodeMethodABI = (abi, args, deployData) => { + const inputLength = Array.isArray(abi.inputs) ? abi.inputs.length : 0; + if (inputLength !== args.length) { + throw new Web3ContractError(`The number of arguments is not matching the methods required number. You need to pass ${inputLength} arguments.`); + } + const params = encodeParameters(Array.isArray(abi.inputs) ? abi.inputs : [], args).replace('0x', ''); + if (isAbiConstructorFragment(abi)) { + if (!deployData) + throw new Web3ContractError('The contract has no contract data option set. This is necessary to append the constructor parameters.'); + if (!deployData.startsWith('0x')) { + return `0x${deployData}${params}`; + } + return `${deployData}${params}`; + } + return `${encodeFunctionSignature(abi)}${params}`; +}; +export const decodeMethodReturn = (abi, returnValues) => { + // If it was constructor then we need to return contract address + if (abi.type === 'constructor') { + return returnValues; + } + if (!returnValues) { + // Using "null" value intentionally to match legacy behavior + // eslint-disable-next-line no-null/no-null + return null; + } + const value = returnValues.length >= 2 ? returnValues.slice(2) : returnValues; + if (!abi.outputs) { + // eslint-disable-next-line no-null/no-null + return null; + } + const result = decodeParameters([...abi.outputs], value); + if (result.__length__ === 1) { + return result[0]; + } + return result; +}; +//# sourceMappingURL=encoding.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/encoding.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/encoding.js.map new file mode 100644 index 0000000..9681e4b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/encoding.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.js","sourceRoot":"","sources":["../../src/encoding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAON,UAAU,EACV,SAAS,GAET,MAAM,YAAY,CAAC;AAEpB,OAAO,EACN,gBAAgB,EAChB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,gBAAgB,EAChB,wBAAwB,EACxB,2BAA2B,GAC3B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAG1C,MAAM,CAAC,MAAM,cAAc,GAAG,CAC7B,EAAE,OAAO,EAAmB,EAC5B,KAA+C,EAC/C,OAAgB,EACf,EAAE;;IACH,MAAM,MAAM,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,mCAAI,EAAE,CAAC;IACrC,MAAM,IAAI,GAAsB,EAAE,CAAC;IAEnC,IAAI,CAAC,SAAS,CAAC,OAAO,aA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GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC;IAEzD,IAAI,MAAM,CAAC,UAAU,KAAK,CAAC,EAAE;QAC5B,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;KACjB;IAED,OAAO,MAAM,CAAC;AACf,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/index.js new file mode 100644 index 0000000..edaf753 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/index.js @@ -0,0 +1,48 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The `web3.eth.Contract` object makes it easy to interact with smart contracts on the Ethereum blockchain. + * When you create a new contract object you give it the JSON interface of the respective smart contract and + * web3 will auto convert all calls into low level ABI calls over RPC for you. + * This allows you to interact with smart contracts as if they were JavaScript objects. + * + * To use it standalone: + * + * ```ts + * const Contract = require('web3-eth-contract'); + * + * // set provider for all later instances to use + * Contract.setProvider('ws://localhost:8546'); + * + * const contract = new Contract(jsonInterface, address); + * + * contract.methods.somFunc().send({from: ....}) + * .on('receipt', function(){ + * ... + * }); + * ``` + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Contract } from './contract.js'; +export * from './encoding.js'; +export * from './contract.js'; +export * from './log_subscription.js'; +export * from './types.js'; +export default Contract; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/index.js.map new file mode 100644 index 0000000..82f3494 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH;;GAEG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,cAAc,eAAe,CAAC;AAE9B,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,YAAY,CAAC;AAE3B,eAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/log_subscription.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/log_subscription.js new file mode 100644 index 0000000..084a919 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/log_subscription.js @@ -0,0 +1,89 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3Subscription } from 'web3-core'; +import { decodeEventABI } from 'web3-eth'; +/** + * LogSubscription to be used to subscribe to events logs. + * + * Following events are supported and can be accessed with either {@link LogsSubscription.once} or ${@link LogsSubscription.on} methods. + * + * - **connected**: Emitted when the subscription is connected. + * - **data**: Fires on each incoming event with the event object as argument. + * - **changed**: Fires on each event which was removed from the blockchain. The event will have the additional property `removed: true`. + * - **error**: Fires on each error. + * + * ```ts + * const subscription = await myContract.events.MyEvent({ + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0 + * }); + * + * subscription.on("connected", function(subscriptionId){ + * console.log(subscriptionId); + * }); + * + * subscription.on('data', function(event){ + * console.log(event); // same results as the optional callback above + * }); + * + * subscription.on('changed', function(event){ + * // remove event from local database + * }) + * + * subscription.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * + * // event output example + * > { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * } + * ``` + */ +export class LogsSubscription extends Web3Subscription { + constructor(args, options) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + super(args, options); + this.address = args.address; + this.topics = args.topics; + this.abi = args.abi; + this.jsonInterface = args.jsonInterface; + } + _buildSubscriptionParams() { + return ['logs', { address: this.address, topics: this.topics }]; + } + formatSubscriptionResult(data) { + return decodeEventABI(this.abi, data, this.jsonInterface, super.returnFormat); + } +} +//# sourceMappingURL=log_subscription.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/log_subscription.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/log_subscription.js.map new file mode 100644 index 0000000..6b4f5b0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/log_subscription.js.map @@ -0,0 +1 @@ +{"version":3,"file":"log_subscription.js","sourceRoot":"","sources":["../../src/log_subscription.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAWF,OAAO,EAAsB,gBAAgB,EAA2B,MAAM,WAAW,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,MAAM,OAAO,gBAAiB,SAAQ,gBAOrC;IA0CA,YACC,IAMC,EACD,OAKC;QAED,iEAAiE;QACjE,KAAK,CAAC,IAAI,EAAE,OAAc,CAAC,CAAC;QAE5B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACpB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC;IACzC,CAAC;IAES,wBAAwB;QACjC,OAAO,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACjE,CAAC;IAES,wBAAwB,CAAC,IAAc;QAChD,OAAO,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAiB,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5F,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/types.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/utils.js b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/utils.js new file mode 100644 index 0000000..37c1a0f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/utils.js @@ -0,0 +1,113 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3ContractError } from 'web3-errors'; +import { isNullish, mergeDeep, isContractInitOptions } from 'web3-utils'; +import { encodeMethodABI } from './encoding.js'; +const dataInputEncodeMethodHelper = (txParams, abi, params, dataInputFill) => { + var _a, _b; + const tx = {}; + if (!isNullish(txParams.data) || dataInputFill === 'both') { + tx.data = encodeMethodABI(abi, params, ((_a = txParams.data) !== null && _a !== void 0 ? _a : txParams.input)); + } + if (!isNullish(txParams.input) || dataInputFill === 'both') { + tx.input = encodeMethodABI(abi, params, ((_b = txParams.input) !== null && _b !== void 0 ? _b : txParams.data)); + } + // if input and data is empty, use web3config default + if (isNullish(tx.input) && isNullish(tx.data)) { + tx[dataInputFill] = encodeMethodABI(abi, params); + } + return { data: tx.data, input: tx.input }; +}; +export const getSendTxParams = ({ abi, params, options, contractOptions, }) => { + var _a, _b, _c; + const deploymentCall = (_c = (_b = (_a = options === null || options === void 0 ? void 0 : options.input) !== null && _a !== void 0 ? _a : options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : contractOptions.input) !== null && _c !== void 0 ? _c : contractOptions.data; + if (!deploymentCall && !(options === null || options === void 0 ? void 0 : options.to) && !contractOptions.address) { + throw new Web3ContractError('Contract address not specified'); + } + if (!(options === null || options === void 0 ? void 0 : options.from) && !contractOptions.from) { + throw new Web3ContractError('Contract "from" address not specified'); + } + let txParams = mergeDeep({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +export const getEthTxCallParams = ({ abi, params, options, contractOptions, }) => { + if (!(options === null || options === void 0 ? void 0 : options.to) && !contractOptions.address) { + throw new Web3ContractError('Contract address not specified'); + } + let txParams = mergeDeep({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +export const getEstimateGasParams = ({ abi, params, options, contractOptions, }) => { + let txParams = mergeDeep({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +export { isContractInitOptions } from 'web3-utils'; +export const isWeb3ContractContext = (options) => typeof options === 'object' && !isNullish(options) && + Object.keys(options).length !== 0 && !isContractInitOptions(options); +export const getCreateAccessListParams = ({ abi, params, options, contractOptions, }) => { + if (!(options === null || options === void 0 ? void 0 : options.to) && !contractOptions.address) { + throw new Web3ContractError('Contract address not specified'); + } + if (!(options === null || options === void 0 ? void 0 : options.from) && !contractOptions.from) { + throw new Web3ContractError('Contract "from" address not specified'); + } + let txParams = mergeDeep({ + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, options); + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options === null || options === void 0 ? void 0 : options.dataInputFill); + txParams = Object.assign(Object.assign({}, txParams), { data: dataInput.data, input: dataInput.input }); + return txParams; +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/utils.js.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/utils.js.map new file mode 100644 index 0000000..1829e27 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAYhD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAGhD,MAAM,2BAA2B,GAAG,CACnC,QAAoD,EACpD,GAAwB,EACxB,MAAiB,EACjB,aAAyC,EACC,EAAE;;IAC5C,MAAM,EAAE,GAA4C,EAAE,CAAC;IACvD,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,aAAa,KAAK,MAAM,EAAE;QAC1D,EAAE,CAAC,IAAI,GAAG,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,CAAC,MAAA,QAAQ,CAAC,IAAI,mCAAI,QAAQ,CAAC,KAAK,CAAc,CAAC,CAAC;KACvF;IACD,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,aAAa,KAAK,MAAM,EAAE;QAC3D,EAAE,CAAC,KAAK,GAAG,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,CAAC,MAAA,QAAQ,CAAC,KAAK,mCAAI,QAAQ,CAAC,IAAI,CAAc,CAAC,CAAC;KACxF;IACD,qDAAqD;IACrD,IAAI,SAAS,CAAC,EAAE,CAAC,KAAK,CA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AAO,EAAE;QAC7C,MAAM,IAAI,iBAAiB,CAAC,gCAAgC,CAAC,CAAC;KAC9D;IAED,IAAI,CAAC,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,CAAA,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE;QAC5C,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;KACrE;IAED,IAAI,QAAQ,GAAG,SAAS,CACvB;QACC,EAAE,EAAE,eAAe,CAAC,OAAO;QAC3B,GAAG,EAAE,eAAe,CAAC,GAAG;QACxB,QAAQ,EAAE,eAAe,CAAC,QAAQ;QAClC,IAAI,EAAE,eAAe,CAAC,IAAI;QAC1B,KAAK,EAAE,eAAe,CAAC,KAAK;QAC5B,oBAAoB,EAAE,eAAe,CAAC,oBAAoB;QAC1D,YAAY,EAAE,eAAe,CAAC,YAAY;QAC1C,IAAI,EAAE,eAAe,CAAC,IAAI;KAC1B,EACD,OAA6C,CACN,CAAC;IAEzC,MAAM,SAAS,GAAG,2BAA2B,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa,CAAC,CAAC;IAC7F,QAAQ,mCAAQ,QAAQ,KAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,GAAE,CAAC;IAEzE,OAAO,QAAQ,CAAC;AACjB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/constant.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/constant.d.ts new file mode 100644 index 0000000..3cfcf39 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/constant.d.ts @@ -0,0 +1,2 @@ +export { ALL_EVENTS, ALL_EVENTS_ABI } from 'web3-eth'; +//# sourceMappingURL=constant.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/constant.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/constant.d.ts.map new file mode 100644 index 0000000..0855115 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/constant.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constant.d.ts","sourceRoot":"","sources":["../../src/constant.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/contract.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/contract.d.ts new file mode 100644 index 0000000..edeaa61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/contract.d.ts @@ -0,0 +1,322 @@ +import { Web3Context, Web3EventEmitter, Web3PromiEvent } from 'web3-core'; +import { NewHeadsSubscription, SendTransactionEvents } from 'web3-eth'; +import { AbiFunctionFragment, ContractAbi, ContractConstructorArgs, ContractEvent, ContractEvents, ContractMethod, ContractMethodInputParameters, ContractMethodOutputParameters, Address, EthExecutionAPI, Filter, FilterAbis, HexString, ContractInitOptions, PayableCallOptions, DataFormat, DEFAULT_RETURN_FORMAT, EventLog, ContractOptions } from 'web3-types'; +import { LogsSubscription } from './log_subscription.js'; +import { ContractEventOptions, NonPayableMethodObject, PayableMethodObject, PayableTxOptions, Web3ContractContext } from './types.js'; +declare type ContractBoundMethod = ContractMethod> = (...args: Method['Inputs']) => Method['Abi']['stateMutability'] extends 'payable' | 'pure' ? PayableMethodObject : NonPayableMethodObject; +export declare type ContractOverloadedMethodInputs> = NonNullable | ContractOverloadedMethodInputs : undefined : undefined>; +export declare type ContractOverloadedMethodOutputs> = NonNullable | ContractOverloadedMethodOutputs : undefined : undefined>; +export declare type ContractMethodsInterface = { + [MethodAbi in FilterAbis as MethodAbi['name']]: ContractBoundMethod; +} & { + [key: string]: ContractBoundMethod; +}; +/** + * @hidden + * The event object can be accessed from `myContract.events.myEvent`. + * + * \> Remember: To subscribe to an event, your provider must have support for subscriptions. + * + * ```ts + * const subscription = await myContract.events.MyEvent([options]) + * ``` + * + * @param options - The options used to subscribe for the event + * @returns - A Promise resolved with {@link LogsSubscription} object + */ +export declare type ContractBoundEvent = (options?: ContractEventOptions) => LogsSubscription; +export declare type ContractEventsInterface = ContractEvents> = { + [Name in keyof Events | 'allEvents']: ContractBoundEvent; +} & { + [key: string]: ContractBoundEvent; +}; +export declare type ContractEventEmitterInterface = { + [EventAbi in FilterAbis as EventAbi['name']]: ContractEvent['Inputs']; +}; +declare const contractSubscriptions: { + logs: typeof LogsSubscription; + newHeads: typeof NewHeadsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; +}; +/** + * The class designed to interact with smart contracts on the Ethereum blockchain. + */ +export declare class Contract extends Web3Context implements Web3EventEmitter> { + /** + * The options `object` for the contract instance. `from`, `gas` and `gasPrice` are used as fallback values when sending transactions. + * + * ```ts + * myContract.options; + * > { + * address: '0x1234567890123456789012345678901234567891', + * jsonInterface: [...], + * from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', + * gasPrice: '10000000000000', + * gas: 1000000 + * } + * + * myContract.options.from = '0x1234567890123456789012345678901234567891'; // default from address + * myContract.options.gasPrice = '20000000000000'; // default gas price in wei + * myContract.options.gas = 5000000; // provide as fallback always 5M gas + * ``` + */ + readonly options: ContractOptions; + /** + * Set to true if you want contracts' defaults to sync with global defaults. + */ + syncWithContext: boolean; + private _errorsInterface; + private _jsonInterface; + private _address?; + private _functions; + private readonly _overloadedMethodAbis; + private _methods; + private _events; + /** + * Set property to `data`, `input`, or `both` to change the property of the contract being sent to the + * RPC provider when using contract methods. + * Default is `input` + */ + private context?; + /** + * Creates a new contract instance with all its methods and events defined in its ABI provided. + * + * ```ts + * new web3.eth.Contract(jsonInterface[, address][, options]) + * ``` + * + * @param jsonInterface - The JSON interface for the contract to instantiate. + * @param address - The address of the smart contract to call. + * @param options - The options of the contract. Some are used as fallbacks for calls and transactions. + * @param context - The context of the contract used for customizing the behavior of the contract. + * @returns - The contract instance with all its methods and events. + * + * ```ts title="Example" + * var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', { + * from: '0x1234567890123456789012345678901234567891', // default from address + * gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case + * }); + * ``` + * + * To use the type safe interface for these contracts you have to include the ABI definitions in your Typescript project and then declare these as `const`. + * + * ```ts title="Example" + * const myContractAbi = [....] as const; // ABI definitions + * const myContract = new web3.eth.Contract(myContractAbi, '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'); + * ``` + */ + constructor(jsonInterface: Abi, context?: Web3ContractContext | Web3Context, returnFormat?: DataFormat); + constructor(jsonInterface: Abi, address?: Address, contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, returnFormat?: DataFormat); + constructor(jsonInterface: Abi, options?: ContractInitOptions, contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, returnFormat?: DataFormat); + constructor(jsonInterface: Abi, address: Address | undefined, options: ContractInitOptions, contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, returnFormat?: DataFormat); + /** + * Subscribe to an event. + * + * ```ts + * await myContract.events.MyEvent([options]) + * ``` + * + * There is a special event `allEvents` that can be used to subscribe all events. + * + * ```ts + * await myContract.events.allEvents([options]) + * ``` + * + * @returns - When individual event is accessed will returns {@link ContractBoundEvent} object + */ + get events(): ContractEventsInterface>; + /** + * Creates a transaction object for that method, which then can be `called`, `send`, `estimated`, `createAccessList` , or `ABI encoded`. + * + * The methods of this smart contract are available through: + * + * The name: `myContract.methods.myMethod(123)` + * The name with parameters: `myContract.methods['myMethod(uint256)'](123)` + * The signature `myContract.methods['0x58cf5f10'](123)` + * + * This allows calling functions with same name but different parameters from the JavaScript contract object. + * + * \> The method signature does not provide a type safe interface, so we recommend to use method `name` instead. + * + * ```ts + * // calling a method + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using a promise + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using the events + * const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * sendObject.on('transactionHash', function(hash){ + * ... + * }); + * sendObject.on('receipt', function(receipt){ + * ... + * }); + * sendObject.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * sendObject.on('error', function(error, receipt) { + * ... + * }); + * ``` + * + * @returns - Either returns {@link PayableMethodObject} or {@link NonPayableMethodObject} based on the definitions of the ABI of that contract. + */ + get methods(): ContractMethodsInterface; + /** + * Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone. + * + * @returns - The new contract instance. + * + * ```ts + * const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress}); + * + * const contract2 = contract1.clone(); + * contract2.options.address = address2; + * + * (contract1.options.address !== contract2.options.address); + * > true + * ``` + */ + clone(): Contract; + /** + * Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance. + * + * ```ts + * myContract.deploy({ + * input: '0x12345...', // data keyword can be used, too. If input is used, data will be ignored. + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }, function(error, transactionHash){ ... }) + * .on('error', function(error){ ... }) + * .on('transactionHash', function(transactionHash){ ... }) + * .on('receipt', function(receipt){ + * console.log(receipt.contractAddress) // contains the new contract address + * }) + * .on('confirmation', function(confirmationNumber, receipt){ ... }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // When the data is already set as an option to the contract itself + * myContract.options.data = '0x12345...'; + * + * myContract.deploy({ + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // Simply encoding + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .encodeABI(); + * > '0x12345...0000012345678765432' + * + * + * // Gas estimation + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .estimateGas(function(err, gas){ + * console.log(gas); + * }); + * ``` + * + * @returns - The transaction object + */ + deploy(deployOptions?: { + /** + * The byte code of the contract. + */ + data?: HexString; + input?: HexString; + /** + * The arguments which get passed to the constructor on deployment. + */ + arguments?: ContractConstructorArgs; + }): { + arguments: never[] | NonNullable>; + send: (options?: PayableTxOptions) => Web3PromiEvent, SendTransactionEvents>; + estimateGas: (options?: PayableCallOptions, returnFormat?: ReturnFormat) => Promise; + encodeABI: () => string; + }; + /** + * Gets past events for this contract. + * + * ```ts + * const events = await myContract.getPastEvents('MyEvent', { + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0, + * toBlock: 'latest' + * }); + * + * > [{ + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * },{ + * ... + * }] + * ``` + * + * @param eventName - The name of the event in the contract, or `allEvents` to get all events. + * @param filter - The filter options used to get events. + * @param returnFormat - Return format + * @returns - An array with the past event `Objects`, matching the given event name and filter. + */ + getPastEvents(returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + getPastEvents(eventName: keyof ContractEvents | 'allEvents' | 'ALLEVENTS', returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + getPastEvents(filter: Omit, returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + getPastEvents(eventName: keyof ContractEvents | 'allEvents' | 'ALLEVENTS', filter: Omit, returnFormat?: ReturnFormat): Promise<(string | EventLog)[]>; + private _parseAndSetAddress; + private _parseAndSetJsonInterface; + private _getAbiParams; + private _createContractMethod; + private _contractMethodCall; + private _contractMethodCreateAccessList; + private _contractMethodSend; + private _contractMethodDeploySend; + private _contractMethodEstimateGas; + private _createContractEvent; + protected subscribeToContextEvents(context: T): void; +} +export {}; +//# sourceMappingURL=contract.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/contract.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/contract.d.ts.map new file mode 100644 index 0000000..6dbe669 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/contract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src/contract.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,WAAW,EACX,gBAAgB,EAChB,cAAc,EAGd,MAAM,WAAW,CAAC;AAOnB,OAAO,EAON,oBAAoB,EAGpB,qBAAqB,EACrB,MAAM,UAAU,CAAC;AAUlB,OAAO,EAKN,mBAAmB,EACnB,WAAW,EACX,uBAAuB,EACvB,aAAa,EACb,cAAc,EACd,cAAc,EACd,6BAA6B,EAC7B,8BAA8B,EAC9B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AC,EAC/B,YAAY,CAAC,EAAE,YAAY,GACzB,OAAO,CAAC,CAAC,MAAM,GAAG,QAAQ,CAAC,EAAE,CAAC;IAqFjC,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,yBAAyB;IAsFjC,OAAO,CAAC,aAAa;IAUrB,OAAO,CAAC,qBAAqB;YA+Ff,mBAAmB;YA+BnB,+BAA+B;IA8B7C,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,yBAAyB;YAmCnB,0BAA0B;IA0BxC,OAAO,CAAC,oBAAoB;IA+C5B,SAAS,CAAC,wBAAwB,CAAC,CAAC,SAAS,WAAW,EAAE,OAAO,EAAE,CAAC,GAAG,IAAI;CAW3E"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/encoding.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/encoding.d.ts new file mode 100644 index 0000000..466de30 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/encoding.d.ts @@ -0,0 +1,11 @@ +import { AbiConstructorFragment, AbiEventFragment, AbiFunctionFragment, Filter, HexString, ContractOptions } from 'web3-types'; +export { decodeEventABI } from 'web3-eth'; +declare type Writeable = { + -readonly [P in keyof T]: T[P]; +}; +export declare const encodeEventABI: ({ address }: ContractOptions, event: AbiEventFragment & { + signature: string; +}, options?: Filter) => Writeable; +export declare const encodeMethodABI: (abi: AbiFunctionFragment | AbiConstructorFragment, args: unknown[], deployData?: HexString) => string; +export declare const decodeMethodReturn: (abi: AbiFunctionFragment, returnValues?: HexString) => unknown; +//# sourceMappingURL=encoding.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/encoding.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/encoding.d.ts.map new file mode 100644 index 0000000..14defda --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/encoding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["../../src/encoding.ts"],"names":[],"mappings":"AAmBA,OAAO,EACN,sBAAsB,EACtB,gBAAgB,EAChB,mBAAmB,EACnB,MAAM,EACN,SAAS,EAIT,eAAe,EACf,MAAM,YAAY,CAAC;AAepB,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,aAAK,SAAS,CAAC,CAAC,IAAI;IAAE,CAAC,UAAU,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC;AACvD,eAAO,MAAM,cAAc,gBACb,eAAe,SACrB,gBAAgB,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,YACrC,MAAM,sBAgEhB,CAAC;AAEF,eAAO,MAAM,eAAe,QACtB,mBAAmB,GAAG,sBAAsB,QAC3C,OAAO,EAAE,eACF,SAAS,WA4BtB,CAAC;AAEF,eAAO,MAAM,kBAAkB,QAAS,mBAAmB,iBAAiB,SAAS,YAwBpF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/index.d.ts new file mode 100644 index 0000000..06a4b02 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/index.d.ts @@ -0,0 +1,32 @@ +/** + * The `web3.eth.Contract` object makes it easy to interact with smart contracts on the Ethereum blockchain. + * When you create a new contract object you give it the JSON interface of the respective smart contract and + * web3 will auto convert all calls into low level ABI calls over RPC for you. + * This allows you to interact with smart contracts as if they were JavaScript objects. + * + * To use it standalone: + * + * ```ts + * const Contract = require('web3-eth-contract'); + * + * // set provider for all later instances to use + * Contract.setProvider('ws://localhost:8546'); + * + * const contract = new Contract(jsonInterface, address); + * + * contract.methods.somFunc().send({from: ....}) + * .on('receipt', function(){ + * ... + * }); + * ``` + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Contract } from './contract.js'; +export * from './encoding.js'; +export * from './contract.js'; +export * from './log_subscription.js'; +export * from './types.js'; +export default Contract; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/index.d.ts.map new file mode 100644 index 0000000..7a8d776 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH;;GAEG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,cAAc,eAAe,CAAC;AAE9B,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,YAAY,CAAC;AAE3B,eAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/log_subscription.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/log_subscription.d.ts new file mode 100644 index 0000000..b48d1b8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/log_subscription.d.ts @@ -0,0 +1,113 @@ +import { AbiEventFragment, HexString, Topic, DataFormat, EventLog, ContractAbiWithSignature } from 'web3-types'; +import { Web3RequestManager, Web3Subscription, Web3SubscriptionManager } from 'web3-core'; +/** + * LogSubscription to be used to subscribe to events logs. + * + * Following events are supported and can be accessed with either {@link LogsSubscription.once} or ${@link LogsSubscription.on} methods. + * + * - **connected**: Emitted when the subscription is connected. + * - **data**: Fires on each incoming event with the event object as argument. + * - **changed**: Fires on each event which was removed from the blockchain. The event will have the additional property `removed: true`. + * - **error**: Fires on each error. + * + * ```ts + * const subscription = await myContract.events.MyEvent({ + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0 + * }); + * + * subscription.on("connected", function(subscriptionId){ + * console.log(subscriptionId); + * }); + * + * subscription.on('data', function(event){ + * console.log(event); // same results as the optional callback above + * }); + * + * subscription.on('changed', function(event){ + * // remove event from local database + * }) + * + * subscription.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * + * // event output example + * > { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * } + * ``` + */ +export declare class LogsSubscription extends Web3Subscription<{ + data: EventLog; + changed: EventLog & { + removed: true; + }; +}, { + address?: HexString; + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment; +}> { + /** + * Address of tye contract + */ + readonly address?: HexString; + /** + * The list of topics subscribed + */ + readonly topics?: (Topic | Topic[] | null)[]; + /** + * The {@doclink glossary/json_interface | JSON Interface} of the event. + */ + readonly abi: AbiEventFragment & { + signature: HexString; + }; + readonly jsonInterface: ContractAbiWithSignature; + constructor(args: { + address?: HexString; + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { + signature: HexString; + }; + jsonInterface: ContractAbiWithSignature; + }, options: { + subscriptionManager: Web3SubscriptionManager; + returnFormat?: DataFormat; + }); + /** + * @deprecated This constructor overloading should not be used + */ + constructor(args: { + address?: HexString; + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { + signature: HexString; + }; + jsonInterface: ContractAbiWithSignature; + }, options: { + requestManager: Web3RequestManager; + returnFormat?: DataFormat; + }); + protected _buildSubscriptionParams(): (string | { + address: string | undefined; + topics: (string | string[] | null)[] | undefined; + })[]; + protected formatSubscriptionResult(data: EventLog): EventLog; +} +//# sourceMappingURL=log_subscription.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/log_subscription.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/log_subscription.d.ts.map new file mode 100644 index 0000000..e493b51 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/log_subscription.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"log_subscription.d.ts","sourceRoot":"","sources":["../../src/log_subscription.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,gBAAgB,EAEhB,SAAS,EACT,KAAK,EACL,UAAU,EACV,QAAQ,EACR,wBAAwB,EACxB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AAG1F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,qBAAa,gBAAiB,SAAQ,gBAAgB,CACrD;IACC,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,EAAE,QAAQ,GAAG;QAAE,OAAO,EAAE,IAAI,CAAA;KAAE,CAAC;CACtC,EAED;IAAE,OAAO,CAAC,EAAE,SAAS,CAAC;IAAC,MAAM,CAAC,EAAE,CAAC,KAAK,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;IAAC,GAAG,EAAE,gBAAgB,CAAA;CAAE,CACnF;IACA;;OAEG;IACH,SAAgB,OAAO,CAAC,EAAE,SAAS,CAAC;IAEpC;;OAEG;IAEH,SAAgB,MAAM,CAAC,EAAE,CAAC,KAAK,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;IAEpD;;OAEG;IACH,SAAgB,GAAG,EAAE,gBAAgB,GAAG;QAAE,SAAS,EAAE,SAAS,CAAA;KAAE,CAAC;IAEjE,SAAgB,aAAa,EAAE,wBAAwB,CAAC;gBAGvD,IAAI,EAAE;QACL,OAAO,CAAC,EAAE,SAAS,CAAC;QAEpB,MAAM,CAAC,EAAE,CAAC,KAAK,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QACpC,GAAG,EAAE,gBAAgB,GAAG;YAAE,SAAS,EAAE,SAAS,CAAA;SAAE,CAAC;QACjD,aAAa,EAAE,wBAAwB,CAAC;KACxC,EACD,OAAO,EAAE;QAAE,mBAAmB,EAAE,uBAAuB,CAAC;QAAC,YAAY,CAAC,EAAE,UAAU,CAAA;KAAE;IAErF;;OAEG;gBAEF,IAAI,EAAE;QACL,OAAO,CAAC,EAAE,SAAS,CAAC;QAEpB,MAAM,CAAC,EAAE,CAAC,KAAK,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QACpC,GAAG,EAAE,gBAAgB,GAAG;YAAE,SAAS,EAAE,SAAS,CAAA;SAAE,CAAC;QACjD,aAAa,EAAE,wBAAwB,CAAC;KACxC,EACD,OAAO,EAAE;QAAE,cAAc,EAAE,kBAAkB,CAAC;QAAC,YAAY,CAAC,EAAE,UAAU,CAAA;KAAE;IA0B3E,SAAS,CAAC,wBAAwB;;;;IAIlC,SAAS,CAAC,wBAAwB,CAAC,IAAI,EAAE,QAAQ;CAGjD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/types.d.ts new file mode 100644 index 0000000..dbeaaa7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/types.d.ts @@ -0,0 +1,367 @@ +import { Web3ContextInitOptions, Web3PromiEvent } from 'web3-core'; +import { AccessListResult, BlockNumberOrTag, EthExecutionAPI, HexString, Numbers, TransactionReceipt, NonPayableCallOptions, PayableCallOptions, DataFormat, DEFAULT_RETURN_FORMAT, FormatType } from 'web3-types'; +import { NewHeadsSubscription, SendTransactionEvents } from 'web3-eth'; +import { LogsSubscription } from './log_subscription.js'; +export declare type NonPayableTxOptions = NonPayableCallOptions; +export declare type PayableTxOptions = PayableCallOptions; +export { ContractAbiWithSignature, EventLog, ContractOptions } from 'web3-types'; +export interface ContractEventOptions { + /** + * Let you filter events by indexed parameters, e.g. `{filter: {myNumber: [12,13]}}` means all events where `myNumber` is `12` or `13`. + */ + filter?: Record; + /** + * The block number (greater than or equal to) from which to get events on. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized` can also be used. For specific range use {@link Contract.getPastEvents}. + */ + fromBlock?: BlockNumberOrTag; + /** + * This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically. Each topic can also be a nested array of topics that behaves as `or` operation between the given nested topics. + */ + topics?: string[]; +} +export interface NonPayableMethodObject { + arguments: Inputs; + /** + * This will call a method and execute its smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state. + * + * ```ts + * // using the promise + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // MULTI-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(uint256 myNumber, string myString) { + * return (23456, "Hello!%"); + * } + * } + * + * // web3.js + * var MyContract = new web3.eth.Contract(abi, address); + * const result = MyContract.methods.myFunction().call() + * console.log(result) + * > Result { + * myNumber: '23456', + * myString: 'Hello!%', + * 0: '23456', // these are here as fallbacks if the name is not know or given + * 1: 'Hello!%' + * } + * + * + * // SINGLE-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(string myString) { + * return "Hello!%"; + * } + * } + * + * // web3.js + * const MyContract = new web3.eth.Contract(abi, address); + * const result = await MyContract.methods.myFunction().call(); + * console.log(result); + * > "Hello!%" + * ``` + * + * @param tx - The options used for calling. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns - The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices. + */ + call(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise; + /** + * This will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state. + * + * ```ts + * await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * + * // using the event emitter + * const sendObj = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}) + * sendObj.on('transactionHash', function(hash){ + * ... + * }); + * + * sendObj.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * + * sendObj.on('receipt', function(receipt){ + * // receipt example + * console.log(receipt); + * > { + * "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", + * "transactionIndex": 0, + * "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", + * "blockNumber": 3, + * "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * "cumulativeGasUsed": 314159, + * "gasUsed": 30234, + * "events": { + * "MyEvent": { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * "MyOtherEvent": { + * ... + * }, + * "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array + * } + * } + * }); + * + * sendObj.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * ``` + * + * @param tx - The options used for sending. + * @returns - Returns a {@link PromiEvent} resolved with transaction receipt. + */ + send(tx?: NonPayableTxOptions): Web3PromiEvent, SendTransactionEvents>; + /** + * Returns the amount of gas consumed by executing the method locally without creating a new transaction on the blockchain. + * The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be + * different when sending the transaction later, as the state of the smart contract can be different at that time. + * + * ```ts + * const gasAmount = await myContract.methods.myMethod(123).estimateGas({gas: 5000000}); + * if(gasAmount == 5000000) { + * console.log('Method ran out of gas'); + * } + * ``` + * + * @param options - The options used for calling + * @param returnFormat - The data format you want the output in. + * @returns - The gas amount estimated. + */ + estimateGas(options?: NonPayableCallOptions, returnFormat?: ReturnFormat): Promise>; + /** + * Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. + * This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. + * Set the data field on `web3.eth.sendTransaction` options as the encodeABI() result and it is the same as calling the contract method with `contract.myMethod.send()`. + * + * Some use cases for encodeABI() include: preparing a smart contract transaction for a multi signature wallet, + * working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls. + * + * @returns - The encoded ABI byte code to send via a transaction or call. + */ + encodeABI(): string; + /** + * This method generates an access list for a transaction. You must specify a `from` address and `gas` if it’s not specified in options. + * + * @param options - The options used for createAccessList. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * + * ```ts + * const result = await MyContract.methods.myFunction().createAccessList(); + * console.log(result); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise; +} +export interface PayableMethodObject { + arguments: Inputs; + /** + * Will call a method and execute its smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state. + * + * ```ts + * // using the promise + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // MULTI-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(uint256 myNumber, string myString) { + * return (23456, "Hello!%"); + * } + * } + * + * // web3.js + * var MyContract = new web3.eth.Contract(abi, address); + * const result = MyContract.methods.myFunction().call() + * console.log(result) + * > Result { + * myNumber: '23456', + * myString: 'Hello!%', + * 0: '23456', // these are here as fallbacks if the name is not know or given + * 1: 'Hello!%' + * } + * + * + * // SINGLE-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(string myString) { + * return "Hello!%"; + * } + * } + * + * // web3.js + * const MyContract = new web3.eth.Contract(abi, address); + * const result = await MyContract.methods.myFunction().call(); + * console.log(result); + * > "Hello!%" + * ``` + * + * @param tx - The options used for calling. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns - The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices. + */ + call(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise; + /** + * Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state. + * + * ```ts + * await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * + * // using the event emitter + * const sendObj = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}) + * sendObj.on('transactionHash', function(hash){ + * ... + * }); + * + * sendObj.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * + * sendObj.on('receipt', function(receipt){ + * // receipt example + * console.log(receipt); + * > { + * "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", + * "transactionIndex": 0, + * "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", + * "blockNumber": 3, + * "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * "cumulativeGasUsed": 314159, + * "gasUsed": 30234, + * "events": { + * "MyEvent": { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * "MyOtherEvent": { + * ... + * }, + * "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array + * } + * } + * }); + * + * sendObj.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * ``` + * + * @param tx - The options used for sending. + * @returns - Returns a {@link PromiEvent} object resolved with transaction receipt. + */ + send(tx?: PayableTxOptions): Web3PromiEvent, SendTransactionEvents>; + /** + * Returns the amount of gas consumed by executing the method locally without creating a new transaction on the blockchain. + * The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be + * different when sending the transaction later, as the state of the smart contract can be different at that time. + * + * ```ts + * const gasAmount = await myContract.methods.myMethod(123).estimateGas({gas: 5000000}); + * if(gasAmount == 5000000) { + * console.log('Method ran out of gas'); + * } + * ``` + * + * @param options - The options used for calling + * @param returnFormat - The data format you want the output in. + * @returns - The gas amount estimated. + */ + estimateGas(options?: PayableCallOptions, returnFormat?: ReturnFormat): Promise>; + /** + * Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. + * This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. + * Set the data field on `web3.eth.sendTransaction` options as the encodeABI() result and it is the same as calling the contract method with `contract.myMethod.send()`. + * + * Some use cases for encodeABI() include: preparing a smart contract transaction for a multi signature wallet, + * working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls. + * + * @returns - The encoded ABI byte code to send via a transaction or call. + */ + encodeABI(): HexString; + /** + * This method generates an access list for a transaction. You must specify a `from` address and `gas` if it’s not specified in options. + * + * @param options - The options used for createAccessList. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * + * ```ts + * const result = await MyContract.methods.myFunction().createAccessList(); + * console.log(result); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + *``` + */ + createAccessList(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise; +} +export declare type Web3ContractContext = Partial>; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/types.d.ts.map new file mode 100644 index 0000000..26fcef1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACnE,OAAO,EACN,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,SAAS,EACT,OAAO,EACP,kBAAkB,EAClB,qBAAqB,EACrB,kBAAkB,EAClB,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAu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AAI,EAAE,OAAO,gBAAgB,CAAC;IAC9B,QAAQ,EAAE,OAAO,oBAAoB,CAAC;IACtC,eAAe,EAAE,OAAO,oBAAoB,CAAC;CAC7C,CACD,CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/utils.d.ts new file mode 100644 index 0000000..2badb13 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/utils.d.ts @@ -0,0 +1,45 @@ +import { TransactionForAccessList, AbiFunctionFragment, TransactionWithSenderAPI, TransactionCall, HexString, Address, NonPayableCallOptions, PayableCallOptions, ContractOptions } from 'web3-types'; +export declare const getSendTxParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + input?: string | undefined; + data?: string | undefined; + to?: string | undefined; + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => TransactionCall; +export declare const getEthTxCallParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + to?: string | undefined; + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => TransactionCall; +export declare const getEstimateGasParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => Partial; +export { isContractInitOptions } from 'web3-utils'; +export declare const isWeb3ContractContext: (options: unknown) => options is Partial>; +export declare const getCreateAccessListParams: ({ abi, params, options, contractOptions, }: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: ((NonPayableCallOptions | PayableCallOptions) & { + to?: string | undefined; + dataInputFill?: "data" | "input" | "both" | undefined; + }) | undefined; + contractOptions: ContractOptions; +}) => TransactionForAccessList; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/lib/types/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/utils.d.ts.map new file mode 100644 index 0000000..b1808d3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/lib/types/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAkBA,OAAO,EACN,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACxB,eAAe,EACf,SAAS,EACT,OAAO,EACP,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,MAAM,YAAY,CAAC;AA0BpB,eAAO,MAAM,eAAe;SAMtB,mBAAmB;YAChB,OAAO,EAAE;;;;;;;qBAOA,eAAe;MAC7B,eA2BH,CAAC;AAEF,eAAO,MAAM,kBAAkB;SAMzB,mBAAmB;YAChB,OAAO,EAAE;;;;;qBAKA,eAAe;MAC7B,eAsBH,CAAC;AAEF,eAAO,MAAM,oBAAoB;SAM3B,mBAAmB;YAChB,OAAO,EAAE;;;;qBAIA,eAAe;MAC7B,QAAQ,wBAAwB,CAiBnC,CAAC;AAEF,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEnD,eAAO,MAAM,qBAAqB,YAAa,OAAO;;;;GAEe,CAAC;AAEtE,eAAO,MAAM,yBAAyB;SAMhC,mBAAmB;YAChB,OAAO,EAAE;;;;;qBAKA,eAAe;MAC7B,wBA2BH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-contract/package.json b/test/merkletreejs/node_modules/web3-eth-contract/package.json new file mode 100644 index 0000000..751486b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/package.json @@ -0,0 +1,73 @@ +{ + "name": "web3-eth-contract", + "version": "4.1.4", + "description": "Web3 module to interact with Ethereum smart contracts.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ethereum/web3.js/tree/4.x/packages/web3-eth-contract", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --runInBand --forceExit --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --runInBand --forceExit", + "test:e2e:electron": "npx cypress run --headless --browser electron --env grep='ignore',invert=true", + "test:e2e:chrome": "npx cypress run --headless --browser chrome --env grep='ignore',invert=true", + "test:e2e:firefox": "npx cypress run --headless --browser firefox --env grep='ignore',invert=true" + }, + "dependencies": { + "web3-core": "^4.3.2", + "web3-errors": "^1.1.4", + "web3-eth": "^4.3.1", + "web3-eth-abi": "^4.1.4", + "web3-types": "^1.3.1", + "web3-utils": "^4.1.0", + "web3-validator": "^2.0.3" + }, + "devDependencies": { + "@humeris/espresso-shot": "^4.0.0", + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4", + "web3-eth-accounts": "^4.1.0" + }, + "gitHead": "b9b5fe0210da1a4ebf62e2b54f37a9c747bfa136" +} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/constant.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/constant.ts new file mode 100644 index 0000000..6be67ff --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/constant.ts @@ -0,0 +1,17 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export { ALL_EVENTS, ALL_EVENTS_ABI } from 'web3-eth'; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/contract.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/contract.ts new file mode 100644 index 0000000..197762c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/contract.ts @@ -0,0 +1,1222 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + Web3Context, + Web3EventEmitter, + Web3PromiEvent, + Web3ConfigEvent, + Web3SubscriptionManager, +} from 'web3-core'; +import { + ContractExecutionError, + ContractTransactionDataAndInputError, + SubscriptionError, + Web3ContractError, +} from 'web3-errors'; +import { + createAccessList, + call, + estimateGas, + getLogs, + sendTransaction, + decodeEventABI, + NewHeadsSubscription, + ALL_EVENTS, + ALL_EVENTS_ABI, + SendTransactionEvents, +} from 'web3-eth'; +import { + encodeEventSignature, + encodeFunctionSignature, + decodeContractErrorData, + isAbiErrorFragment, + isAbiEventFragment, + isAbiFunctionFragment, + jsonInterfaceMethodToString, +} from 'web3-eth-abi'; +import { + AbiConstructorFragment, + AbiErrorFragment, + AbiEventFragment, + AbiFragment, + AbiFunctionFragment, + ContractAbi, + ContractConstructorArgs, + ContractEvent, + ContractEvents, + ContractMethod, + ContractMethodInputParameters, + ContractMethodOutputParameters, + Address, + BlockNumberOrTag, + BlockTags, + Bytes, + EthExecutionAPI, + Filter, + FilterAbis, + HexString, + LogsInput, + Mutable, + ContractInitOptions, + NonPayableCallOptions, + PayableCallOptions, + DataFormat, + DEFAULT_RETURN_FORMAT, + Numbers, + Web3ValidationErrorObject, + EventLog, + ContractAbiWithSignature, + ContractOptions, +} from 'web3-types'; +import { format, isDataFormat, keccak256, toChecksumAddress } from 'web3-utils'; +import { + isNullish, + validator, + utils as validatorUtils, + ValidationSchemaInput, + Web3ValidatorError, +} from 'web3-validator'; +import { decodeMethodReturn, encodeEventABI, encodeMethodABI } from './encoding.js'; +import { LogsSubscription } from './log_subscription.js'; +import { + ContractEventOptions, + NonPayableMethodObject, + NonPayableTxOptions, + PayableMethodObject, + PayableTxOptions, + Web3ContractContext, +} from './types.js'; +import { + getCreateAccessListParams, + getEstimateGasParams, + getEthTxCallParams, + getSendTxParams, + isContractInitOptions, + isWeb3ContractContext, +} from './utils.js'; + +type ContractBoundMethod< + Abi extends AbiFunctionFragment, + Method extends ContractMethod = ContractMethod, +> = ( + ...args: Method['Inputs'] +) => Method['Abi']['stateMutability'] extends 'payable' | 'pure' + ? PayableMethodObject + : NonPayableMethodObject; + +export type ContractOverloadedMethodInputs> = NonNullable< + AbiArr extends readonly [] + ? undefined + : AbiArr extends readonly [infer A, ...infer R] + ? A extends AbiFunctionFragment + ? ContractMethodInputParameters | ContractOverloadedMethodInputs + : undefined + : undefined +>; + +export type ContractOverloadedMethodOutputs> = NonNullable< + AbiArr extends readonly [] + ? undefined + : AbiArr extends readonly [infer A, ...infer R] + ? A extends AbiFunctionFragment + ? ContractMethodOutputParameters | ContractOverloadedMethodOutputs + : undefined + : undefined +>; + +// To avoid circular dependency between types and encoding, declared these types here. +export type ContractMethodsInterface = { + [MethodAbi in FilterAbis< + Abi, + AbiFunctionFragment & { type: 'function' } + > as MethodAbi['name']]: ContractBoundMethod; + // To allow users to use method signatures + // eslint-disable-next-line @typescript-eslint/no-explicit-any +} & { [key: string]: ContractBoundMethod }; + +/** + * @hidden + * The event object can be accessed from `myContract.events.myEvent`. + * + * \> Remember: To subscribe to an event, your provider must have support for subscriptions. + * + * ```ts + * const subscription = await myContract.events.MyEvent([options]) + * ``` + * + * @param options - The options used to subscribe for the event + * @returns - A Promise resolved with {@link LogsSubscription} object + */ +export type ContractBoundEvent = (options?: ContractEventOptions) => LogsSubscription; + +// To avoid circular dependency between types and encoding, declared these types here. +export type ContractEventsInterface< + Abi extends ContractAbi, + Events extends ContractEvents = ContractEvents, +> = { + [Name in keyof Events | 'allEvents']: ContractBoundEvent; +} & { + [key: string]: ContractBoundEvent; +}; + +// To avoid circular dependency between types and encoding, declared these types here. +export type ContractEventEmitterInterface = { + [EventAbi in FilterAbis< + Abi, + AbiFunctionFragment & { type: 'event' } + > as EventAbi['name']]: ContractEvent['Inputs']; +}; + +type EventParameters = Parameters[2]; + +const contractSubscriptions = { + logs: LogsSubscription, + newHeads: NewHeadsSubscription, + newBlockHeaders: NewHeadsSubscription, +}; + +/** + * The class designed to interact with smart contracts on the Ethereum blockchain. + */ +export class Contract + extends Web3Context + implements Web3EventEmitter> +{ + /** + * The options `object` for the contract instance. `from`, `gas` and `gasPrice` are used as fallback values when sending transactions. + * + * ```ts + * myContract.options; + * > { + * address: '0x1234567890123456789012345678901234567891', + * jsonInterface: [...], + * from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', + * gasPrice: '10000000000000', + * gas: 1000000 + * } + * + * myContract.options.from = '0x1234567890123456789012345678901234567891'; // default from address + * myContract.options.gasPrice = '20000000000000'; // default gas price in wei + * myContract.options.gas = 5000000; // provide as fallback always 5M gas + * ``` + */ + + public readonly options: ContractOptions; + + /** + * Set to true if you want contracts' defaults to sync with global defaults. + */ + public syncWithContext = false; + + private _errorsInterface!: AbiErrorFragment[]; + private _jsonInterface!: ContractAbiWithSignature; + private _address?: Address; + private _functions: Record< + string, + { + signature: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + method: ContractBoundMethod; + } + > = {}; + private readonly _overloadedMethodAbis: Map; + private _methods!: ContractMethodsInterface; + private _events!: ContractEventsInterface; + /** + * Set property to `data`, `input`, or `both` to change the property of the contract being sent to the + * RPC provider when using contract methods. + * Default is `input` + */ + + private context?: Web3Context; + /** + * Creates a new contract instance with all its methods and events defined in its ABI provided. + * + * ```ts + * new web3.eth.Contract(jsonInterface[, address][, options]) + * ``` + * + * @param jsonInterface - The JSON interface for the contract to instantiate. + * @param address - The address of the smart contract to call. + * @param options - The options of the contract. Some are used as fallbacks for calls and transactions. + * @param context - The context of the contract used for customizing the behavior of the contract. + * @returns - The contract instance with all its methods and events. + * + * ```ts title="Example" + * var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', { + * from: '0x1234567890123456789012345678901234567891', // default from address + * gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case + * }); + * ``` + * + * To use the type safe interface for these contracts you have to include the ABI definitions in your Typescript project and then declare these as `const`. + * + * ```ts title="Example" + * const myContractAbi = [....] as const; // ABI definitions + * const myContract = new web3.eth.Contract(myContractAbi, '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'); + * ``` + */ + public constructor( + jsonInterface: Abi, + context?: Web3ContractContext | Web3Context, + returnFormat?: DataFormat, + ); + public constructor( + jsonInterface: Abi, + address?: Address, + contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, + returnFormat?: DataFormat, + ); + public constructor( + jsonInterface: Abi, + options?: ContractInitOptions, + contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, + returnFormat?: DataFormat, + ); + public constructor( + jsonInterface: Abi, + address: Address | undefined, + options: ContractInitOptions, + contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, + returnFormat?: DataFormat, + ); + public constructor( + jsonInterface: Abi, + addressOrOptionsOrContext?: + | Address + | ContractInitOptions + | Web3ContractContext + | Web3Context, + optionsOrContextOrReturnFormat?: + | ContractInitOptions + | Web3ContractContext + | Web3Context + | DataFormat, + contextOrReturnFormat?: Web3ContractContext | Web3Context | DataFormat, + returnFormat?: DataFormat, + ) { + // eslint-disable-next-line no-nested-ternary + const options = isContractInitOptions(addressOrOptionsOrContext) + ? addressOrOptionsOrContext + : isContractInitOptions(optionsOrContextOrReturnFormat) + ? optionsOrContextOrReturnFormat + : undefined; + + let contractContext; + if (isWeb3ContractContext(addressOrOptionsOrContext)) { + contractContext = addressOrOptionsOrContext; + } else if (isWeb3ContractContext(optionsOrContextOrReturnFormat)) { + contractContext = optionsOrContextOrReturnFormat; + } else { + contractContext = contextOrReturnFormat; + } + + let provider; + if ( + typeof addressOrOptionsOrContext === 'object' && + 'provider' in addressOrOptionsOrContext + ) { + provider = addressOrOptionsOrContext.provider; + } else if ( + typeof optionsOrContextOrReturnFormat === 'object' && + 'provider' in optionsOrContextOrReturnFormat + ) { + provider = optionsOrContextOrReturnFormat.provider; + } else if ( + typeof contextOrReturnFormat === 'object' && + 'provider' in contextOrReturnFormat + ) { + provider = contextOrReturnFormat.provider; + } else { + provider = Contract.givenProvider; + } + + super({ + ...contractContext, + provider, + registeredSubscriptions: contractSubscriptions, + }); + if ( + !isNullish(options) && + !isNullish(options.data) && + !isNullish(options.input) && + this.config.contractDataInputFill !== 'both' + ) + throw new ContractTransactionDataAndInputError({ + data: options.data as HexString, + input: options.input as HexString, + }); + this._overloadedMethodAbis = new Map(); + + // eslint-disable-next-line no-nested-ternary + const returnDataFormat = isDataFormat(contextOrReturnFormat) + ? contextOrReturnFormat + : isDataFormat(optionsOrContextOrReturnFormat) + ? optionsOrContextOrReturnFormat + : returnFormat ?? DEFAULT_RETURN_FORMAT; + const address = + typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined; + this.config.contractDataInputFill = + (options as ContractInitOptions)?.dataInputFill ?? + this.config.contractDataInputFill; + this._parseAndSetJsonInterface(jsonInterface, returnDataFormat); + + if (!isNullish(address)) { + this._parseAndSetAddress(address, returnDataFormat); + } + + this.options = { + address, + jsonInterface: this._jsonInterface, + gas: options?.gas ?? options?.gasLimit, + gasPrice: options?.gasPrice, + from: options?.from, + input: options?.input, + data: options?.data, + }; + + this.syncWithContext = (options as ContractInitOptions)?.syncWithContext ?? false; + if (contractContext instanceof Web3Context) { + this.subscribeToContextEvents(contractContext); + } + Object.defineProperty(this.options, 'address', { + set: (value: Address) => this._parseAndSetAddress(value, returnDataFormat), + get: () => this._address, + }); + + Object.defineProperty(this.options, 'jsonInterface', { + set: (value: ContractAbi) => this._parseAndSetJsonInterface(value, returnDataFormat), + get: () => this._jsonInterface, + }); + + if (contractContext instanceof Web3Context) { + contractContext.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.setConfig({ [event.name]: event.newValue }); + }); + } + } + + /** + * Subscribe to an event. + * + * ```ts + * await myContract.events.MyEvent([options]) + * ``` + * + * There is a special event `allEvents` that can be used to subscribe all events. + * + * ```ts + * await myContract.events.allEvents([options]) + * ``` + * + * @returns - When individual event is accessed will returns {@link ContractBoundEvent} object + */ + public get events() { + return this._events; + } + + /** + * Creates a transaction object for that method, which then can be `called`, `send`, `estimated`, `createAccessList` , or `ABI encoded`. + * + * The methods of this smart contract are available through: + * + * The name: `myContract.methods.myMethod(123)` + * The name with parameters: `myContract.methods['myMethod(uint256)'](123)` + * The signature `myContract.methods['0x58cf5f10'](123)` + * + * This allows calling functions with same name but different parameters from the JavaScript contract object. + * + * \> The method signature does not provide a type safe interface, so we recommend to use method `name` instead. + * + * ```ts + * // calling a method + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using a promise + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // or sending and using the events + * const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * sendObject.on('transactionHash', function(hash){ + * ... + * }); + * sendObject.on('receipt', function(receipt){ + * ... + * }); + * sendObject.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * sendObject.on('error', function(error, receipt) { + * ... + * }); + * ``` + * + * @returns - Either returns {@link PayableMethodObject} or {@link NonPayableMethodObject} based on the definitions of the ABI of that contract. + */ + public get methods() { + return this._methods; + } + + /** + * Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone. + * + * @returns - The new contract instance. + * + * ```ts + * const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress}); + * + * const contract2 = contract1.clone(); + * contract2.options.address = address2; + * + * (contract1.options.address !== contract2.options.address); + * > true + * ``` + */ + public clone() { + let newContract: Contract; + if (this.options.address) { + newContract = new Contract( + [...this._jsonInterface, ...this._errorsInterface] as unknown as Abi, + this.options.address, + { + gas: this.options.gas, + gasPrice: this.options.gasPrice, + from: this.options.from, + input: this.options.input, + data: this.options.data, + provider: this.currentProvider, + syncWithContext: this.syncWithContext, + dataInputFill: this.config.contractDataInputFill, + }, + this.getContextObject(), + ); + } else { + newContract = new Contract( + [...this._jsonInterface, ...this._errorsInterface] as unknown as Abi, + { + gas: this.options.gas, + gasPrice: this.options.gasPrice, + from: this.options.from, + input: this.options.input, + data: this.options.data, + provider: this.currentProvider, + syncWithContext: this.syncWithContext, + dataInputFill: this.config.contractDataInputFill, + }, + this.getContextObject(), + ); + } + if (this.context) newContract.subscribeToContextEvents(this.context); + + return newContract; + } + + /** + * Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance. + * + * ```ts + * myContract.deploy({ + * input: '0x12345...', // data keyword can be used, too. If input is used, data will be ignored. + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }, function(error, transactionHash){ ... }) + * .on('error', function(error){ ... }) + * .on('transactionHash', function(transactionHash){ ... }) + * .on('receipt', function(receipt){ + * console.log(receipt.contractAddress) // contains the new contract address + * }) + * .on('confirmation', function(confirmationNumber, receipt){ ... }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // When the data is already set as an option to the contract itself + * myContract.options.data = '0x12345...'; + * + * myContract.deploy({ + * arguments: [123, 'My String'] + * }) + * .send({ + * from: '0x1234567890123456789012345678901234567891', + * gas: 1500000, + * gasPrice: '30000000000000' + * }) + * .then(function(newContractInstance){ + * console.log(newContractInstance.options.address) // instance with the new contract address + * }); + * + * + * // Simply encoding + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .encodeABI(); + * > '0x12345...0000012345678765432' + * + * + * // Gas estimation + * myContract.deploy({ + * input: '0x12345...', + * arguments: [123, 'My String'] + * }) + * .estimateGas(function(err, gas){ + * console.log(gas); + * }); + * ``` + * + * @returns - The transaction object + */ + public deploy(deployOptions?: { + /** + * The byte code of the contract. + */ + data?: HexString; + input?: HexString; + /** + * The arguments which get passed to the constructor on deployment. + */ + arguments?: ContractConstructorArgs; + }) { + let abi = this._jsonInterface.find(j => j.type === 'constructor') as AbiConstructorFragment; + if (!abi) { + abi = { + type: 'constructor', + inputs: [], + stateMutability: '', + } as AbiConstructorFragment; + } + + const _input = format( + { format: 'bytes' }, + deployOptions?.input ?? this.options.input, + DEFAULT_RETURN_FORMAT, + ); + + const _data = format( + { format: 'bytes' }, + deployOptions?.data ?? this.options.data, + DEFAULT_RETURN_FORMAT, + ); + + if ((!_input || _input.trim() === '0x') && (!_data || _data.trim() === '0x')) { + throw new Web3ContractError('contract creation without any data provided.'); + } + + const args = deployOptions?.arguments ?? []; + + const contractOptions: ContractOptions = { ...this.options, input: _input, data: _data }; + const deployData = _input ?? _data; + return { + arguments: args, + send: ( + options?: PayableTxOptions, + ): Web3PromiEvent< + Contract, + SendTransactionEvents + > => { + const modifiedOptions = { ...options }; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._contractMethodDeploySend( + abi as AbiFunctionFragment, + args as unknown[], + modifiedOptions, + contractOptions, + ); + }, + estimateGas: async ( + options?: PayableCallOptions, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) => { + const modifiedOptions = { ...options }; + return this._contractMethodEstimateGas({ + abi: abi as AbiFunctionFragment, + params: args as unknown[], + returnFormat, + options: modifiedOptions, + contractOptions, + }); + }, + encodeABI: () => + encodeMethodABI( + abi as AbiFunctionFragment, + args as unknown[], + format({ format: 'bytes' }, deployData as Bytes, DEFAULT_RETURN_FORMAT), + ), + }; + } + + /** + * Gets past events for this contract. + * + * ```ts + * const events = await myContract.getPastEvents('MyEvent', { + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0, + * toBlock: 'latest' + * }); + * + * > [{ + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * },{ + * ... + * }] + * ``` + * + * @param eventName - The name of the event in the contract, or `allEvents` to get all events. + * @param filter - The filter options used to get events. + * @param returnFormat - Return format + * @returns - An array with the past event `Objects`, matching the given event name and filter. + */ + public async getPastEvents( + returnFormat?: ReturnFormat, + ): Promise<(string | EventLog)[]>; + public async getPastEvents( + eventName: keyof ContractEvents | 'allEvents' | 'ALLEVENTS', + returnFormat?: ReturnFormat, + ): Promise<(string | EventLog)[]>; + public async getPastEvents( + filter: Omit, + returnFormat?: ReturnFormat, + ): Promise<(string | EventLog)[]>; + public async getPastEvents( + eventName: keyof ContractEvents | 'allEvents' | 'ALLEVENTS', + filter: Omit, + returnFormat?: ReturnFormat, + ): Promise<(string | EventLog)[]>; + public async getPastEvents( + param1?: + | keyof ContractEvents + | 'allEvents' + | 'ALLEVENTS' + | Omit + | ReturnFormat, + param2?: Omit | ReturnFormat, + param3?: ReturnFormat, + ): Promise<(string | EventLog)[]> { + const eventName = typeof param1 === 'string' ? param1 : ALL_EVENTS; + + const options = + // eslint-disable-next-line no-nested-ternary + typeof param1 !== 'string' && !isDataFormat(param1) + ? param1 + : !isDataFormat(param2) + ? param2 + : {}; + + // eslint-disable-next-line no-nested-ternary + const returnFormat = isDataFormat(param1) + ? param1 + : isDataFormat(param2) + ? param2 + : param3 ?? DEFAULT_RETURN_FORMAT; + + const abi = + eventName === 'allEvents' || eventName === ALL_EVENTS + ? ALL_EVENTS_ABI + : (this._jsonInterface.find( + j => 'name' in j && j.name === eventName, + ) as AbiEventFragment & { signature: string }); + + if (!abi) { + throw new Web3ContractError(`Event ${eventName} not found.`); + } + + const { fromBlock, toBlock, topics, address } = encodeEventABI( + this.options, + abi, + options ?? {}, + ); + + const logs = await getLogs(this, { fromBlock, toBlock, topics, address }, returnFormat); + const decodedLogs = logs.map(log => + typeof log === 'string' + ? log + : decodeEventABI(abi, log as LogsInput, this._jsonInterface, returnFormat), + ); + + const filter = options?.filter ?? {}; + const filterKeys = Object.keys(filter); + + if (filterKeys.length > 0) { + return decodedLogs.filter(log => { + if (typeof log === 'string') return true; + + return filterKeys.every((key: string) => { + if (Array.isArray(filter[key])) { + return (filter[key] as Numbers[]).some( + (v: Numbers) => + String(log.returnValues[key]).toUpperCase() === + String(v).toUpperCase(), + ); + } + + const inputAbi = abi.inputs?.filter(input => input.name === key)[0]; + if (inputAbi?.indexed && inputAbi.type === 'string') { + const hashedIndexedString = keccak256(filter[key] as string); + if (hashedIndexedString === String(log.returnValues[key])) return true; + } + + return ( + String(log.returnValues[key]).toUpperCase() === + String(filter[key]).toUpperCase() + ); + }); + }); + } + + return decodedLogs; + } + + private _parseAndSetAddress(value?: Address, returnFormat: DataFormat = DEFAULT_RETURN_FORMAT) { + this._address = value + ? toChecksumAddress(format({ format: 'address' }, value, returnFormat)) + : value; + } + + private _parseAndSetJsonInterface( + abis: ContractAbi, + returnFormat: DataFormat = DEFAULT_RETURN_FORMAT, + ) { + this._functions = {}; + this._methods = {} as ContractMethodsInterface; + this._events = {} as ContractEventsInterface; + + let result: ContractAbi = []; + + const functionsAbi = abis.filter(abi => abi.type !== 'error'); + const errorsAbi = abis.filter(abi => + isAbiErrorFragment(abi), + ) as unknown as AbiErrorFragment[]; + + for (const a of functionsAbi) { + const abi: Mutable = { + ...a, + signature: '', + }; + + if (isAbiFunctionFragment(abi)) { + const methodName = jsonInterfaceMethodToString(abi); + const methodSignature = encodeFunctionSignature(methodName); + abi.signature = methodSignature; + + // make constant and payable backwards compatible + abi.constant = + abi.stateMutability === 'view' ?? + abi.stateMutability === 'pure' ?? + abi.constant; + + abi.payable = abi.stateMutability === 'payable' ?? abi.payable; + this._overloadedMethodAbis.set(abi.name, [ + ...(this._overloadedMethodAbis.get(abi.name) ?? []), + abi, + ]); + const abiFragment = this._overloadedMethodAbis.get(abi.name) ?? []; + const contractMethod = this._createContractMethod< + typeof abiFragment, + AbiErrorFragment + >(abiFragment, errorsAbi); + + this._functions[methodName] = { + signature: methodSignature, + method: contractMethod, + }; + + // We don't know a particular type of the Abi method so can't type check + this._methods[abi.name as keyof ContractMethodsInterface] = this._functions[ + methodName + ].method as never; + + // We don't know a particular type of the Abi method so can't type check + this._methods[methodName as keyof ContractMethodsInterface] = this._functions[ + methodName + ].method as never; + + // We don't know a particular type of the Abi method so can't type check + this._methods[methodSignature as keyof ContractMethodsInterface] = this + ._functions[methodName].method as never; + } else if (isAbiEventFragment(abi)) { + const eventName = jsonInterfaceMethodToString(abi); + const eventSignature = encodeEventSignature(eventName); + const event = this._createContractEvent(abi, returnFormat); + abi.signature = eventSignature; + + if (!(eventName in this._events) || abi.name === 'bound') { + // It's a private type and we don't want to expose it and no need to check + this._events[eventName as keyof ContractEventsInterface] = event as never; + } + // It's a private type and we don't want to expose it and no need to check + this._events[abi.name as keyof ContractEventsInterface] = event as never; + // It's a private type and we don't want to expose it and no need to check + this._events[eventSignature as keyof ContractEventsInterface] = event as never; + } + + result = [...result, abi]; + } + + this._events.allEvents = this._createContractEvent(ALL_EVENTS_ABI, returnFormat); + this._jsonInterface = [...result] as unknown as ContractAbiWithSignature; + this._errorsInterface = errorsAbi; + } + + // eslint-disable-next-line class-methods-use-this + private _getAbiParams(abi: AbiFunctionFragment, params: unknown[]): Array { + try { + return validatorUtils.transformJsonDataToAbiFormat(abi.inputs ?? [], params); + } catch (error) { + throw new Web3ContractError( + `Invalid parameters for method ${abi.name}: ${(error as Error).message}`, + ); + } + } + + private _createContractMethod( + abiArr: T, + errorsAbis: E[], + ): ContractBoundMethod { + const abi = abiArr[abiArr.length - 1]; + return (...params: unknown[]) => { + let abiParams!: Array; + const abis = this._overloadedMethodAbis.get(abi.name) ?? []; + let methodAbi: AbiFunctionFragment = abis[0]; + const internalErrorsAbis = errorsAbis; + + const arrayOfAbis: AbiFunctionFragment[] = abis.filter( + _abi => (_abi.inputs ?? []).length === params.length, + ); + + if (abis.length === 1 || arrayOfAbis.length === 0) { + abiParams = this._getAbiParams(methodAbi, params); + validator.validate(abi.inputs ?? [], abiParams); + } else { + const errors: Web3ValidationErrorObject[] = []; + + for (const _abi of arrayOfAbis) { + try { + abiParams = this._getAbiParams(_abi, params); + validator.validate( + _abi.inputs as unknown as ValidationSchemaInput, + abiParams, + ); + methodAbi = _abi; + break; + } catch (e) { + errors.push(e as Web3ValidationErrorObject); + } + } + if (errors.length === arrayOfAbis.length) { + throw new Web3ValidatorError(errors); + } + } + const methods = { + arguments: abiParams, + + call: async ( + options?: PayableCallOptions | NonPayableCallOptions, + block?: BlockNumberOrTag, + ) => + this._contractMethodCall( + methodAbi, + abiParams, + internalErrorsAbis, + options, + block, + ), + + send: (options?: PayableTxOptions | NonPayableTxOptions) => + this._contractMethodSend(methodAbi, abiParams, internalErrorsAbis, options), + + estimateGas: async ( + options?: PayableCallOptions | NonPayableCallOptions, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) => + this._contractMethodEstimateGas({ + abi: methodAbi, + params: abiParams, + returnFormat, + options, + }), + + encodeABI: () => encodeMethodABI(methodAbi, abiParams), + + createAccessList: async ( + options?: PayableCallOptions | NonPayableCallOptions, + block?: BlockNumberOrTag, + ) => + this._contractMethodCreateAccessList( + methodAbi, + abiParams, + internalErrorsAbis, + options, + block, + ), + }; + + if (methodAbi.stateMutability === 'payable') { + return methods as PayableMethodObject< + ContractOverloadedMethodInputs, + ContractOverloadedMethodOutputs + >; + } + return methods as NonPayableMethodObject< + ContractOverloadedMethodInputs, + ContractOverloadedMethodOutputs + >; + }; + } + + private async _contractMethodCall( + abi: AbiFunctionFragment, + params: unknown[], + errorsAbi: AbiErrorFragment[], + options?: Options, + block?: BlockNumberOrTag, + ) { + const tx = getEthTxCallParams({ + abi, + params, + options: { + ...options, + dataInputFill: this.config.contractDataInputFill, + }, + contractOptions: { + ...this.options, + from: this.options.from ?? this.config.defaultAccount, + }, + }); + try { + const result = await call(this, tx, block, DEFAULT_RETURN_FORMAT); + return decodeMethodReturn(abi, result); + } catch (error: unknown) { + if (error instanceof ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + decodeContractErrorData(errorsAbi, error.innerError); + } + throw error; + } + } + + private async _contractMethodCreateAccessList< + Options extends PayableCallOptions | NonPayableCallOptions, + >( + abi: AbiFunctionFragment, + params: unknown[], + errorsAbi: AbiErrorFragment[], + options?: Options, + block?: BlockNumberOrTag, + ) { + const tx = getCreateAccessListParams({ + abi, + params, + options: { ...options, dataInputFill: this.config.contractDataInputFill }, + contractOptions: { + ...this.options, + from: this.options.from ?? this.config.defaultAccount, + }, + }); + + try { + return createAccessList(this, tx, block, DEFAULT_RETURN_FORMAT); + } catch (error: unknown) { + if (error instanceof ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + decodeContractErrorData(errorsAbi, error.innerError); + } + throw error; + } + } + + private _contractMethodSend( + abi: AbiFunctionFragment, + params: unknown[], + errorsAbi: AbiErrorFragment[], + options?: Options, + contractOptions?: ContractOptions, + ) { + let modifiedContractOptions = contractOptions ?? this.options; + modifiedContractOptions = { + ...modifiedContractOptions, + input: undefined, + from: modifiedContractOptions.from ?? this.defaultAccount ?? undefined, + }; + const tx = getSendTxParams({ + abi, + params, + options: { ...options, dataInputFill: this.config.contractDataInputFill }, + contractOptions: modifiedContractOptions, + }); + + const transactionToSend = sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + contractAbi: this._jsonInterface, + }); + + // eslint-disable-next-line no-void + void transactionToSend.on('error', (error: unknown) => { + if (error instanceof ContractExecutionError) { + // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 + decodeContractErrorData(errorsAbi, error.innerError); + } + }); + return transactionToSend; + } + + private _contractMethodDeploySend( + abi: AbiFunctionFragment, + params: unknown[], + options?: Options, + contractOptions?: ContractOptions, + ) { + let modifiedContractOptions = contractOptions ?? this.options; + modifiedContractOptions = { + ...modifiedContractOptions, + from: modifiedContractOptions.from ?? this.defaultAccount ?? undefined, + }; + const tx = getSendTxParams({ + abi, + params, + options: { ...options, dataInputFill: this.config.contractDataInputFill }, + contractOptions: modifiedContractOptions, + }); + return sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { + transactionResolver: receipt => { + if (receipt.status === BigInt(0)) { + throw new Web3ContractError("code couldn't be stored", receipt); + } + + const newContract = this.clone(); + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + newContract.options.address = receipt.contractAddress; + return newContract; + }, + contractAbi: this._jsonInterface, + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + }); + } + + private async _contractMethodEstimateGas< + Options extends PayableCallOptions | NonPayableCallOptions, + ReturnFormat extends DataFormat, + >({ + abi, + params, + returnFormat, + options, + contractOptions, + }: { + abi: AbiFunctionFragment; + params: unknown[]; + returnFormat: ReturnFormat; + options?: Options; + contractOptions?: ContractOptions; + }) { + const tx = getEstimateGasParams({ + abi, + params, + options: { ...options, dataInputFill: this.config.contractDataInputFill }, + contractOptions: contractOptions ?? this.options, + }); + return estimateGas(this, tx, BlockTags.LATEST, returnFormat); + } + + // eslint-disable-next-line class-methods-use-this + private _createContractEvent( + abi: AbiEventFragment & { signature: HexString }, + returnFormat: DataFormat = DEFAULT_RETURN_FORMAT, + ): ContractBoundEvent { + return (...params: unknown[]) => { + const { topics, fromBlock } = encodeEventABI( + this.options, + abi, + params[0] as EventParameters, + ); + const sub = new LogsSubscription( + { + address: this.options.address, + topics, + abi, + jsonInterface: this._jsonInterface, + }, + { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + subscriptionManager: this.subscriptionManager as Web3SubscriptionManager< + unknown, + any + >, + returnFormat, + }, + ); + if (!isNullish(fromBlock)) { + // emit past events when fromBlock is defined + this.getPastEvents(abi.name, { fromBlock, topics }, returnFormat) + .then(logs => { + logs.forEach(log => sub.emit('data', log as EventLog)); + }) + .catch((error: Error) => { + sub.emit( + 'error', + new SubscriptionError('Failed to get past events.', error), + ); + }); + } + this.subscriptionManager?.addSubscription(sub).catch((error: Error) => { + sub.emit('error', new SubscriptionError('Failed to subscribe.', error)); + }); + + return sub; + }; + } + + protected subscribeToContextEvents(context: T): void { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const contractThis = this; + this.context = context; + + if (contractThis.syncWithContext) { + context.on(Web3ConfigEvent.CONFIG_CHANGE, event => { + contractThis.setConfig({ [event.name]: event.newValue }); + }); + } + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/encoding.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/encoding.ts new file mode 100644 index 0000000..aa06db4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/encoding.ts @@ -0,0 +1,174 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { format, isNullish, keccak256 } from 'web3-utils'; + +import { + AbiConstructorFragment, + AbiEventFragment, + AbiFunctionFragment, + Filter, + HexString, + Topic, + FMT_NUMBER, + FMT_BYTES, + ContractOptions, +} from 'web3-types'; + +import { + decodeParameters, + encodeEventSignature, + encodeFunctionSignature, + encodeParameter, + encodeParameters, + isAbiConstructorFragment, + jsonInterfaceMethodToString, +} from 'web3-eth-abi'; + +import { blockSchema, ALL_EVENTS } from 'web3-eth'; +import { Web3ContractError } from 'web3-errors'; + +export { decodeEventABI } from 'web3-eth'; + +type Writeable = { -readonly [P in keyof T]: T[P] }; +export const encodeEventABI = ( + { address }: ContractOptions, + event: AbiEventFragment & { signature: string }, + options?: Filter, +) => { + const topics = options?.topics; + const filter = options?.filter ?? {}; + const opts: Writeable = {}; + + if (!isNullish(options?.fromBlock)) { + opts.fromBlock = format(blockSchema.properties.number, options?.fromBlock, { + number: FMT_NUMBER.HEX, + bytes: FMT_BYTES.HEX, + }); + } + if (!isNullish(options?.toBlock)) { + opts.toBlock = format(blockSchema.properties.number, options?.toBlock, { + number: FMT_NUMBER.HEX, + bytes: FMT_BYTES.HEX, + }); + } + + if (topics && Array.isArray(topics)) { + opts.topics = [...topics] as Topic[]; + } else { + opts.topics = []; + // add event signature + if (event && !event.anonymous && ![ALL_EVENTS, 'allEvents'].includes(event.name)) { + opts.topics.push( + event.signature ?? encodeEventSignature(jsonInterfaceMethodToString(event)), + ); + } + + // add event topics (indexed arguments) + if (![ALL_EVENTS, 'allEvents'].includes(event.name) && event.inputs) { + for (const input of event.inputs) { + if (!input.indexed) { + continue; + } + + const value = filter[input.name]; + if (!value) { + // eslint-disable-next-line no-null/no-null + opts.topics.push(null); + continue; + } + + // TODO: https://github.com/ethereum/web3.js/issues/344 + // TODO: deal properly with components + if (Array.isArray(value)) { + opts.topics.push(value.map(v => encodeParameter(input.type, v))); + } else if (input.type === 'string') { + opts.topics.push(keccak256(value as string)); + } else { + opts.topics.push(encodeParameter(input.type, value)); + } + } + } + } + + if (!opts.topics.length) delete opts.topics; + + if (address) { + opts.address = address.toLowerCase(); + } + + return opts; +}; + +export const encodeMethodABI = ( + abi: AbiFunctionFragment | AbiConstructorFragment, + args: unknown[], + deployData?: HexString, +) => { + const inputLength = Array.isArray(abi.inputs) ? abi.inputs.length : 0; + if (inputLength !== args.length) { + throw new Web3ContractError( + `The number of arguments is not matching the methods required number. You need to pass ${inputLength} arguments.`, + ); + } + + const params = encodeParameters(Array.isArray(abi.inputs) ? abi.inputs : [], args).replace( + '0x', + '', + ); + + if (isAbiConstructorFragment(abi)) { + if (!deployData) + throw new Web3ContractError( + 'The contract has no contract data option set. This is necessary to append the constructor parameters.', + ); + + if (!deployData.startsWith('0x')) { + return `0x${deployData}${params}`; + } + + return `${deployData}${params}`; + } + + return `${encodeFunctionSignature(abi)}${params}`; +}; + +export const decodeMethodReturn = (abi: AbiFunctionFragment, returnValues?: HexString) => { + // If it was constructor then we need to return contract address + if (abi.type === 'constructor') { + return returnValues; + } + + if (!returnValues) { + // Using "null" value intentionally to match legacy behavior + // eslint-disable-next-line no-null/no-null + return null; + } + + const value = returnValues.length >= 2 ? returnValues.slice(2) : returnValues; + if (!abi.outputs) { + // eslint-disable-next-line no-null/no-null + return null; + } + const result = decodeParameters([...abi.outputs], value); + + if (result.__length__ === 1) { + return result[0]; + } + + return result; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/index.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/index.ts new file mode 100644 index 0000000..2293753 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/index.ts @@ -0,0 +1,51 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The `web3.eth.Contract` object makes it easy to interact with smart contracts on the Ethereum blockchain. + * When you create a new contract object you give it the JSON interface of the respective smart contract and + * web3 will auto convert all calls into low level ABI calls over RPC for you. + * This allows you to interact with smart contracts as if they were JavaScript objects. + * + * To use it standalone: + * + * ```ts + * const Contract = require('web3-eth-contract'); + * + * // set provider for all later instances to use + * Contract.setProvider('ws://localhost:8546'); + * + * const contract = new Contract(jsonInterface, address); + * + * contract.methods.somFunc().send({from: ....}) + * .on('receipt', function(){ + * ... + * }); + * ``` + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Contract } from './contract.js'; + +export * from './encoding.js'; + +export * from './contract.js'; +export * from './log_subscription.js'; +export * from './types.js'; + +export default Contract; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/log_subscription.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/log_subscription.ts new file mode 100644 index 0000000..6ace1e1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/log_subscription.ts @@ -0,0 +1,164 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + AbiEventFragment, + LogsInput, + HexString, + Topic, + DataFormat, + EventLog, + ContractAbiWithSignature, +} from 'web3-types'; +import { Web3RequestManager, Web3Subscription, Web3SubscriptionManager } from 'web3-core'; +import { decodeEventABI } from 'web3-eth'; + +/** + * LogSubscription to be used to subscribe to events logs. + * + * Following events are supported and can be accessed with either {@link LogsSubscription.once} or ${@link LogsSubscription.on} methods. + * + * - **connected**: Emitted when the subscription is connected. + * - **data**: Fires on each incoming event with the event object as argument. + * - **changed**: Fires on each event which was removed from the blockchain. The event will have the additional property `removed: true`. + * - **error**: Fires on each error. + * + * ```ts + * const subscription = await myContract.events.MyEvent({ + * filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23 + * fromBlock: 0 + * }); + * + * subscription.on("connected", function(subscriptionId){ + * console.log(subscriptionId); + * }); + * + * subscription.on('data', function(event){ + * console.log(event); // same results as the optional callback above + * }); + * + * subscription.on('changed', function(event){ + * // remove event from local database + * }) + * + * subscription.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * + * // event output example + * > { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * } + * ``` + */ +export class LogsSubscription extends Web3Subscription< + { + data: EventLog; + changed: EventLog & { removed: true }; + }, + // eslint-disable-next-line @typescript-eslint/ban-types + { address?: HexString; topics?: (Topic | Topic[] | null)[]; abi: AbiEventFragment } +> { + /** + * Address of tye contract + */ + public readonly address?: HexString; + + /** + * The list of topics subscribed + */ + // eslint-disable-next-line @typescript-eslint/ban-types + public readonly topics?: (Topic | Topic[] | null)[]; + + /** + * The {@doclink glossary/json_interface | JSON Interface} of the event. + */ + public readonly abi: AbiEventFragment & { signature: HexString }; + + public readonly jsonInterface: ContractAbiWithSignature; + + public constructor( + args: { + address?: HexString; + // eslint-disable-next-line @typescript-eslint/ban-types + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { signature: HexString }; + jsonInterface: ContractAbiWithSignature; + }, + options: { subscriptionManager: Web3SubscriptionManager; returnFormat?: DataFormat }, + ); + /** + * @deprecated This constructor overloading should not be used + */ + public constructor( + args: { + address?: HexString; + // eslint-disable-next-line @typescript-eslint/ban-types + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { signature: HexString }; + jsonInterface: ContractAbiWithSignature; + }, + options: { requestManager: Web3RequestManager; returnFormat?: DataFormat }, + ); + public constructor( + args: { + address?: HexString; + // eslint-disable-next-line @typescript-eslint/ban-types + topics?: (Topic | Topic[] | null)[]; + abi: AbiEventFragment & { signature: HexString }; + jsonInterface: ContractAbiWithSignature; + }, + options: ( + | { subscriptionManager: Web3SubscriptionManager } + | { requestManager: Web3RequestManager } + ) & { + returnFormat?: DataFormat; + }, + ) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + super(args, options as any); + + this.address = args.address; + this.topics = args.topics; + this.abi = args.abi; + this.jsonInterface = args.jsonInterface; + } + + protected _buildSubscriptionParams() { + return ['logs', { address: this.address, topics: this.topics }]; + } + + protected formatSubscriptionResult(data: EventLog) { + return decodeEventABI(this.abi, data as LogsInput, this.jsonInterface, super.returnFormat); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/types.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/types.ts new file mode 100644 index 0000000..fc66826 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/types.ts @@ -0,0 +1,439 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3ContextInitOptions, Web3PromiEvent } from 'web3-core'; +import { + AccessListResult, + BlockNumberOrTag, + EthExecutionAPI, + HexString, + Numbers, + TransactionReceipt, + NonPayableCallOptions, + PayableCallOptions, + DataFormat, + DEFAULT_RETURN_FORMAT, + FormatType, +} from 'web3-types'; +import { NewHeadsSubscription, SendTransactionEvents } from 'web3-eth'; +import { LogsSubscription } from './log_subscription.js'; + +export type NonPayableTxOptions = NonPayableCallOptions; +export type PayableTxOptions = PayableCallOptions; +export { ContractAbiWithSignature, EventLog, ContractOptions } from 'web3-types'; + +export interface ContractEventOptions { + /** + * Let you filter events by indexed parameters, e.g. `{filter: {myNumber: [12,13]}}` means all events where `myNumber` is `12` or `13`. + */ + filter?: Record; + /** + * The block number (greater than or equal to) from which to get events on. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized` can also be used. For specific range use {@link Contract.getPastEvents}. + */ + fromBlock?: BlockNumberOrTag; + /** + * This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically. Each topic can also be a nested array of topics that behaves as `or` operation between the given nested topics. + */ + topics?: string[]; +} + +export interface NonPayableMethodObject { + arguments: Inputs; + /** + * This will call a method and execute its smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state. + * + * ```ts + * // using the promise + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // MULTI-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(uint256 myNumber, string myString) { + * return (23456, "Hello!%"); + * } + * } + * + * // web3.js + * var MyContract = new web3.eth.Contract(abi, address); + * const result = MyContract.methods.myFunction().call() + * console.log(result) + * > Result { + * myNumber: '23456', + * myString: 'Hello!%', + * 0: '23456', // these are here as fallbacks if the name is not know or given + * 1: 'Hello!%' + * } + * + * + * // SINGLE-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(string myString) { + * return "Hello!%"; + * } + * } + * + * // web3.js + * const MyContract = new web3.eth.Contract(abi, address); + * const result = await MyContract.methods.myFunction().call(); + * console.log(result); + * > "Hello!%" + * ``` + * + * @param tx - The options used for calling. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns - The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices. + */ + + call( + tx?: NonPayableCallOptions, + block?: BlockNumberOrTag, + ): Promise; + + /** + * This will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state. + * + * ```ts + * await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * + * // using the event emitter + * const sendObj = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}) + * sendObj.on('transactionHash', function(hash){ + * ... + * }); + * + * sendObj.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * + * sendObj.on('receipt', function(receipt){ + * // receipt example + * console.log(receipt); + * > { + * "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", + * "transactionIndex": 0, + * "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", + * "blockNumber": 3, + * "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * "cumulativeGasUsed": 314159, + * "gasUsed": 30234, + * "events": { + * "MyEvent": { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * "MyOtherEvent": { + * ... + * }, + * "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array + * } + * } + * }); + * + * sendObj.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * ``` + * + * @param tx - The options used for sending. + * @returns - Returns a {@link PromiEvent} resolved with transaction receipt. + */ + send( + tx?: NonPayableTxOptions, + ): Web3PromiEvent< + FormatType, + SendTransactionEvents + >; + + /** + * Returns the amount of gas consumed by executing the method locally without creating a new transaction on the blockchain. + * The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be + * different when sending the transaction later, as the state of the smart contract can be different at that time. + * + * ```ts + * const gasAmount = await myContract.methods.myMethod(123).estimateGas({gas: 5000000}); + * if(gasAmount == 5000000) { + * console.log('Method ran out of gas'); + * } + * ``` + * + * @param options - The options used for calling + * @param returnFormat - The data format you want the output in. + * @returns - The gas amount estimated. + */ + estimateGas( + options?: NonPayableCallOptions, + returnFormat?: ReturnFormat, + ): Promise>; + + /** + * Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. + * This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. + * Set the data field on `web3.eth.sendTransaction` options as the encodeABI() result and it is the same as calling the contract method with `contract.myMethod.send()`. + * + * Some use cases for encodeABI() include: preparing a smart contract transaction for a multi signature wallet, + * working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls. + * + * @returns - The encoded ABI byte code to send via a transaction or call. + */ + encodeABI(): string; + + /** + * This method generates an access list for a transaction. You must specify a `from` address and `gas` if it’s not specified in options. + * + * @param options - The options used for createAccessList. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * + * ```ts + * const result = await MyContract.methods.myFunction().createAccessList(); + * console.log(result); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList( + tx?: NonPayableCallOptions, + block?: BlockNumberOrTag, + ): Promise; +} + +export interface PayableMethodObject { + arguments: Inputs; + /** + * Will call a method and execute its smart contract method in the EVM without sending any transaction. Note calling cannot alter the smart contract state. + * + * ```ts + * // using the promise + * const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * // MULTI-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(uint256 myNumber, string myString) { + * return (23456, "Hello!%"); + * } + * } + * + * // web3.js + * var MyContract = new web3.eth.Contract(abi, address); + * const result = MyContract.methods.myFunction().call() + * console.log(result) + * > Result { + * myNumber: '23456', + * myString: 'Hello!%', + * 0: '23456', // these are here as fallbacks if the name is not know or given + * 1: 'Hello!%' + * } + * + * + * // SINGLE-ARGUMENT RETURN: + * // Solidity + * contract MyContract { + * function myFunction() returns(string myString) { + * return "Hello!%"; + * } + * } + * + * // web3.js + * const MyContract = new web3.eth.Contract(abi, address); + * const result = await MyContract.methods.myFunction().call(); + * console.log(result); + * > "Hello!%" + * ``` + * + * @param tx - The options used for calling. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns - The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices. + */ + call( + tx?: PayableCallOptions, + block?: BlockNumberOrTag, + ): Promise; + + /** + * Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state. + * + * ```ts + * await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}); + * + * + * // using the event emitter + * const sendObj = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}) + * sendObj.on('transactionHash', function(hash){ + * ... + * }); + * + * sendObj.on('confirmation', function(confirmationNumber, receipt){ + * ... + * }); + * + * sendObj.on('receipt', function(receipt){ + * // receipt example + * console.log(receipt); + * > { + * "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b", + * "transactionIndex": 0, + * "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46", + * "blockNumber": 3, + * "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * "cumulativeGasUsed": 314159, + * "gasUsed": 30234, + * "events": { + * "MyEvent": { + * returnValues: { + * myIndexedParam: 20, + * myOtherIndexedParam: '0x123456789...', + * myNonIndexParam: 'My String' + * }, + * raw: { + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * }, + * event: 'MyEvent', + * signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * "MyOtherEvent": { + * ... + * }, + * "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array + * } + * } + * }); + * + * sendObj.on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt. + * ... + * }); + * ``` + * + * @param tx - The options used for sending. + * @returns - Returns a {@link PromiEvent} object resolved with transaction receipt. + */ + send( + tx?: PayableTxOptions, + ): Web3PromiEvent< + FormatType, + SendTransactionEvents + >; + + /** + * Returns the amount of gas consumed by executing the method locally without creating a new transaction on the blockchain. + * The returned amount can be used as a gas estimate for executing the transaction publicly. The actual gas used can be + * different when sending the transaction later, as the state of the smart contract can be different at that time. + * + * ```ts + * const gasAmount = await myContract.methods.myMethod(123).estimateGas({gas: 5000000}); + * if(gasAmount == 5000000) { + * console.log('Method ran out of gas'); + * } + * ``` + * + * @param options - The options used for calling + * @param returnFormat - The data format you want the output in. + * @returns - The gas amount estimated. + */ + estimateGas( + options?: PayableCallOptions, + returnFormat?: ReturnFormat, + ): Promise>; + + /** + * Encodes the ABI for this method. The resulting hex string is 32-bit function signature hash plus the passed parameters in Solidity tightly packed format. + * This can be used to send a transaction, call a method, or pass it into another smart contract’s method as arguments. + * Set the data field on `web3.eth.sendTransaction` options as the encodeABI() result and it is the same as calling the contract method with `contract.myMethod.send()`. + * + * Some use cases for encodeABI() include: preparing a smart contract transaction for a multi signature wallet, + * working with offline wallets and cold storage and creating transaction payload for complex smart contract proxy calls. + * + * @returns - The encoded ABI byte code to send via a transaction or call. + */ + encodeABI(): HexString; + + /** + * This method generates an access list for a transaction. You must specify a `from` address and `gas` if it’s not specified in options. + * + * @param options - The options used for createAccessList. + * @param block - If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as `earliest`, `latest`, `pending`, `safe` or `finalized can also be used. Useful for requesting data from or replaying transactions in past blocks. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * + * ```ts + * const result = await MyContract.methods.myFunction().createAccessList(); + * console.log(result); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + *``` + */ + createAccessList(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise; +} + +export type Web3ContractContext = Partial< + Web3ContextInitOptions< + EthExecutionAPI, + { + logs: typeof LogsSubscription; + newHeads: typeof NewHeadsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; + } + > +>; diff --git a/test/merkletreejs/node_modules/web3-eth-contract/src/utils.ts b/test/merkletreejs/node_modules/web3-eth-contract/src/utils.ts new file mode 100644 index 0000000..f3d4552 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-contract/src/utils.ts @@ -0,0 +1,213 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3ContractError } from 'web3-errors'; +import { + TransactionForAccessList, + AbiFunctionFragment, + TransactionWithSenderAPI, + TransactionCall, + HexString, + Address, + NonPayableCallOptions, + PayableCallOptions, + ContractOptions, +} from 'web3-types'; +import { isNullish, mergeDeep, isContractInitOptions } from 'web3-utils'; +import { encodeMethodABI } from './encoding.js'; +import { Web3ContractContext } from './types.js'; + +const dataInputEncodeMethodHelper = ( + txParams: TransactionCall | TransactionForAccessList, + abi: AbiFunctionFragment, + params: unknown[], + dataInputFill?: 'data' | 'input' | 'both', +): { data?: HexString; input?: HexString } => { + const tx: { data?: HexString; input?: HexString } = {}; + if (!isNullish(txParams.data) || dataInputFill === 'both') { + tx.data = encodeMethodABI(abi, params, (txParams.data ?? txParams.input) as HexString); + } + if (!isNullish(txParams.input) || dataInputFill === 'both') { + tx.input = encodeMethodABI(abi, params, (txParams.input ?? txParams.data) as HexString); + } + // if input and data is empty, use web3config default + if (isNullish(tx.input) && isNullish(tx.data)) { + tx[dataInputFill as 'data' | 'input'] = encodeMethodABI(abi, params); + } + + return { data: tx.data as HexString, input: tx.input as HexString }; +}; + +export const getSendTxParams = ({ + abi, + params, + options, + contractOptions, +}: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: (PayableCallOptions | NonPayableCallOptions) & { + input?: HexString; + data?: HexString; + to?: Address; + dataInputFill?: 'input' | 'data' | 'both'; + }; + contractOptions: ContractOptions; +}): TransactionCall => { + const deploymentCall = + options?.input ?? options?.data ?? contractOptions.input ?? contractOptions.data; + if (!deploymentCall && !options?.to && !contractOptions.address) { + throw new Web3ContractError('Contract address not specified'); + } + + if (!options?.from && !contractOptions.from) { + throw new Web3ContractError('Contract "from" address not specified'); + } + let txParams = mergeDeep( + { + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, + options as unknown as Record, + ) as unknown as TransactionCall; + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill); + txParams = { ...txParams, data: dataInput.data, input: dataInput.input }; + + return txParams; +}; + +export const getEthTxCallParams = ({ + abi, + params, + options, + contractOptions, +}: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: (PayableCallOptions | NonPayableCallOptions) & { + to?: Address; + dataInputFill?: 'input' | 'data' | 'both'; + }; + contractOptions: ContractOptions; +}): TransactionCall => { + if (!options?.to && !contractOptions.address) { + throw new Web3ContractError('Contract address not specified'); + } + let txParams = mergeDeep( + { + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, + options as unknown as Record, + ) as unknown as TransactionCall; + + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill); + txParams = { ...txParams, data: dataInput.data, input: dataInput.input }; + + return txParams; +}; + +export const getEstimateGasParams = ({ + abi, + params, + options, + contractOptions, +}: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: (PayableCallOptions | NonPayableCallOptions) & { + dataInputFill?: 'input' | 'data' | 'both'; + }; + contractOptions: ContractOptions; +}): Partial => { + let txParams = mergeDeep( + { + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + data: contractOptions.data, + }, + options as unknown as Record, + ) as unknown as TransactionCall; + + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill); + txParams = { ...txParams, data: dataInput.data, input: dataInput.input }; + + return txParams as TransactionWithSenderAPI; +}; + +export { isContractInitOptions } from 'web3-utils'; + +export const isWeb3ContractContext = (options: unknown): options is Web3ContractContext => + typeof options === 'object' && !isNullish(options) && + Object.keys(options).length !== 0 && !isContractInitOptions(options); + +export const getCreateAccessListParams = ({ + abi, + params, + options, + contractOptions, +}: { + abi: AbiFunctionFragment; + params: unknown[]; + options?: (PayableCallOptions | NonPayableCallOptions) & { + to?: Address; + dataInputFill?: 'input' | 'data' | 'both'; + }; + contractOptions: ContractOptions; +}): TransactionForAccessList => { + if (!options?.to && !contractOptions.address) { + throw new Web3ContractError('Contract address not specified'); + } + + if (!options?.from && !contractOptions.from) { + throw new Web3ContractError('Contract "from" address not specified'); + } + + let txParams = mergeDeep( + { + to: contractOptions.address, + gas: contractOptions.gas, + gasPrice: contractOptions.gasPrice, + from: contractOptions.from, + input: contractOptions.input, + maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas, + maxFeePerGas: contractOptions.maxFeePerGas, + data: contractOptions.data, + }, + options as unknown as Record, + ) as unknown as TransactionForAccessList; + + const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill); + txParams = { ...txParams, data: dataInput.data, input: dataInput.input }; + + return txParams; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/LICENSE b/test/merkletreejs/node_modules/web3-eth-ens/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth-ens/README.md b/test/merkletreejs/node_modules/web3-eth-ens/README.md new file mode 100644 index 0000000..ea4f306 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - ENS + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth-ens` This package has ENS functions for interacting with Ethereum Name Service. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth-ens) or using [Yarn](https://yarnpkg.com/package/web3-eth-ens) + +### Using NPM + +```bash +npm install web3-eth-ens +``` + +### Using Yarn + +```bash +yarn add web3-eth-ens +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth-ens +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-ens%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth-ens +[downloads-image]: https://img.shields.io/npm/dm/web3-eth-ens?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.d.ts new file mode 100644 index 0000000..537af7d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.d.ts @@ -0,0 +1,125 @@ +export declare const ENSRegistryAbi: readonly [{ + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "label"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }]; + readonly name: "NewOwner"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "resolver"; + readonly type: "address"; + }]; + readonly name: "NewResolver"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }]; + readonly name: "Transfer"; + readonly type: "event"; +}, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "recordExists"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "resolver"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "ttl"; + readonly outputs: readonly [{ + readonly internalType: "uint64"; + readonly name: ""; + readonly type: "uint64"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}]; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.js new file mode 100644 index 0000000..af1dd7f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.js @@ -0,0 +1,186 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ENSRegistryAbi = void 0; +// https://github.com/ensdomains/ens-contracts/blob/master/contracts/registry/ENSRegistry.sol +exports.ENSRegistryAbi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'bytes32', + name: 'label', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'owner', + type: 'address', + }, + ], + name: 'NewOwner', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'resolver', + type: 'address', + }, + ], + name: 'NewResolver', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'owner', + type: 'address', + }, + ], + name: 'Transfer', + type: 'event', + }, + { + inputs: [ + { + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + internalType: 'address', + name: 'operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'owner', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'recordExists', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'resolver', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'ttl', + outputs: [ + { + internalType: 'uint64', + name: '', + type: 'uint64', + }, + ], + stateMutability: 'view', + type: 'function', + }, +]; +//# sourceMappingURL=ENSRegistry.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.js.map new file mode 100644 index 0000000..3813b2f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/ENSRegistry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ENSRegistry.js","sourceRoot":"","sources":["../../../../src/abi/ens/ENSRegistry.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6FAA6F;AAChF,QAAA,cAAc,GAAG;IAC7B;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,KAAK;gBACd,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,UAAU;QAChB,IAAI,EAAE,OAAO;KACb;IACD;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,KAAK;gBACd,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,aAAa;QACnB,IAAI,EAAE,OAAO;KACb;IACD;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aAC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ACf;SACD;QACD,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,SAAS;aACf;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;IACD;QACC,MAAM,EAAE;YACP;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,KAAK;QACX,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,QAAQ;gBACtB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,QAAQ;aACd;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;CACQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.d.ts new file mode 100644 index 0000000..c962b0a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.d.ts @@ -0,0 +1,443 @@ +export declare const PublicResolverAbi: readonly [{ + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "a"; + readonly type: "address"; + }]; + readonly name: "AddrChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "newAddress"; + readonly type: "bytes"; + }]; + readonly name: "AddressChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "bool"; + readonly name: "approved"; + readonly type: "bool"; + }]; + readonly name: "ApprovalForAll"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "hash"; + readonly type: "bytes"; + }]; + readonly name: "ContenthashChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "name"; + readonly type: "bytes"; + }, { + readonly indexed: false; + readonly internalType: "uint16"; + readonly name: "resource"; + readonly type: "uint16"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "record"; + readonly type: "bytes"; + }]; + readonly name: "DNSRecordChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "name"; + readonly type: "bytes"; + }, { + readonly indexed: false; + readonly internalType: "uint16"; + readonly name: "resource"; + readonly type: "uint16"; + }]; + readonly name: "DNSRecordDeleted"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "DNSZoneCleared"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "lastzonehash"; + readonly type: "bytes"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "zonehash"; + readonly type: "bytes"; + }]; + readonly name: "DNSZonehashChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "implementer"; + readonly type: "address"; + }]; + readonly name: "InterfaceChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "name"; + readonly type: "string"; + }]; + readonly name: "NameChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly name: "PubkeyChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "string"; + readonly name: "indexedKey"; + readonly type: "string"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }]; + readonly name: "TextChanged"; + readonly type: "event"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "contentTypes"; + readonly type: "uint256"; + }]; + readonly name: "ABI"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }, { + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "addr"; + readonly outputs: readonly [{ + readonly internalType: "address payable"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }]; + readonly name: "addr"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "contenthash"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "name"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint16"; + readonly name: "resource"; + readonly type: "uint16"; + }]; + readonly name: "dnsRecord"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "name"; + readonly type: "bytes32"; + }]; + readonly name: "hasDNSRecords"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }]; + readonly name: "interfaceImplementer"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "account"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "name"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "pubkey"; + readonly outputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }]; + readonly name: "supportsInterface"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }]; + readonly name: "text"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "zonehash"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}]; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.js new file mode 100644 index 0000000..5b89ba7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.js @@ -0,0 +1,596 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PublicResolverAbi = void 0; +// https://github.com/ensdomains/ens-contracts/blob/master/contracts/resolvers/PublicResolver.sol +exports.PublicResolverAbi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'a', + type: 'address', + }, + ], + name: 'AddrChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'uint256', + name: 'coinType', + type: 'uint256', + }, + { + indexed: false, + internalType: 'bytes', + name: 'newAddress', + type: 'bytes', + }, + ], + name: 'AddressChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + indexed: true, + internalType: 'address', + name: 'operator', + type: 'address', + }, + { + indexed: false, + internalType: 'bool', + name: 'approved', + type: 'bool', + }, + ], + name: 'ApprovalForAll', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'hash', + type: 'bytes', + }, + ], + name: 'ContenthashChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'name', + type: 'bytes', + }, + { + indexed: false, + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + { + indexed: false, + internalType: 'bytes', + name: 'record', + type: 'bytes', + }, + ], + name: 'DNSRecordChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'name', + type: 'bytes', + }, + { + indexed: false, + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + ], + name: 'DNSRecordDeleted', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'DNSZoneCleared', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'lastzonehash', + type: 'bytes', + }, + { + indexed: false, + internalType: 'bytes', + name: 'zonehash', + type: 'bytes', + }, + ], + name: 'DNSZonehashChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + { + indexed: false, + internalType: 'address', + name: 'implementer', + type: 'address', + }, + ], + name: 'InterfaceChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'string', + name: 'name', + type: 'string', + }, + ], + name: 'NameChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes32', + name: 'x', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes32', + name: 'y', + type: 'bytes32', + }, + ], + name: 'PubkeyChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'string', + name: 'indexedKey', + type: 'string', + }, + { + indexed: false, + internalType: 'string', + name: 'key', + type: 'string', + }, + ], + name: 'TextChanged', + type: 'event', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'uint256', + name: 'contentTypes', + type: 'uint256', + }, + ], + name: 'ABI', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'addr', + outputs: [ + { + internalType: 'address payable', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'uint256', + name: 'coinType', + type: 'uint256', + }, + ], + name: 'addr', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'contenthash', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'name', + type: 'bytes32', + }, + { + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + ], + name: 'dnsRecord', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'name', + type: 'bytes32', + }, + ], + name: 'hasDNSRecords', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + ], + name: 'interfaceImplementer', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: 'account', + type: 'address', + }, + { + internalType: 'address', + name: 'operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'name', + outputs: [ + { + internalType: 'string', + name: '', + type: 'string', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'pubkey', + outputs: [ + { + internalType: 'bytes32', + name: 'x', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'y', + type: 'bytes32', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + ], + name: 'supportsInterface', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'string', + name: 'key', + type: 'string', + }, + ], + name: 'text', + outputs: [ + { + internalType: 'string', + name: '', + type: 'string', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'zonehash', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, +]; +//# sourceMappingURL=PublicResolver.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.js.map new file mode 100644 index 0000000..c9c179d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/abi/ens/PublicResolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PublicResolver.js","sourceRoot":"","sources":["../../../../src/abi/ens/PublicResolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,iGAAiG;AACpF,QAAA,iBAAiB,GAAG;IAChC;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,KAAK;gBACd,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,GAAG;gBACT,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,aAAa;QACnB,IAAI,EAAE,OAAO;KACb;IACD;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,KAAK;gBACd,YAAY,EAAE,S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AAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,OAAO;gBACrB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,OAAO;aACb;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;CACQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.d.ts new file mode 100644 index 0000000..ac18cb7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.d.ts @@ -0,0 +1,21 @@ +/** + * An object holding the interface Ids of the ENS resolver contracts. Please see [how to write a resolver](https://docs.ens.domains/contract-developer-guide/writing-a-resolver). + */ +export declare const interfaceIds: { + [T: string]: string; +}; +/** + * An object holding the functionsthat are supported by the ENS resolver contracts/interfaces. + */ +export declare const methodsInInterface: { + [T: string]: string; +}; +/** + * An object holding the addressed of the ENS registries on the different networks (mainnet, goerli). + */ +export declare const registryAddresses: { + [T: string]: string; +}; +export declare const networkIds: { + [T: string]: string; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.js new file mode 100644 index 0000000..2c9430e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.js @@ -0,0 +1,54 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.networkIds = exports.registryAddresses = exports.methodsInInterface = exports.interfaceIds = void 0; +// +/** + * An object holding the interface Ids of the ENS resolver contracts. Please see [how to write a resolver](https://docs.ens.domains/contract-developer-guide/writing-a-resolver). + */ +exports.interfaceIds = { + addr: '0x3b3b57de', + name: '0x691f3431', + abi: '0x2203ab56', + pubkey: '0xc8690233', + text: '0x59d1d43c', + contenthash: '0xbc1c58d1', +}; +/** + * An object holding the functionsthat are supported by the ENS resolver contracts/interfaces. + */ +exports.methodsInInterface = { + setAddr: 'addr', + addr: 'addr', + setPubkey: 'pubkey', + pubkey: 'pubkey', + setContenthash: 'contenthash', + contenthash: 'contenthash', +}; +/** + * An object holding the addressed of the ENS registries on the different networks (mainnet, goerli). + */ +exports.registryAddresses = { + main: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', + goerli: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', +}; +exports.networkIds = { + '0x1': 'main', + '0x5': 'goerli', +}; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.js.map new file mode 100644 index 0000000..6a3b1e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,EAAE;AACF;;GAEG;AACU,QAAA,YAAY,GAA4B;IACpD,IAAI,EAAE,YAAY;IAClB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,YAAY;IACjB,MAAM,EAAE,YAAY;IACpB,IAAI,EAAE,YAAY;IAClB,WAAW,EAAE,YAAY;CACzB,CAAC;AAEF;;GAEG;AACU,QAAA,kBAAkB,GAA4B;IAC1D,OAAO,EAAE,MAAM;IACf,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,QAAQ;IACnB,MAAM,EAAE,QAAQ;IAChB,cAAc,EAAE,aAAa;IAC7B,WAAW,EAAE,aAAa;CAC1B,CAAC;AAEF;;GAEG;AACU,QAAA,iBAAiB,GAA4B;IACzD,IAAI,EAAE,4CAA4C;IAClD,MAAM,EAAE,4CAA4C;CACpD,CAAC;AAEW,QAAA,UAAU,GAA4B;IAClD,KAAK,EAAE,MAAM;IACb,KAAK,EAAE,QAAQ;CACf,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.d.ts new file mode 100644 index 0000000..a07181b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.d.ts @@ -0,0 +1,433 @@ +import { Web3Context, Web3ContextObject } from 'web3-core'; +import { Contract } from 'web3-eth-contract'; +import { EthExecutionAPI, SupportedProviders, Web3NetAPI } from 'web3-types'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +/** + * This class is designed to interact with the ENS system on the Ethereum blockchain. + * + */ +export declare class ENS extends Web3Context { + /** + * The registryAddress property can be used to define a custom registry address when you are connected to an unknown chain. It defaults to the main registry address. + */ + registryAddress: string; + private readonly _registry; + private readonly _resolver; + private _detectedAddress?; + private _lastSyncCheck?; + /** + * Use to create an instance of ENS + * @param registryAddr - (Optional) The address of the ENS registry (default: mainnet registry address) + * @param provider - (Optional) The provider to use for the ENS instance + * @example + * ```ts + * const ens = new ENS( + * "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + * "http://localhost:8545" + * ); + * + * console.log( ens.defaultChain); + * > mainnet + * ``` + */ + constructor(registryAddr?: string, provider?: SupportedProviders | Web3ContextObject | string); + /** + * Returns the Resolver by the given address + * @param name - The name of the ENS domain + * @returns - An contract instance of the resolver + * + * @example + * ```ts + * const resolver = await ens.getResolver('resolver'); + * + * console.log(resolver.options.address); + * > '0x1234567890123456789012345678901234567890' + * ``` + */ + getResolver(name: string): Promise>; + /** + * Returns true if the record exists + * @param name - The ENS name + * @returns - Returns `true` if node exists in this ENS registry. This will return `false` for records that are in the legacy ENS registry but have not yet been migrated to the new one. + * @example + * ```ts + * const exists = await web3.eth.ens.recordExists('ethereum.eth'); + * ``` + */ + recordExists(name: string): Promise; + /** + * Returns the caching TTL (time-to-live) of an ENS name. + * @param name - The ENS name + * @returns - Returns the caching TTL (time-to-live) of a name. + * @example + * ```ts + * const owner = await web3.eth.ens.getTTL('ethereum.eth'); + * ``` + */ + getTTL(name: string): Promise; + /** + * Returns the owner by the given name and current configured or detected Registry + * @param name - The ENS name + * @returns - Returns the address of the owner of the name. + * @example + * ```ts + * const owner = await web3.eth.ens.getOwner('ethereum.eth'); + * ``` + */ + getOwner(name: string): Promise; + /** + * Resolves an ENS name to an Ethereum address. + * @param ENSName - The ENS name to resolve + * @param coinType - (Optional) The coin type, defaults to 60 (ETH) + * @returns - The Ethereum address of the given name + * ```ts + * const address = await web3.eth.ens.getAddress('ethereum.eth'); + * console.log(address); + * > '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' + * ``` + */ + getAddress(ENSName: string, coinType?: number): Promise>; + /** + * Returns the X and Y coordinates of the curve point for the public key. + * @param ENSName - The ENS name + * @returns - The X and Y coordinates of the curve point for the public key + * @example + * ```ts + * const key = await web3.eth.ens.getPubkey('ethereum.eth'); + * console.log(key); + * > { + * "0": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "1": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "x": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "y": "0x0000000000000000000000000000000000000000000000000000000000000000" + * } + * ``` + */ + getPubkey(ENSName: string): Promise> & Record<0, import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & [] & Record<"x", import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & Record<"y", import("web3-types").MatchPrimitiveType<"bytes32", unknown>>>; + /** + * Returns the content hash object associated with an ENS node. + * @param ENSName - The ENS name + * @returns - The content hash object associated with an ENS node + * @example + * ```ts + * const hash = await web3.eth.ens.getContenthash('ethereum.eth'); + * console.log(hash); + * > 'QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL' + * ``` + */ + getContenthash(ENSName: string): Promise>; + /** + * Checks if the current used network is synced and looks for ENS support there. + * Throws an error if not. + * @returns - The address of the ENS registry if the network has been detected successfully + * @example + * ```ts + * console.log(await web3.eth.ens.checkNetwork()); + * > '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' + * ``` + */ + checkNetwork(): Promise; + /** + * Returns true if the related Resolver does support the given signature or interfaceId. + * @param ENSName - The ENS name + * @param interfaceId - The signature of the function or the interfaceId as described in the ENS documentation + * @returns - `true` if the related Resolver does support the given signature or interfaceId. + * @example + * ```ts + * const supports = await web3.eth.ens.supportsInterface('ethereum.eth', 'addr(bytes32'); + * console.log(supports); + * > true + * ``` + */ + supportsInterface(ENSName: string, interfaceId: string): Promise>; + /** + * @returns - Returns all events that can be emitted by the ENS registry. + */ + get events(): import("web3-eth-contract").ContractEventsInterface mainnet + * ``` + */ + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "recordExists"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "resolver"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "ttl"; + readonly outputs: readonly [{ + readonly internalType: "uint64"; + readonly name: ""; + readonly type: "uint64"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }], import("web3-types").ContractEvents mainnet + * ``` + */ + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "recordExists"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "resolver"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "ttl"; + readonly outputs: readonly [{ + readonly internalType: "uint64"; + readonly name: ""; + readonly type: "uint64"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }]>>; +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.js new file mode 100644 index 0000000..d70e5fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.js @@ -0,0 +1,233 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ENS = void 0; +const web3_core_1 = require("web3-core"); +const web3_errors_1 = require("web3-errors"); +const web3_eth_1 = require("web3-eth"); +const web3_net_1 = require("web3-net"); +const web3_types_1 = require("web3-types"); +const config_js_1 = require("./config.js"); +const registry_js_1 = require("./registry.js"); +const resolver_js_1 = require("./resolver.js"); +/** + * This class is designed to interact with the ENS system on the Ethereum blockchain. + * + */ +class ENS extends web3_core_1.Web3Context { + /** + * Use to create an instance of ENS + * @param registryAddr - (Optional) The address of the ENS registry (default: mainnet registry address) + * @param provider - (Optional) The provider to use for the ENS instance + * @example + * ```ts + * const ens = new ENS( + * "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + * "http://localhost:8545" + * ); + * + * console.log( ens.defaultChain); + * > mainnet + * ``` + */ + constructor(registryAddr, provider) { + super(provider !== null && provider !== void 0 ? provider : ''); + this.registryAddress = registryAddr !== null && registryAddr !== void 0 ? registryAddr : config_js_1.registryAddresses.main; // will default to main registry address + this._registry = new registry_js_1.Registry(this.getContextObject(), registryAddr); + this._resolver = new resolver_js_1.Resolver(this._registry); + } + /** + * Returns the Resolver by the given address + * @param name - The name of the ENS domain + * @returns - An contract instance of the resolver + * + * @example + * ```ts + * const resolver = await ens.getResolver('resolver'); + * + * console.log(resolver.options.address); + * > '0x1234567890123456789012345678901234567890' + * ``` + */ + getResolver(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.getResolver(name); + }); + } + /** + * Returns true if the record exists + * @param name - The ENS name + * @returns - Returns `true` if node exists in this ENS registry. This will return `false` for records that are in the legacy ENS registry but have not yet been migrated to the new one. + * @example + * ```ts + * const exists = await web3.eth.ens.recordExists('ethereum.eth'); + * ``` + */ + recordExists(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.recordExists(name); + }); + } + /** + * Returns the caching TTL (time-to-live) of an ENS name. + * @param name - The ENS name + * @returns - Returns the caching TTL (time-to-live) of a name. + * @example + * ```ts + * const owner = await web3.eth.ens.getTTL('ethereum.eth'); + * ``` + */ + getTTL(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.getTTL(name); + }); + } + /** + * Returns the owner by the given name and current configured or detected Registry + * @param name - The ENS name + * @returns - Returns the address of the owner of the name. + * @example + * ```ts + * const owner = await web3.eth.ens.getOwner('ethereum.eth'); + * ``` + */ + getOwner(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.getOwner(name); + }); + } + /** + * Resolves an ENS name to an Ethereum address. + * @param ENSName - The ENS name to resolve + * @param coinType - (Optional) The coin type, defaults to 60 (ETH) + * @returns - The Ethereum address of the given name + * ```ts + * const address = await web3.eth.ens.getAddress('ethereum.eth'); + * console.log(address); + * > '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' + * ``` + */ + getAddress(ENSName, coinType = 60) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.getAddress(ENSName, coinType); + }); + } + /** + * Returns the X and Y coordinates of the curve point for the public key. + * @param ENSName - The ENS name + * @returns - The X and Y coordinates of the curve point for the public key + * @example + * ```ts + * const key = await web3.eth.ens.getPubkey('ethereum.eth'); + * console.log(key); + * > { + * "0": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "1": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "x": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "y": "0x0000000000000000000000000000000000000000000000000000000000000000" + * } + * ``` + */ + getPubkey(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.getPubkey(ENSName); + }); + } + /** + * Returns the content hash object associated with an ENS node. + * @param ENSName - The ENS name + * @returns - The content hash object associated with an ENS node + * @example + * ```ts + * const hash = await web3.eth.ens.getContenthash('ethereum.eth'); + * console.log(hash); + * > 'QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL' + * ``` + */ + getContenthash(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.getContenthash(ENSName); + }); + } + /** + * Checks if the current used network is synced and looks for ENS support there. + * Throws an error if not. + * @returns - The address of the ENS registry if the network has been detected successfully + * @example + * ```ts + * console.log(await web3.eth.ens.checkNetwork()); + * > '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' + * ``` + */ + checkNetwork() { + return __awaiter(this, void 0, void 0, function* () { + const now = Date.now() / 1000; + if (!this._lastSyncCheck || now - this._lastSyncCheck > 3600) { + const syncInfo = yield (0, web3_eth_1.isSyncing)(this); + if (!(typeof syncInfo === 'boolean' && !syncInfo)) { + throw new web3_errors_1.ENSNetworkNotSyncedError(); + } + this._lastSyncCheck = now; + } + if (this._detectedAddress) { + return this._detectedAddress; + } + const networkType = yield (0, web3_net_1.getId)(this, Object.assign(Object.assign({}, web3_types_1.DEFAULT_RETURN_FORMAT), { number: web3_types_1.FMT_NUMBER.HEX })); // get the network from provider + const addr = config_js_1.registryAddresses[config_js_1.networkIds[networkType]]; + if (typeof addr === 'undefined') { + throw new web3_errors_1.ENSUnsupportedNetworkError(networkType); + } + this._detectedAddress = addr; + return this._detectedAddress; + }); + } + /** + * Returns true if the related Resolver does support the given signature or interfaceId. + * @param ENSName - The ENS name + * @param interfaceId - The signature of the function or the interfaceId as described in the ENS documentation + * @returns - `true` if the related Resolver does support the given signature or interfaceId. + * @example + * ```ts + * const supports = await web3.eth.ens.supportsInterface('ethereum.eth', 'addr(bytes32'); + * console.log(supports); + * > true + * ``` + */ + supportsInterface(ENSName, interfaceId) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.supportsInterface(ENSName, interfaceId); + }); + } + /** + * @returns - Returns all events that can be emitted by the ENS registry. + */ + get events() { + return this._registry.events; + } +} +exports.ENS = ENS; +//# sourceMappingURL=ens.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.js.map new file mode 100644 index 0000000..4b9aaee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/ens.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ens.js","sourceRoot":"","sources":["../../src/ens.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,yCAA2D;AAC3D,6CAAmF;AACnF,uCAAqC;AAErC,uCAAiC;AACjC,2CAMoB;AAEpB,2CAA4D;AAC5D,+CAAyC;AACzC,+CAAyC;AAEzC;;;GAGG;AACH,MAAa,GAAI,SAAQ,uBAAyC;IAUjE;;;;;;;;;;;;;;OAcG;IACH,YACC,YAAqB,EACrB,QAGS;QAET,KAAK,CAA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AI,CAAC,SAAS,CAAC,MAAM,CAAC;IAC9B,CAAC;CACD;AA7MD,kBA6MC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.d.ts new file mode 100644 index 0000000..84a12fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.d.ts @@ -0,0 +1,16 @@ +/** + * The `web3.eth.ens` functions let you interact with ENS. We recommend reading the [ENS documentation](https://docs.ens.domains/) to get deeper insights about the internals of the name service. + * + * ## Breaking Changes + * + * - All the API level interfaces returning or accepting `null` in 1.x, use `undefined` in 4.x. + * - Functions don't accept a callback anymore. + * - Functions that accepted an optional `TransactionConfig` as the last argument, now accept an optional `NonPayableCallOptions`. See `web3-eth-contract` package for more details. + * - Removed all non-read methods. If you need modifing resolver or registry, please use https://www.npmjs.com/package/@ensdomains/ensjs + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { registryAddresses } from './config.js'; +export * from './ens.js'; +export { registryAddresses }; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.js new file mode 100644 index 0000000..c05be49 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.js @@ -0,0 +1,50 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.registryAddresses = void 0; +/** + * The `web3.eth.ens` functions let you interact with ENS. We recommend reading the [ENS documentation](https://docs.ens.domains/) to get deeper insights about the internals of the name service. + * + * ## Breaking Changes + * + * - All the API level interfaces returning or accepting `null` in 1.x, use `undefined` in 4.x. + * - Functions don't accept a callback anymore. + * - Functions that accepted an optional `TransactionConfig` as the last argument, now accept an optional `NonPayableCallOptions`. See `web3-eth-contract` package for more details. + * - Removed all non-read methods. If you need modifing resolver or registry, please use https://www.npmjs.com/package/@ensdomains/ensjs + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +const config_js_1 = require("./config.js"); +Object.defineProperty(exports, "registryAddresses", { enumerable: true, get: function () { return config_js_1.registryAddresses; } }); +__exportStar(require("./ens.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.js.map new file mode 100644 index 0000000..ba499af --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;AAEF;;;;;;;;;GASG;AACH;;GAEG;AACH,2CAAgD;AAGvC,kGAHA,6BAAiB,OAGA;AAD1B,2CAAyB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.d.ts new file mode 100644 index 0000000..05694b5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.d.ts @@ -0,0 +1,703 @@ +import { Web3ContextObject } from 'web3-core'; +import { Contract } from 'web3-eth-contract'; +import { Address } from 'web3-types'; +export declare class Registry { + private readonly contract; + private readonly context; + constructor(context: Web3ContextObject, customRegistryAddress?: Address); + getOwner(name: string): Promise; + getTTL(name: string): Promise>; + recordExists(name: string): Promise>; + getResolver(name: string): Promise>; + get events(): import("web3-eth-contract").ContractEventsInterface>; +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.js new file mode 100644 index 0000000..e02cafe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.js @@ -0,0 +1,97 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Registry = void 0; +const web3_eth_contract_1 = require("web3-eth-contract"); +const ENSRegistry_js_1 = require("./abi/ens/ENSRegistry.js"); +const PublicResolver_js_1 = require("./abi/ens/PublicResolver.js"); +const config_js_1 = require("./config.js"); +const utils_js_1 = require("./utils.js"); +class Registry { + constructor(context, customRegistryAddress) { + this.contract = new web3_eth_contract_1.Contract(ENSRegistry_js_1.ENSRegistryAbi, customRegistryAddress !== null && customRegistryAddress !== void 0 ? customRegistryAddress : config_js_1.registryAddresses.main, context); + this.context = context; + } + getOwner(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + const result = this.contract.methods.owner((0, utils_js_1.namehash)(name)).call(); + return result; + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + getTTL(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + return this.contract.methods.ttl((0, utils_js_1.namehash)(name)).call(); + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + recordExists(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + const promise = this.contract.methods.recordExists((0, utils_js_1.namehash)(name)).call(); + return promise; + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + getResolver(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + return this.contract.methods + .resolver((0, utils_js_1.namehash)(name)) + .call() + .then(address => { + // address type is unknown, not sure why + if (typeof address === 'string') { + const contract = new web3_eth_contract_1.Contract(PublicResolver_js_1.PublicResolverAbi, address, this.context); + // TODO: set contract provider needs to be added when ens current provider + return contract; + } + throw new Error(); + }); + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + get events() { + return this.contract.events; + } +} +exports.Registry = Registry; +//# sourceMappingURL=registry.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.js.map new file mode 100644 index 0000000..4db56bf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/registry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/registry.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAGF,yDAA6C;AAE7C,6DAA0D;AAC1D,mEAAgE;AAChE,2CAAgD;AAChD,yCAAsC;AAEtC,MAAa,QAAQ;IAIpB,YAAmB,OAA0B,EAAE,qBAA+B;QAC7E,IAAI,CAAC,QAAQ,GAAG,IAAI,4BAAQ,CAC3B,+BAAc,EACd,qBAAqB,aAArB,qBAAqB,cAArB,qBAAqB,GAAI,6BAAiB,CAAC,IAAI,EAC/C,OAAO,CACP,CAAC;QAEF,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAEY,QAAQ,CAAC,IAAY;;YACjC,IAAI;gBACH,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,IAAA,mBAAQ,EAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAElE,OAAO,MAAM,CAAC;aACd;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAEY,MAAM,CAAC,IAAY;;YAC/B,IAAI;gBACH,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAA,mBAAQ,EAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;aACxD;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAEY,YAAY,CAAC,IAAY;;YACrC,IAAI;gBACH,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,IAAA,mBAAQ,EAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAE1E,OAAO,OAAO,CAAC;aACf;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAEY,WAAW,CAAC,IAAY;;YACpC,IAAI;gBACH,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO;qBAC1B,QAAQ,CAAC,IAAA,mBAAQ,EAAC,IAAI,CAAC,CAAC;qBACxB,IAAI,EAAE;qBACN,IAAI,CAAC,OAAO,CAAC,EAAE;oBACf,wCAAwC;oBACxC,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;wBAChC,MAAM,QAAQ,GAAG,IAAI,4BAAQ,CAAC,qCAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;wBACxE,0EAA0E;wBAC1E,OAAO,QAAQ,CAAC;qBAChB;oBACD,MAAM,IAAI,KAAK,EAAE,CAAC;gBACnB,CAAC,CAAC,CAAC;aACJ;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAED,IAAW,MAAM;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;IAC7B,CAAC;CACD;AAhED,4BAgEC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.d.ts new file mode 100644 index 0000000..b19739f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.d.ts @@ -0,0 +1,13 @@ +import { Contract } from 'web3-eth-contract'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +import { Registry } from './registry.js'; +export declare class Resolver { + private readonly registry; + constructor(registry: Registry); + private getResolverContractAdapter; + checkInterfaceSupport(resolverContract: Contract, methodName: string): Promise; + supportsInterface(ENSName: string, interfaceId: string): Promise>; + getAddress(ENSName: string, coinType?: number): Promise>; + getPubkey(ENSName: string): Promise> & Record<0, import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & [] & Record<"x", import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & Record<"y", import("web3-types").MatchPrimitiveType<"bytes32", unknown>>>; + getContenthash(ENSName: string): Promise>; +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.js new file mode 100644 index 0000000..5c46305 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.js @@ -0,0 +1,98 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Resolver = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const config_js_1 = require("./config.js"); +const utils_js_1 = require("./utils.js"); +// Default public resolver +// https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol +class Resolver { + constructor(registry) { + this.registry = registry; + } + getResolverContractAdapter(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + // TODO : (Future 4.1.0 TDB) cache resolver contract if frequently queried same ENS name, refresh cache based on TTL and usage, also limit cache size, optional cache with a flag + return this.registry.getResolver(ENSName); + }); + } + // https://eips.ethereum.org/EIPS/eip-165 + // eslint-disable-next-line class-methods-use-this + checkInterfaceSupport(resolverContract, methodName) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + if ((0, web3_utils_1.isNullish)(config_js_1.interfaceIds[methodName])) + throw new web3_errors_1.ResolverMethodMissingError((_a = resolverContract.options.address) !== null && _a !== void 0 ? _a : '', methodName); + const supported = yield resolverContract.methods + .supportsInterface(config_js_1.interfaceIds[methodName]) + .call(); + if (!supported) + throw new web3_errors_1.ResolverMethodMissingError((_b = resolverContract.options.address) !== null && _b !== void 0 ? _b : '', methodName); + }); + } + supportsInterface(ENSName, interfaceId) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + let interfaceIdParam = interfaceId; + if (!(0, web3_validator_1.isHexStrict)(interfaceIdParam)) { + interfaceIdParam = (_a = (0, web3_utils_1.sha3)(interfaceId)) !== null && _a !== void 0 ? _a : ''; + if (interfaceId === '') + throw new Error('Invalid interface Id'); + interfaceIdParam = interfaceIdParam.slice(0, 10); + } + return resolverContract.methods.supportsInterface(interfaceIdParam).call(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-inferrable-types + getAddress(ENSName, coinType = 60) { + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + yield this.checkInterfaceSupport(resolverContract, config_js_1.methodsInInterface.addr); + return resolverContract.methods.addr((0, utils_js_1.namehash)(ENSName), coinType).call(); + }); + } + getPubkey(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + yield this.checkInterfaceSupport(resolverContract, config_js_1.methodsInInterface.pubkey); + return resolverContract.methods.pubkey((0, utils_js_1.namehash)(ENSName)).call(); + }); + } + getContenthash(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + yield this.checkInterfaceSupport(resolverContract, config_js_1.methodsInInterface.contenthash); + return resolverContract.methods.contenthash((0, utils_js_1.namehash)(ENSName)).call(); + }); + } +} +exports.Resolver = Resolver; +//# sourceMappingURL=resolver.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.js.map new file mode 100644 index 0000000..78ae37a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver.js","sourceRoot":"","sources":["../../src/resolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,6CAAyD;AAEzD,2CAA6C;AAC7C,mDAA6C;AAE7C,2CAA+D;AAE/D,yCAAsC;AAEtC,2BAA2B;AAC3B,oFAAoF;AAEpF,MAAa,QAAQ;IAGpB,YAAmB,QAAkB;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;IAEa,0BAA0B,CAAC,OAAe;;YACvD,kLAAkL;YAClL,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;KAAA;IAED,0CAA0C;IAC1C,kDAAkD;IACr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BAAkB,CAAC,IAAI,CAAC,CAAC;YAE5E,OAAO,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,IAAA,mBAAQ,EAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;QAC1E,CAAC;KAAA;IAEY,SAAS,CAAC,OAAe;;YACrC,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,0BAA0B,CAAC,OAAO,CAAC,CAAC;YAExE,MAAM,IAAI,CAAC,qBAAqB,CAAC,gBAAgB,EAAE,8BAAkB,CAAC,MAAM,CAAC,CAAC;YAE9E,OAAO,gBAAgB,CAAC,OAAO,CAAC,MAAM,CAAC,IAAA,mBAAQ,EAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAClE,CAAC;KAAA;IAEY,cAAc,CAAC,OAAe;;YAC1C,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,0BAA0B,CAAC,OAAO,CAAC,CAAC;YAExE,MAAM,IAAI,CAAC,qBAAqB,CAAC,gBAAgB,EAAE,8BAAkB,CAAC,WAAW,CAAC,CAAC;YAEnF,OAAO,gBAAgB,CAAC,OAAO,CAAC,WAAW,CAAC,IAAA,mBAAQ,EAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACvE,CAAC;KAAA;CACD;AA3ED,4BA2EC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.d.ts new file mode 100644 index 0000000..7aa7385 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.d.ts @@ -0,0 +1,2 @@ +export declare const normalize: (name: string) => string; +export declare const namehash: (inputName: string) => string; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.js new file mode 100644 index 0000000..8d19c9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.js @@ -0,0 +1,42 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.namehash = exports.normalize = void 0; +const web3_utils_1 = require("web3-utils"); +// eslint-disable-next-line camelcase +const ens_normalize_1 = require("@adraffy/ens-normalize"); +const normalize = (name) => (0, ens_normalize_1.ens_normalize)(name); +exports.normalize = normalize; +const namehash = (inputName) => { + // Reject empty names: + let node = ''; + for (let i = 0; i < 32; i += 1) { + node += '00'; + } + if (inputName) { + const name = (0, exports.normalize)(inputName); + const labels = name.split('.'); + for (let i = labels.length - 1; i >= 0; i -= 1) { + const labelSha = (0, web3_utils_1.sha3Raw)(labels[i]).slice(2); + node = (0, web3_utils_1.sha3Raw)(`0x${node}${labelSha}`).slice(2); + } + } + return `0x${node}`; +}; +exports.namehash = namehash; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.js.map new file mode 100644 index 0000000..254fd61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/commonjs/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAqC;AACrC,qCAAqC;AACrC,0DAAuD;AAEhD,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,6BAAa,EAAC,IAAI,CAAC,CAAC;AAAlD,QAAA,SAAS,aAAyC;AAExD,MAAM,QAAQ,GAAG,CAAC,SAAiB,EAAE,EAAE;IAC7C,sBAAsB;IACtB,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;QAC/B,IAAI,IAAI,IAAI,CAAC;KACb;IAED,IAAI,SAAS,EAAE;QACd,MAAM,IAAI,GAAG,IAAA,iBAAS,EAAC,SAAS,CAAC,CAAC;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAE/B,KAAK,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;YAC/C,MAAM,QAAQ,GAAG,IAAA,oBAAO,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,GAAG,IAAA,oBAAO,EAAC,KAAK,IAAI,GAAG,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;SAChD;KACD;IAED,OAAO,KAAK,IAAI,EAAE,CAAC;AACpB,CAAC,CAAC;AAlBW,QAAA,QAAQ,YAkBnB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/ENSRegistry.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/ENSRegistry.js new file mode 100644 index 0000000..6d9520f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/ENSRegistry.js @@ -0,0 +1,183 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// https://github.com/ensdomains/ens-contracts/blob/master/contracts/registry/ENSRegistry.sol +export const ENSRegistryAbi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'bytes32', + name: 'label', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'owner', + type: 'address', + }, + ], + name: 'NewOwner', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'resolver', + type: 'address', + }, + ], + name: 'NewResolver', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'owner', + type: 'address', + }, + ], + name: 'Transfer', + type: 'event', + }, + { + inputs: [ + { + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + internalType: 'address', + name: 'operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'owner', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'recordExists', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'resolver', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'ttl', + outputs: [ + { + internalType: 'uint64', + name: '', + type: 'uint64', + }, + ], + stateMutability: 'view', + type: 'function', + }, +]; +//# sourceMappingURL=ENSRegistry.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/ENSRegistry.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/ENSRegistry.js.map new file mode 100644 index 0000000..22d0792 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/ENSRegistry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ENSRegistry.js","sourceRoot":"","sources":["../../../../src/abi/ens/ENSRegistry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,6FAA6F;AAC7F,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,KAAK;gBACd,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,UAAU;QAChB,IAAI,EAAE,OAAO;KACb;IACD;QACC,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE;YACP;gBACC,OAAO,EAAE,IAAI;gBACb,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,OAAO,EAAE,KAAK;gBACd,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,IAAI,EAAE,cAAc;QACpB,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,MAAM;gBACpB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,MAAM;aACZ;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;IACD;QACC,MAAM,EAAE;YACP;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,SAAS;aACf;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;IACD;QACC,MAAM,EAAE;YACP;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,KAAK;QACX,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,QAAQ;gBACtB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,QAAQ;aACd;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;CACQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/PublicResolver.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/PublicResolver.js new file mode 100644 index 0000000..a3914e1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/PublicResolver.js @@ -0,0 +1,593 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// https://github.com/ensdomains/ens-contracts/blob/master/contracts/resolvers/PublicResolver.sol +export const PublicResolverAbi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'a', + type: 'address', + }, + ], + name: 'AddrChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'uint256', + name: 'coinType', + type: 'uint256', + }, + { + indexed: false, + internalType: 'bytes', + name: 'newAddress', + type: 'bytes', + }, + ], + name: 'AddressChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + indexed: true, + internalType: 'address', + name: 'operator', + type: 'address', + }, + { + indexed: false, + internalType: 'bool', + name: 'approved', + type: 'bool', + }, + ], + name: 'ApprovalForAll', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'hash', + type: 'bytes', + }, + ], + name: 'ContenthashChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'name', + type: 'bytes', + }, + { + indexed: false, + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + { + indexed: false, + internalType: 'bytes', + name: 'record', + type: 'bytes', + }, + ], + name: 'DNSRecordChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'name', + type: 'bytes', + }, + { + indexed: false, + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + ], + name: 'DNSRecordDeleted', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'DNSZoneCleared', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'lastzonehash', + type: 'bytes', + }, + { + indexed: false, + internalType: 'bytes', + name: 'zonehash', + type: 'bytes', + }, + ], + name: 'DNSZonehashChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + { + indexed: false, + internalType: 'address', + name: 'implementer', + type: 'address', + }, + ], + name: 'InterfaceChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'string', + name: 'name', + type: 'string', + }, + ], + name: 'NameChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes32', + name: 'x', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes32', + name: 'y', + type: 'bytes32', + }, + ], + name: 'PubkeyChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'string', + name: 'indexedKey', + type: 'string', + }, + { + indexed: false, + internalType: 'string', + name: 'key', + type: 'string', + }, + ], + name: 'TextChanged', + type: 'event', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'uint256', + name: 'contentTypes', + type: 'uint256', + }, + ], + name: 'ABI', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'addr', + outputs: [ + { + internalType: 'address payable', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'uint256', + name: 'coinType', + type: 'uint256', + }, + ], + name: 'addr', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'contenthash', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'name', + type: 'bytes32', + }, + { + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + ], + name: 'dnsRecord', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'name', + type: 'bytes32', + }, + ], + name: 'hasDNSRecords', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + ], + name: 'interfaceImplementer', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: 'account', + type: 'address', + }, + { + internalType: 'address', + name: 'operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'name', + outputs: [ + { + internalType: 'string', + name: '', + type: 'string', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'pubkey', + outputs: [ + { + internalType: 'bytes32', + name: 'x', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'y', + type: 'bytes32', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + ], + name: 'supportsInterface', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'string', + name: 'key', + type: 'string', + }, + ], + name: 'text', + outputs: [ + { + internalType: 'string', + name: '', + type: 'string', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'zonehash', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, +]; +//# sourceMappingURL=PublicResolver.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/PublicResolver.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/PublicResolver.js.map new file mode 100644 index 0000000..85f2b75 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/abi/ens/PublicResolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PublicResolver.js","sourceRoot":"","sources":["../../../../src/abi/ens/PublicResolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,iGAAiG;AACjG,MAAM,CAAC,MAAM,iBAAiB,G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EAAE,EAAE;gBACR,IAAI,EAAE,MAAM;aACZ;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;IACD;QACC,MAAM,EAAE;YACP;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;YACD;gBACC,YAAY,EAAE,QAAQ;gBACtB,IAAI,EAAE,KAAK;gBACX,IAAI,EAAE,QAAQ;aACd;SACD;QACD,IAAI,EAAE,MAAM;QACZ,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,QAAQ;gBACtB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,QAAQ;aACd;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;IACD;QACC,MAAM,EAAE;YACP;gBACC,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,SAAS;aACf;SACD;QACD,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE;YACR;gBACC,YAAY,EAAE,OAAO;gBACrB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,OAAO;aACb;SACD;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KAChB;CACQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/config.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/config.js new file mode 100644 index 0000000..5062d42 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/config.js @@ -0,0 +1,51 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// +/** + * An object holding the interface Ids of the ENS resolver contracts. Please see [how to write a resolver](https://docs.ens.domains/contract-developer-guide/writing-a-resolver). + */ +export const interfaceIds = { + addr: '0x3b3b57de', + name: '0x691f3431', + abi: '0x2203ab56', + pubkey: '0xc8690233', + text: '0x59d1d43c', + contenthash: '0xbc1c58d1', +}; +/** + * An object holding the functionsthat are supported by the ENS resolver contracts/interfaces. + */ +export const methodsInInterface = { + setAddr: 'addr', + addr: 'addr', + setPubkey: 'pubkey', + pubkey: 'pubkey', + setContenthash: 'contenthash', + contenthash: 'contenthash', +}; +/** + * An object holding the addressed of the ENS registries on the different networks (mainnet, goerli). + */ +export const registryAddresses = { + main: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', + goerli: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', +}; +export const networkIds = { + '0x1': 'main', + '0x5': 'goerli', +}; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/config.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/config.js.map new file mode 100644 index 0000000..f6f7e13 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,EAAE;AACF;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAA4B;IACpD,IAAI,EAAE,YAAY;IAClB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,YAAY;IACjB,MAAM,EAAE,YAAY;IACpB,IAAI,EAAE,YAAY;IAClB,WAAW,EAAE,YAAY;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAA4B;IAC1D,OAAO,EAAE,MAAM;IACf,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,QAAQ;IACnB,MAAM,EAAE,QAAQ;IAChB,cAAc,EAAE,aAAa;IAC7B,WAAW,EAAE,aAAa;CAC1B,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAA4B;IACzD,IAAI,EAAE,4CAA4C;IAClD,MAAM,EAAE,4CAA4C;CACpD,CAAC;AAEF,MAAM,CAAC,MAAM,UAAU,GAA4B;IAClD,KAAK,EAAE,MAAM;IACb,KAAK,EAAE,QAAQ;CACf,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/ens.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/ens.js new file mode 100644 index 0000000..5e4028a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/ens.js @@ -0,0 +1,229 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { Web3Context } from 'web3-core'; +import { ENSNetworkNotSyncedError, ENSUnsupportedNetworkError } from 'web3-errors'; +import { isSyncing } from 'web3-eth'; +import { getId } from 'web3-net'; +import { DEFAULT_RETURN_FORMAT, FMT_NUMBER, } from 'web3-types'; +import { networkIds, registryAddresses } from './config.js'; +import { Registry } from './registry.js'; +import { Resolver } from './resolver.js'; +/** + * This class is designed to interact with the ENS system on the Ethereum blockchain. + * + */ +export class ENS extends Web3Context { + /** + * Use to create an instance of ENS + * @param registryAddr - (Optional) The address of the ENS registry (default: mainnet registry address) + * @param provider - (Optional) The provider to use for the ENS instance + * @example + * ```ts + * const ens = new ENS( + * "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + * "http://localhost:8545" + * ); + * + * console.log( ens.defaultChain); + * > mainnet + * ``` + */ + constructor(registryAddr, provider) { + super(provider !== null && provider !== void 0 ? provider : ''); + this.registryAddress = registryAddr !== null && registryAddr !== void 0 ? registryAddr : registryAddresses.main; // will default to main registry address + this._registry = new Registry(this.getContextObject(), registryAddr); + this._resolver = new Resolver(this._registry); + } + /** + * Returns the Resolver by the given address + * @param name - The name of the ENS domain + * @returns - An contract instance of the resolver + * + * @example + * ```ts + * const resolver = await ens.getResolver('resolver'); + * + * console.log(resolver.options.address); + * > '0x1234567890123456789012345678901234567890' + * ``` + */ + getResolver(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.getResolver(name); + }); + } + /** + * Returns true if the record exists + * @param name - The ENS name + * @returns - Returns `true` if node exists in this ENS registry. This will return `false` for records that are in the legacy ENS registry but have not yet been migrated to the new one. + * @example + * ```ts + * const exists = await web3.eth.ens.recordExists('ethereum.eth'); + * ``` + */ + recordExists(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.recordExists(name); + }); + } + /** + * Returns the caching TTL (time-to-live) of an ENS name. + * @param name - The ENS name + * @returns - Returns the caching TTL (time-to-live) of a name. + * @example + * ```ts + * const owner = await web3.eth.ens.getTTL('ethereum.eth'); + * ``` + */ + getTTL(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.getTTL(name); + }); + } + /** + * Returns the owner by the given name and current configured or detected Registry + * @param name - The ENS name + * @returns - Returns the address of the owner of the name. + * @example + * ```ts + * const owner = await web3.eth.ens.getOwner('ethereum.eth'); + * ``` + */ + getOwner(name) { + return __awaiter(this, void 0, void 0, function* () { + return this._registry.getOwner(name); + }); + } + /** + * Resolves an ENS name to an Ethereum address. + * @param ENSName - The ENS name to resolve + * @param coinType - (Optional) The coin type, defaults to 60 (ETH) + * @returns - The Ethereum address of the given name + * ```ts + * const address = await web3.eth.ens.getAddress('ethereum.eth'); + * console.log(address); + * > '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' + * ``` + */ + getAddress(ENSName, coinType = 60) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.getAddress(ENSName, coinType); + }); + } + /** + * Returns the X and Y coordinates of the curve point for the public key. + * @param ENSName - The ENS name + * @returns - The X and Y coordinates of the curve point for the public key + * @example + * ```ts + * const key = await web3.eth.ens.getPubkey('ethereum.eth'); + * console.log(key); + * > { + * "0": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "1": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "x": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "y": "0x0000000000000000000000000000000000000000000000000000000000000000" + * } + * ``` + */ + getPubkey(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.getPubkey(ENSName); + }); + } + /** + * Returns the content hash object associated with an ENS node. + * @param ENSName - The ENS name + * @returns - The content hash object associated with an ENS node + * @example + * ```ts + * const hash = await web3.eth.ens.getContenthash('ethereum.eth'); + * console.log(hash); + * > 'QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL' + * ``` + */ + getContenthash(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.getContenthash(ENSName); + }); + } + /** + * Checks if the current used network is synced and looks for ENS support there. + * Throws an error if not. + * @returns - The address of the ENS registry if the network has been detected successfully + * @example + * ```ts + * console.log(await web3.eth.ens.checkNetwork()); + * > '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' + * ``` + */ + checkNetwork() { + return __awaiter(this, void 0, void 0, function* () { + const now = Date.now() / 1000; + if (!this._lastSyncCheck || now - this._lastSyncCheck > 3600) { + const syncInfo = yield isSyncing(this); + if (!(typeof syncInfo === 'boolean' && !syncInfo)) { + throw new ENSNetworkNotSyncedError(); + } + this._lastSyncCheck = now; + } + if (this._detectedAddress) { + return this._detectedAddress; + } + const networkType = yield getId(this, Object.assign(Object.assign({}, DEFAULT_RETURN_FORMAT), { number: FMT_NUMBER.HEX })); // get the network from provider + const addr = registryAddresses[networkIds[networkType]]; + if (typeof addr === 'undefined') { + throw new ENSUnsupportedNetworkError(networkType); + } + this._detectedAddress = addr; + return this._detectedAddress; + }); + } + /** + * Returns true if the related Resolver does support the given signature or interfaceId. + * @param ENSName - The ENS name + * @param interfaceId - The signature of the function or the interfaceId as described in the ENS documentation + * @returns - `true` if the related Resolver does support the given signature or interfaceId. + * @example + * ```ts + * const supports = await web3.eth.ens.supportsInterface('ethereum.eth', 'addr(bytes32'); + * console.log(supports); + * > true + * ``` + */ + supportsInterface(ENSName, interfaceId) { + return __awaiter(this, void 0, void 0, function* () { + return this._resolver.supportsInterface(ENSName, interfaceId); + }); + } + /** + * @returns - Returns all events that can be emitted by the ENS registry. + */ + get events() { + return this._registry.events; + } +} +//# sourceMappingURL=ens.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/ens.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/ens.js.map new file mode 100644 index 0000000..6114537 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/ens.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ens.js","sourceRoot":"","sources":["../../src/ens.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAAE,WAAW,EAAqB,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,OAAO,EAA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AChC,MAAM,IAAI,0BAA0B,CAAC,WAAW,CAAC,CAAC;aAClD;YAED,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAC7B,OAAO,IAAI,CAAC,gBAAgB,CAAC;QAC9B,CAAC;KAAA;IAED;;;;;;;;;;;OAWG;IACU,iBAAiB,CAAC,OAAe,EAAE,WAAmB;;YAClE,OAAO,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QAC/D,CAAC;KAAA;IAED;;OAEG;IACH,IAAW,MAAM;QAChB,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;IAC9B,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/index.js new file mode 100644 index 0000000..c2a884f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/index.js @@ -0,0 +1,33 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The `web3.eth.ens` functions let you interact with ENS. We recommend reading the [ENS documentation](https://docs.ens.domains/) to get deeper insights about the internals of the name service. + * + * ## Breaking Changes + * + * - All the API level interfaces returning or accepting `null` in 1.x, use `undefined` in 4.x. + * - Functions don't accept a callback anymore. + * - Functions that accepted an optional `TransactionConfig` as the last argument, now accept an optional `NonPayableCallOptions`. See `web3-eth-contract` package for more details. + * - Removed all non-read methods. If you need modifing resolver or registry, please use https://www.npmjs.com/package/@ensdomains/ensjs + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { registryAddresses } from './config.js'; +export * from './ens.js'; +export { registryAddresses }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/index.js.map new file mode 100644 index 0000000..7f38458 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;GASG;AACH;;GAEG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/registry.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/registry.js new file mode 100644 index 0000000..e0f2f5f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/registry.js @@ -0,0 +1,93 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { Contract } from 'web3-eth-contract'; +import { ENSRegistryAbi } from './abi/ens/ENSRegistry.js'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +import { registryAddresses } from './config.js'; +import { namehash } from './utils.js'; +export class Registry { + constructor(context, customRegistryAddress) { + this.contract = new Contract(ENSRegistryAbi, customRegistryAddress !== null && customRegistryAddress !== void 0 ? customRegistryAddress : registryAddresses.main, context); + this.context = context; + } + getOwner(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + const result = this.contract.methods.owner(namehash(name)).call(); + return result; + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + getTTL(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + return this.contract.methods.ttl(namehash(name)).call(); + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + recordExists(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + const promise = this.contract.methods.recordExists(namehash(name)).call(); + return promise; + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + getResolver(name) { + return __awaiter(this, void 0, void 0, function* () { + try { + return this.contract.methods + .resolver(namehash(name)) + .call() + .then(address => { + // address type is unknown, not sure why + if (typeof address === 'string') { + const contract = new Contract(PublicResolverAbi, address, this.context); + // TODO: set contract provider needs to be added when ens current provider + return contract; + } + throw new Error(); + }); + } + catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + }); + } + get events() { + return this.contract.events; + } +} +//# sourceMappingURL=registry.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/registry.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/registry.js.map new file mode 100644 index 0000000..17804b5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/registry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAGF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAE7C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,OAAO,QAAQ;IAIpB,YAAmB,OAA0B,EAAE,qBAA+B;QAC7E,IAAI,CAAC,QAAQ,GAAG,IAAI,QAAQ,CAC3B,cAAc,EACd,qBAAqB,aAArB,qBAAqB,cAArB,qBAAqB,GAAI,iBAAiB,CAAC,IAAI,EAC/C,OAAO,CACP,CAAC;QAEF,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAEY,QAAQ,CAAC,IAAY;;YACjC,IAAI;gBACH,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAElE,OAAO,MAAM,CAAC;aACd;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAEY,MAAM,CAAC,IAAY;;YAC/B,IAAI;gBACH,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;aACxD;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAEY,YAAY,CAAC,IAAY;;YACrC,IAAI;gBACH,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAE1E,OAAO,OAAO,CAAC;aACf;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAEY,WAAW,CAAC,IAAY;;YACpC,IAAI;gBACH,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO;qBAC1B,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;qBACxB,IAAI,EAAE;qBACN,IAAI,CAAC,OAAO,CAAC,EAAE;oBACf,wCAAwC;oBACxC,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;wBAChC,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;wBACxE,0EAA0E;wBAC1E,OAAO,QAAQ,CAAC;qBAChB;oBACD,MAAM,IAAI,KAAK,EAAE,CAAC;gBACnB,CAAC,CAAC,CAAC;aACJ;YAAC,OAAO,KAAK,EAAE;gBACf,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,sGAAsG;aACzH;QACF,CAAC;KAAA;IAED,IAAW,MAAM;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;IAC7B,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/resolver.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/resolver.js new file mode 100644 index 0000000..5950c4a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/resolver.js @@ -0,0 +1,94 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { ResolverMethodMissingError } from 'web3-errors'; +import { isNullish, sha3 } from 'web3-utils'; +import { isHexStrict } from 'web3-validator'; +import { interfaceIds, methodsInInterface } from './config.js'; +import { namehash } from './utils.js'; +// Default public resolver +// https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol +export class Resolver { + constructor(registry) { + this.registry = registry; + } + getResolverContractAdapter(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + // TODO : (Future 4.1.0 TDB) cache resolver contract if frequently queried same ENS name, refresh cache based on TTL and usage, also limit cache size, optional cache with a flag + return this.registry.getResolver(ENSName); + }); + } + // https://eips.ethereum.org/EIPS/eip-165 + // eslint-disable-next-line class-methods-use-this + checkInterfaceSupport(resolverContract, methodName) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + if (isNullish(interfaceIds[methodName])) + throw new ResolverMethodMissingError((_a = resolverContract.options.address) !== null && _a !== void 0 ? _a : '', methodName); + const supported = yield resolverContract.methods + .supportsInterface(interfaceIds[methodName]) + .call(); + if (!supported) + throw new ResolverMethodMissingError((_b = resolverContract.options.address) !== null && _b !== void 0 ? _b : '', methodName); + }); + } + supportsInterface(ENSName, interfaceId) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + let interfaceIdParam = interfaceId; + if (!isHexStrict(interfaceIdParam)) { + interfaceIdParam = (_a = sha3(interfaceId)) !== null && _a !== void 0 ? _a : ''; + if (interfaceId === '') + throw new Error('Invalid interface Id'); + interfaceIdParam = interfaceIdParam.slice(0, 10); + } + return resolverContract.methods.supportsInterface(interfaceIdParam).call(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-inferrable-types + getAddress(ENSName, coinType = 60) { + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + yield this.checkInterfaceSupport(resolverContract, methodsInInterface.addr); + return resolverContract.methods.addr(namehash(ENSName), coinType).call(); + }); + } + getPubkey(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + yield this.checkInterfaceSupport(resolverContract, methodsInInterface.pubkey); + return resolverContract.methods.pubkey(namehash(ENSName)).call(); + }); + } + getContenthash(ENSName) { + return __awaiter(this, void 0, void 0, function* () { + const resolverContract = yield this.getResolverContractAdapter(ENSName); + yield this.checkInterfaceSupport(resolverContract, methodsInInterface.contenthash); + return resolverContract.methods.contenthash(namehash(ENSName)).call(); + }); + } +} +//# sourceMappingURL=resolver.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/resolver.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/resolver.js.map new file mode 100644 index 0000000..c73c58a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver.js","sourceRoot":"","sources":["../../src/resolver.ts"],"names":[],"mapp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AE,kBAAkB,CAAC,WAAW,CAAC,CAAC;YAEnF,OAAO,gBAAgB,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACvE,CAAC;KAAA;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/utils.js b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/utils.js new file mode 100644 index 0000000..7a77c7a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/utils.js @@ -0,0 +1,37 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { sha3Raw } from 'web3-utils'; +// eslint-disable-next-line camelcase +import { ens_normalize } from '@adraffy/ens-normalize'; +export const normalize = (name) => ens_normalize(name); +export const namehash = (inputName) => { + // Reject empty names: + let node = ''; + for (let i = 0; i < 32; i += 1) { + node += '00'; + } + if (inputName) { + const name = normalize(inputName); + const labels = name.split('.'); + for (let i = labels.length - 1; i >= 0; i -= 1) { + const labelSha = sha3Raw(labels[i]).slice(2); + node = sha3Raw(`0x${node}${labelSha}`).slice(2); + } + } + return `0x${node}`; +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/utils.js.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/utils.js.map new file mode 100644 index 0000000..9d346fb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,qCAAqC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;AAE/D,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,SAAiB,EAAE,EAAE;IAC7C,sBAAsB;IACtB,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;QAC/B,IAAI,IAAI,IAAI,CAAC;KACb;IAED,IAAI,SAAS,EAAE;QACd,MAAM,IAAI,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAE/B,KAAK,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;YAC/C,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7C,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,GAAG,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;SAChD;KACD;IAED,OAAO,KAAK,IAAI,EAAE,CAAC;AACpB,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/ENSRegistry.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/ENSRegistry.d.ts new file mode 100644 index 0000000..60ebf2c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/ENSRegistry.d.ts @@ -0,0 +1,126 @@ +export declare const ENSRegistryAbi: readonly [{ + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "label"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }]; + readonly name: "NewOwner"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "resolver"; + readonly type: "address"; + }]; + readonly name: "NewResolver"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }]; + readonly name: "Transfer"; + readonly type: "event"; +}, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "recordExists"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "resolver"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "ttl"; + readonly outputs: readonly [{ + readonly internalType: "uint64"; + readonly name: ""; + readonly type: "uint64"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}]; +//# sourceMappingURL=ENSRegistry.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/ENSRegistry.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/ENSRegistry.d.ts.map new file mode 100644 index 0000000..5cce414 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/ENSRegistry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ENSRegistry.d.ts","sourceRoot":"","sources":["../../../../src/abi/ens/ENSRegistry.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoKjB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/PublicResolver.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/PublicResolver.d.ts new file mode 100644 index 0000000..e82f41b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/PublicResolver.d.ts @@ -0,0 +1,444 @@ +export declare const PublicResolverAbi: readonly [{ + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "a"; + readonly type: "address"; + }]; + readonly name: "AddrChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "newAddress"; + readonly type: "bytes"; + }]; + readonly name: "AddressChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "bool"; + readonly name: "approved"; + readonly type: "bool"; + }]; + readonly name: "ApprovalForAll"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "hash"; + readonly type: "bytes"; + }]; + readonly name: "ContenthashChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "name"; + readonly type: "bytes"; + }, { + readonly indexed: false; + readonly internalType: "uint16"; + readonly name: "resource"; + readonly type: "uint16"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "record"; + readonly type: "bytes"; + }]; + readonly name: "DNSRecordChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "name"; + readonly type: "bytes"; + }, { + readonly indexed: false; + readonly internalType: "uint16"; + readonly name: "resource"; + readonly type: "uint16"; + }]; + readonly name: "DNSRecordDeleted"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "DNSZoneCleared"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "lastzonehash"; + readonly type: "bytes"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "zonehash"; + readonly type: "bytes"; + }]; + readonly name: "DNSZonehashChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "implementer"; + readonly type: "address"; + }]; + readonly name: "InterfaceChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "name"; + readonly type: "string"; + }]; + readonly name: "NameChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly name: "PubkeyChanged"; + readonly type: "event"; +}, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "string"; + readonly name: "indexedKey"; + readonly type: "string"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }]; + readonly name: "TextChanged"; + readonly type: "event"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "contentTypes"; + readonly type: "uint256"; + }]; + readonly name: "ABI"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }, { + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "addr"; + readonly outputs: readonly [{ + readonly internalType: "address payable"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }]; + readonly name: "addr"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "contenthash"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "name"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint16"; + readonly name: "resource"; + readonly type: "uint16"; + }]; + readonly name: "dnsRecord"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "name"; + readonly type: "bytes32"; + }]; + readonly name: "hasDNSRecords"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }]; + readonly name: "interfaceImplementer"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "account"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "name"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "pubkey"; + readonly outputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }]; + readonly name: "supportsInterface"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }]; + readonly name: "text"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "zonehash"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; +}]; +//# sourceMappingURL=PublicResolver.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/PublicResolver.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/PublicResolver.d.ts.map new file mode 100644 index 0000000..db4b111 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/abi/ens/PublicResolver.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PublicResolver.d.ts","sourceRoot":"","sources":["../../../../src/abi/ens/PublicResolver.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8jBpB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/config.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/config.d.ts new file mode 100644 index 0000000..99128be --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/config.d.ts @@ -0,0 +1,22 @@ +/** + * An object holding the interface Ids of the ENS resolver contracts. Please see [how to write a resolver](https://docs.ens.domains/contract-developer-guide/writing-a-resolver). + */ +export declare const interfaceIds: { + [T: string]: string; +}; +/** + * An object holding the functionsthat are supported by the ENS resolver contracts/interfaces. + */ +export declare const methodsInInterface: { + [T: string]: string; +}; +/** + * An object holding the addressed of the ENS registries on the different networks (mainnet, goerli). + */ +export declare const registryAddresses: { + [T: string]: string; +}; +export declare const networkIds: { + [T: string]: string; +}; +//# sourceMappingURL=config.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/config.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/config.d.ts.map new file mode 100644 index 0000000..4c3fffc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CAO/C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kBAAkB,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CAOrD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CAGpD,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CAG7C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/ens.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/ens.d.ts new file mode 100644 index 0000000..5d5e0d6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/ens.d.ts @@ -0,0 +1,434 @@ +import { Web3Context, Web3ContextObject } from 'web3-core'; +import { Contract } from 'web3-eth-contract'; +import { EthExecutionAPI, SupportedProviders, Web3NetAPI } from 'web3-types'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +/** + * This class is designed to interact with the ENS system on the Ethereum blockchain. + * + */ +export declare class ENS extends Web3Context { + /** + * The registryAddress property can be used to define a custom registry address when you are connected to an unknown chain. It defaults to the main registry address. + */ + registryAddress: string; + private readonly _registry; + private readonly _resolver; + private _detectedAddress?; + private _lastSyncCheck?; + /** + * Use to create an instance of ENS + * @param registryAddr - (Optional) The address of the ENS registry (default: mainnet registry address) + * @param provider - (Optional) The provider to use for the ENS instance + * @example + * ```ts + * const ens = new ENS( + * "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + * "http://localhost:8545" + * ); + * + * console.log( ens.defaultChain); + * > mainnet + * ``` + */ + constructor(registryAddr?: string, provider?: SupportedProviders | Web3ContextObject | string); + /** + * Returns the Resolver by the given address + * @param name - The name of the ENS domain + * @returns - An contract instance of the resolver + * + * @example + * ```ts + * const resolver = await ens.getResolver('resolver'); + * + * console.log(resolver.options.address); + * > '0x1234567890123456789012345678901234567890' + * ``` + */ + getResolver(name: string): Promise>; + /** + * Returns true if the record exists + * @param name - The ENS name + * @returns - Returns `true` if node exists in this ENS registry. This will return `false` for records that are in the legacy ENS registry but have not yet been migrated to the new one. + * @example + * ```ts + * const exists = await web3.eth.ens.recordExists('ethereum.eth'); + * ``` + */ + recordExists(name: string): Promise; + /** + * Returns the caching TTL (time-to-live) of an ENS name. + * @param name - The ENS name + * @returns - Returns the caching TTL (time-to-live) of a name. + * @example + * ```ts + * const owner = await web3.eth.ens.getTTL('ethereum.eth'); + * ``` + */ + getTTL(name: string): Promise; + /** + * Returns the owner by the given name and current configured or detected Registry + * @param name - The ENS name + * @returns - Returns the address of the owner of the name. + * @example + * ```ts + * const owner = await web3.eth.ens.getOwner('ethereum.eth'); + * ``` + */ + getOwner(name: string): Promise; + /** + * Resolves an ENS name to an Ethereum address. + * @param ENSName - The ENS name to resolve + * @param coinType - (Optional) The coin type, defaults to 60 (ETH) + * @returns - The Ethereum address of the given name + * ```ts + * const address = await web3.eth.ens.getAddress('ethereum.eth'); + * console.log(address); + * > '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' + * ``` + */ + getAddress(ENSName: string, coinType?: number): Promise>; + /** + * Returns the X and Y coordinates of the curve point for the public key. + * @param ENSName - The ENS name + * @returns - The X and Y coordinates of the curve point for the public key + * @example + * ```ts + * const key = await web3.eth.ens.getPubkey('ethereum.eth'); + * console.log(key); + * > { + * "0": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "1": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "x": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "y": "0x0000000000000000000000000000000000000000000000000000000000000000" + * } + * ``` + */ + getPubkey(ENSName: string): Promise> & Record<0, import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & [] & Record<"x", import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & Record<"y", import("web3-types").MatchPrimitiveType<"bytes32", unknown>>>; + /** + * Returns the content hash object associated with an ENS node. + * @param ENSName - The ENS name + * @returns - The content hash object associated with an ENS node + * @example + * ```ts + * const hash = await web3.eth.ens.getContenthash('ethereum.eth'); + * console.log(hash); + * > 'QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL' + * ``` + */ + getContenthash(ENSName: string): Promise>; + /** + * Checks if the current used network is synced and looks for ENS support there. + * Throws an error if not. + * @returns - The address of the ENS registry if the network has been detected successfully + * @example + * ```ts + * console.log(await web3.eth.ens.checkNetwork()); + * > '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' + * ``` + */ + checkNetwork(): Promise; + /** + * Returns true if the related Resolver does support the given signature or interfaceId. + * @param ENSName - The ENS name + * @param interfaceId - The signature of the function or the interfaceId as described in the ENS documentation + * @returns - `true` if the related Resolver does support the given signature or interfaceId. + * @example + * ```ts + * const supports = await web3.eth.ens.supportsInterface('ethereum.eth', 'addr(bytes32'); + * console.log(supports); + * > true + * ``` + */ + supportsInterface(ENSName: string, interfaceId: string): Promise>; + /** + * @returns - Returns all events that can be emitted by the ENS registry. + */ + get events(): import("web3-eth-contract").ContractEventsInterface mainnet + * ``` + */ + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "recordExists"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "resolver"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "ttl"; + readonly outputs: readonly [{ + readonly internalType: "uint64"; + readonly name: ""; + readonly type: "uint64"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }], import("web3-types").ContractEvents mainnet + * ``` + */ + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "operator"; + readonly type: "address"; + }]; + readonly name: "isApprovedForAll"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "recordExists"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "resolver"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "ttl"; + readonly outputs: readonly [{ + readonly internalType: "uint64"; + readonly name: ""; + readonly type: "uint64"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }]>>; +} +//# sourceMappingURL=ens.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/ens.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/ens.d.ts.map new file mode 100644 index 0000000..77a40d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/ens.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ens.d.ts","sourceRoot":"","sources":["../../src/ens.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAG3D,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAE7C,OAAO,EAEN,eAAe,EAEf,kBAAkB,EAClB,UAAU,EACV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAKhE;;;GAGG;AACH,qBAAa,GAAI,SAAQ,WAAW,CAAC,eAAe,GAAG,UAAU,CAAC;IACjE;;OAEG;IACI,eAAe,EAAE,MAAM,CAAC;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IACrC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IACrC,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAClC,OAAO,CAAC,cAAc,CAAC,CAAS;IAEhC;;;;;;;;;;;;;;OAcG;gBAEF,YAAY,CAAC,EAAE,MAAM,EACrB,QAAQ,CAAC,EACN,kBAAkB,CAAC,eAAe,GAAG,UAAU,CAAC,GAChD,iBAAiB,CAAC,eAAe,GAAG,UAAU,CAAC,GAC/C,MAAM;IAQV;;;;;;;;;;;;OAYG;IACU,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO,iBAAiB,CAAC,CAAC;IAInF;;;;;;;;OAQG;IACU,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAIzD;;;;;;;;OAQG;IACU,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAInD;;;;;;;;OAQG;IACU,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAIrD;;;;;;;;;;OAUG;IACU,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,SAAK;IAItD;;;;;;;;;;;;;;;OAeG;IACU,SAAS,CAAC,OAAO,EAAE,MAAM;IAItC;;;;;;;;;;OAUG;IACU,cAAc,CAAC,OAAO,EAAE,MAAM;IAI3C;;;;;;;;;OASG;IACU,YAAY;IA6BzB;;;;;;;;;;;OAWG;IACU,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM;IAInE;;OAEG;IACH,IAAW,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;YA9MlB;;;eAGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAWF;;;;;;;;;;;;;;eAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA5BJ;;;eAGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAWF;;;;;;;;;;;;;;eAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAoLF;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/index.d.ts new file mode 100644 index 0000000..1fa58ea --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/index.d.ts @@ -0,0 +1,17 @@ +/** + * The `web3.eth.ens` functions let you interact with ENS. We recommend reading the [ENS documentation](https://docs.ens.domains/) to get deeper insights about the internals of the name service. + * + * ## Breaking Changes + * + * - All the API level interfaces returning or accepting `null` in 1.x, use `undefined` in 4.x. + * - Functions don't accept a callback anymore. + * - Functions that accepted an optional `TransactionConfig` as the last argument, now accept an optional `NonPayableCallOptions`. See `web3-eth-contract` package for more details. + * - Removed all non-read methods. If you need modifing resolver or registry, please use https://www.npmjs.com/package/@ensdomains/ensjs + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { registryAddresses } from './config.js'; +export * from './ens.js'; +export { registryAddresses }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/index.d.ts.map new file mode 100644 index 0000000..354a768 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;GASG;AACH;;GAEG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/registry.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/registry.d.ts new file mode 100644 index 0000000..1ccdf13 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/registry.d.ts @@ -0,0 +1,704 @@ +import { Web3ContextObject } from 'web3-core'; +import { Contract } from 'web3-eth-contract'; +import { Address } from 'web3-types'; +export declare class Registry { + private readonly contract; + private readonly context; + constructor(context: Web3ContextObject, customRegistryAddress?: Address); + getOwner(name: string): Promise; + getTTL(name: string): Promise>; + recordExists(name: string): Promise>; + getResolver(name: string): Promise>; + get events(): import("web3-eth-contract").ContractEventsInterface>; +} +//# sourceMappingURL=registry.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/registry.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/registry.d.ts.map new file mode 100644 index 0000000..b82c0f3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/registry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/registry.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAMrC,qBAAa,QAAQ;IACpB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkC;IAC3D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;gBAEzB,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,CAAC,EAAE,OAAO;IAUjE,QAAQ,CAAC,IAAI,EAAE,MAAM;IAUrB,MAAM,CAAC,IAAI,EAAE,MAAM;IAQnB,YAAY,CAAC,IAAI,EAAE,MAAM;IAUzB,WAAW,CAAC,IAAI,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAmBrC,IAAW,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAEhB;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/resolver.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/resolver.d.ts new file mode 100644 index 0000000..e3837df --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/resolver.d.ts @@ -0,0 +1,14 @@ +import { Contract } from 'web3-eth-contract'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +import { Registry } from './registry.js'; +export declare class Resolver { + private readonly registry; + constructor(registry: Registry); + private getResolverContractAdapter; + checkInterfaceSupport(resolverContract: Contract, methodName: string): Promise; + supportsInterface(ENSName: string, interfaceId: string): Promise>; + getAddress(ENSName: string, coinType?: number): Promise>; + getPubkey(ENSName: string): Promise> & Record<0, import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & [] & Record<"x", import("web3-types").MatchPrimitiveType<"bytes32", unknown>> & Record<"y", import("web3-types").MatchPrimitiveType<"bytes32", unknown>>>; + getContenthash(ENSName: string): Promise>; +} +//# sourceMappingURL=resolver.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/resolver.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/resolver.d.ts.map new file mode 100644 index 0000000..e1d2dfc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/resolver.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../../src/resolver.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAMzC,qBAAa,QAAQ;IACpB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAW;gBAEjB,QAAQ,EAAE,QAAQ;YAIvB,0BAA0B;IAO3B,qBAAqB,CACjC,gBAAgB,EAAE,QAAQ,CAAC,OAAO,iBAAiB,CAAC,EACpD,UAAU,EAAE,MAAM;IAmBN,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM;IAiBtD,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAW;IAQjD,SAAS,CAAC,OAAO,EAAE,MAAM;IAQzB,cAAc,CAAC,OAAO,EAAE,MAAM;CAO3C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/utils.d.ts b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/utils.d.ts new file mode 100644 index 0000000..efc0608 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/utils.d.ts @@ -0,0 +1,3 @@ +export declare const normalize: (name: string) => string; +export declare const namehash: (inputName: string) => string; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/lib/types/utils.d.ts.map b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/utils.d.ts.map new file mode 100644 index 0000000..168bbeb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/lib/types/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,SAAS,SAAU,MAAM,WAAwB,CAAC;AAE/D,eAAO,MAAM,QAAQ,cAAe,MAAM,WAkBzC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-ens/package.json b/test/merkletreejs/node_modules/web3-eth-ens/package.json new file mode 100644 index 0000000..cb11756 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/package.json @@ -0,0 +1,72 @@ +{ + "name": "web3-eth-ens", + "version": "4.0.8", + "description": "This package has ENS functions for interacting with Ethereum Name Service.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js", + "ens:download:registry": "curl -L -o test/fixtures/ens/registry.json 'https://api.etherscan.io/api?module=contract&action=getabi&address=0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'", + "ens:download:reverse_registrar": "curl -L -o test/fixtures/ens/reverse_registrar.json 'https://api.etherscan.io/api?module=contract&action=getabi&address=0x084b1c3c81545d370f3634392de611caabff8148'" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "@adraffy/ens-normalize": "^1.8.8", + "web3-core": "^4.3.0", + "web3-errors": "^1.1.3", + "web3-eth": "^4.3.1", + "web3-eth-contract": "^4.1.2", + "web3-net": "^4.0.7", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "web3-validator": "^2.0.3" + }, + "gitHead": "41824d669db6aae87d7917122a28d5f057f5aa74" +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/abi/ens/ENSRegistry.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/abi/ens/ENSRegistry.ts new file mode 100644 index 0000000..bcac4c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/abi/ens/ENSRegistry.ts @@ -0,0 +1,183 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// https://github.com/ensdomains/ens-contracts/blob/master/contracts/registry/ENSRegistry.sol +export const ENSRegistryAbi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'bytes32', + name: 'label', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'owner', + type: 'address', + }, + ], + name: 'NewOwner', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'resolver', + type: 'address', + }, + ], + name: 'NewResolver', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'owner', + type: 'address', + }, + ], + name: 'Transfer', + type: 'event', + }, + { + inputs: [ + { + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + internalType: 'address', + name: 'operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'owner', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'recordExists', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'resolver', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'ttl', + outputs: [ + { + internalType: 'uint64', + name: '', + type: 'uint64', + }, + ], + stateMutability: 'view', + type: 'function', + }, +] as const; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/abi/ens/PublicResolver.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/abi/ens/PublicResolver.ts new file mode 100644 index 0000000..83b927b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/abi/ens/PublicResolver.ts @@ -0,0 +1,593 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// https://github.com/ensdomains/ens-contracts/blob/master/contracts/resolvers/PublicResolver.sol +export const PublicResolverAbi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'address', + name: 'a', + type: 'address', + }, + ], + name: 'AddrChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'uint256', + name: 'coinType', + type: 'uint256', + }, + { + indexed: false, + internalType: 'bytes', + name: 'newAddress', + type: 'bytes', + }, + ], + name: 'AddressChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + indexed: true, + internalType: 'address', + name: 'operator', + type: 'address', + }, + { + indexed: false, + internalType: 'bool', + name: 'approved', + type: 'bool', + }, + ], + name: 'ApprovalForAll', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'hash', + type: 'bytes', + }, + ], + name: 'ContenthashChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'name', + type: 'bytes', + }, + { + indexed: false, + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + { + indexed: false, + internalType: 'bytes', + name: 'record', + type: 'bytes', + }, + ], + name: 'DNSRecordChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'name', + type: 'bytes', + }, + { + indexed: false, + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + ], + name: 'DNSRecordDeleted', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'DNSZoneCleared', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes', + name: 'lastzonehash', + type: 'bytes', + }, + { + indexed: false, + internalType: 'bytes', + name: 'zonehash', + type: 'bytes', + }, + ], + name: 'DNSZonehashChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + { + indexed: false, + internalType: 'address', + name: 'implementer', + type: 'address', + }, + ], + name: 'InterfaceChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'string', + name: 'name', + type: 'string', + }, + ], + name: 'NameChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes32', + name: 'x', + type: 'bytes32', + }, + { + indexed: false, + internalType: 'bytes32', + name: 'y', + type: 'bytes32', + }, + ], + name: 'PubkeyChanged', + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + indexed: true, + internalType: 'string', + name: 'indexedKey', + type: 'string', + }, + { + indexed: false, + internalType: 'string', + name: 'key', + type: 'string', + }, + ], + name: 'TextChanged', + type: 'event', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'uint256', + name: 'contentTypes', + type: 'uint256', + }, + ], + name: 'ABI', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'addr', + outputs: [ + { + internalType: 'address payable', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'uint256', + name: 'coinType', + type: 'uint256', + }, + ], + name: 'addr', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'contenthash', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'name', + type: 'bytes32', + }, + { + internalType: 'uint16', + name: 'resource', + type: 'uint16', + }, + ], + name: 'dnsRecord', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'name', + type: 'bytes32', + }, + ], + name: 'hasDNSRecords', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + ], + name: 'interfaceImplementer', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: 'account', + type: 'address', + }, + { + internalType: 'address', + name: 'operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'name', + outputs: [ + { + internalType: 'string', + name: '', + type: 'string', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'pubkey', + outputs: [ + { + internalType: 'bytes32', + name: 'x', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'y', + type: 'bytes32', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes4', + name: 'interfaceID', + type: 'bytes4', + }, + ], + name: 'supportsInterface', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + { + internalType: 'string', + name: 'key', + type: 'string', + }, + ], + name: 'text', + outputs: [ + { + internalType: 'string', + name: '', + type: 'string', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'bytes32', + name: 'node', + type: 'bytes32', + }, + ], + name: 'zonehash', + outputs: [ + { + internalType: 'bytes', + name: '', + type: 'bytes', + }, + ], + stateMutability: 'view', + type: 'function', + }, +] as const; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/config.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/config.ts new file mode 100644 index 0000000..1437c97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/config.ts @@ -0,0 +1,54 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// +/** + * An object holding the interface Ids of the ENS resolver contracts. Please see [how to write a resolver](https://docs.ens.domains/contract-developer-guide/writing-a-resolver). + */ +export const interfaceIds: { [T: string]: string } = { + addr: '0x3b3b57de', + name: '0x691f3431', + abi: '0x2203ab56', + pubkey: '0xc8690233', + text: '0x59d1d43c', + contenthash: '0xbc1c58d1', +}; + +/** + * An object holding the functionsthat are supported by the ENS resolver contracts/interfaces. + */ +export const methodsInInterface: { [T: string]: string } = { + setAddr: 'addr', + addr: 'addr', + setPubkey: 'pubkey', + pubkey: 'pubkey', + setContenthash: 'contenthash', + contenthash: 'contenthash', +}; + +/** + * An object holding the addressed of the ENS registries on the different networks (mainnet, goerli). + */ +export const registryAddresses: { [T: string]: string } = { + main: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', + goerli: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', +}; + +export const networkIds: { [T: string]: string } = { + '0x1': 'main', + '0x5': 'goerli', +}; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/ens.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/ens.ts new file mode 100644 index 0000000..26c642e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/ens.ts @@ -0,0 +1,244 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Context, Web3ContextObject } from 'web3-core'; +import { ENSNetworkNotSyncedError, ENSUnsupportedNetworkError } from 'web3-errors'; +import { isSyncing } from 'web3-eth'; +import { Contract } from 'web3-eth-contract'; +import { getId } from 'web3-net'; +import { + DEFAULT_RETURN_FORMAT, + EthExecutionAPI, + FMT_NUMBER, + SupportedProviders, + Web3NetAPI, +} from 'web3-types'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +import { networkIds, registryAddresses } from './config.js'; +import { Registry } from './registry.js'; +import { Resolver } from './resolver.js'; + +/** + * This class is designed to interact with the ENS system on the Ethereum blockchain. + * + */ +export class ENS extends Web3Context { + /** + * The registryAddress property can be used to define a custom registry address when you are connected to an unknown chain. It defaults to the main registry address. + */ + public registryAddress: string; + private readonly _registry: Registry; + private readonly _resolver: Resolver; + private _detectedAddress?: string; + private _lastSyncCheck?: number; + + /** + * Use to create an instance of ENS + * @param registryAddr - (Optional) The address of the ENS registry (default: mainnet registry address) + * @param provider - (Optional) The provider to use for the ENS instance + * @example + * ```ts + * const ens = new ENS( + * "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + * "http://localhost:8545" + * ); + * + * console.log( ens.defaultChain); + * > mainnet + * ``` + */ + public constructor( + registryAddr?: string, + provider?: + | SupportedProviders + | Web3ContextObject + | string, + ) { + super(provider ?? ''); + this.registryAddress = registryAddr ?? registryAddresses.main; // will default to main registry address + this._registry = new Registry(this.getContextObject(), registryAddr); + this._resolver = new Resolver(this._registry); + } + + /** + * Returns the Resolver by the given address + * @param name - The name of the ENS domain + * @returns - An contract instance of the resolver + * + * @example + * ```ts + * const resolver = await ens.getResolver('resolver'); + * + * console.log(resolver.options.address); + * > '0x1234567890123456789012345678901234567890' + * ``` + */ + public async getResolver(name: string): Promise> { + return this._registry.getResolver(name); + } + + /** + * Returns true if the record exists + * @param name - The ENS name + * @returns - Returns `true` if node exists in this ENS registry. This will return `false` for records that are in the legacy ENS registry but have not yet been migrated to the new one. + * @example + * ```ts + * const exists = await web3.eth.ens.recordExists('ethereum.eth'); + * ``` + */ + public async recordExists(name: string): Promise { + return this._registry.recordExists(name); + } + + /** + * Returns the caching TTL (time-to-live) of an ENS name. + * @param name - The ENS name + * @returns - Returns the caching TTL (time-to-live) of a name. + * @example + * ```ts + * const owner = await web3.eth.ens.getTTL('ethereum.eth'); + * ``` + */ + public async getTTL(name: string): Promise { + return this._registry.getTTL(name); + } + + /** + * Returns the owner by the given name and current configured or detected Registry + * @param name - The ENS name + * @returns - Returns the address of the owner of the name. + * @example + * ```ts + * const owner = await web3.eth.ens.getOwner('ethereum.eth'); + * ``` + */ + public async getOwner(name: string): Promise { + return this._registry.getOwner(name); + } + + /** + * Resolves an ENS name to an Ethereum address. + * @param ENSName - The ENS name to resolve + * @param coinType - (Optional) The coin type, defaults to 60 (ETH) + * @returns - The Ethereum address of the given name + * ```ts + * const address = await web3.eth.ens.getAddress('ethereum.eth'); + * console.log(address); + * > '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' + * ``` + */ + public async getAddress(ENSName: string, coinType = 60) { + return this._resolver.getAddress(ENSName, coinType); + } + + /** + * Returns the X and Y coordinates of the curve point for the public key. + * @param ENSName - The ENS name + * @returns - The X and Y coordinates of the curve point for the public key + * @example + * ```ts + * const key = await web3.eth.ens.getPubkey('ethereum.eth'); + * console.log(key); + * > { + * "0": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "1": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "x": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "y": "0x0000000000000000000000000000000000000000000000000000000000000000" + * } + * ``` + */ + public async getPubkey(ENSName: string) { + return this._resolver.getPubkey(ENSName); + } + + /** + * Returns the content hash object associated with an ENS node. + * @param ENSName - The ENS name + * @returns - The content hash object associated with an ENS node + * @example + * ```ts + * const hash = await web3.eth.ens.getContenthash('ethereum.eth'); + * console.log(hash); + * > 'QmaEBknbGT4bTQiQoe2VNgBJbRfygQGktnaW5TbuKixjYL' + * ``` + */ + public async getContenthash(ENSName: string) { + return this._resolver.getContenthash(ENSName); + } + + /** + * Checks if the current used network is synced and looks for ENS support there. + * Throws an error if not. + * @returns - The address of the ENS registry if the network has been detected successfully + * @example + * ```ts + * console.log(await web3.eth.ens.checkNetwork()); + * > '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' + * ``` + */ + public async checkNetwork() { + const now = Date.now() / 1000; + if (!this._lastSyncCheck || now - this._lastSyncCheck > 3600) { + const syncInfo = await isSyncing(this); + + if (!(typeof syncInfo === 'boolean' && !syncInfo)) { + throw new ENSNetworkNotSyncedError(); + } + + this._lastSyncCheck = now; + } + + if (this._detectedAddress) { + return this._detectedAddress; + } + const networkType = await getId(this, { + ...DEFAULT_RETURN_FORMAT, + number: FMT_NUMBER.HEX, + }); // get the network from provider + const addr = registryAddresses[networkIds[networkType]]; + + if (typeof addr === 'undefined') { + throw new ENSUnsupportedNetworkError(networkType); + } + + this._detectedAddress = addr; + return this._detectedAddress; + } + + /** + * Returns true if the related Resolver does support the given signature or interfaceId. + * @param ENSName - The ENS name + * @param interfaceId - The signature of the function or the interfaceId as described in the ENS documentation + * @returns - `true` if the related Resolver does support the given signature or interfaceId. + * @example + * ```ts + * const supports = await web3.eth.ens.supportsInterface('ethereum.eth', 'addr(bytes32'); + * console.log(supports); + * > true + * ``` + */ + public async supportsInterface(ENSName: string, interfaceId: string) { + return this._resolver.supportsInterface(ENSName, interfaceId); + } + + /** + * @returns - Returns all events that can be emitted by the ENS registry. + */ + public get events() { + return this._registry.events; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/index.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/index.ts new file mode 100644 index 0000000..b57e671 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/index.ts @@ -0,0 +1,34 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The `web3.eth.ens` functions let you interact with ENS. We recommend reading the [ENS documentation](https://docs.ens.domains/) to get deeper insights about the internals of the name service. + * + * ## Breaking Changes + * + * - All the API level interfaces returning or accepting `null` in 1.x, use `undefined` in 4.x. + * - Functions don't accept a callback anymore. + * - Functions that accepted an optional `TransactionConfig` as the last argument, now accept an optional `NonPayableCallOptions`. See `web3-eth-contract` package for more details. + * - Removed all non-read methods. If you need modifing resolver or registry, please use https://www.npmjs.com/package/@ensdomains/ensjs + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { registryAddresses } from './config.js'; + +export * from './ens.js'; +export { registryAddresses }; diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/registry.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/registry.ts new file mode 100644 index 0000000..1c41435 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/registry.ts @@ -0,0 +1,90 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3ContextObject } from 'web3-core'; +import { Contract } from 'web3-eth-contract'; +import { Address } from 'web3-types'; +import { ENSRegistryAbi } from './abi/ens/ENSRegistry.js'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +import { registryAddresses } from './config.js'; +import { namehash } from './utils.js'; + +export class Registry { + private readonly contract: Contract; + private readonly context: Web3ContextObject; + + public constructor(context: Web3ContextObject, customRegistryAddress?: Address) { + this.contract = new Contract( + ENSRegistryAbi, + customRegistryAddress ?? registryAddresses.main, + context, + ); + + this.context = context; + } + + public async getOwner(name: string) { + try { + const result = this.contract.methods.owner(namehash(name)).call(); + + return result; + } catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + } + + public async getTTL(name: string) { + try { + return this.contract.methods.ttl(namehash(name)).call(); + } catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + } + + public async recordExists(name: string) { + try { + const promise = this.contract.methods.recordExists(namehash(name)).call(); + + return promise; + } catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + } + + public async getResolver(name: string) { + try { + return this.contract.methods + .resolver(namehash(name)) + .call() + .then(address => { + // address type is unknown, not sure why + if (typeof address === 'string') { + const contract = new Contract(PublicResolverAbi, address, this.context); + // TODO: set contract provider needs to be added when ens current provider + return contract; + } + throw new Error(); + }); + } catch (error) { + throw new Error(); // TODO: TransactionRevertInstructionError Needs to be added after web3-eth call method is implemented + } + } + + public get events() { + return this.contract.events; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/resolver.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/resolver.ts new file mode 100644 index 0000000..3540455 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/resolver.ts @@ -0,0 +1,105 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ResolverMethodMissingError } from 'web3-errors'; +import { Contract } from 'web3-eth-contract'; +import { isNullish, sha3 } from 'web3-utils'; +import { isHexStrict } from 'web3-validator'; +import { PublicResolverAbi } from './abi/ens/PublicResolver.js'; +import { interfaceIds, methodsInInterface } from './config.js'; +import { Registry } from './registry.js'; +import { namehash } from './utils.js'; + +// Default public resolver +// https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol + +export class Resolver { + private readonly registry: Registry; + + public constructor(registry: Registry) { + this.registry = registry; + } + + private async getResolverContractAdapter(ENSName: string) { + // TODO : (Future 4.1.0 TDB) cache resolver contract if frequently queried same ENS name, refresh cache based on TTL and usage, also limit cache size, optional cache with a flag + return this.registry.getResolver(ENSName); + } + + // https://eips.ethereum.org/EIPS/eip-165 + // eslint-disable-next-line class-methods-use-this + public async checkInterfaceSupport( + resolverContract: Contract, + methodName: string, + ) { + if (isNullish(interfaceIds[methodName])) + throw new ResolverMethodMissingError( + resolverContract.options.address ?? '', + methodName, + ); + + const supported = await resolverContract.methods + .supportsInterface(interfaceIds[methodName]) + .call(); + + if (!supported) + throw new ResolverMethodMissingError( + resolverContract.options.address ?? '', + methodName, + ); + } + + public async supportsInterface(ENSName: string, interfaceId: string) { + const resolverContract = await this.getResolverContractAdapter(ENSName); + + let interfaceIdParam = interfaceId; + + if (!isHexStrict(interfaceIdParam)) { + interfaceIdParam = sha3(interfaceId) ?? ''; + + if (interfaceId === '') throw new Error('Invalid interface Id'); + + interfaceIdParam = interfaceIdParam.slice(0, 10); + } + + return resolverContract.methods.supportsInterface(interfaceIdParam).call(); + } + + // eslint-disable-next-line @typescript-eslint/no-inferrable-types + public async getAddress(ENSName: string, coinType: number = 60) { + const resolverContract = await this.getResolverContractAdapter(ENSName); + + await this.checkInterfaceSupport(resolverContract, methodsInInterface.addr); + + return resolverContract.methods.addr(namehash(ENSName), coinType).call(); + } + + public async getPubkey(ENSName: string) { + const resolverContract = await this.getResolverContractAdapter(ENSName); + + await this.checkInterfaceSupport(resolverContract, methodsInInterface.pubkey); + + return resolverContract.methods.pubkey(namehash(ENSName)).call(); + } + + public async getContenthash(ENSName: string) { + const resolverContract = await this.getResolverContractAdapter(ENSName); + + await this.checkInterfaceSupport(resolverContract, methodsInInterface.contenthash); + + return resolverContract.methods.contenthash(namehash(ENSName)).call(); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-ens/src/utils.ts b/test/merkletreejs/node_modules/web3-eth-ens/src/utils.ts new file mode 100644 index 0000000..0184929 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-ens/src/utils.ts @@ -0,0 +1,42 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { sha3Raw } from 'web3-utils'; +// eslint-disable-next-line camelcase +import { ens_normalize } from '@adraffy/ens-normalize'; + +export const normalize = (name: string) => ens_normalize(name); + +export const namehash = (inputName: string) => { + // Reject empty names: + let node = ''; + for (let i = 0; i < 32; i += 1) { + node += '00'; + } + + if (inputName) { + const name = normalize(inputName); + const labels = name.split('.'); + + for (let i = labels.length - 1; i >= 0; i -= 1) { + const labelSha = sha3Raw(labels[i]).slice(2); + node = sha3Raw(`0x${node}${labelSha}`).slice(2); + } + } + + return `0x${node}`; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-iban/LICENSE b/test/merkletreejs/node_modules/web3-eth-iban/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth-iban/README.md b/test/merkletreejs/node_modules/web3-eth-iban/README.md new file mode 100644 index 0000000..11c7e52 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - IBAN + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth-iban` This package converts Ethereum addresses to IBAN addresses a vice versa. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth-iban) or using [Yarn](https://yarnpkg.com/package/web3-eth-iban) + +### Using NPM + +```bash +npm install web3-eth-iban +``` + +### Using Yarn + +```bash +yarn add web3-eth-iban +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth-iban +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-iban%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth-iban +[downloads-image]: https://img.shields.io/npm/dm/web3-eth-iban?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.d.ts b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.d.ts new file mode 100644 index 0000000..9e3d82a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.d.ts @@ -0,0 +1,263 @@ +import { HexString } from 'web3-types'; +import { IbanOptions } from './types.js'; +/** + * Converts Ethereum addresses to IBAN or BBAN addresses and vice versa. + */ +export declare class Iban { + private readonly _iban; + /** + * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to + * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. + */ + private static readonly _iso13616Prepare; + /** + * return the bigint of the given string with the specified base + */ + private static readonly _parseInt; + /** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + */ + private static readonly _mod9710; + /** + * A static method that checks if an IBAN is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isDirect("XE81ETHXREGGAVOFYORK"); + * > false + * ``` + */ + static isDirect(iban: string): boolean; + /** + * An instance method that checks if iban number is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isDirect(); + * > false + * ``` + */ + isDirect(): boolean; + /** + * A static method that checks if an IBAN is Indirect. + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isIndirect("XE81ETHXREGGAVOFYORK"); + * > true + * ``` + */ + static isIndirect(iban: string): boolean; + /** + * check if iban number if indirect + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isIndirect(); + * > true + * ``` + */ + isIndirect(): boolean; + /** + * This method could be used to check if a given string is valid IBAN object. + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a string to be checked if it is in IBAN + * @returns - true if it is valid IBAN + * + * @example + * ```ts + * web3.eth.Iban.isValid("XE81ETHXREGGAVOFYORK"); + * > true + * + * web3.eth.Iban.isValid("XE82ETHXREGGAVOFYORK"); + * > false // because the checksum is incorrect + * ``` + */ + static isValid(iban: string): boolean; + /** + * Should be called to check if the early provided IBAN is correct. + * Note: this is also available as a static method. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isValid(); + * > true + * + * const iban = new web3.eth.Iban("XE82ETHXREGGAVOFYORK"); + * iban.isValid(); + * > false // because the checksum is incorrect + * ``` + */ + isValid(): boolean; + /** + * Construct a direct or indirect IBAN that has conversion methods and validity checks. + * If the provided string was not of either the length of a direct IBAN (34 or 35), + * nor the length of an indirect IBAN (20), an Error will be thrown ('Invalid IBAN was provided'). + * + * @param iban - a Direct or an Indirect IBAN + * @returns - Iban instance + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > Iban { _iban: 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' } + * ``` + */ + constructor(iban: string); + /** + * Convert the passed BBAN to an IBAN for this country specification. + * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @param bban - the BBAN to convert to IBAN + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromBban('ETHXREGGAVOFYORK'); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromBban(bban: string): Iban; + /** + * Should be used to create IBAN object for given institution and identifier + * + * @param options - an object holds the `institution` and the `identifier` which will be composed to create an `Iban` object from. + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.createIndirect({ + * institution: "XREG", + * identifier: "GAVOFYORK" + * }); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static createIndirect(options: IbanOptions): Iban; + /** + * This method should be used to create iban object from an Ethereum address. + * + * @param address - an Ethereum address + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromAddress(address: HexString): Iban; + /** + * This method should be used to create an ethereum address from a Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a Direct IBAN address + * @return the equivalent ethereum address + * + * @example + * ```ts + * web3.eth.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + static toAddress: (iban: string) => HexString; + /** + * This method should be used to create the equivalent ethereum address for the early provided Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a static method. + * + * @return the equivalent ethereum address + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * iban.toAddress(); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + toAddress: () => HexString; + /** + * This method should be used to create IBAN address from an Ethereum address + * + * @param address - an Ethereum address + * @return the equivalent IBAN address + * + * @example + * ```ts + * web3.eth.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS" + * ``` + */ + static toIban(address: HexString): string; + /** + * Should be called to get client identifier within institution + * + * @return the client of the IBAN instance. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.client(); + * > 'GAVOFYORK' + * ``` + */ + client(): string; + /** + * Returns the IBAN checksum of the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.checksum(); + * > "81" + * ``` + * + */ + checksum(): string; + /** + * Returns institution identifier from the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.institution(); + * > 'XREG' + * ``` + */ + institution(): string; + /** + * Simply returns the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + * iban.toString(); + * > 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' + * ``` + */ + toString(): string; +} diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.js b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.js new file mode 100644 index 0000000..2e9af77 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.js @@ -0,0 +1,365 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Iban = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +/** + * Converts Ethereum addresses to IBAN or BBAN addresses and vice versa. + */ +class Iban { + /** + * Construct a direct or indirect IBAN that has conversion methods and validity checks. + * If the provided string was not of either the length of a direct IBAN (34 or 35), + * nor the length of an indirect IBAN (20), an Error will be thrown ('Invalid IBAN was provided'). + * + * @param iban - a Direct or an Indirect IBAN + * @returns - Iban instance + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > Iban { _iban: 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' } + * ``` + */ + constructor(iban) { + /** + * This method should be used to create the equivalent ethereum address for the early provided Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a static method. + * + * @return the equivalent ethereum address + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * iban.toAddress(); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + this.toAddress = () => { + if (this.isDirect()) { + // check if Iban can be converted to an address + const base36 = this._iban.slice(4); + const parsedBigInt = Iban._parseInt(base36, 36); // convert the base36 string to a bigint + const paddedBigInt = (0, web3_utils_1.leftPad)(parsedBigInt, 40); + return (0, web3_utils_1.toChecksumAddress)(paddedBigInt); + } + throw new Error('Iban is indirect and cannot be converted. Must be length of 34 or 35'); + }; + if (Iban.isIndirect(iban) || Iban.isDirect(iban)) { + this._iban = iban; + } + else { + throw new Error('Invalid IBAN was provided'); + } + } + /** + * A static method that checks if an IBAN is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isDirect("XE81ETHXREGGAVOFYORK"); + * > false + * ``` + */ + static isDirect(iban) { + return iban.length === 34 || iban.length === 35; + } + /** + * An instance method that checks if iban number is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isDirect(); + * > false + * ``` + */ + isDirect() { + return Iban.isDirect(this._iban); + } + /** + * A static method that checks if an IBAN is Indirect. + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isIndirect("XE81ETHXREGGAVOFYORK"); + * > true + * ``` + */ + static isIndirect(iban) { + return iban.length === 20; + } + /** + * check if iban number if indirect + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isIndirect(); + * > true + * ``` + */ + isIndirect() { + return Iban.isIndirect(this._iban); + } + /** + * This method could be used to check if a given string is valid IBAN object. + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a string to be checked if it is in IBAN + * @returns - true if it is valid IBAN + * + * @example + * ```ts + * web3.eth.Iban.isValid("XE81ETHXREGGAVOFYORK"); + * > true + * + * web3.eth.Iban.isValid("XE82ETHXREGGAVOFYORK"); + * > false // because the checksum is incorrect + * ``` + */ + static isValid(iban) { + return (/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(iban) && + Iban._mod9710(Iban._iso13616Prepare(iban)) === 1); + } + /** + * Should be called to check if the early provided IBAN is correct. + * Note: this is also available as a static method. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isValid(); + * > true + * + * const iban = new web3.eth.Iban("XE82ETHXREGGAVOFYORK"); + * iban.isValid(); + * > false // because the checksum is incorrect + * ``` + */ + isValid() { + return Iban.isValid(this._iban); + } + /** + * Convert the passed BBAN to an IBAN for this country specification. + * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @param bban - the BBAN to convert to IBAN + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromBban('ETHXREGGAVOFYORK'); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromBban(bban) { + const countryCode = 'XE'; + const remainder = this._mod9710(this._iso13616Prepare(`${countryCode}00${bban}`)); + const checkDigit = `0${(98 - remainder).toString()}`.slice(-2); + return new Iban(`${countryCode}${checkDigit}${bban}`); + } + /** + * Should be used to create IBAN object for given institution and identifier + * + * @param options - an object holds the `institution` and the `identifier` which will be composed to create an `Iban` object from. + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.createIndirect({ + * institution: "XREG", + * identifier: "GAVOFYORK" + * }); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static createIndirect(options) { + return Iban.fromBban(`ETH${options.institution}${options.identifier}`); + } + /** + * This method should be used to create iban object from an Ethereum address. + * + * @param address - an Ethereum address + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromAddress(address) { + if (!(0, web3_validator_1.isAddress)(address)) { + throw new web3_errors_1.InvalidAddressError(address); + } + const num = BigInt((0, web3_utils_1.hexToNumber)(address)); + const base36 = num.toString(36); + const padded = (0, web3_utils_1.leftPad)(base36, 15); + return Iban.fromBban(padded.toUpperCase()); + } + /** + * This method should be used to create IBAN address from an Ethereum address + * + * @param address - an Ethereum address + * @return the equivalent IBAN address + * + * @example + * ```ts + * web3.eth.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS" + * ``` + */ + static toIban(address) { + return Iban.fromAddress(address).toString(); + } + /** + * Should be called to get client identifier within institution + * + * @return the client of the IBAN instance. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.client(); + * > 'GAVOFYORK' + * ``` + */ + client() { + return this.isIndirect() ? this._iban.slice(11) : ''; + } + /** + * Returns the IBAN checksum of the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.checksum(); + * > "81" + * ``` + * + */ + checksum() { + return this._iban.slice(2, 4); + } + /** + * Returns institution identifier from the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.institution(); + * > 'XREG' + * ``` + */ + institution() { + return this.isIndirect() ? this._iban.slice(7, 11) : ''; + } + /** + * Simply returns the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + * iban.toString(); + * > 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' + * ``` + */ + toString() { + return this._iban; + } +} +exports.Iban = Iban; +/** + * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to + * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. + */ +Iban._iso13616Prepare = (iban) => { + const A = 'A'.charCodeAt(0); + const Z = 'Z'.charCodeAt(0); + const upperIban = iban.toUpperCase(); + const modifiedIban = `${upperIban.slice(4)}${upperIban.slice(0, 4)}`; + return modifiedIban + .split('') + .map(n => { + const code = n.charCodeAt(0); + if (code >= A && code <= Z) { + // A = 10, B = 11, ... Z = 35 + return code - A + 10; + } + return n; + }) + .join(''); +}; +/** + * return the bigint of the given string with the specified base + */ +Iban._parseInt = (str, base) => [...str].reduce((acc, curr) => BigInt(parseInt(curr, base)) + BigInt(base) * acc, BigInt(0)); +/** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + */ +Iban._mod9710 = (iban) => { + let remainder = iban; + let block; + while (remainder.length > 2) { + block = remainder.slice(0, 9); + remainder = `${(parseInt(block, 10) % 97).toString()}${remainder.slice(block.length)}`; + } + return parseInt(remainder, 10) % 97; +}; +/** + * This method should be used to create an ethereum address from a Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a Direct IBAN address + * @return the equivalent ethereum address + * + * @example + * ```ts + * web3.eth.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ +Iban.toAddress = (iban) => { + const ibanObject = new Iban(iban); + return ibanObject.toAddress(); +}; +//# sourceMappingURL=iban.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.js.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.js.map new file mode 100644 index 0000000..f37d576 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/iban.js.map @@ -0,0 +1 @@ +{"version":3,"file":"iban.js","sourceRoot":"","sources":["../../src/iban.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,2CAAqE;AACrE,mDAA2C;AAC3C,6CAAkD;AAGlD;;GAEG;AACH,MAAa,IAAI;IAmKhB;;;;;;;;;;;;;OAaG;IACH,YAAmB,IAAY;QA6F/B;;;;;;;;;;;;;;WAcG;QACI,cAAS,GAAG,GAAc,EAAE;YAClC,IAAI,IAAI,CAAC,QAAQ,EAAE,EAAE;gBACpB,+CAA+C;gBAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBACnC,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,wCAAwC;gBACzF,MAAM,YAAY,GAAG,IAAA,oBAAO,EAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBAC/C,OAAO,IAAA,8BAAiB,EAAC,YAAY,CAAC,CAAC;aACvC;YACD,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;QACzF,CAAC,CAAC;QApHD,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;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IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,EAChE,MAAM,CAAC,CAAC,CAAC,CACT,CAAC;AAEH;;GAEG;AACqB,aAAQ,GAAG,CAAC,IAAY,EAAU,EAAE;IAC3D,IAAI,SAAS,GAAG,IAAI,CAAC;IACrB,IAAI,KAAK,CAAC;IAEV,OAAO,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC9B,SAAS,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,EAAE,GAAG,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;KACvF;IAED,OAAO,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC;AACrC,CAAC,CAAC;AAyMF;;;;;;;;;;;;;;GAcG;AACW,cAAS,GAAG,CAAC,IAAY,EAAa,EAAE;IACrD,MAAM,UAAU,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAClC,OAAO,UAAU,CAAC,SAAS,EAAE,CAAC;AAC/B,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.d.ts new file mode 100644 index 0000000..4fd949c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.d.ts @@ -0,0 +1,4 @@ +import { Iban } from './iban.js'; +export * from './iban.js'; +export * from './types.js'; +export default Iban; diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.js new file mode 100644 index 0000000..1a2d537 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.js @@ -0,0 +1,37 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const iban_js_1 = require("./iban.js"); +__exportStar(require("./iban.js"), exports); +__exportStar(require("./types.js"), exports); +exports.default = iban_js_1.Iban; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.js.map new file mode 100644 index 0000000..09a4987 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF,uCAAiC;AAEjC,4CAA0B;AAC1B,6CAA2B;AAE3B,kBAAe,cAAI,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.d.ts new file mode 100644 index 0000000..0a8eae3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.d.ts @@ -0,0 +1,7 @@ +/** + * An object that could hold the components for an Indirect IBAN (BBAN) + */ +export declare type IbanOptions = { + institution: string; + identifier: string; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/iban.js b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/iban.js new file mode 100644 index 0000000..4712544 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/iban.js @@ -0,0 +1,361 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { toChecksumAddress, leftPad, hexToNumber } from 'web3-utils'; +import { isAddress } from 'web3-validator'; +import { InvalidAddressError } from 'web3-errors'; +/** + * Converts Ethereum addresses to IBAN or BBAN addresses and vice versa. + */ +export class Iban { + /** + * Construct a direct or indirect IBAN that has conversion methods and validity checks. + * If the provided string was not of either the length of a direct IBAN (34 or 35), + * nor the length of an indirect IBAN (20), an Error will be thrown ('Invalid IBAN was provided'). + * + * @param iban - a Direct or an Indirect IBAN + * @returns - Iban instance + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > Iban { _iban: 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' } + * ``` + */ + constructor(iban) { + /** + * This method should be used to create the equivalent ethereum address for the early provided Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a static method. + * + * @return the equivalent ethereum address + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * iban.toAddress(); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + this.toAddress = () => { + if (this.isDirect()) { + // check if Iban can be converted to an address + const base36 = this._iban.slice(4); + const parsedBigInt = Iban._parseInt(base36, 36); // convert the base36 string to a bigint + const paddedBigInt = leftPad(parsedBigInt, 40); + return toChecksumAddress(paddedBigInt); + } + throw new Error('Iban is indirect and cannot be converted. Must be length of 34 or 35'); + }; + if (Iban.isIndirect(iban) || Iban.isDirect(iban)) { + this._iban = iban; + } + else { + throw new Error('Invalid IBAN was provided'); + } + } + /** + * A static method that checks if an IBAN is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isDirect("XE81ETHXREGGAVOFYORK"); + * > false + * ``` + */ + static isDirect(iban) { + return iban.length === 34 || iban.length === 35; + } + /** + * An instance method that checks if iban number is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isDirect(); + * > false + * ``` + */ + isDirect() { + return Iban.isDirect(this._iban); + } + /** + * A static method that checks if an IBAN is Indirect. + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isIndirect("XE81ETHXREGGAVOFYORK"); + * > true + * ``` + */ + static isIndirect(iban) { + return iban.length === 20; + } + /** + * check if iban number if indirect + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isIndirect(); + * > true + * ``` + */ + isIndirect() { + return Iban.isIndirect(this._iban); + } + /** + * This method could be used to check if a given string is valid IBAN object. + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a string to be checked if it is in IBAN + * @returns - true if it is valid IBAN + * + * @example + * ```ts + * web3.eth.Iban.isValid("XE81ETHXREGGAVOFYORK"); + * > true + * + * web3.eth.Iban.isValid("XE82ETHXREGGAVOFYORK"); + * > false // because the checksum is incorrect + * ``` + */ + static isValid(iban) { + return (/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(iban) && + Iban._mod9710(Iban._iso13616Prepare(iban)) === 1); + } + /** + * Should be called to check if the early provided IBAN is correct. + * Note: this is also available as a static method. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isValid(); + * > true + * + * const iban = new web3.eth.Iban("XE82ETHXREGGAVOFYORK"); + * iban.isValid(); + * > false // because the checksum is incorrect + * ``` + */ + isValid() { + return Iban.isValid(this._iban); + } + /** + * Convert the passed BBAN to an IBAN for this country specification. + * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @param bban - the BBAN to convert to IBAN + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromBban('ETHXREGGAVOFYORK'); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromBban(bban) { + const countryCode = 'XE'; + const remainder = this._mod9710(this._iso13616Prepare(`${countryCode}00${bban}`)); + const checkDigit = `0${(98 - remainder).toString()}`.slice(-2); + return new Iban(`${countryCode}${checkDigit}${bban}`); + } + /** + * Should be used to create IBAN object for given institution and identifier + * + * @param options - an object holds the `institution` and the `identifier` which will be composed to create an `Iban` object from. + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.createIndirect({ + * institution: "XREG", + * identifier: "GAVOFYORK" + * }); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static createIndirect(options) { + return Iban.fromBban(`ETH${options.institution}${options.identifier}`); + } + /** + * This method should be used to create iban object from an Ethereum address. + * + * @param address - an Ethereum address + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromAddress(address) { + if (!isAddress(address)) { + throw new InvalidAddressError(address); + } + const num = BigInt(hexToNumber(address)); + const base36 = num.toString(36); + const padded = leftPad(base36, 15); + return Iban.fromBban(padded.toUpperCase()); + } + /** + * This method should be used to create IBAN address from an Ethereum address + * + * @param address - an Ethereum address + * @return the equivalent IBAN address + * + * @example + * ```ts + * web3.eth.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS" + * ``` + */ + static toIban(address) { + return Iban.fromAddress(address).toString(); + } + /** + * Should be called to get client identifier within institution + * + * @return the client of the IBAN instance. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.client(); + * > 'GAVOFYORK' + * ``` + */ + client() { + return this.isIndirect() ? this._iban.slice(11) : ''; + } + /** + * Returns the IBAN checksum of the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.checksum(); + * > "81" + * ``` + * + */ + checksum() { + return this._iban.slice(2, 4); + } + /** + * Returns institution identifier from the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.institution(); + * > 'XREG' + * ``` + */ + institution() { + return this.isIndirect() ? this._iban.slice(7, 11) : ''; + } + /** + * Simply returns the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + * iban.toString(); + * > 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' + * ``` + */ + toString() { + return this._iban; + } +} +/** + * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to + * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. + */ +Iban._iso13616Prepare = (iban) => { + const A = 'A'.charCodeAt(0); + const Z = 'Z'.charCodeAt(0); + const upperIban = iban.toUpperCase(); + const modifiedIban = `${upperIban.slice(4)}${upperIban.slice(0, 4)}`; + return modifiedIban + .split('') + .map(n => { + const code = n.charCodeAt(0); + if (code >= A && code <= Z) { + // A = 10, B = 11, ... Z = 35 + return code - A + 10; + } + return n; + }) + .join(''); +}; +/** + * return the bigint of the given string with the specified base + */ +Iban._parseInt = (str, base) => [...str].reduce((acc, curr) => BigInt(parseInt(curr, base)) + BigInt(base) * acc, BigInt(0)); +/** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + */ +Iban._mod9710 = (iban) => { + let remainder = iban; + let block; + while (remainder.length > 2) { + block = remainder.slice(0, 9); + remainder = `${(parseInt(block, 10) % 97).toString()}${remainder.slice(block.length)}`; + } + return parseInt(remainder, 10) % 97; +}; +/** + * This method should be used to create an ethereum address from a Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a Direct IBAN address + * @return the equivalent ethereum address + * + * @example + * ```ts + * web3.eth.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ +Iban.toAddress = (iban) => { + const ibanObject = new Iban(iban); + return ibanObject.toAddress(); +}; +//# sourceMappingURL=iban.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/iban.js.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/iban.js.map new file mode 100644 index 0000000..172ba9e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/iban.js.map @@ -0,0 +1 @@ +{"version":3,"file":"iban.js","sourceRoot":"","sources":["../../src/iban.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAGlD;;GAEG;AACH,MAAM,OAAO,IAAI;IAmKhB;;;;;;;;;;;;;OAaG;IACH,YAAmB,IAAY;QA6F/B;;;;;;;;;;;;;;WAcG;QACI,cAAS,GAAG,GAAc,EAAE;YAClC,IAAI,IAAI,CAAC,QAAQ,EAAE,EAAE;gBACpB,+CAA+C;gBAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBACnC,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,wCAAwC;gBACzF,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBAC/C,OAAO,iBAAiB,CAAC,YAAY,CAAC,CAAC;aACvC;YACD,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;QACzF,CAAC,CAAC;QApHD,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,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AAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,EAChE,MAAM,CAAC,CAAC,CAAC,CACT,CAAC;AAEH;;GAEG;AACqB,aAAQ,GAAG,CAAC,IAAY,EAAU,EAAE;IAC3D,IAAI,SAAS,GAAG,IAAI,CAAC;IACrB,IAAI,KAAK,CAAC;IAEV,OAAO,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC9B,SAAS,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,EAAE,GAAG,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;KACvF;IAED,OAAO,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC;AACrC,CAAC,CAAC;AAyMF;;;;;;;;;;;;;;GAcG;AACW,cAAS,GAAG,CAAC,IAAY,EAAa,EAAE;IACrD,MAAM,UAAU,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAClC,OAAO,UAAU,CAAC,SAAS,EAAE,CAAC;AAC/B,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/index.js new file mode 100644 index 0000000..1395d1d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/index.js @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Iban } from './iban.js'; +export * from './iban.js'; +export * from './types.js'; +export default Iban; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/index.js.map new file mode 100644 index 0000000..2d48b9e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAE3B,eAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/types.js b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/types/iban.d.ts b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/iban.d.ts new file mode 100644 index 0000000..29d3a3d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/iban.d.ts @@ -0,0 +1,264 @@ +import { HexString } from 'web3-types'; +import { IbanOptions } from './types.js'; +/** + * Converts Ethereum addresses to IBAN or BBAN addresses and vice versa. + */ +export declare class Iban { + private readonly _iban; + /** + * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to + * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. + */ + private static readonly _iso13616Prepare; + /** + * return the bigint of the given string with the specified base + */ + private static readonly _parseInt; + /** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + */ + private static readonly _mod9710; + /** + * A static method that checks if an IBAN is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isDirect("XE81ETHXREGGAVOFYORK"); + * > false + * ``` + */ + static isDirect(iban: string): boolean; + /** + * An instance method that checks if iban number is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isDirect(); + * > false + * ``` + */ + isDirect(): boolean; + /** + * A static method that checks if an IBAN is Indirect. + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isIndirect("XE81ETHXREGGAVOFYORK"); + * > true + * ``` + */ + static isIndirect(iban: string): boolean; + /** + * check if iban number if indirect + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isIndirect(); + * > true + * ``` + */ + isIndirect(): boolean; + /** + * This method could be used to check if a given string is valid IBAN object. + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a string to be checked if it is in IBAN + * @returns - true if it is valid IBAN + * + * @example + * ```ts + * web3.eth.Iban.isValid("XE81ETHXREGGAVOFYORK"); + * > true + * + * web3.eth.Iban.isValid("XE82ETHXREGGAVOFYORK"); + * > false // because the checksum is incorrect + * ``` + */ + static isValid(iban: string): boolean; + /** + * Should be called to check if the early provided IBAN is correct. + * Note: this is also available as a static method. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isValid(); + * > true + * + * const iban = new web3.eth.Iban("XE82ETHXREGGAVOFYORK"); + * iban.isValid(); + * > false // because the checksum is incorrect + * ``` + */ + isValid(): boolean; + /** + * Construct a direct or indirect IBAN that has conversion methods and validity checks. + * If the provided string was not of either the length of a direct IBAN (34 or 35), + * nor the length of an indirect IBAN (20), an Error will be thrown ('Invalid IBAN was provided'). + * + * @param iban - a Direct or an Indirect IBAN + * @returns - Iban instance + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > Iban { _iban: 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' } + * ``` + */ + constructor(iban: string); + /** + * Convert the passed BBAN to an IBAN for this country specification. + * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @param bban - the BBAN to convert to IBAN + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromBban('ETHXREGGAVOFYORK'); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromBban(bban: string): Iban; + /** + * Should be used to create IBAN object for given institution and identifier + * + * @param options - an object holds the `institution` and the `identifier` which will be composed to create an `Iban` object from. + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.createIndirect({ + * institution: "XREG", + * identifier: "GAVOFYORK" + * }); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static createIndirect(options: IbanOptions): Iban; + /** + * This method should be used to create iban object from an Ethereum address. + * + * @param address - an Ethereum address + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + static fromAddress(address: HexString): Iban; + /** + * This method should be used to create an ethereum address from a Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a Direct IBAN address + * @return the equivalent ethereum address + * + * @example + * ```ts + * web3.eth.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + static toAddress: (iban: string) => HexString; + /** + * This method should be used to create the equivalent ethereum address for the early provided Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a static method. + * + * @return the equivalent ethereum address + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * iban.toAddress(); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + toAddress: () => HexString; + /** + * This method should be used to create IBAN address from an Ethereum address + * + * @param address - an Ethereum address + * @return the equivalent IBAN address + * + * @example + * ```ts + * web3.eth.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS" + * ``` + */ + static toIban(address: HexString): string; + /** + * Should be called to get client identifier within institution + * + * @return the client of the IBAN instance. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.client(); + * > 'GAVOFYORK' + * ``` + */ + client(): string; + /** + * Returns the IBAN checksum of the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.checksum(); + * > "81" + * ``` + * + */ + checksum(): string; + /** + * Returns institution identifier from the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.institution(); + * > 'XREG' + * ``` + */ + institution(): string; + /** + * Simply returns the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + * iban.toString(); + * > 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' + * ``` + */ + toString(): string; +} +//# sourceMappingURL=iban.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/types/iban.d.ts.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/iban.d.ts.map new file mode 100644 index 0000000..b934d68 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/iban.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"iban.d.ts","sourceRoot":"","sources":["../../src/iban.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC;;GAEG;AACH,qBAAa,IAAI;IAChB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAE/B;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAkBtC;IAEF;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAI9B;IAEH;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAU9B;IAEF;;;;;;;;;;;;OAYG;WACW,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI7C;;;;;;;;;;;;;OAaG;IACI,QAAQ,IAAI,OAAO;IAI1B;;;;;;;;;;;;OAYG;WACW,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI/C;;;;;;;;;;;;;OAaG;IACI,UAAU,IAAI,OAAO;IAI5B;;;;;;;;;;;;;;;OAeG;WACW,OAAO,CAAC,IAAI,EAAE,MAAM;IAOlC;;;;;;;;;;;;;;OAcG;IACI,OAAO,IAAI,OAAO;IAIzB;;;;;;;;;;;;;OAaG;gBACgB,IAAI,EAAE,MAAM;IAQ/B;;;;;;;;;;;;;OAaG;WACW,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAS1C;;;;;;;;;;;;;;OAcG;WACW,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI;IAIxD;;;;;;;;;;;OAWG;WACW,WAAW,CAAC,OAAO,EAAE,SAAS,GAAG,IAAI;IAWnD;;;;;;;;;;;;;;OAcG;IACH,OAAc,SAAS,SAAU,MAAM,KAAG,SAAS,CAGjD;IAEF;;;;;;;;;;;;;;OAcG;IACI,SAAS,QAAO,SAAS,CAS9B;IAEF;;;;;;;;;;;OAWG;WACW,MAAM,CAAC,OAAO,EAAE,SAAS,GAAG,MAAM;IAIhD;;;;;;;;;;;OAWG;IACI,MAAM,IAAI,MAAM;IAIvB;;;;;;;;;;OAUG;IACI,QAAQ,IAAI,MAAM;IAIzB;;;;;;;;;OASG;IACI,WAAW,IAAI,MAAM;IAI5B;;;;;;;;;OASG;IACI,QAAQ,IAAI,MAAM;CAGzB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/index.d.ts new file mode 100644 index 0000000..3cafb9b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/index.d.ts @@ -0,0 +1,5 @@ +import { Iban } from './iban.js'; +export * from './iban.js'; +export * from './types.js'; +export default Iban; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/index.d.ts.map new file mode 100644 index 0000000..1fb3c8e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAE3B,eAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/types.d.ts new file mode 100644 index 0000000..b68152c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/types.d.ts @@ -0,0 +1,8 @@ +/** + * An object that could hold the components for an Indirect IBAN (BBAN) + */ +export declare type IbanOptions = { + institution: string; + identifier: string; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/types.d.ts.map new file mode 100644 index 0000000..efe27d3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA;;GAEG;AACH,oBAAY,WAAW,GAAG;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACnB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-iban/package.json b/test/merkletreejs/node_modules/web3-eth-iban/package.json new file mode 100644 index 0000000..b787b2d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/package.json @@ -0,0 +1,65 @@ +{ + "name": "web3-eth-iban", + "version": "4.0.7", + "description": "This package converts Ethereum addresses to IBAN addresses and vice versa.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --runInBand --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --runInBand" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "web3-validator": "^2.0.3" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-eth-iban/src/iban.ts b/test/merkletreejs/node_modules/web3-eth-iban/src/iban.ts new file mode 100644 index 0000000..db7e024 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/src/iban.ts @@ -0,0 +1,397 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { HexString } from 'web3-types'; +import { toChecksumAddress, leftPad, hexToNumber } from 'web3-utils'; +import { isAddress } from 'web3-validator'; +import { InvalidAddressError } from 'web3-errors'; +import { IbanOptions } from './types.js'; + +/** + * Converts Ethereum addresses to IBAN or BBAN addresses and vice versa. + */ +export class Iban { + private readonly _iban: string; + + /** + * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to + * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. + */ + private static readonly _iso13616Prepare = (iban: string): string => { + const A = 'A'.charCodeAt(0); + const Z = 'Z'.charCodeAt(0); + + const upperIban = iban.toUpperCase(); + const modifiedIban = `${upperIban.slice(4)}${upperIban.slice(0, 4)}`; + + return modifiedIban + .split('') + .map(n => { + const code = n.charCodeAt(0); + if (code >= A && code <= Z) { + // A = 10, B = 11, ... Z = 35 + return code - A + 10; + } + return n; + }) + .join(''); + }; + + /** + * return the bigint of the given string with the specified base + */ + private static readonly _parseInt = (str: string, base: number): bigint => + [...str].reduce( + (acc, curr) => BigInt(parseInt(curr, base)) + BigInt(base) * acc, + BigInt(0), + ); + + /** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + */ + private static readonly _mod9710 = (iban: string): number => { + let remainder = iban; + let block; + + while (remainder.length > 2) { + block = remainder.slice(0, 9); + remainder = `${(parseInt(block, 10) % 97).toString()}${remainder.slice(block.length)}`; + } + + return parseInt(remainder, 10) % 97; + }; + + /** + * A static method that checks if an IBAN is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isDirect("XE81ETHXREGGAVOFYORK"); + * > false + * ``` + */ + public static isDirect(iban: string): boolean { + return iban.length === 34 || iban.length === 35; + } + + /** + * An instance method that checks if iban number is Direct. + * It actually check the length of the provided variable and, only if it is 34 or 35, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is a Direct IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isDirect(); + * > false + * ``` + */ + public isDirect(): boolean { + return Iban.isDirect(this._iban); + } + + /** + * A static method that checks if an IBAN is Indirect. + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a method at an Iban instance. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * web3.eth.Iban.isIndirect("XE81ETHXREGGAVOFYORK"); + * > true + * ``` + */ + public static isIndirect(iban: string): boolean { + return iban.length === 20; + } + + /** + * check if iban number if indirect + * It actually check the length of the provided variable and, only if it is 20, it returns true. + * Note: this is also available as a static method. + * @param iban - an IBAN to be checked + * @returns - `true` if the provided `iban` is an Indirect IBAN, and `false` otherwise. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isIndirect(); + * > true + * ``` + */ + public isIndirect(): boolean { + return Iban.isIndirect(this._iban); + } + + /** + * This method could be used to check if a given string is valid IBAN object. + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a string to be checked if it is in IBAN + * @returns - true if it is valid IBAN + * + * @example + * ```ts + * web3.eth.Iban.isValid("XE81ETHXREGGAVOFYORK"); + * > true + * + * web3.eth.Iban.isValid("XE82ETHXREGGAVOFYORK"); + * > false // because the checksum is incorrect + * ``` + */ + public static isValid(iban: string) { + return ( + /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(iban) && + Iban._mod9710(Iban._iso13616Prepare(iban)) === 1 + ); + } + + /** + * Should be called to check if the early provided IBAN is correct. + * Note: this is also available as a static method. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.isValid(); + * > true + * + * const iban = new web3.eth.Iban("XE82ETHXREGGAVOFYORK"); + * iban.isValid(); + * > false // because the checksum is incorrect + * ``` + */ + public isValid(): boolean { + return Iban.isValid(this._iban); + } + + /** + * Construct a direct or indirect IBAN that has conversion methods and validity checks. + * If the provided string was not of either the length of a direct IBAN (34 or 35), + * nor the length of an indirect IBAN (20), an Error will be thrown ('Invalid IBAN was provided'). + * + * @param iban - a Direct or an Indirect IBAN + * @returns - Iban instance + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > Iban { _iban: 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' } + * ``` + */ + public constructor(iban: string) { + if (Iban.isIndirect(iban) || Iban.isDirect(iban)) { + this._iban = iban; + } else { + throw new Error('Invalid IBAN was provided'); + } + } + + /** + * Convert the passed BBAN to an IBAN for this country specification. + * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @param bban - the BBAN to convert to IBAN + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromBban('ETHXREGGAVOFYORK'); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + public static fromBban(bban: string): Iban { + const countryCode = 'XE'; + + const remainder = this._mod9710(this._iso13616Prepare(`${countryCode}00${bban}`)); + const checkDigit = `0${(98 - remainder).toString()}`.slice(-2); + + return new Iban(`${countryCode}${checkDigit}${bban}`); + } + + /** + * Should be used to create IBAN object for given institution and identifier + * + * @param options - an object holds the `institution` and the `identifier` which will be composed to create an `Iban` object from. + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.createIndirect({ + * institution: "XREG", + * identifier: "GAVOFYORK" + * }); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + public static createIndirect(options: IbanOptions): Iban { + return Iban.fromBban(`ETH${options.institution}${options.identifier}`); + } + + /** + * This method should be used to create iban object from an Ethereum address. + * + * @param address - an Ethereum address + * @returns an Iban class instance that holds the equivalent IBAN + * + * @example + * ```ts + * web3.eth.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"} + * ``` + */ + public static fromAddress(address: HexString): Iban { + if (!isAddress(address)) { + throw new InvalidAddressError(address); + } + + const num = BigInt(hexToNumber(address)); + const base36 = num.toString(36); + const padded = leftPad(base36, 15); + return Iban.fromBban(padded.toUpperCase()); + } + + /** + * This method should be used to create an ethereum address from a Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a method at an Iban instance. + * + * @param iban - a Direct IBAN address + * @return the equivalent ethereum address + * + * @example + * ```ts + * web3.eth.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + public static toAddress = (iban: string): HexString => { + const ibanObject = new Iban(iban); + return ibanObject.toAddress(); + }; + + /** + * This method should be used to create the equivalent ethereum address for the early provided Direct IBAN address. + * If the provided string was not a direct IBAN (has the length of 34 or 35), an Error will be thrown: + * ('Iban is indirect and cannot be converted. Must be length of 34 or 35'). + * Note: this is also available as a static method. + * + * @return the equivalent ethereum address + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"); + * iban.toAddress(); + * > "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8" + * ``` + */ + public toAddress = (): HexString => { + if (this.isDirect()) { + // check if Iban can be converted to an address + const base36 = this._iban.slice(4); + const parsedBigInt = Iban._parseInt(base36, 36); // convert the base36 string to a bigint + const paddedBigInt = leftPad(parsedBigInt, 40); + return toChecksumAddress(paddedBigInt); + } + throw new Error('Iban is indirect and cannot be converted. Must be length of 34 or 35'); + }; + + /** + * This method should be used to create IBAN address from an Ethereum address + * + * @param address - an Ethereum address + * @return the equivalent IBAN address + * + * @example + * ```ts + * web3.eth.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"); + * > "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS" + * ``` + */ + public static toIban(address: HexString): string { + return Iban.fromAddress(address).toString(); + } + + /** + * Should be called to get client identifier within institution + * + * @return the client of the IBAN instance. + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.client(); + * > 'GAVOFYORK' + * ``` + */ + public client(): string { + return this.isIndirect() ? this._iban.slice(11) : ''; + } + + /** + * Returns the IBAN checksum of the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.checksum(); + * > "81" + * ``` + * + */ + public checksum(): string { + return this._iban.slice(2, 4); + } + + /** + * Returns institution identifier from the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban("XE81ETHXREGGAVOFYORK"); + * iban.institution(); + * > 'XREG' + * ``` + */ + public institution(): string { + return this.isIndirect() ? this._iban.slice(7, 11) : ''; + } + + /** + * Simply returns the early provided IBAN + * + * @example + * ```ts + * const iban = new web3.eth.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + * iban.toString(); + * > 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS' + * ``` + */ + public toString(): string { + return this._iban; + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-iban/src/index.ts b/test/merkletreejs/node_modules/web3-eth-iban/src/index.ts new file mode 100644 index 0000000..bda252d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/src/index.ts @@ -0,0 +1,23 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Iban } from './iban.js'; + +export * from './iban.js'; +export * from './types.js'; + +export default Iban; diff --git a/test/merkletreejs/node_modules/web3-eth-iban/src/types.ts b/test/merkletreejs/node_modules/web3-eth-iban/src/types.ts new file mode 100644 index 0000000..b563c1c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-iban/src/types.ts @@ -0,0 +1,24 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * An object that could hold the components for an Indirect IBAN (BBAN) + */ +export type IbanOptions = { + institution: string; + identifier: string; +}; diff --git a/test/merkletreejs/node_modules/web3-eth-personal/LICENSE b/test/merkletreejs/node_modules/web3-eth-personal/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth-personal/README.md b/test/merkletreejs/node_modules/web3-eth-personal/README.md new file mode 100644 index 0000000..857d97d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Web3-Eth-Personal + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth-personal` Web3 module to interact with the Ethereum blockchain accounts stored in the node. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth-personal) or using [Yarn](https://yarnpkg.com/package/web3-eth-personal) + +### Using NPM + +```bash +npm install web3-eth-personal +``` + +### Using Yarn + +```bash +yarn add web3-eth-personal +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth-personal +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-personal%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth-personal +[downloads-image]: https://img.shields.io/npm/dm/web3-eth-personal?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.d.ts new file mode 100644 index 0000000..7df4cf4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.d.ts @@ -0,0 +1,21 @@ +/** + * The `web3-eth-personal` package allows you to interact with the Ethereum node’s accounts. + * + * **_NOTE:_** Many of these functions send sensitive information like passwords. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * + * import Personal from 'web3-eth-personal'; + * + * const personal = new Personal('http://localhost:8545'); + * + * or using the web3 umbrella package + * + * import Personal from 'web3-eth-personal'; + * const web3 = new Web3('http://localhost:8545'); + * // web3.eth.personal + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Personal } from './personal.js'; +export * from './personal.js'; +export default Personal; diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.js new file mode 100644 index 0000000..d58e3a9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.js @@ -0,0 +1,54 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * The `web3-eth-personal` package allows you to interact with the Ethereum node’s accounts. + * + * **_NOTE:_** Many of these functions send sensitive information like passwords. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * + * import Personal from 'web3-eth-personal'; + * + * const personal = new Personal('http://localhost:8545'); + * + * or using the web3 umbrella package + * + * import Personal from 'web3-eth-personal'; + * const web3 = new Web3('http://localhost:8545'); + * // web3.eth.personal + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +const personal_js_1 = require("./personal.js"); +__exportStar(require("./personal.js"), exports); +exports.default = personal_js_1.Personal; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.js.map new file mode 100644 index 0000000..2cb1509 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF;;;;;;;;;;;;;;GAcG;AACH;;GAEG;AACH,+CAAyC;AAEzC,gDAA8B;AAE9B,kBAAe,sBAAQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.d.ts b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.d.ts new file mode 100644 index 0000000..421294d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.d.ts @@ -0,0 +1,186 @@ +import { Web3Context } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; +export declare class Personal extends Web3Context { + /** + *Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using `web3.eth.accounts.create()` will not add accounts into this list. For that use `web3.eth.personal.newAccount()`. + * @returns - An array of addresses controlled by the node. + * @example + * ```ts + * const accounts = await personal.getAccounts(); + * console.log(accounts); + * > + * [ + * '0x79D7BbaC53C9aF700d0B250e9AE789E503Fcd6AE', + * '0xe2597eB05CF9a87eB1309e86750C903EC38E527e', + * '0x7eD0e85B8E1E925600B4373e6d108F34AB38a401', + * '0xE4bEEf667408b99053dC147Ed19592aDa0d77F59', + * '0x7AB80aeB6bb488B7f6c41c58e83Ef248eB39c882', + * '0x12B1D9d74d73b1C3A245B19C1C5501c653aF1af9', + * '0x1a6075A263Ee140e00Dbf8E374Fc5A443d097894', + * '0x4FEC0A51024B13030D26E70904B066C6d41157A5', + * '0x03095dc4857BB26f3a4550c5651Df8b7f6b6B1Ef', + * '0xac0B9b6e8A17991cb172B2ABAF45Fb5eb769E540' + * ] + * ``` + */ + getAccounts(): Promise; + /** + * Creates a new account and returns its address. + * **_NOTE:_** This function sends a sensitive information like password. Never call this function over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * @param password - The password to encrypt the account with. + * @returns - The address of the new account. + * @example + * ```ts + * const addr = await web3.eth.personal.newAccount('password'); + * console.log(addr); + * > '0x1234567891011121314151617181920212223456' + * ``` + */ + newAccount(password: string): Promise; + /** + * Unlocks an account for a given duration. + * @param address - The address of the account to unlock. + * @param password - The password of the account to unlock. + * @param unlockDuration - The duration in seconds to unlock the account for. + * @example + * ```ts + * await personal.unlockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * "123456", + * 600 + * ); + * ``` + */ + unlockAccount(address: Address, password: string, unlockDuration: number): Promise; + /** + * Locks the given account + * @param address - The address of the account to lock. + * @returns - `true` if the account was locked, otherwise `false`. + * @example + * ```ts + * await personal.lockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e" + * ); + */ + lockAccount(address: Address): Promise; + /** + * Imports the given private key into the key store, encrypting it with the passphrase. + * @param keyData - An unencrypted private key (hex string). + * @param passphrase - The password of the account + * @returns - The address of the new account. + * @example + * ```ts + * const accountAddress = await personal.importRawKey( + * "abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6", + * "123456" + * ); + * + * console.log(unlockTx); + * > 0x8727a8b34ec833154b72b62cac05d69f86eb6556 + * ``` + */ + importRawKey(keyData: HexString, passphrase: string): Promise; + /** + * This method sends a transaction over the management API. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction options + * @param passphrase - The passphrase of the current account + * @returns - The transaction hash + * @example + * ```ts + * const txHash = personal + * .sendTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(txHash); + * > 0x9445325c3c5638c9fe425b003b8c32f03e9f99d409555a650a6838ba712bb51b + * ``` + */ + sendTransaction(tx: Transaction, passphrase: string): Promise; + /** + * Signs a transaction. This account needs to be unlocked. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction data to sign. See {@link sendTransaction} for more information. + * @param passphrase - The password of the `from` account, to sign the transaction with. + * @returns - The RLP encoded transaction. The `raw` property can be used to send the transaction using {@link sendSignedTransaction}. + * @example + * ```ts + * const tx = personal + * .signTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000000000000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(tx); + * + * > { + * raw: '0xf86e808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080820a95a0c951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526a038b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * tx: { + * type: '0x0', + * nonce: '0x0', + * gasPrice: '0x4a817c800', + * maxPriorityFeePerGas: null, + * maxFeePerGas: null, + * gas: '0x5208', + * value: '0xde0b6b3a7640000', + * input: '0x', + * v: '0xa95', + * r: '0xc951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526', + * s: '0x38b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * to: '0x3535353535353535353535353535353535353535', + * hash: '0x65e3df790ab2a32068b13cff970b26445b8995229ae4abbed61bd996f09fce69' + * } + * } + * ``` + */ + signTransaction(tx: Transaction, passphrase: string): Promise; + /** + * Calculates an Ethereum specific signature with: + * sign(keccak256("\x19Ethereum Signed Message:\n" + dataToSign.length + dataToSign))) + * Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. + * + * If you have the original message and the signed message, you can discover the signing account address using web3.eth.personal.ecRecover + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param data - The data to sign. + * @param address - The address to sign with. + * @param passphrase - The passphrase to decrypt the account with. + * @returns - The signature. + * @example + * ```ts + * const sig = await personal .sign("Hello world", "0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E", "123456") + * console.log(sig) + * > 0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b + * ``` + */ + sign(data: HexString, address: Address, passphrase: string): Promise; + /** + * Recovers the account that signed the data. + * @param signedData - Data that was signed. If String it will be converted using {@link utf8ToHex} + * @param signature - The signature + * @returns - The address of the account that signed the data. + * @example + * ```ts + * const address = await personal.ecRecover( + * "Hello world", + * "0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b" + * ); + * console.log(address); + * > 0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e + * ``` + */ + ecRecover(signedData: HexString, signature: string): Promise; +} diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.js b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.js new file mode 100644 index 0000000..636c6a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.js @@ -0,0 +1,275 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Personal = void 0; +const web3_core_1 = require("web3-core"); +const rpcWrappers = __importStar(require("./rpc_method_wrappers.js")); +class Personal extends web3_core_1.Web3Context { + /** + *Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using `web3.eth.accounts.create()` will not add accounts into this list. For that use `web3.eth.personal.newAccount()`. + * @returns - An array of addresses controlled by the node. + * @example + * ```ts + * const accounts = await personal.getAccounts(); + * console.log(accounts); + * > + * [ + * '0x79D7BbaC53C9aF700d0B250e9AE789E503Fcd6AE', + * '0xe2597eB05CF9a87eB1309e86750C903EC38E527e', + * '0x7eD0e85B8E1E925600B4373e6d108F34AB38a401', + * '0xE4bEEf667408b99053dC147Ed19592aDa0d77F59', + * '0x7AB80aeB6bb488B7f6c41c58e83Ef248eB39c882', + * '0x12B1D9d74d73b1C3A245B19C1C5501c653aF1af9', + * '0x1a6075A263Ee140e00Dbf8E374Fc5A443d097894', + * '0x4FEC0A51024B13030D26E70904B066C6d41157A5', + * '0x03095dc4857BB26f3a4550c5651Df8b7f6b6B1Ef', + * '0xac0B9b6e8A17991cb172B2ABAF45Fb5eb769E540' + * ] + * ``` + */ + getAccounts() { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.getAccounts(this.requestManager); + }); + } + /** + * Creates a new account and returns its address. + * **_NOTE:_** This function sends a sensitive information like password. Never call this function over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * @param password - The password to encrypt the account with. + * @returns - The address of the new account. + * @example + * ```ts + * const addr = await web3.eth.personal.newAccount('password'); + * console.log(addr); + * > '0x1234567891011121314151617181920212223456' + * ``` + */ + newAccount(password) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.newAccount(this.requestManager, password); + }); + } + /** + * Unlocks an account for a given duration. + * @param address - The address of the account to unlock. + * @param password - The password of the account to unlock. + * @param unlockDuration - The duration in seconds to unlock the account for. + * @example + * ```ts + * await personal.unlockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * "123456", + * 600 + * ); + * ``` + */ + unlockAccount(address, password, unlockDuration) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.unlockAccount(this.requestManager, address, password, unlockDuration); + }); + } + /** + * Locks the given account + * @param address - The address of the account to lock. + * @returns - `true` if the account was locked, otherwise `false`. + * @example + * ```ts + * await personal.lockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e" + * ); + */ + lockAccount(address) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.lockAccount(this.requestManager, address); + }); + } + /** + * Imports the given private key into the key store, encrypting it with the passphrase. + * @param keyData - An unencrypted private key (hex string). + * @param passphrase - The password of the account + * @returns - The address of the new account. + * @example + * ```ts + * const accountAddress = await personal.importRawKey( + * "abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6", + * "123456" + * ); + * + * console.log(unlockTx); + * > 0x8727a8b34ec833154b72b62cac05d69f86eb6556 + * ``` + */ + importRawKey(keyData, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.importRawKey(this.requestManager, keyData, passphrase); + }); + } + /** + * This method sends a transaction over the management API. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction options + * @param passphrase - The passphrase of the current account + * @returns - The transaction hash + * @example + * ```ts + * const txHash = personal + * .sendTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(txHash); + * > 0x9445325c3c5638c9fe425b003b8c32f03e9f99d409555a650a6838ba712bb51b + * ``` + */ + sendTransaction(tx, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase); + }); + } + /** + * Signs a transaction. This account needs to be unlocked. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction data to sign. See {@link sendTransaction} for more information. + * @param passphrase - The password of the `from` account, to sign the transaction with. + * @returns - The RLP encoded transaction. The `raw` property can be used to send the transaction using {@link sendSignedTransaction}. + * @example + * ```ts + * const tx = personal + * .signTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000000000000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(tx); + * + * > { + * raw: '0xf86e808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080820a95a0c951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526a038b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * tx: { + * type: '0x0', + * nonce: '0x0', + * gasPrice: '0x4a817c800', + * maxPriorityFeePerGas: null, + * maxFeePerGas: null, + * gas: '0x5208', + * value: '0xde0b6b3a7640000', + * input: '0x', + * v: '0xa95', + * r: '0xc951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526', + * s: '0x38b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * to: '0x3535353535353535353535353535353535353535', + * hash: '0x65e3df790ab2a32068b13cff970b26445b8995229ae4abbed61bd996f09fce69' + * } + * } + * ``` + */ + signTransaction(tx, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.signTransaction(this.requestManager, tx, passphrase); + }); + } + /** + * Calculates an Ethereum specific signature with: + * sign(keccak256("\x19Ethereum Signed Message:\n" + dataToSign.length + dataToSign))) + * Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. + * + * If you have the original message and the signed message, you can discover the signing account address using web3.eth.personal.ecRecover + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param data - The data to sign. + * @param address - The address to sign with. + * @param passphrase - The passphrase to decrypt the account with. + * @returns - The signature. + * @example + * ```ts + * const sig = await personal .sign("Hello world", "0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E", "123456") + * console.log(sig) + * > 0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b + * ``` + */ + sign(data, address, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.sign(this.requestManager, data, address, passphrase); + }); + } + /** + * Recovers the account that signed the data. + * @param signedData - Data that was signed. If String it will be converted using {@link utf8ToHex} + * @param signature - The signature + * @returns - The address of the account that signed the data. + * @example + * ```ts + * const address = await personal.ecRecover( + * "Hello world", + * "0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b" + * ); + * console.log(address); + * > 0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e + * ``` + */ + ecRecover(signedData, signature) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.ecRecover(this.requestManager, signedData, signature); + }); + } +} +exports.Personal = Personal; +//# sourceMappingURL=personal.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.js.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.js.map new file mode 100644 index 0000000..6aec151 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/personal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"personal.js","sourceRoot":"","sources":["../../src/personal.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,yCAAwC;AAGxC,sEAAwD;AAExD,MAAa,QAAS,SAAQ,uBAA2B;IACxD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACU,WAAW;;YACvB,OAAO,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACrD,CAAC;KAAA;IAED;;;;;;;;;;;OAWG;IACU,UAAU,CAAC,QAAgB;;YACvC,OAAO,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;QAC9D,CAAC;KAAA;IAED;;;;;;;;;;;;;OAaG;IACU,aAAa,CAAC,OAAgB,EAAE,QAAgB,EAAE,cAAsB;;YACpF,OAAO,WAAW,CAAC,aAAa,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;QAC1F,CAAC;KAAA;IACD;;;;;;;;;OASG;IACU,WAAW,CAAC,OAAgB;;YACxC,OAAO,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QAC9D,CAAC;KAAA;IACD;;;;;;;;;;;;;;;OAeG;IACU,YAAY,CAAC,OAAkB,EAAE,UAAkB;;YAC/D,OAAO,WAAW,CAAC,YAAY,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAC3E,CAAC;KAAA;IAED;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACU,eAAe,CAAC,EAAe,EAAE,UAAkB;;YAC/D,OAAO,WAAW,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,EAAE,UAAU,CAAC,CAAC;QACzE,CAAC;KAAA;IACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAyCG;IACU,eAAe,CAAC,EAAe,EAAE,UAAkB;;YAC/D,OAAO,WAAW,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,EAAE,UAAU,CAAC,CAAC;QACzE,CAAC;KAAA;IACD;;;;;;;;;;;;;;;;;OAiBG;IACU,IAAI,CAAC,IAAe,EAAE,OAAgB,EAAE,UAAkB;;YACtE,OAAO,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QACzE,CAAC;KAAA;IAED;;;;;;;;;;;;;;OAcG;IACU,SAAS,CAAC,UAAqB,EAAE,SAAiB;;YAC9D,OAAO,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;QAC1E,CAAC;KAAA;CACD;AA7MD,4BA6MC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.d.ts b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.d.ts new file mode 100644 index 0000000..b5c1d03 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.d.ts @@ -0,0 +1,11 @@ +import { Web3RequestManager } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; +export declare const getAccounts: (requestManager: Web3RequestManager) => Promise; +export declare const newAccount: (requestManager: Web3RequestManager, password: string) => Promise; +export declare const unlockAccount: (requestManager: Web3RequestManager, address: Address, password: string, unlockDuration: number) => Promise; +export declare const lockAccount: (requestManager: Web3RequestManager, address: Address) => Promise; +export declare const importRawKey: (requestManager: Web3RequestManager, keyData: HexString, passphrase: string) => Promise; +export declare const sendTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const signTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const sign: (requestManager: Web3RequestManager, data: HexString, address: Address, passphrase: string) => Promise; +export declare const ecRecover: (requestManager: Web3RequestManager, signedData: HexString, signature: string) => Promise; diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.js b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.js new file mode 100644 index 0000000..2dbdddd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.js @@ -0,0 +1,66 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ecRecover = exports.sign = exports.signTransaction = exports.sendTransaction = exports.importRawKey = exports.lockAccount = exports.unlockAccount = exports.newAccount = exports.getAccounts = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_eth_1 = require("web3-eth"); +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const web3_rpc_methods_1 = require("web3-rpc-methods"); +const getAccounts = (requestManager) => __awaiter(void 0, void 0, void 0, function* () { + const result = yield web3_rpc_methods_1.personalRpcMethods.getAccounts(requestManager); + return result.map(web3_utils_1.toChecksumAddress); +}); +exports.getAccounts = getAccounts; +const newAccount = (requestManager, password) => __awaiter(void 0, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string'], [password]); + const result = yield web3_rpc_methods_1.personalRpcMethods.newAccount(requestManager, password); + return (0, web3_utils_1.toChecksumAddress)(result); +}); +exports.newAccount = newAccount; +const unlockAccount = (requestManager, address, password, unlockDuration) => __awaiter(void 0, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'string', 'uint'], [address, password, unlockDuration]); + return web3_rpc_methods_1.personalRpcMethods.unlockAccount(requestManager, address, password, unlockDuration); +}); +exports.unlockAccount = unlockAccount; +const lockAccount = (requestManager, address) => __awaiter(void 0, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address'], [address]); + return web3_rpc_methods_1.personalRpcMethods.lockAccount(requestManager, address); +}); +exports.lockAccount = lockAccount; +const importRawKey = (requestManager, keyData, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string', 'string'], [keyData, passphrase]); + return web3_rpc_methods_1.personalRpcMethods.importRawKey(requestManager, keyData, passphrase); +}); +exports.importRawKey = importRawKey; +const sendTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + const formattedTx = (0, web3_eth_1.formatTransaction)(tx, web3_types_1.ETH_DATA_FORMAT); + return web3_rpc_methods_1.personalRpcMethods.sendTransaction(requestManager, formattedTx, passphrase); +}); +exports.sendTransaction = sendTransaction; +const signTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + const formattedTx = (0, web3_eth_1.formatTransaction)(tx, web3_types_1.ETH_DATA_FORMAT); + return web3_rpc_methods_1.personalRpcMethods.signTransaction(requestManager, formattedTx, passphrase); +}); +exports.signTransaction = signTransaction; +const sign = (requestManager, data, address, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string', 'address', 'string'], [data, address, passphrase]); + const dataToSign = (0, web3_validator_1.isHexStrict)(data) ? data : (0, web3_utils_1.utf8ToHex)(data); + return web3_rpc_methods_1.personalRpcMethods.sign(requestManager, dataToSign, address, passphrase); +}); +exports.sign = sign; +const ecRecover = (requestManager, signedData, signature) => __awaiter(void 0, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string', 'string'], [signedData, signature]); + const signedDataString = (0, web3_validator_1.isHexStrict)(signedData) ? signedData : (0, web3_utils_1.utf8ToHex)(signedData); + return web3_rpc_methods_1.personalRpcMethods.ecRecover(requestManager, signedDataString, signature); +}); +exports.ecRecover = ecRecover; +//# sourceMappingURL=rpc_method_wrappers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.js.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.js.map new file mode 100644 index 0000000..bd3ebba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/commonjs/rpc_method_wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.js","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":";;;;;;;;;;;;AAiBA,2CAA0D;AAC1D,uCAA6C;AAC7C,2CAA8F;AAC9F,mDAAwD;AACxD,uDAAsD;AAE/C,MAAM,WAAW,GAAG,CAAO,cAAkD,EAAE,EAAE;IACvF,MAAM,MAAM,GAAG,MAAM,qCAAkB,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;IAEpE,OAAO,MAAM,CAAC,GAAG,CAAC,8BAAiB,CAAC,CAAC;AACtC,CAAC,CAAA,CAAC;AAJW,QAAA,WAAW,eAItB;AAEK,MAAM,UAAU,GAAG,CACzB,cAAkD,EAClD,QAAgB,EACf,EAAE;IACH,0BAAS,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE3C,MAAM,MAAM,GAAG,MAAM,qCAAkB,CAAC,UAAU,CAAC,cAAc,EAAE,QAAQ,CA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AAO,qCAAkB,CAAC,SAAS,CAAC,cAAc,EAAE,gBAAgB,EAAE,SAAS,CAAC,CAAC;AAClF,CAAC,CAAA,CAAC;AAVW,QAAA,SAAS,aAUpB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/index.js new file mode 100644 index 0000000..3dc3871 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/index.js @@ -0,0 +1,38 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The `web3-eth-personal` package allows you to interact with the Ethereum node’s accounts. + * + * **_NOTE:_** Many of these functions send sensitive information like passwords. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * + * import Personal from 'web3-eth-personal'; + * + * const personal = new Personal('http://localhost:8545'); + * + * or using the web3 umbrella package + * + * import Personal from 'web3-eth-personal'; + * const web3 = new Web3('http://localhost:8545'); + * // web3.eth.personal + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Personal } from './personal.js'; +export * from './personal.js'; +export default Personal; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/index.js.map new file mode 100644 index 0000000..3ac1f5b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;;;;;;GAcG;AACH;;GAEG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,cAAc,eAAe,CAAC;AAE9B,eAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/personal.js b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/personal.js new file mode 100644 index 0000000..48ca416 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/personal.js @@ -0,0 +1,248 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { Web3Context } from 'web3-core'; +import * as rpcWrappers from './rpc_method_wrappers.js'; +export class Personal extends Web3Context { + /** + *Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using `web3.eth.accounts.create()` will not add accounts into this list. For that use `web3.eth.personal.newAccount()`. + * @returns - An array of addresses controlled by the node. + * @example + * ```ts + * const accounts = await personal.getAccounts(); + * console.log(accounts); + * > + * [ + * '0x79D7BbaC53C9aF700d0B250e9AE789E503Fcd6AE', + * '0xe2597eB05CF9a87eB1309e86750C903EC38E527e', + * '0x7eD0e85B8E1E925600B4373e6d108F34AB38a401', + * '0xE4bEEf667408b99053dC147Ed19592aDa0d77F59', + * '0x7AB80aeB6bb488B7f6c41c58e83Ef248eB39c882', + * '0x12B1D9d74d73b1C3A245B19C1C5501c653aF1af9', + * '0x1a6075A263Ee140e00Dbf8E374Fc5A443d097894', + * '0x4FEC0A51024B13030D26E70904B066C6d41157A5', + * '0x03095dc4857BB26f3a4550c5651Df8b7f6b6B1Ef', + * '0xac0B9b6e8A17991cb172B2ABAF45Fb5eb769E540' + * ] + * ``` + */ + getAccounts() { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.getAccounts(this.requestManager); + }); + } + /** + * Creates a new account and returns its address. + * **_NOTE:_** This function sends a sensitive information like password. Never call this function over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * @param password - The password to encrypt the account with. + * @returns - The address of the new account. + * @example + * ```ts + * const addr = await web3.eth.personal.newAccount('password'); + * console.log(addr); + * > '0x1234567891011121314151617181920212223456' + * ``` + */ + newAccount(password) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.newAccount(this.requestManager, password); + }); + } + /** + * Unlocks an account for a given duration. + * @param address - The address of the account to unlock. + * @param password - The password of the account to unlock. + * @param unlockDuration - The duration in seconds to unlock the account for. + * @example + * ```ts + * await personal.unlockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * "123456", + * 600 + * ); + * ``` + */ + unlockAccount(address, password, unlockDuration) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.unlockAccount(this.requestManager, address, password, unlockDuration); + }); + } + /** + * Locks the given account + * @param address - The address of the account to lock. + * @returns - `true` if the account was locked, otherwise `false`. + * @example + * ```ts + * await personal.lockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e" + * ); + */ + lockAccount(address) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.lockAccount(this.requestManager, address); + }); + } + /** + * Imports the given private key into the key store, encrypting it with the passphrase. + * @param keyData - An unencrypted private key (hex string). + * @param passphrase - The password of the account + * @returns - The address of the new account. + * @example + * ```ts + * const accountAddress = await personal.importRawKey( + * "abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6", + * "123456" + * ); + * + * console.log(unlockTx); + * > 0x8727a8b34ec833154b72b62cac05d69f86eb6556 + * ``` + */ + importRawKey(keyData, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.importRawKey(this.requestManager, keyData, passphrase); + }); + } + /** + * This method sends a transaction over the management API. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction options + * @param passphrase - The passphrase of the current account + * @returns - The transaction hash + * @example + * ```ts + * const txHash = personal + * .sendTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(txHash); + * > 0x9445325c3c5638c9fe425b003b8c32f03e9f99d409555a650a6838ba712bb51b + * ``` + */ + sendTransaction(tx, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase); + }); + } + /** + * Signs a transaction. This account needs to be unlocked. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction data to sign. See {@link sendTransaction} for more information. + * @param passphrase - The password of the `from` account, to sign the transaction with. + * @returns - The RLP encoded transaction. The `raw` property can be used to send the transaction using {@link sendSignedTransaction}. + * @example + * ```ts + * const tx = personal + * .signTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000000000000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(tx); + * + * > { + * raw: '0xf86e808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080820a95a0c951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526a038b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * tx: { + * type: '0x0', + * nonce: '0x0', + * gasPrice: '0x4a817c800', + * maxPriorityFeePerGas: null, + * maxFeePerGas: null, + * gas: '0x5208', + * value: '0xde0b6b3a7640000', + * input: '0x', + * v: '0xa95', + * r: '0xc951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526', + * s: '0x38b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * to: '0x3535353535353535353535353535353535353535', + * hash: '0x65e3df790ab2a32068b13cff970b26445b8995229ae4abbed61bd996f09fce69' + * } + * } + * ``` + */ + signTransaction(tx, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.signTransaction(this.requestManager, tx, passphrase); + }); + } + /** + * Calculates an Ethereum specific signature with: + * sign(keccak256("\x19Ethereum Signed Message:\n" + dataToSign.length + dataToSign))) + * Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. + * + * If you have the original message and the signed message, you can discover the signing account address using web3.eth.personal.ecRecover + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param data - The data to sign. + * @param address - The address to sign with. + * @param passphrase - The passphrase to decrypt the account with. + * @returns - The signature. + * @example + * ```ts + * const sig = await personal .sign("Hello world", "0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E", "123456") + * console.log(sig) + * > 0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b + * ``` + */ + sign(data, address, passphrase) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.sign(this.requestManager, data, address, passphrase); + }); + } + /** + * Recovers the account that signed the data. + * @param signedData - Data that was signed. If String it will be converted using {@link utf8ToHex} + * @param signature - The signature + * @returns - The address of the account that signed the data. + * @example + * ```ts + * const address = await personal.ecRecover( + * "Hello world", + * "0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b" + * ); + * console.log(address); + * > 0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e + * ``` + */ + ecRecover(signedData, signature) { + return __awaiter(this, void 0, void 0, function* () { + return rpcWrappers.ecRecover(this.requestManager, signedData, signature); + }); + } +} +//# sourceMappingURL=personal.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/personal.js.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/personal.js.map new file mode 100644 index 0000000..55f791a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/personal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"personal.js","sourceRoot":"","sources":["../../src/personal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAGxC,OAAO,KAAK,WAAW,MAAM,0BAA0B,CAAC;AAExD,MAAM,OAAO,QAAS,SAAQ,WAA2B;IACxD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACU,WAAW;;YACvB,OAAO,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACrD,CAAC;KAAA;IAED;;;;;;;;;;;OAWG;IACU,UAAU,CAAC,QAAgB;;YACvC,OAAO,WAAW,CAAC,UAAU,CAAC,IAAI,C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;YAC9D,OAAO,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;QAC1E,CAAC;KAAA;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/rpc_method_wrappers.js b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/rpc_method_wrappers.js new file mode 100644 index 0000000..117472f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/rpc_method_wrappers.js @@ -0,0 +1,54 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { toChecksumAddress, utf8ToHex } from 'web3-utils'; +import { formatTransaction } from 'web3-eth'; +import { ETH_DATA_FORMAT } from 'web3-types'; +import { validator, isHexStrict } from 'web3-validator'; +import { personalRpcMethods } from 'web3-rpc-methods'; +export const getAccounts = (requestManager) => __awaiter(void 0, void 0, void 0, function* () { + const result = yield personalRpcMethods.getAccounts(requestManager); + return result.map(toChecksumAddress); +}); +export const newAccount = (requestManager, password) => __awaiter(void 0, void 0, void 0, function* () { + validator.validate(['string'], [password]); + const result = yield personalRpcMethods.newAccount(requestManager, password); + return toChecksumAddress(result); +}); +export const unlockAccount = (requestManager, address, password, unlockDuration) => __awaiter(void 0, void 0, void 0, function* () { + validator.validate(['address', 'string', 'uint'], [address, password, unlockDuration]); + return personalRpcMethods.unlockAccount(requestManager, address, password, unlockDuration); +}); +export const lockAccount = (requestManager, address) => __awaiter(void 0, void 0, void 0, function* () { + validator.validate(['address'], [address]); + return personalRpcMethods.lockAccount(requestManager, address); +}); +export const importRawKey = (requestManager, keyData, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + validator.validate(['string', 'string'], [keyData, passphrase]); + return personalRpcMethods.importRawKey(requestManager, keyData, passphrase); +}); +export const sendTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT); + return personalRpcMethods.sendTransaction(requestManager, formattedTx, passphrase); +}); +export const signTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT); + return personalRpcMethods.signTransaction(requestManager, formattedTx, passphrase); +}); +export const sign = (requestManager, data, address, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + validator.validate(['string', 'address', 'string'], [data, address, passphrase]); + const dataToSign = isHexStrict(data) ? data : utf8ToHex(data); + return personalRpcMethods.sign(requestManager, dataToSign, address, passphrase); +}); +export const ecRecover = (requestManager, signedData, signature) => __awaiter(void 0, void 0, void 0, function* () { + validator.validate(['string', 'string'], [signedData, signature]); + const signedDataString = isHexStrict(signedData) ? signedData : utf8ToHex(signedData); + return personalRpcMethods.ecRecover(requestManager, signedDataString, signature); +}); +//# sourceMappingURL=rpc_method_wrappers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/rpc_method_wrappers.js.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/rpc_method_wrappers.js.map new file mode 100644 index 0000000..4b7777b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/esm/rpc_method_wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.js","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":";;;;;;;;;AAiBA,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC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SAAS,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,kBAAkB,CAAC,IAAI,CAAC,cAAc,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;AACjF,CAAC,CAAA,CAAC;AAEF,MAAM,CAAC,MAAM,SAAS,GAAG,CACxB,cAAkD,EAClD,UAAqB,EACrB,SAAiB,EAChB,EAAE;IACH,SAAS,CAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC,CAAC;IAElE,MAAM,gBAAgB,GAAG,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;IAEtF,OAAO,kBAAkB,CAAC,SAAS,CAAC,cAAc,EAAE,gBAAgB,EAAE,SAAS,CAAC,CAAC;AAClF,CAAC,CAAA,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/index.d.ts new file mode 100644 index 0000000..42b932b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/index.d.ts @@ -0,0 +1,22 @@ +/** + * The `web3-eth-personal` package allows you to interact with the Ethereum node’s accounts. + * + * **_NOTE:_** Many of these functions send sensitive information like passwords. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * + * import Personal from 'web3-eth-personal'; + * + * const personal = new Personal('http://localhost:8545'); + * + * or using the web3 umbrella package + * + * import Personal from 'web3-eth-personal'; + * const web3 = new Web3('http://localhost:8545'); + * // web3.eth.personal + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Personal } from './personal.js'; +export * from './personal.js'; +export default Personal; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/index.d.ts.map new file mode 100644 index 0000000..e2fe98e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;;;;GAcG;AACH;;GAEG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,cAAc,eAAe,CAAC;AAE9B,eAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/types/personal.d.ts b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/personal.d.ts new file mode 100644 index 0000000..cb30c30 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/personal.d.ts @@ -0,0 +1,187 @@ +import { Web3Context } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; +export declare class Personal extends Web3Context { + /** + *Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using `web3.eth.accounts.create()` will not add accounts into this list. For that use `web3.eth.personal.newAccount()`. + * @returns - An array of addresses controlled by the node. + * @example + * ```ts + * const accounts = await personal.getAccounts(); + * console.log(accounts); + * > + * [ + * '0x79D7BbaC53C9aF700d0B250e9AE789E503Fcd6AE', + * '0xe2597eB05CF9a87eB1309e86750C903EC38E527e', + * '0x7eD0e85B8E1E925600B4373e6d108F34AB38a401', + * '0xE4bEEf667408b99053dC147Ed19592aDa0d77F59', + * '0x7AB80aeB6bb488B7f6c41c58e83Ef248eB39c882', + * '0x12B1D9d74d73b1C3A245B19C1C5501c653aF1af9', + * '0x1a6075A263Ee140e00Dbf8E374Fc5A443d097894', + * '0x4FEC0A51024B13030D26E70904B066C6d41157A5', + * '0x03095dc4857BB26f3a4550c5651Df8b7f6b6B1Ef', + * '0xac0B9b6e8A17991cb172B2ABAF45Fb5eb769E540' + * ] + * ``` + */ + getAccounts(): Promise; + /** + * Creates a new account and returns its address. + * **_NOTE:_** This function sends a sensitive information like password. Never call this function over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * @param password - The password to encrypt the account with. + * @returns - The address of the new account. + * @example + * ```ts + * const addr = await web3.eth.personal.newAccount('password'); + * console.log(addr); + * > '0x1234567891011121314151617181920212223456' + * ``` + */ + newAccount(password: string): Promise; + /** + * Unlocks an account for a given duration. + * @param address - The address of the account to unlock. + * @param password - The password of the account to unlock. + * @param unlockDuration - The duration in seconds to unlock the account for. + * @example + * ```ts + * await personal.unlockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * "123456", + * 600 + * ); + * ``` + */ + unlockAccount(address: Address, password: string, unlockDuration: number): Promise; + /** + * Locks the given account + * @param address - The address of the account to lock. + * @returns - `true` if the account was locked, otherwise `false`. + * @example + * ```ts + * await personal.lockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e" + * ); + */ + lockAccount(address: Address): Promise; + /** + * Imports the given private key into the key store, encrypting it with the passphrase. + * @param keyData - An unencrypted private key (hex string). + * @param passphrase - The password of the account + * @returns - The address of the new account. + * @example + * ```ts + * const accountAddress = await personal.importRawKey( + * "abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6", + * "123456" + * ); + * + * console.log(unlockTx); + * > 0x8727a8b34ec833154b72b62cac05d69f86eb6556 + * ``` + */ + importRawKey(keyData: HexString, passphrase: string): Promise; + /** + * This method sends a transaction over the management API. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction options + * @param passphrase - The passphrase of the current account + * @returns - The transaction hash + * @example + * ```ts + * const txHash = personal + * .sendTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(txHash); + * > 0x9445325c3c5638c9fe425b003b8c32f03e9f99d409555a650a6838ba712bb51b + * ``` + */ + sendTransaction(tx: Transaction, passphrase: string): Promise; + /** + * Signs a transaction. This account needs to be unlocked. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction data to sign. See {@link sendTransaction} for more information. + * @param passphrase - The password of the `from` account, to sign the transaction with. + * @returns - The RLP encoded transaction. The `raw` property can be used to send the transaction using {@link sendSignedTransaction}. + * @example + * ```ts + * const tx = personal + * .signTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000000000000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(tx); + * + * > { + * raw: '0xf86e808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080820a95a0c951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526a038b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * tx: { + * type: '0x0', + * nonce: '0x0', + * gasPrice: '0x4a817c800', + * maxPriorityFeePerGas: null, + * maxFeePerGas: null, + * gas: '0x5208', + * value: '0xde0b6b3a7640000', + * input: '0x', + * v: '0xa95', + * r: '0xc951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526', + * s: '0x38b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * to: '0x3535353535353535353535353535353535353535', + * hash: '0x65e3df790ab2a32068b13cff970b26445b8995229ae4abbed61bd996f09fce69' + * } + * } + * ``` + */ + signTransaction(tx: Transaction, passphrase: string): Promise; + /** + * Calculates an Ethereum specific signature with: + * sign(keccak256("\x19Ethereum Signed Message:\n" + dataToSign.length + dataToSign))) + * Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. + * + * If you have the original message and the signed message, you can discover the signing account address using web3.eth.personal.ecRecover + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param data - The data to sign. + * @param address - The address to sign with. + * @param passphrase - The passphrase to decrypt the account with. + * @returns - The signature. + * @example + * ```ts + * const sig = await personal .sign("Hello world", "0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E", "123456") + * console.log(sig) + * > 0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b + * ``` + */ + sign(data: HexString, address: Address, passphrase: string): Promise; + /** + * Recovers the account that signed the data. + * @param signedData - Data that was signed. If String it will be converted using {@link utf8ToHex} + * @param signature - The signature + * @returns - The address of the account that signed the data. + * @example + * ```ts + * const address = await personal.ecRecover( + * "Hello world", + * "0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b" + * ); + * console.log(address); + * > 0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e + * ``` + */ + ecRecover(signedData: HexString, signature: string): Promise; +} +//# sourceMappingURL=personal.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/types/personal.d.ts.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/personal.d.ts.map new file mode 100644 index 0000000..639e0a4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/personal.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"personal.d.ts","sourceRoot":"","sources":["../../src/personal.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAI7E,qBAAa,QAAS,SAAQ,WAAW,CAAC,cAAc,CAAC;IACxD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACU,WAAW;IAIxB;;;;;;;;;;;OAWG;IACU,UAAU,CAAC,QAAQ,EAAE,MAAM;IAIxC;;;;;;;;;;;;;OAaG;IACU,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM;IAGrF;;;;;;;;;OASG;IACU,WAAW,CAAC,OAAO,EAAE,OAAO;IAGzC;;;;;;;;;;;;;;;OAeG;IACU,YAAY,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM;IAIhE;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACU,eAAe,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM;IAGhE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAyCG;IACU,eAAe,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM;IAGhE;;;;;;;;;;;;;;;;;OAiBG;IACU,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM;IAIvE;;;;;;;;;;;;;;OAcG;IACU,SAAS,CAAC,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM;CAG/D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/types/rpc_method_wrappers.d.ts b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/rpc_method_wrappers.d.ts new file mode 100644 index 0000000..7499d46 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/rpc_method_wrappers.d.ts @@ -0,0 +1,12 @@ +import { Web3RequestManager } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; +export declare const getAccounts: (requestManager: Web3RequestManager) => Promise; +export declare const newAccount: (requestManager: Web3RequestManager, password: string) => Promise; +export declare const unlockAccount: (requestManager: Web3RequestManager, address: Address, password: string, unlockDuration: number) => Promise; +export declare const lockAccount: (requestManager: Web3RequestManager, address: Address) => Promise; +export declare const importRawKey: (requestManager: Web3RequestManager, keyData: HexString, passphrase: string) => Promise; +export declare const sendTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const signTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const sign: (requestManager: Web3RequestManager, data: HexString, address: Address, passphrase: string) => Promise; +export declare const ecRecover: (requestManager: Web3RequestManager, signedData: HexString, signature: string) => Promise; +//# sourceMappingURL=rpc_method_wrappers.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/lib/types/rpc_method_wrappers.d.ts.map b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/rpc_method_wrappers.d.ts.map new file mode 100644 index 0000000..9025ff5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/lib/types/rpc_method_wrappers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.d.ts","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAG/C,OAAO,EAAE,OAAO,EAAE,cAAc,EAAmB,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAI9F,eAAO,MAAM,WAAW,mBAA0B,mBAAmB,cAAc,CAAC,sBAInF,CAAC;AAEF,eAAO,MAAM,UAAU,mBACN,mBAAmB,cAAc,CAAC,YACxC,MAAM,oBAOhB,CAAC;AAEF,eAAO,MAAM,aAAa,mBACT,mBAAmB,cAAc,CAAC,WACzC,OAAO,YACN,MAAM,kBACA,MAAM,qBAKtB,CAAC;AAEF,eAAO,MAAM,WAAW,mBACP,mBAAmB,cAAc,CAAC,WACzC,OAAO,qBAKhB,CAAC;AAEF,eAAO,MAAM,YAAY,mBACR,mBAAmB,cAAc,CAAC,WACzC,SAAS,cACN,MAAM,oBAKlB,CAAC;AAEF,eAAO,MAAM,eAAe,mBACX,mBAAmB,cAAc,CAAC,MAC9C,WAAW,cACH,MAAM,oBAKlB,CAAC;AAEF,eAAO,MAAM,eAAe,mBACX,mBAAmB,cAAc,CAAC,MAC9C,WAAW,cACH,MAAM,oBAKlB,CAAC;AAEF,eAAO,MAAM,IAAI,mBACA,mBAAmB,cAAc,CAAC,QAC5C,SAAS,WACN,OAAO,cACJ,MAAM,oBAOlB,CAAC;AAEF,eAAO,MAAM,SAAS,mBACL,mBAAmB,cAAc,CAAC,cACtC,SAAS,aACV,MAAM,oBAOjB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth-personal/package.json b/test/merkletreejs/node_modules/web3-eth-personal/package.json new file mode 100644 index 0000000..cc7601b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/package.json @@ -0,0 +1,68 @@ +{ + "name": "web3-eth-personal", + "version": "4.0.8", + "description": "Web3 module to interact with the Ethereum blockchain accounts stored in the node.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js" + }, + "dependencies": { + "web3-core": "^4.3.0", + "web3-eth": "^4.3.1", + "web3-rpc-methods": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "web3-validator": "^2.0.3" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4", + "web3-providers-ws": "^4.0.7" + }, + "gitHead": "41824d669db6aae87d7917122a28d5f057f5aa74" +} diff --git a/test/merkletreejs/node_modules/web3-eth-personal/src/index.ts b/test/merkletreejs/node_modules/web3-eth-personal/src/index.ts new file mode 100644 index 0000000..62576d7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/src/index.ts @@ -0,0 +1,40 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The `web3-eth-personal` package allows you to interact with the Ethereum node’s accounts. + * + * **_NOTE:_** Many of these functions send sensitive information like passwords. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * + * import Personal from 'web3-eth-personal'; + * + * const personal = new Personal('http://localhost:8545'); + * + * or using the web3 umbrella package + * + * import Personal from 'web3-eth-personal'; + * const web3 = new Web3('http://localhost:8545'); + * // web3.eth.personal + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import { Personal } from './personal.js'; + +export * from './personal.js'; + +export default Personal; diff --git a/test/merkletreejs/node_modules/web3-eth-personal/src/personal.ts b/test/merkletreejs/node_modules/web3-eth-personal/src/personal.ts new file mode 100644 index 0000000..f89f6fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/src/personal.ts @@ -0,0 +1,228 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Context } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; + +import * as rpcWrappers from './rpc_method_wrappers.js'; + +export class Personal extends Web3Context { + /** + *Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using `web3.eth.accounts.create()` will not add accounts into this list. For that use `web3.eth.personal.newAccount()`. + * @returns - An array of addresses controlled by the node. + * @example + * ```ts + * const accounts = await personal.getAccounts(); + * console.log(accounts); + * > + * [ + * '0x79D7BbaC53C9aF700d0B250e9AE789E503Fcd6AE', + * '0xe2597eB05CF9a87eB1309e86750C903EC38E527e', + * '0x7eD0e85B8E1E925600B4373e6d108F34AB38a401', + * '0xE4bEEf667408b99053dC147Ed19592aDa0d77F59', + * '0x7AB80aeB6bb488B7f6c41c58e83Ef248eB39c882', + * '0x12B1D9d74d73b1C3A245B19C1C5501c653aF1af9', + * '0x1a6075A263Ee140e00Dbf8E374Fc5A443d097894', + * '0x4FEC0A51024B13030D26E70904B066C6d41157A5', + * '0x03095dc4857BB26f3a4550c5651Df8b7f6b6B1Ef', + * '0xac0B9b6e8A17991cb172B2ABAF45Fb5eb769E540' + * ] + * ``` + */ + public async getAccounts() { + return rpcWrappers.getAccounts(this.requestManager); + } + + /** + * Creates a new account and returns its address. + * **_NOTE:_** This function sends a sensitive information like password. Never call this function over a unsecured Websocket or HTTP provider, as your password will be sent in plain text! + * @param password - The password to encrypt the account with. + * @returns - The address of the new account. + * @example + * ```ts + * const addr = await web3.eth.personal.newAccount('password'); + * console.log(addr); + * > '0x1234567891011121314151617181920212223456' + * ``` + */ + public async newAccount(password: string) { + return rpcWrappers.newAccount(this.requestManager, password); + } + + /** + * Unlocks an account for a given duration. + * @param address - The address of the account to unlock. + * @param password - The password of the account to unlock. + * @param unlockDuration - The duration in seconds to unlock the account for. + * @example + * ```ts + * await personal.unlockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * "123456", + * 600 + * ); + * ``` + */ + public async unlockAccount(address: Address, password: string, unlockDuration: number) { + return rpcWrappers.unlockAccount(this.requestManager, address, password, unlockDuration); + } + /** + * Locks the given account + * @param address - The address of the account to lock. + * @returns - `true` if the account was locked, otherwise `false`. + * @example + * ```ts + * await personal.lockAccount( + * "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e" + * ); + */ + public async lockAccount(address: Address) { + return rpcWrappers.lockAccount(this.requestManager, address); + } + /** + * Imports the given private key into the key store, encrypting it with the passphrase. + * @param keyData - An unencrypted private key (hex string). + * @param passphrase - The password of the account + * @returns - The address of the new account. + * @example + * ```ts + * const accountAddress = await personal.importRawKey( + * "abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6", + * "123456" + * ); + * + * console.log(unlockTx); + * > 0x8727a8b34ec833154b72b62cac05d69f86eb6556 + * ``` + */ + public async importRawKey(keyData: HexString, passphrase: string) { + return rpcWrappers.importRawKey(this.requestManager, keyData, passphrase); + } + + /** + * This method sends a transaction over the management API. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction options + * @param passphrase - The passphrase of the current account + * @returns - The transaction hash + * @example + * ```ts + * const txHash = personal + * .sendTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(txHash); + * > 0x9445325c3c5638c9fe425b003b8c32f03e9f99d409555a650a6838ba712bb51b + * ``` + */ + public async sendTransaction(tx: Transaction, passphrase: string) { + return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase); + } + /** + * Signs a transaction. This account needs to be unlocked. + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param tx - The transaction data to sign. See {@link sendTransaction} for more information. + * @param passphrase - The password of the `from` account, to sign the transaction with. + * @returns - The RLP encoded transaction. The `raw` property can be used to send the transaction using {@link sendSignedTransaction}. + * @example + * ```ts + * const tx = personal + * .signTransaction({ + * from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", + * gasPrice: "20000000000", + * gas: "21000", + * to: "0x3535353535353535353535353535353535353535", + * value: "1000000000000000000", + * data: "", + * nonce: 0, + * }, + * "123456"); + * + * console.log(tx); + * + * > { + * raw: '0xf86e808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080820a95a0c951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526a038b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * tx: { + * type: '0x0', + * nonce: '0x0', + * gasPrice: '0x4a817c800', + * maxPriorityFeePerGas: null, + * maxFeePerGas: null, + * gas: '0x5208', + * value: '0xde0b6b3a7640000', + * input: '0x', + * v: '0xa95', + * r: '0xc951c03238fe930e6e69ab9d6af9f29248a514048e44884f0e60c4de40de3526', + * s: '0x38b71399bf0c8925749ab79e91ce6cd2fc068c84c18ff6a197b48c4cbef01e00', + * to: '0x3535353535353535353535353535353535353535', + * hash: '0x65e3df790ab2a32068b13cff970b26445b8995229ae4abbed61bd996f09fce69' + * } + * } + * ``` + */ + public async signTransaction(tx: Transaction, passphrase: string) { + return rpcWrappers.signTransaction(this.requestManager, tx, passphrase); + } + /** + * Calculates an Ethereum specific signature with: + * sign(keccak256("\x19Ethereum Signed Message:\n" + dataToSign.length + dataToSign))) + * Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. + * + * If you have the original message and the signed message, you can discover the signing account address using web3.eth.personal.ecRecover + * **_NOTE:_** Sending your account password over an unsecured HTTP RPC connection is highly unsecure. + * @param data - The data to sign. + * @param address - The address to sign with. + * @param passphrase - The passphrase to decrypt the account with. + * @returns - The signature. + * @example + * ```ts + * const sig = await personal .sign("Hello world", "0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E", "123456") + * console.log(sig) + * > 0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b + * ``` + */ + public async sign(data: HexString, address: Address, passphrase: string) { + return rpcWrappers.sign(this.requestManager, data, address, passphrase); + } + + /** + * Recovers the account that signed the data. + * @param signedData - Data that was signed. If String it will be converted using {@link utf8ToHex} + * @param signature - The signature + * @returns - The address of the account that signed the data. + * @example + * ```ts + * const address = await personal.ecRecover( + * "Hello world", + * "0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b" + * ); + * console.log(address); + * > 0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e + * ``` + */ + public async ecRecover(signedData: HexString, signature: string) { + return rpcWrappers.ecRecover(this.requestManager, signedData, signature); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth-personal/src/rpc_method_wrappers.ts b/test/merkletreejs/node_modules/web3-eth-personal/src/rpc_method_wrappers.ts new file mode 100644 index 0000000..5149171 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth-personal/src/rpc_method_wrappers.ts @@ -0,0 +1,114 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3RequestManager } from 'web3-core'; +import { toChecksumAddress, utf8ToHex } from 'web3-utils'; +import { formatTransaction } from 'web3-eth'; +import { Address, EthPersonalAPI, ETH_DATA_FORMAT, HexString, Transaction } from 'web3-types'; +import { validator, isHexStrict } from 'web3-validator'; +import { personalRpcMethods } from 'web3-rpc-methods'; + +export const getAccounts = async (requestManager: Web3RequestManager) => { + const result = await personalRpcMethods.getAccounts(requestManager); + + return result.map(toChecksumAddress); +}; + +export const newAccount = async ( + requestManager: Web3RequestManager, + password: string, +) => { + validator.validate(['string'], [password]); + + const result = await personalRpcMethods.newAccount(requestManager, password); + + return toChecksumAddress(result); +}; + +export const unlockAccount = async ( + requestManager: Web3RequestManager, + address: Address, + password: string, + unlockDuration: number, +) => { + validator.validate(['address', 'string', 'uint'], [address, password, unlockDuration]); + + return personalRpcMethods.unlockAccount(requestManager, address, password, unlockDuration); +}; + +export const lockAccount = async ( + requestManager: Web3RequestManager, + address: Address, +) => { + validator.validate(['address'], [address]); + + return personalRpcMethods.lockAccount(requestManager, address); +}; + +export const importRawKey = async ( + requestManager: Web3RequestManager, + keyData: HexString, + passphrase: string, +) => { + validator.validate(['string', 'string'], [keyData, passphrase]); + + return personalRpcMethods.importRawKey(requestManager, keyData, passphrase); +}; + +export const sendTransaction = async ( + requestManager: Web3RequestManager, + tx: Transaction, + passphrase: string, +) => { + const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT); + + return personalRpcMethods.sendTransaction(requestManager, formattedTx, passphrase); +}; + +export const signTransaction = async ( + requestManager: Web3RequestManager, + tx: Transaction, + passphrase: string, +) => { + const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT); + + return personalRpcMethods.signTransaction(requestManager, formattedTx, passphrase); +}; + +export const sign = async ( + requestManager: Web3RequestManager, + data: HexString, + address: Address, + passphrase: string, +) => { + validator.validate(['string', 'address', 'string'], [data, address, passphrase]); + + const dataToSign = isHexStrict(data) ? data : utf8ToHex(data); + + return personalRpcMethods.sign(requestManager, dataToSign, address, passphrase); +}; + +export const ecRecover = async ( + requestManager: Web3RequestManager, + signedData: HexString, + signature: string, +) => { + validator.validate(['string', 'string'], [signedData, signature]); + + const signedDataString = isHexStrict(signedData) ? signedData : utf8ToHex(signedData); + + return personalRpcMethods.ecRecover(requestManager, signedDataString, signature); +}; diff --git a/test/merkletreejs/node_modules/web3-eth/LICENSE b/test/merkletreejs/node_modules/web3-eth/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-eth/README.md b/test/merkletreejs/node_modules/web3-eth/README.md new file mode 100644 index 0000000..a7d675b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Eth + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-eth` contains modules to interact with the Ethereum blockchain and smart contracts. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-eth) or using [Yarn](https://yarnpkg.com/package/web3-eth) + +### Using NPM + +```bash +npm install web3-eth +``` + +### Using Yarn + +```bash +yarn add web3-eth +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-eth +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-eth +[downloads-image]: https://img.shields.io/npm/dm/web3-eth?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.d.ts new file mode 100644 index 0000000..43558e9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.d.ts @@ -0,0 +1,14 @@ +import { FMT_BYTES, FMT_NUMBER } from 'web3-types'; +export declare const ALL_EVENTS = "ALLEVENTS"; +export declare const ALL_EVENTS_ABI: import("web3-types").AbiBaseFragment & { + readonly name: string; + readonly type: string; + readonly inputs?: readonly import("web3-types").AbiParameter[] | undefined; + readonly anonymous?: boolean | undefined; +} & { + signature: string; +}; +export declare const NUMBER_DATA_FORMAT: { + readonly bytes: FMT_BYTES.HEX; + readonly number: FMT_NUMBER.NUMBER; +}; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.js new file mode 100644 index 0000000..12202a3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NUMBER_DATA_FORMAT = exports.ALL_EVENTS_ABI = exports.ALL_EVENTS = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_types_1 = require("web3-types"); +exports.ALL_EVENTS = 'ALLEVENTS'; +exports.ALL_EVENTS_ABI = { + name: exports.ALL_EVENTS, + signature: '', + type: 'event', + inputs: [], +}; +exports.NUMBER_DATA_FORMAT = { bytes: web3_types_1.FMT_BYTES.HEX, number: web3_types_1.FMT_NUMBER.NUMBER }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.js.map new file mode 100644 index 0000000..4bac7bb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,2CAAqE;AAExD,QAAA,UAAU,GAAG,WAAW,CAAC;AACzB,QAAA,cAAc,GAAG;IAC7B,IAAI,EAAE,kBAAU;IAChB,SAAS,EAAE,EAAE;IACb,IAAI,EAAE,OAAO;IACb,MAAM,EAAE,EAAE;CACkC,CAAC;AAEjC,QAAA,kBAAkB,GAAG,EAAE,KAAK,EAAE,sBAAS,CAAC,GAAG,EAAE,MAAM,EAAE,uBAAU,CAAC,MAAM,EAAW,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.d.ts new file mode 100644 index 0000000..c43da42 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.d.ts @@ -0,0 +1,48 @@ +/** + * The `web3-eth` package allows you to interact with an Ethereum blockchain and Ethereum smart contracts. + * + * To use this package standalone and use its methods use: + * ```ts + * import { Web3Context } from 'web3-core'; + * import { BlockTags } from 'web3-types'; + * import { DEFAULT_RETURN_FORMAT } from 'web3-types'; + * import { getBalance} from 'web3-eth'; + * + * getBalance( + * new Web3Context('http://127.0.0.1:8545'), + * '0x407d73d8a49eeb85d32cf465507dd71d507100c1', + * BlockTags.LATEST, + * DEFAULT_RETURN_FORMAT + * ).then(console.log); + * > 1000000000000n + * ``` + * + * To use this package within the `web3` object use: + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * web3.eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1').then(console.log); + * > 1000000000000n + *``` + * + * With `web3-eth` you can also subscribe (if supported by provider) to events in the Ethereum Blockchain, using the `subscribe` function. See more at the {@link Web3Eth.subscribe} function. + */ +/** + * + */ +import 'setimmediate'; +import { Web3Eth } from './web3_eth.js'; +export * from './web3_eth.js'; +export * from './utils/decoding.js'; +export * from './schemas.js'; +export * from './constants.js'; +export * from './types.js'; +export * from './validation.js'; +export * from './rpc_method_wrappers.js'; +export * from './utils/format_transaction.js'; +export * from './utils/prepare_transaction_for_signing.js'; +export * from './web3_subscriptions.js'; +export { detectTransactionType } from './utils/detect_transaction_type.js'; +export { transactionBuilder } from './utils/transaction_builder.js'; +export default Web3Eth; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.js new file mode 100644 index 0000000..50927ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.js @@ -0,0 +1,84 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.transactionBuilder = exports.detectTransactionType = void 0; +/** + * The `web3-eth` package allows you to interact with an Ethereum blockchain and Ethereum smart contracts. + * + * To use this package standalone and use its methods use: + * ```ts + * import { Web3Context } from 'web3-core'; + * import { BlockTags } from 'web3-types'; + * import { DEFAULT_RETURN_FORMAT } from 'web3-types'; + * import { getBalance} from 'web3-eth'; + * + * getBalance( + * new Web3Context('http://127.0.0.1:8545'), + * '0x407d73d8a49eeb85d32cf465507dd71d507100c1', + * BlockTags.LATEST, + * DEFAULT_RETURN_FORMAT + * ).then(console.log); + * > 1000000000000n + * ``` + * + * To use this package within the `web3` object use: + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * web3.eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1').then(console.log); + * > 1000000000000n + *``` + * + * With `web3-eth` you can also subscribe (if supported by provider) to events in the Ethereum Blockchain, using the `subscribe` function. See more at the {@link Web3Eth.subscribe} function. + */ +/** + * + */ +require("setimmediate"); +const web3_eth_js_1 = require("./web3_eth.js"); +__exportStar(require("./web3_eth.js"), exports); +__exportStar(require("./utils/decoding.js"), exports); +__exportStar(require("./schemas.js"), exports); +__exportStar(require("./constants.js"), exports); +__exportStar(require("./types.js"), exports); +__exportStar(require("./validation.js"), exports); +__exportStar(require("./rpc_method_wrappers.js"), exports); +__exportStar(require("./utils/format_transaction.js"), exports); +__exportStar(require("./utils/prepare_transaction_for_signing.js"), exports); +__exportStar(require("./web3_subscriptions.js"), exports); +var detect_transaction_type_js_1 = require("./utils/detect_transaction_type.js"); +Object.defineProperty(exports, "detectTransactionType", { enumerable: true, get: function () { return detect_transaction_type_js_1.detectTransactionType; } }); +var transaction_builder_js_1 = require("./utils/transaction_builder.js"); +Object.defineProperty(exports, "transactionBuilder", { enumerable: true, get: function () { return transaction_builder_js_1.transactionBuilder; } }); +exports.default = web3_eth_js_1.Web3Eth; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.js.map new file mode 100644 index 0000000..a758ee6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH;;GAEG;AACH,wBAAsB;AAEtB,+CAAwC;AAExC,gDAA8B;AAC9B,sDAAoC;AACpC,+CAA6B;AAC7B,iDAA+B;AAC/B,6CAA2B;AAC3B,kDAAgC;AAChC,2DAAyC;AACzC,gEAA8C;AAC9C,6EAA2D;AAC3D,0DAAwC;AACxC,iFAA2E;AAAlE,mIAAA,qBAAqB,OAAA;AAC9B,yEAAoE;AAA3D,4HAAA,kBAAkB,OAAA;AAE3B,kBAAe,qBAAO,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.d.ts new file mode 100644 index 0000000..8e534e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.d.ts @@ -0,0 +1,478 @@ +import { FormatType, DataFormat, EthExecutionAPI, SignedTransactionInfoAPI, Address, BlockNumberOrTag, Bytes, Filter, Numbers, TransactionReceipt, Transaction, TransactionCall, Web3EthExecutionAPI, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, TransactionForAccessList, Eip712TypedData } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { SendSignedTransactionEvents, SendSignedTransactionOptions, SendTransactionEvents, SendTransactionOptions } from './types.js'; +/** + * View additional documentations here: {@link Web3Eth.getProtocolVersion} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const getProtocolVersion: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.isSyncing} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const isSyncing: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.getCoinbase} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const getCoinbase: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.isMining} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const isMining: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.getHashRate} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getHashRate(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getGasPrice} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getGasPrice(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBlockNumber} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlockNumber(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBalance} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBalance(web3Context: Web3Context, address: Address, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getStorageAt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getStorageAt(web3Context: Web3Context, address: Address, storageSlot: Numbers, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getCode} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getCode(web3Context: Web3Context, address: Address, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlock(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, hydrated: boolean | undefined, returnFormat: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; +}>; +/** + * View additional documentations here: {@link Web3Eth.getBlockTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlockTransactionCount(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBlockUncleCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlockUncleCount(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getUncle} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getUncle(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, uncleIndex: Numbers, returnFormat: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; +}>; +/** + * View additional documentations here: {@link Web3Eth.getTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransaction(web3Context: Web3Context, transactionHash: Bytes, returnFormat: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | undefined>; +/** + * View additional documentations here: {@link Web3Eth.getPendingTransactions} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getPendingTransactions(web3Context: Web3Context, returnFormat: ReturnFormat): Promise<{ + from?: string | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; +}[]>; +/** + * View additional documentations here: {@link Web3Eth.getTransactionFromBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransactionFromBlock(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, transactionIndex: Numbers, returnFormat: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | undefined>; +/** + * View additional documentations here: {@link Web3Eth.getTransactionReceipt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransactionReceipt(web3Context: Web3Context, transactionHash: Bytes, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransactionCount(web3Context: Web3Context, address: Address, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.sendTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function sendTransaction>(web3Context: Web3Context, transaction: Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex, returnFormat: ReturnFormat, options?: SendTransactionOptions): Web3PromiEvent>; +/** + * View additional documentations here: {@link Web3Eth.sendSignedTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function sendSignedTransaction>(web3Context: Web3Context, signedTransaction: Bytes, returnFormat: ReturnFormat, options?: SendSignedTransactionOptions): Web3PromiEvent>; +/** + * View additional documentations here: {@link Web3Eth.sign} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function sign(web3Context: Web3Context, message: Bytes, addressOrIndex: Address | number, returnFormat: ReturnFormat): Promise<{ + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; +} | import("web3-types").ByteTypes[ReturnFormat["bytes"]]>; +/** + * View additional documentations here: {@link Web3Eth.signTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function signTransaction(web3Context: Web3Context, transaction: Transaction, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.call} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function call(web3Context: Web3Context, transaction: TransactionCall, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.estimateGas} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function estimateGas(web3Context: Web3Context, transaction: Transaction, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getPastLogs} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getLogs(web3Context: Web3Context, filter: Filter, returnFormat: ReturnFormat): Promise<(string | { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; +})[]>; +/** + * View additional documentations here: {@link Web3Eth.getChainId} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getChainId(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getProof} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getProof(web3Context: Web3Context, address: Address, storageKeys: Bytes[], blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise<{ + readonly balance: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly codeHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly storageHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly accountProof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + readonly storageProof: { + readonly key: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly value: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly proof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + }[]; +}>; +/** + * View additional documentations here: {@link Web3Eth.getFeeHistory} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getFeeHistory(web3Context: Web3Context, blockCount: Numbers, newestBlock: BlockNumberOrTag | undefined, rewardPercentiles: Numbers[], returnFormat: ReturnFormat): Promise<{ + readonly oldestBlock: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly reward: import("web3-types").NumberTypes[ReturnFormat["number"]][][]; + readonly gasUsedRatio: import("web3-types").NumberTypes[ReturnFormat["number"]][]; +}>; +/** + * View additional documentations here: {@link Web3Eth.createAccessList} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function createAccessList(web3Context: Web3Context, transaction: TransactionForAccessList, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise<{ + readonly accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + readonly gasUsed?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; +}>; +/** + * View additional documentations here: {@link Web3Eth.signTypedData} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function signTypedData(web3Context: Web3Context, address: Address, typedData: Eip712TypedData, useLegacy: boolean, returnFormat: ReturnFormat): Promise; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.js new file mode 100644 index 0000000..ca0349a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.js @@ -0,0 +1,626 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.signTypedData = exports.createAccessList = exports.getFeeHistory = exports.getProof = exports.getChainId = exports.getLogs = exports.estimateGas = exports.call = exports.signTransaction = exports.sign = exports.sendSignedTransaction = exports.sendTransaction = exports.getTransactionCount = exports.getTransactionReceipt = exports.getTransactionFromBlock = exports.getPendingTransactions = exports.getTransaction = exports.getUncle = exports.getBlockUncleCount = exports.getBlockTransactionCount = exports.getBlock = exports.getCode = exports.getStorageAt = exports.getBalance = exports.getBlockNumber = exports.getGasPrice = exports.getHashRate = exports.isMining = exports.getCoinbase = exports.isSyncing = exports.getProtocolVersion = void 0; +// Disabling because returnTypes must be last param to match 1.x params +/* eslint-disable default-param-last */ +const web3_types_1 = require("web3-types"); +const web3_core_1 = require("web3-core"); +const web3_utils_1 = require("web3-utils"); +const web3_eth_accounts_1 = require("web3-eth-accounts"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const web3_rpc_methods_1 = require("web3-rpc-methods"); +const decode_signed_transaction_js_1 = require("./utils/decode_signed_transaction.js"); +const schemas_js_1 = require("./schemas.js"); +// eslint-disable-next-line import/no-cycle +const transaction_builder_js_1 = require("./utils/transaction_builder.js"); +const format_transaction_js_1 = require("./utils/format_transaction.js"); +// eslint-disable-next-line import/no-cycle +const try_send_transaction_js_1 = require("./utils/try_send_transaction.js"); +// eslint-disable-next-line import/no-cycle +const wait_for_transaction_receipt_js_1 = require("./utils/wait_for_transaction_receipt.js"); +const constants_js_1 = require("./constants.js"); +// eslint-disable-next-line import/no-cycle +const send_tx_helper_js_1 = require("./utils/send_tx_helper.js"); +/** + * View additional documentations here: {@link Web3Eth.getProtocolVersion} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +const getProtocolVersion = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return web3_rpc_methods_1.ethRpcMethods.getProtocolVersion(web3Context.requestManager); }); +exports.getProtocolVersion = getProtocolVersion; +// TODO Add returnFormat parameter +/** + * View additional documentations here: {@link Web3Eth.isSyncing} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +const isSyncing = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return web3_rpc_methods_1.ethRpcMethods.getSyncing(web3Context.requestManager); }); +exports.isSyncing = isSyncing; +// TODO consider adding returnFormat parameter (to format address as bytes) +/** + * View additional documentations here: {@link Web3Eth.getCoinbase} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +const getCoinbase = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return web3_rpc_methods_1.ethRpcMethods.getCoinbase(web3Context.requestManager); }); +exports.getCoinbase = getCoinbase; +/** + * View additional documentations here: {@link Web3Eth.isMining} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +const isMining = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return web3_rpc_methods_1.ethRpcMethods.getMining(web3Context.requestManager); }); +exports.isMining = isMining; +/** + * View additional documentations here: {@link Web3Eth.getHashRate} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getHashRate(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.getHashRate(web3Context.requestManager); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getHashRate = getHashRate; +/** + * View additional documentations here: {@link Web3Eth.getGasPrice} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getGasPrice(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.getGasPrice(web3Context.requestManager); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getGasPrice = getGasPrice; +/** + * View additional documentations here: {@link Web3Eth.getBlockNumber} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getBlockNumber(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.getBlockNumber(web3Context.requestManager); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getBlockNumber = getBlockNumber; +/** + * View additional documentations here: {@link Web3Eth.getBalance} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getBalance(web3Context, address, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getBalance(web3Context.requestManager, address, blockNumberFormatted); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getBalance = getBalance; +/** + * View additional documentations here: {@link Web3Eth.getStorageAt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getStorageAt(web3Context, address, storageSlot, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const storageSlotFormatted = (0, web3_utils_1.format)({ format: 'uint' }, storageSlot, web3_types_1.ETH_DATA_FORMAT); + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getStorageAt(web3Context.requestManager, address, storageSlotFormatted, blockNumberFormatted); + return (0, web3_utils_1.format)({ format: 'bytes' }, response, returnFormat); + }); +} +exports.getStorageAt = getStorageAt; +/** + * View additional documentations here: {@link Web3Eth.getCode} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getCode(web3Context, address, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getCode(web3Context.requestManager, address, blockNumberFormatted); + return (0, web3_utils_1.format)({ format: 'bytes' }, response, returnFormat); + }); +} +exports.getCode = getCode; +/** + * View additional documentations here: {@link Web3Eth.getBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getBlock(web3Context, block = web3Context.defaultBlock, hydrated = false, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + let response; + if ((0, web3_validator_1.isBytes)(block)) { + const blockHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getBlockByHash(web3Context.requestManager, blockHashFormatted, hydrated); + } + else { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(block) + ? block + : (0, web3_utils_1.format)({ format: 'uint' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getBlockByNumber(web3Context.requestManager, blockNumberFormatted, hydrated); + } + return (0, web3_utils_1.format)(schemas_js_1.blockSchema, response, returnFormat); + }); +} +exports.getBlock = getBlock; +/** + * View additional documentations here: {@link Web3Eth.getBlockTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getBlockTransactionCount(web3Context, block = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + let response; + if ((0, web3_validator_1.isBytes)(block)) { + const blockHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getBlockTransactionCountByHash(web3Context.requestManager, blockHashFormatted); + } + else { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(block) + ? block + : (0, web3_utils_1.format)({ format: 'uint' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getBlockTransactionCountByNumber(web3Context.requestManager, blockNumberFormatted); + } + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getBlockTransactionCount = getBlockTransactionCount; +/** + * View additional documentations here: {@link Web3Eth.getBlockUncleCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getBlockUncleCount(web3Context, block = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + let response; + if ((0, web3_validator_1.isBytes)(block)) { + const blockHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getUncleCountByBlockHash(web3Context.requestManager, blockHashFormatted); + } + else { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(block) + ? block + : (0, web3_utils_1.format)({ format: 'uint' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getUncleCountByBlockNumber(web3Context.requestManager, blockNumberFormatted); + } + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getBlockUncleCount = getBlockUncleCount; +/** + * View additional documentations here: {@link Web3Eth.getUncle} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getUncle(web3Context, block = web3Context.defaultBlock, uncleIndex, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const uncleIndexFormatted = (0, web3_utils_1.format)({ format: 'uint' }, uncleIndex, web3_types_1.ETH_DATA_FORMAT); + let response; + if ((0, web3_validator_1.isBytes)(block)) { + const blockHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getUncleByBlockHashAndIndex(web3Context.requestManager, blockHashFormatted, uncleIndexFormatted); + } + else { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(block) + ? block + : (0, web3_utils_1.format)({ format: 'uint' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getUncleByBlockNumberAndIndex(web3Context.requestManager, blockNumberFormatted, uncleIndexFormatted); + } + return (0, web3_utils_1.format)(schemas_js_1.blockSchema, response, returnFormat); + }); +} +exports.getUncle = getUncle; +/** + * View additional documentations here: {@link Web3Eth.getTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getTransaction(web3Context, transactionHash, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, transactionHash, web3_types_1.DEFAULT_RETURN_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getTransactionByHash(web3Context.requestManager, transactionHashFormatted); + return (0, web3_validator_1.isNullish)(response) + ? response + : (0, format_transaction_js_1.formatTransaction)(response, returnFormat, { fillInputAndData: true }); + }); +} +exports.getTransaction = getTransaction; +/** + * View additional documentations here: {@link Web3Eth.getPendingTransactions} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getPendingTransactions(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.getPendingTransactions(web3Context.requestManager); + return response.map(transaction => (0, format_transaction_js_1.formatTransaction)(transaction, returnFormat, { + fillInputAndData: true, + })); + }); +} +exports.getPendingTransactions = getPendingTransactions; +/** + * View additional documentations here: {@link Web3Eth.getTransactionFromBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getTransactionFromBlock(web3Context, block = web3Context.defaultBlock, transactionIndex, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionIndexFormatted = (0, web3_utils_1.format)({ format: 'uint' }, transactionIndex, web3_types_1.ETH_DATA_FORMAT); + let response; + if ((0, web3_validator_1.isBytes)(block)) { + const blockHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getTransactionByBlockHashAndIndex(web3Context.requestManager, blockHashFormatted, transactionIndexFormatted); + } + else { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(block) + ? block + : (0, web3_utils_1.format)({ format: 'uint' }, block, web3_types_1.ETH_DATA_FORMAT); + response = yield web3_rpc_methods_1.ethRpcMethods.getTransactionByBlockNumberAndIndex(web3Context.requestManager, blockNumberFormatted, transactionIndexFormatted); + } + return (0, web3_validator_1.isNullish)(response) + ? response + : (0, format_transaction_js_1.formatTransaction)(response, returnFormat, { fillInputAndData: true }); + }); +} +exports.getTransactionFromBlock = getTransactionFromBlock; +/** + * View additional documentations here: {@link Web3Eth.getTransactionReceipt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getTransactionReceipt(web3Context, transactionHash, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, transactionHash, web3_types_1.DEFAULT_RETURN_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getTransactionReceipt(web3Context.requestManager, transactionHashFormatted); + return (0, web3_validator_1.isNullish)(response) + ? response + : (0, web3_utils_1.format)(schemas_js_1.transactionReceiptSchema, response, returnFormat); + }); +} +exports.getTransactionReceipt = getTransactionReceipt; +/** + * View additional documentations here: {@link Web3Eth.getTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getTransactionCount(web3Context, address, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getTransactionCount(web3Context.requestManager, address, blockNumberFormatted); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getTransactionCount = getTransactionCount; +/** + * View additional documentations here: {@link Web3Eth.sendTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function sendTransaction(web3Context, transaction, returnFormat, options = { checkRevertBeforeSending: true }) { + const promiEvent = new web3_core_1.Web3PromiEvent((resolve, reject) => { + setImmediate(() => { + (() => __awaiter(this, void 0, void 0, function* () { + const sendTxHelper = new send_tx_helper_js_1.SendTxHelper({ + web3Context, + promiEvent, + options, + returnFormat, + }); + let transactionFormatted = (0, format_transaction_js_1.formatTransaction)(Object.assign(Object.assign({}, transaction), { from: (0, transaction_builder_js_1.getTransactionFromOrToAttr)('from', web3Context, transaction), to: (0, transaction_builder_js_1.getTransactionFromOrToAttr)('to', web3Context, transaction) }), web3_types_1.ETH_DATA_FORMAT); + try { + transactionFormatted = yield sendTxHelper.populateGasPrice({ + transaction, + transactionFormatted, + }); + yield sendTxHelper.checkRevertBeforeSending(transactionFormatted); + sendTxHelper.emitSending(transactionFormatted); + let wallet; + if (web3Context.wallet && !(0, web3_validator_1.isNullish)(transactionFormatted.from)) { + wallet = web3Context.wallet.get(transactionFormatted.from); + } + const transactionHash = yield sendTxHelper.signAndSend({ + wallet, + tx: transactionFormatted, + }); + const transactionHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, transactionHash, returnFormat); + sendTxHelper.emitSent(transactionFormatted); + sendTxHelper.emitTransactionHash(transactionHashFormatted); + const transactionReceipt = yield (0, wait_for_transaction_receipt_js_1.waitForTransactionReceipt)(web3Context, transactionHash, returnFormat); + const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents((0, web3_utils_1.format)(schemas_js_1.transactionReceiptSchema, transactionReceipt, returnFormat)); + sendTxHelper.emitReceipt(transactionReceiptFormatted); + resolve(yield sendTxHelper.handleResolve({ + receipt: transactionReceiptFormatted, + tx: transactionFormatted, + })); + sendTxHelper.emitConfirmation({ + receipt: transactionReceiptFormatted, + transactionHash, + }); + } + catch (error) { + reject(yield sendTxHelper.handleError({ + error, + tx: transactionFormatted, + })); + } + }))(); + }); + }); + return promiEvent; +} +exports.sendTransaction = sendTransaction; +/** + * View additional documentations here: {@link Web3Eth.sendSignedTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function sendSignedTransaction(web3Context, signedTransaction, returnFormat, options = { checkRevertBeforeSending: true }) { + // TODO - Promise returned in function argument where a void return was expected + // eslint-disable-next-line @typescript-eslint/no-misused-promises + const promiEvent = new web3_core_1.Web3PromiEvent((resolve, reject) => { + setImmediate(() => { + (() => __awaiter(this, void 0, void 0, function* () { + const sendTxHelper = new send_tx_helper_js_1.SendTxHelper({ + web3Context, + promiEvent, + options, + returnFormat, + }); + // Formatting signedTransaction to be send to RPC endpoint + const signedTransactionFormattedHex = (0, web3_utils_1.format)({ format: 'bytes' }, signedTransaction, web3_types_1.ETH_DATA_FORMAT); + const unSerializedTransaction = web3_eth_accounts_1.TransactionFactory.fromSerializedData((0, web3_utils_1.bytesToUint8Array)((0, web3_utils_1.hexToBytes)(signedTransactionFormattedHex))); + const unSerializedTransactionWithFrom = Object.assign(Object.assign({}, unSerializedTransaction.toJSON()), { + // Some providers will default `from` to address(0) causing the error + // reported from `eth_call` to not be the reason the user's tx failed + // e.g. `eth_call` will return an Out of Gas error for a failed + // smart contract execution contract, because the sender, address(0), + // has no balance to pay for the gas of the transaction execution + from: unSerializedTransaction.getSenderAddress().toString() }); + try { + const { v, r, s } = unSerializedTransactionWithFrom, txWithoutSigParams = __rest(unSerializedTransactionWithFrom, ["v", "r", "s"]); + yield sendTxHelper.checkRevertBeforeSending(txWithoutSigParams); + sendTxHelper.emitSending(signedTransactionFormattedHex); + const transactionHash = yield (0, try_send_transaction_js_1.trySendTransaction)(web3Context, () => __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.sendRawTransaction(web3Context.requestManager, signedTransactionFormattedHex); + })); + sendTxHelper.emitSent(signedTransactionFormattedHex); + const transactionHashFormatted = (0, web3_utils_1.format)({ format: 'bytes32' }, transactionHash, returnFormat); + sendTxHelper.emitTransactionHash(transactionHashFormatted); + const transactionReceipt = yield (0, wait_for_transaction_receipt_js_1.waitForTransactionReceipt)(web3Context, transactionHash, returnFormat); + const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents((0, web3_utils_1.format)(schemas_js_1.transactionReceiptSchema, transactionReceipt, returnFormat)); + sendTxHelper.emitReceipt(transactionReceiptFormatted); + resolve(yield sendTxHelper.handleResolve({ + receipt: transactionReceiptFormatted, + tx: unSerializedTransactionWithFrom, + })); + sendTxHelper.emitConfirmation({ + receipt: transactionReceiptFormatted, + transactionHash, + }); + } + catch (error) { + reject(yield sendTxHelper.handleError({ + error, + tx: unSerializedTransactionWithFrom, + })); + } + }))(); + }); + }); + return promiEvent; +} +exports.sendSignedTransaction = sendSignedTransaction; +/** + * View additional documentations here: {@link Web3Eth.sign} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function sign(web3Context, message, addressOrIndex, returnFormat) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const messageFormatted = (0, web3_utils_1.format)({ format: 'bytes' }, message, web3_types_1.DEFAULT_RETURN_FORMAT); + if ((_a = web3Context.wallet) === null || _a === void 0 ? void 0 : _a.get(addressOrIndex)) { + const wallet = web3Context.wallet.get(addressOrIndex); + const signed = wallet.sign(messageFormatted); + return (0, web3_utils_1.format)(schemas_js_1.SignatureObjectSchema, signed, returnFormat); + } + if (typeof addressOrIndex === 'number') { + throw new web3_errors_1.SignatureError(message, 'RPC method "eth_sign" does not support index signatures'); + } + const response = yield web3_rpc_methods_1.ethRpcMethods.sign(web3Context.requestManager, addressOrIndex, messageFormatted); + return (0, web3_utils_1.format)({ format: 'bytes' }, response, returnFormat); + }); +} +exports.sign = sign; +/** + * View additional documentations here: {@link Web3Eth.signTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function signTransaction(web3Context, transaction, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.signTransaction(web3Context.requestManager, (0, format_transaction_js_1.formatTransaction)(transaction, web3_types_1.ETH_DATA_FORMAT)); + // Some clients only return the encoded signed transaction (e.g. Ganache) + // while clients such as Geth return the desired SignedTransactionInfoAPI object + return (0, web3_validator_1.isString)(response) + ? (0, decode_signed_transaction_js_1.decodeSignedTransaction)(response, returnFormat, { + fillInputAndData: true, + }) + : { + raw: (0, web3_utils_1.format)({ format: 'bytes' }, response.raw, returnFormat), + tx: (0, format_transaction_js_1.formatTransaction)(response.tx, returnFormat, { + fillInputAndData: true, + }), + }; + }); +} +exports.signTransaction = signTransaction; +// TODO Decide what to do with transaction.to +// https://github.com/ChainSafe/web3.js/pull/4525#issuecomment-982330076 +/** + * View additional documentations here: {@link Web3Eth.call} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function call(web3Context, transaction, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.call(web3Context.requestManager, (0, format_transaction_js_1.formatTransaction)(transaction, web3_types_1.ETH_DATA_FORMAT), blockNumberFormatted); + return (0, web3_utils_1.format)({ format: 'bytes' }, response, returnFormat); + }); +} +exports.call = call; +// TODO - Investigate whether response is padded as 1.x docs suggest +/** + * View additional documentations here: {@link Web3Eth.estimateGas} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function estimateGas(web3Context, transaction, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionFormatted = (0, format_transaction_js_1.formatTransaction)(transaction, web3_types_1.ETH_DATA_FORMAT); + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.estimateGas(web3Context.requestManager, transactionFormatted, blockNumberFormatted); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.estimateGas = estimateGas; +// TODO - Add input formatting to filter +/** + * View additional documentations here: {@link Web3Eth.getPastLogs} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getLogs(web3Context, filter, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + // format type bigint or number toBlock and fromBlock to hexstring. + let { toBlock, fromBlock } = filter; + if (!(0, web3_validator_1.isNullish)(toBlock)) { + if (typeof toBlock === 'number' || typeof toBlock === 'bigint') { + toBlock = (0, web3_utils_1.numberToHex)(toBlock); + } + } + if (!(0, web3_validator_1.isNullish)(fromBlock)) { + if (typeof fromBlock === 'number' || typeof fromBlock === 'bigint') { + fromBlock = (0, web3_utils_1.numberToHex)(fromBlock); + } + } + const formattedFilter = Object.assign(Object.assign({}, filter), { fromBlock, toBlock }); + const response = yield web3_rpc_methods_1.ethRpcMethods.getLogs(web3Context.requestManager, formattedFilter); + const result = response.map(res => { + if (typeof res === 'string') { + return res; + } + return (0, web3_utils_1.format)(schemas_js_1.logSchema, res, returnFormat); + }); + return result; + }); +} +exports.getLogs = getLogs; +/** + * View additional documentations here: {@link Web3Eth.getChainId} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getChainId(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.getChainId(web3Context.requestManager); + return (0, web3_utils_1.format)({ format: 'uint' }, + // Response is number in hex formatted string + response, returnFormat); + }); +} +exports.getChainId = getChainId; +/** + * View additional documentations here: {@link Web3Eth.getProof} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getProof(web3Context, address, storageKeys, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const storageKeysFormatted = storageKeys.map(storageKey => (0, web3_utils_1.format)({ format: 'bytes' }, storageKey, web3_types_1.ETH_DATA_FORMAT)); + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getProof(web3Context.requestManager, address, storageKeysFormatted, blockNumberFormatted); + return (0, web3_utils_1.format)(schemas_js_1.accountSchema, response, returnFormat); + }); +} +exports.getProof = getProof; +// TODO Throwing an error with Geth, but not Infura +// TODO gasUsedRatio and reward not formatting +/** + * View additional documentations here: {@link Web3Eth.getFeeHistory} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function getFeeHistory(web3Context, blockCount, newestBlock = web3Context.defaultBlock, rewardPercentiles, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockCountFormatted = (0, web3_utils_1.format)({ format: 'uint' }, blockCount, web3_types_1.ETH_DATA_FORMAT); + const newestBlockFormatted = (0, web3_validator_1.isBlockTag)(newestBlock) + ? newestBlock + : (0, web3_utils_1.format)({ format: 'uint' }, newestBlock, web3_types_1.ETH_DATA_FORMAT); + const rewardPercentilesFormatted = (0, web3_utils_1.format)({ + type: 'array', + items: { + format: 'uint', + }, + }, rewardPercentiles, constants_js_1.NUMBER_DATA_FORMAT); + const response = yield web3_rpc_methods_1.ethRpcMethods.getFeeHistory(web3Context.requestManager, blockCountFormatted, newestBlockFormatted, rewardPercentilesFormatted); + return (0, web3_utils_1.format)(schemas_js_1.feeHistorySchema, response, returnFormat); + }); +} +exports.getFeeHistory = getFeeHistory; +/** + * View additional documentations here: {@link Web3Eth.createAccessList} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function createAccessList(web3Context, transaction, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = (0, web3_validator_1.isBlockTag)(blockNumber) + ? blockNumber + : (0, web3_utils_1.format)({ format: 'uint' }, blockNumber, web3_types_1.ETH_DATA_FORMAT); + const response = (yield web3_rpc_methods_1.ethRpcMethods.createAccessList(web3Context.requestManager, (0, format_transaction_js_1.formatTransaction)(transaction, web3_types_1.ETH_DATA_FORMAT), blockNumberFormatted)); + return (0, web3_utils_1.format)(schemas_js_1.accessListResultSchema, response, returnFormat); + }); +} +exports.createAccessList = createAccessList; +/** + * View additional documentations here: {@link Web3Eth.signTypedData} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +function signTypedData(web3Context, address, typedData, useLegacy, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.ethRpcMethods.signTypedData(web3Context.requestManager, address, typedData, useLegacy); + return (0, web3_utils_1.format)({ format: 'bytes' }, response, returnFormat); + }); +} +exports.signTypedData = signTypedData; +//# sourceMappingURL=rpc_method_wrappers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.js.map new file mode 100644 index 0000000..009d6f4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/rpc_method_wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.js","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;AAEF,uEAAuE;AACvE,uCAAuC;AACvC,2CA8BoB;AACpB,yCAAwD;AACxD,2CAAgF;AAChF,yDAAuD;AACvD,mDAA0E;AAC1E,6CAA6C;AAC7C,uDAAiD;AAEjD,uFAA+E;AAC/E,6CAQsB;AAOtB,2CAA2C;AAC3C,2EAA4E;AAC5E,yEAAkE;AAClE,2CAA2C;AAC3C,6EAAqE;AAC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js/schemas.d.ts new file mode 100644 index 0000000..3a9f60f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.d.ts @@ -0,0 +1,904 @@ +export declare const accessListItemSchema: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; +}; +export declare const accessListSchema: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; +}; +export declare const accessListResultSchema: { + type: string; + properties: { + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + gasUsed: { + type: string; + }; + }; +}; +export declare const chainSchema: { + type: string; + enum: string[]; +}; +export declare const hardforkSchema: { + type: string; + enum: string[]; +}; +export declare const customChainSchema: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; +}; +export declare const transactionSchema: { + type: string; + properties: { + from: { + format: string; + }; + to: { + oneOf: ({ + format: string; + type?: undefined; + } | { + type: string; + format?: undefined; + })[]; + }; + value: { + format: string; + }; + gas: { + format: string; + }; + gasPrice: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + type: { + format: string; + }; + maxFeePerGas: { + format: string; + }; + maxPriorityFeePerGas: { + format: string; + }; + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + data: { + format: string; + }; + input: { + format: string; + }; + nonce: { + format: string; + }; + chain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + chainId: { + format: string; + }; + networkId: { + format: string; + }; + common: { + type: string; + properties: { + customChain: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; + }; + baseChain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + }; + }; + gasLimit: { + format: string; + }; + v: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + }; +}; +export declare const transactionInfoSchema: { + type: string; + properties: { + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + hash: { + format: string; + }; + transactionIndex: { + format: string; + }; + from: { + format: string; + }; + to: { + oneOf: ({ + format: string; + type?: undefined; + } | { + type: string; + format?: undefined; + })[]; + }; + value: { + format: string; + }; + gas: { + format: string; + }; + gasPrice: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + type: { + format: string; + }; + maxFeePerGas: { + format: string; + }; + maxPriorityFeePerGas: { + format: string; + }; + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + data: { + format: string; + }; + input: { + format: string; + }; + nonce: { + format: string; + }; + gasLimit: { + format: string; + }; + v: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + chain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + chainId: { + format: string; + }; + networkId: { + format: string; + }; + common: { + type: string; + properties: { + customChain: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; + }; + baseChain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + }; + }; + }; +}; +export declare const blockSchema: { + type: string; + properties: { + parentHash: { + format: string; + }; + sha3Uncles: { + format: string; + }; + miner: { + format: string; + }; + stateRoot: { + format: string; + }; + transactionsRoot: { + format: string; + }; + receiptsRoot: { + format: string; + }; + logsBloom: { + format: string; + }; + difficulty: { + format: string; + }; + number: { + format: string; + }; + gasLimit: { + format: string; + }; + gasUsed: { + format: string; + }; + timestamp: { + format: string; + }; + extraData: { + format: string; + }; + mixHash: { + format: string; + }; + nonce: { + format: string; + }; + totalDifficulty: { + format: string; + }; + baseFeePerGas: { + format: string; + }; + size: { + format: string; + }; + transactions: { + oneOf: ({ + type: string; + items: { + type: string; + properties: { + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + hash: { + format: string; + }; + transactionIndex: { + format: string; + }; + from: { + format: string; + }; + to: { + oneOf: ({ + format: string; + type?: undefined; + } | { + type: string; + format?: undefined; + })[]; + }; + value: { + format: string; + }; + gas: { + format: string; + }; + gasPrice: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + type: { + format: string; + }; + maxFeePerGas: { + format: string; + }; + maxPriorityFeePerGas: { + format: string; + }; + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + data: { + format: string; + }; + input: { + format: string; + }; + nonce: { + format: string; + }; + gasLimit: { + format: string; + }; + v: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + chain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + chainId: { + format: string; + }; + networkId: { + format: string; + }; + common: { + type: string; + properties: { + customChain: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; + }; + baseChain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + }; + }; + }; + format?: undefined; + }; + } | { + type: string; + items: { + format: string; + }; + })[]; + }; + uncles: { + type: string; + items: { + format: string; + }; + }; + hash: { + format: string; + }; + }; +}; +export declare const withdrawalsSchema: { + type: string; + properties: { + index: { + format: string; + }; + validatorIndex: { + format: string; + }; + address: { + format: string; + }; + amount: { + format: string; + }; + }; +}; +export declare const blockHeaderSchema: { + type: string; + properties: { + author: { + format: string; + }; + hash: { + format: string; + }; + parentHash: { + format: string; + }; + receiptsRoot: { + format: string; + }; + miner: { + format: string; + }; + stateRoot: { + format: string; + }; + transactionsRoot: { + format: string; + }; + withdrawalsRoot: { + format: string; + }; + logsBloom: { + format: string; + }; + difficulty: { + format: string; + }; + totalDifficulty: { + format: string; + }; + number: { + format: string; + }; + gasLimit: { + format: string; + }; + gasUsed: { + format: string; + }; + timestamp: { + format: string; + }; + extraData: { + format: string; + }; + nonce: { + format: string; + }; + sha3Uncles: { + format: string; + }; + size: { + format: string; + }; + baseFeePerGas: { + format: string; + }; + excessDataGas: { + format: string; + }; + mixHash: { + format: string; + }; + transactions: { + type: string; + items: { + format: string; + }; + }; + uncles: { + type: string; + items: { + format: string; + }; + }; + withdrawals: { + type: string; + items: { + type: string; + properties: { + index: { + format: string; + }; + validatorIndex: { + format: string; + }; + address: { + format: string; + }; + amount: { + format: string; + }; + }; + }; + }; + }; +}; +export declare const logSchema: { + type: string; + properties: { + removed: { + format: string; + }; + logIndex: { + format: string; + }; + transactionIndex: { + format: string; + }; + transactionHash: { + format: string; + }; + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + address: { + format: string; + }; + data: { + format: string; + }; + topics: { + type: string; + items: { + format: string; + }; + }; + }; +}; +export declare const syncSchema: { + type: string; + properties: { + startingBlock: { + format: string; + }; + currentBlock: { + format: string; + }; + highestBlock: { + format: string; + }; + knownStates: { + format: string; + }; + pulledStates: { + format: string; + }; + }; +}; +export declare const transactionReceiptSchema: { + type: string; + properties: { + transactionHash: { + format: string; + }; + transactionIndex: { + format: string; + }; + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + from: { + format: string; + }; + to: { + format: string; + }; + cumulativeGasUsed: { + format: string; + }; + gasUsed: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + contractAddress: { + format: string; + }; + logs: { + type: string; + items: { + type: string; + properties: { + removed: { + format: string; + }; + logIndex: { + format: string; + }; + transactionIndex: { + format: string; + }; + transactionHash: { + format: string; + }; + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + address: { + format: string; + }; + data: { + format: string; + }; + topics: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + logsBloom: { + format: string; + }; + root: { + format: string; + }; + status: { + format: string; + }; + type: { + format: string; + }; + }; +}; +export declare const SignatureObjectSchema: { + type: string; + properties: { + messageHash: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + v: { + format: string; + }; + message: { + format: string; + }; + signature: { + format: string; + }; + }; +}; +export declare const feeHistorySchema: { + type: string; + properties: { + oldestBlock: { + format: string; + }; + baseFeePerGas: { + type: string; + items: { + format: string; + }; + }; + reward: { + type: string; + items: { + type: string; + items: { + format: string; + }; + }; + }; + gasUsedRatio: { + type: string; + items: { + type: string; + }; + }; + }; +}; +export declare const storageProofSchema: { + type: string; + properties: { + key: { + format: string; + }; + value: { + format: string; + }; + proof: { + type: string; + items: { + format: string; + }; + }; + }; +}; +export declare const accountSchema: { + type: string; + properties: { + balance: { + format: string; + }; + codeHash: { + format: string; + }; + nonce: { + format: string; + }; + storageHash: { + format: string; + }; + accountProof: { + type: string; + items: { + format: string; + }; + }; + storageProof: { + type: string; + items: { + type: string; + properties: { + key: { + format: string; + }; + value: { + format: string; + }; + proof: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + }; +}; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.js new file mode 100644 index 0000000..26cd536 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.js @@ -0,0 +1,587 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.accountSchema = exports.storageProofSchema = exports.feeHistorySchema = exports.SignatureObjectSchema = exports.transactionReceiptSchema = exports.syncSchema = exports.logSchema = exports.blockHeaderSchema = exports.withdrawalsSchema = exports.blockSchema = exports.transactionInfoSchema = exports.transactionSchema = exports.customChainSchema = exports.hardforkSchema = exports.chainSchema = exports.accessListResultSchema = exports.accessListSchema = exports.accessListItemSchema = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +exports.accessListItemSchema = { + type: 'object', + properties: { + address: { + format: 'address', + }, + storageKeys: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +exports.accessListSchema = { + type: 'array', + items: Object.assign({}, exports.accessListItemSchema), +}; +exports.accessListResultSchema = { + type: 'object', + properties: { + accessList: Object.assign({}, exports.accessListSchema), + gasUsed: { + type: 'string', + }, + }, +}; +exports.chainSchema = { + type: 'string', + enum: ['goerli', 'kovan', 'mainnet', 'rinkeby', 'ropsten', 'sepolia'], +}; +exports.hardforkSchema = { + type: 'string', + enum: [ + 'arrowGlacier', + 'berlin', + 'byzantium', + 'chainstart', + 'constantinople', + 'dao', + 'homestead', + 'istanbul', + 'london', + 'merge', + 'muirGlacier', + 'petersburg', + 'shanghai', + 'spuriousDragon', + 'tangerineWhistle', + ], +}; +exports.customChainSchema = { + type: 'object', + properties: { + name: { + format: 'string', + }, + networkId: { + format: 'uint', + }, + chainId: { + format: 'uint', + }, + }, +}; +exports.transactionSchema = { + type: 'object', + properties: { + from: { + format: 'address', + }, + to: { + oneOf: [{ format: 'address' }, { type: 'null' }], + }, + value: { + format: 'uint', + }, + gas: { + format: 'uint', + }, + gasPrice: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + type: { + format: 'uint', + }, + maxFeePerGas: { + format: 'uint', + }, + maxPriorityFeePerGas: { + format: 'uint', + }, + accessList: Object.assign({}, exports.accessListSchema), + data: { + format: 'bytes', + }, + input: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + chain: Object.assign({}, exports.chainSchema), + hardfork: Object.assign({}, exports.hardforkSchema), + chainId: { + format: 'uint', + }, + networkId: { + format: 'uint', + }, + common: { + type: 'object', + properties: { + customChain: Object.assign({}, exports.customChainSchema), + baseChain: Object.assign({}, exports.chainSchema), + hardfork: Object.assign({}, exports.hardforkSchema), + }, + }, + gasLimit: { + format: 'uint', + }, + v: { + format: 'uint', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + }, +}; +exports.transactionInfoSchema = { + type: 'object', + properties: Object.assign(Object.assign({}, exports.transactionSchema.properties), { blockHash: { + format: 'bytes32', + }, blockNumber: { + format: 'uint', + }, hash: { + format: 'bytes32', + }, transactionIndex: { + format: 'uint', + }, from: { + format: 'address', + }, to: { + oneOf: [{ format: 'address' }, { type: 'null' }], + }, value: { + format: 'uint', + }, gas: { + format: 'uint', + }, gasPrice: { + format: 'uint', + }, effectiveGasPrice: { + format: 'uint', + }, type: { + format: 'uint', + }, maxFeePerGas: { + format: 'uint', + }, maxPriorityFeePerGas: { + format: 'uint', + }, accessList: Object.assign({}, exports.accessListSchema), data: { + format: 'bytes', + }, input: { + format: 'bytes', + }, nonce: { + format: 'uint', + }, gasLimit: { + format: 'uint', + }, v: { + format: 'uint', + }, r: { + format: 'bytes32', + }, s: { + format: 'bytes32', + } }), +}; +exports.blockSchema = { + type: 'object', + properties: { + parentHash: { + format: 'bytes32', + }, + sha3Uncles: { + format: 'bytes32', + }, + miner: { + format: 'bytes', + }, + stateRoot: { + format: 'bytes32', + }, + transactionsRoot: { + format: 'bytes32', + }, + receiptsRoot: { + format: 'bytes32', + }, + logsBloom: { + format: 'bytes256', + }, + difficulty: { + format: 'uint', + }, + number: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + timestamp: { + format: 'uint', + }, + extraData: { + format: 'bytes', + }, + mixHash: { + format: 'bytes32', + }, + nonce: { + format: 'uint', + }, + totalDifficulty: { + format: 'uint', + }, + baseFeePerGas: { + format: 'uint', + }, + size: { + format: 'uint', + }, + transactions: { + oneOf: [ + { + type: 'array', + items: Object.assign({}, exports.transactionInfoSchema), + }, + { + type: 'array', + items: { + format: 'bytes32', + }, + }, + ], + }, + uncles: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + hash: { + format: 'bytes32', + }, + }, +}; +exports.withdrawalsSchema = { + type: 'object', + properties: { + index: { + format: 'uint', + }, + validatorIndex: { + format: 'uint', + }, + address: { + format: 'address', + }, + amount: { + format: 'uint', + }, + }, +}; +exports.blockHeaderSchema = { + type: 'object', + properties: { + author: { + format: 'bytes32', + }, + hash: { + format: 'bytes32', + }, + parentHash: { + format: 'bytes32', + }, + receiptsRoot: { + format: 'bytes32', + }, + miner: { + format: 'bytes', + }, + stateRoot: { + format: 'bytes32', + }, + transactionsRoot: { + format: 'bytes32', + }, + withdrawalsRoot: { + format: 'bytes32', + }, + logsBloom: { + format: 'bytes256', + }, + difficulty: { + format: 'uint', + }, + totalDifficulty: { + format: 'uint', + }, + number: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + timestamp: { + format: 'uint', + }, + extraData: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + sha3Uncles: { + format: 'bytes32', + }, + size: { + format: 'uint', + }, + baseFeePerGas: { + format: 'uint', + }, + excessDataGas: { + format: 'uint', + }, + mixHash: { + format: 'bytes32', + }, + transactions: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + uncles: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + withdrawals: { + type: 'array', + items: Object.assign({}, exports.withdrawalsSchema), + }, + }, +}; +exports.logSchema = { + type: 'object', + properties: { + removed: { + format: 'bool', + }, + logIndex: { + format: 'uint', + }, + transactionIndex: { + format: 'uint', + }, + transactionHash: { + format: 'bytes32', + }, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + address: { + format: 'address', + }, + data: { + format: 'bytes', + }, + topics: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +exports.syncSchema = { + type: 'object', + properties: { + startingBlock: { + format: 'string', + }, + currentBlock: { + format: 'string', + }, + highestBlock: { + format: 'string', + }, + knownStates: { + format: 'string', + }, + pulledStates: { + format: 'string', + }, + }, +}; +exports.transactionReceiptSchema = { + type: 'object', + properties: { + transactionHash: { + format: 'bytes32', + }, + transactionIndex: { + format: 'uint', + }, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + from: { + format: 'address', + }, + to: { + format: 'address', + }, + cumulativeGasUsed: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + contractAddress: { + format: 'address', + }, + logs: { + type: 'array', + items: Object.assign({}, exports.logSchema), + }, + logsBloom: { + format: 'bytes', + }, + root: { + format: 'bytes', + }, + status: { + format: 'uint', + }, + type: { + format: 'uint', + }, + }, +}; +exports.SignatureObjectSchema = { + type: 'object', + properties: { + messageHash: { + format: 'bytes', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + v: { + format: 'bytes', + }, + message: { + format: 'bytes', + }, + signature: { + format: 'bytes', + }, + }, +}; +exports.feeHistorySchema = { + type: 'object', + properties: { + oldestBlock: { + format: 'uint', + }, + baseFeePerGas: { + type: 'array', + items: { + format: 'uint', + }, + }, + reward: { + type: 'array', + items: { + type: 'array', + items: { + format: 'uint', + }, + }, + }, + gasUsedRatio: { + type: 'array', + items: { + type: 'number', + }, + }, + }, +}; +exports.storageProofSchema = { + type: 'object', + properties: { + key: { + format: 'bytes32', + }, + value: { + format: 'uint', + }, + proof: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +exports.accountSchema = { + type: 'object', + properties: { + balance: { + format: 'uint', + }, + codeHash: { + format: 'bytes32', + }, + nonce: { + format: 'uint', + }, + storageHash: { + format: 'bytes32', + }, + accountProof: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + storageProof: { + type: 'array', + items: Object.assign({}, exports.storageProofSchema), + }, + }, +}; +//# sourceMappingURL=schemas.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.js.map new file mode 100644 index 0000000..9597143 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/schemas.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/schemas.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACW,QAAA,oBAAoB,GAAG;IACnC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,OAAO,EAAE;YACR,MAAM,EAAE,SAAS;SACjB;QACD,WAAW,EAAE;YACZ,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,SAAS;aACjB;SACD;KACD;CACD,CAAC;AAEW,QAAA,gBAAgB,GAAG;IAC/B,IAAI,EAAE,OAAO;IACb,KAAK,oBACD,4BAAoB,CACvB;CACD,CAAC;AAEW,QAAA,sBAAsB,GAAG;IACrC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,UAAU,oBACN,wBAAgB,CACnB;QACD,OAAO,EAAE;YACR,IAAI,EAAE,QAAQ;SACd;KACD;CACD,CAAC;AAEW,QAAA,WAAW,GAAG;IAC1B,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC;CACrE,CAAC;AAEW,QAAA,cAAc,GAAG;IAC7B,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE;QACL,cAAc;QACd,QAAQ;QACR,WAAW;QACX,YAAY;QACZ,gBAAgB;QAChB,KAAK;QACL,WAAW;QACX,UAAU;QACV,QAAQ;QACR,OAAO;QACP,aAAa;QACb,YAAY;QACZ,UAAU;QACV,gBAAgB;QAChB,kBAAkB;KAClB;CACD,CAAC;AAEW,QAAA,iBAAiB,GAAG;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,IAAI,EAAE;YACL,MAAM,EAAE,QAAQ;SAChB;QACD,SAAS,EAAE;YACV,MAAM,EAAE,MAAM;SACd;QACD,OAAO,EAAE;YACR,MAAM,EAAE,MAAM;SACd;KACD;CACD,CAAC;AAEW,Q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,MAAM;aACd;SACD;QACD,MAAM,EAAE;YACP,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,IAAI,EAAE,OAAO;gBACb,KAAK,EAAE;oBACN,MAAM,EAAE,MAAM;iBACd;aACD;SACD;QACD,YAAY,EAAE;YACb,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,IAAI,EAAE,QAAQ;aACd;SACD;KACD;CACD,CAAC;AAEW,QAAA,kBAAkB,GAAG;IACjC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,GAAG,EAAE;YACJ,MAAM,EAAE,SAAS;SACjB;QACD,KAAK,EAAE;YACN,MAAM,EAAE,MAAM;SACd;QACD,KAAK,EAAE;YACN,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,SAAS;aACjB;SACD;KACD;CACD,CAAC;AAEW,QAAA,aAAa,GAAG;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,OAAO,EAAE;YACR,MAAM,EAAE,MAAM;SACd;QACD,QAAQ,EAAE;YACT,MAAM,EAAE,SAAS;SACjB;QACD,KAAK,EAAE;YACN,MAAM,EAAE,MAAM;SACd;QACD,WAAW,EAAE;YACZ,MAAM,EAAE,SAAS;SACjB;QACD,YAAY,EAAE;YACb,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,SAAS;aACjB;SACD;QACD,YAAY,EAAE;YACb,IAAI,EAAE,OAAO;YACb,KAAK,oBACD,0BAAkB,CACrB;SACD;KACD;CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.d.ts new file mode 100644 index 0000000..1010dcd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.d.ts @@ -0,0 +1,39 @@ +import { ContractExecutionError, TransactionRevertedWithoutReasonError, TransactionRevertInstructionError, TransactionRevertWithCustomError, InvalidResponseError } from 'web3-errors'; +import { FormatType, ETH_DATA_FORMAT, DataFormat, Bytes, ContractAbi, HexString, Numbers, Transaction, TransactionReceipt } from 'web3-types'; +export declare type InternalTransaction = FormatType; +export declare type SendTransactionEventsBase = { + sending: FormatType; + sent: FormatType; + transactionHash: FormatType; + receipt: FormatType; + confirmation: { + confirmations: FormatType; + receipt: FormatType; + latestBlockHash: FormatType; + }; + error: TransactionRevertedWithoutReasonError> | TransactionRevertInstructionError> | TransactionRevertWithCustomError> | InvalidResponseError | ContractExecutionError; +}; +export declare type SendTransactionEvents = SendTransactionEventsBase; +export declare type SendSignedTransactionEvents = SendTransactionEventsBase; +export interface SendTransactionOptions { + ignoreGasPricing?: boolean; + transactionResolver?: (receipt: TransactionReceipt) => ResolveType; + contractAbi?: ContractAbi; + checkRevertBeforeSending?: boolean; + ignoreFillingGasLimit?: boolean; +} +export interface SendSignedTransactionOptions { + transactionResolver?: (receipt: TransactionReceipt) => ResolveType; + contractAbi?: ContractAbi; + checkRevertBeforeSending?: boolean; +} +export interface RevertReason { + reason: string; + signature?: HexString; + data?: HexString; +} +export interface RevertReasonWithCustomError extends RevertReason { + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; +} diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.d.ts new file mode 100644 index 0000000..94e29f1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.d.ts @@ -0,0 +1,11 @@ +import { DataFormat, HexStringBytes, SignedTransactionInfoAPI } from 'web3-types'; +/** + * Decodes an [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded transaction. + * + * @param encodedSignedTransaction The RLP encoded transaction. + * @param returnFormat ({@link DataFormat} Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the RLP encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + */ +export declare function decodeSignedTransaction(encodedSignedTransaction: HexStringBytes, returnFormat: ReturnFormat, options?: { + fillInputAndData?: boolean; +}): SignedTransactionInfoAPI; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.js new file mode 100644 index 0000000..be38831 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeSignedTransaction = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_eth_accounts_1 = require("web3-eth-accounts"); +const detect_transaction_type_js_1 = require("./detect_transaction_type.js"); +const format_transaction_js_1 = require("./format_transaction.js"); +/** + * Decodes an [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded transaction. + * + * @param encodedSignedTransaction The RLP encoded transaction. + * @param returnFormat ({@link DataFormat} Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the RLP encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + */ +function decodeSignedTransaction(encodedSignedTransaction, returnFormat, options = { fillInputAndData: false }) { + return { + raw: (0, web3_utils_1.format)({ format: 'bytes' }, encodedSignedTransaction, returnFormat), + tx: (0, format_transaction_js_1.formatTransaction)(Object.assign(Object.assign({}, web3_eth_accounts_1.TransactionFactory.fromSerializedData((0, web3_utils_1.hexToBytes)(encodedSignedTransaction)).toJSON()), { hash: (0, web3_utils_1.bytesToHex)((0, web3_utils_1.keccak256)((0, web3_utils_1.hexToBytes)(encodedSignedTransaction))), type: (0, detect_transaction_type_js_1.detectRawTransactionType)((0, web3_utils_1.hexToBytes)(encodedSignedTransaction)) }), returnFormat, { fillInputAndData: options.fillInputAndData }), + }; +} +exports.decodeSignedTransaction = decodeSignedTransaction; +//# sourceMappingURL=decode_signed_transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.js.map new file mode 100644 index 0000000..bb4e2f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decode_signed_transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_signed_transaction.js","sourceRoot":"","sources":["../../../src/utils/decode_signed_transaction.ts"],"names":[],"mappings":";;;AAsBA,2CAAuE;AACvE,yDAAuD;AACvD,6EAAwE;AACxE,mEAA4D;AAE5D;;;;;;GAMG;AACH,SAAgB,uBAAuB,CACtC,wBAAwC,EACxC,YAA0B,EAC1B,UAA0C,EAAE,gBAAgB,EAAE,KAAK,EAAE;IAErE,OAAO;QACN,GAAG,EAAE,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,wBAAwB,EAAE,YAAY,CAAC;QACxE,EAAE,EAAE,IAAA,yCAAiB,EACpB,gCACI,sCAAkB,CAAC,kBAAkB,CACvC,IAAA,uBAAU,EAAC,wBAAwB,CAAC,CACpC,CAAC,MAAM,EAAE,KACV,IAAI,EAAE,IAAA,uBAAU,EAAC,IAAA,sBAAS,EAAC,IAAA,uBAAU,EAAC,wBAAwB,CAAC,CAAC,CAAC,EACjE,IAAI,EAAE,IAAA,qDAAwB,EAAC,IAAA,uBAAU,EAAC,wBAAwB,CAAC,CAAC,GAC5C,EACzB,YAAY,EACZ,EAAE,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,EAAE,CAC9C;KACD,CAAC;AACH,CAAC;AAnBD,0DAmBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.d.ts new file mode 100644 index 0000000..6a67905 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.d.ts @@ -0,0 +1,4 @@ +import { AbiEventFragment, LogsInput, DataFormat, EventLog, ContractAbiWithSignature } from 'web3-types'; +export declare const decodeEventABI: (event: AbiEventFragment & { + signature: string; +}, data: LogsInput, jsonInterface: ContractAbiWithSignature, returnFormat?: DataFormat) => EventLog; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.js new file mode 100644 index 0000000..8e5b408 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.js @@ -0,0 +1,64 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeEventABI = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_types_1 = require("web3-types"); +const web3_eth_abi_1 = require("web3-eth-abi"); +const schemas_js_1 = require("../schemas.js"); +const constants_js_1 = require("../constants.js"); +const decodeEventABI = (event, data, jsonInterface, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) => { + var _a, _b, _c, _d, _e; + let modifiedEvent = Object.assign({}, event); + const result = (0, web3_utils_1.format)(schemas_js_1.logSchema, data, returnFormat); + // if allEvents get the right event + if ([constants_js_1.ALL_EVENTS, 'allEvents'].includes(modifiedEvent.name)) { + const matchedEvent = jsonInterface.find(j => j.signature === data.topics[0]); + if (matchedEvent) { + modifiedEvent = matchedEvent; + } + else { + modifiedEvent = { anonymous: true }; + } + } + // create empty inputs if none are present (e.g. anonymous events on allEvents) + modifiedEvent.inputs = (_b = (_a = modifiedEvent.inputs) !== null && _a !== void 0 ? _a : event.inputs) !== null && _b !== void 0 ? _b : []; + // Handle case where an event signature shadows the current ABI with non-identical + // arg indexing. If # of topics doesn't match, event is anon. + if (!modifiedEvent.anonymous) { + let indexedInputs = 0; + ((_c = modifiedEvent.inputs) !== null && _c !== void 0 ? _c : []).forEach(input => { + if (input.indexed) { + indexedInputs += 1; + } + }); + if (indexedInputs > 0 && (data === null || data === void 0 ? void 0 : data.topics) && (data === null || data === void 0 ? void 0 : data.topics.length) !== indexedInputs + 1) { + // checks if event is anonymous + modifiedEvent = Object.assign(Object.assign({}, modifiedEvent), { anonymous: true, inputs: [] }); + } + } + const argTopics = modifiedEvent.anonymous ? data.topics : ((_d = data.topics) !== null && _d !== void 0 ? _d : []).slice(1); + return Object.assign(Object.assign({}, result), { returnValues: (0, web3_eth_abi_1.decodeLog)([...((_e = modifiedEvent.inputs) !== null && _e !== void 0 ? _e : [])], data.data, argTopics), event: modifiedEvent.name, signature: modifiedEvent.anonymous || !data.topics || data.topics.length === 0 || !data.topics[0] + ? undefined + : data.topics[0], raw: { + data: data.data, + topics: data.topics, + } }); +}; +exports.decodeEventABI = decodeEventABI; +//# sourceMappingURL=decoding.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.js.map new file mode 100644 index 0000000..4d6de2d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/decoding.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding.js","sourceRoot":"","sources":["../../../src/utils/decoding.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAoC;AAEpC,2CAOoB;AAEpB,+CAAyC;AAEzC,8CAA0C;AAC1C,kDAA6C;AAEtC,MAAM,cAAc,GAAG,CAC7B,KAA+C,EAC/C,IAAe,EACf,aAAuC,EACvC,eAA2B,kCAAqB,EACrC,EAAE;;IACb,IAAI,aAAa,qBAAQ,KAAK,CAAE,CAAC;IAEjC,MAAM,MAAM,GAAG,IAAA,mBAAM,EAAC,sBAAS,EAAE,IAAI,EAAE,YAAY,CAAC,CAAC;IAErD,mCAAmC;IACnC,IAAI,CAAC,yBAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;QAC3D,MAAM,YAAY,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,KAAK,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7E,IAAI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AAa,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;YACrF,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAElB,GAAG,EAAE;YACJ,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM,EAAE,IAAI,CAAC,MAAM;SACnB,IACA;AACH,CAAC,CAAC;AA7DW,QAAA,cAAc,kBA6DzB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.d.ts new file mode 100644 index 0000000..6d1ae9f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.d.ts @@ -0,0 +1,6 @@ +import { TransactionTypeParser, Web3Context } from 'web3-core'; +import { EthExecutionAPI } from 'web3-types'; +import { InternalTransaction } from '../types.js'; +export declare const defaultTransactionTypeParser: TransactionTypeParser; +export declare const detectTransactionType: (transaction: InternalTransaction, web3Context?: Web3Context) => string | undefined; +export declare const detectRawTransactionType: (transaction: Uint8Array) => string; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.js new file mode 100644 index 0000000..5e91a44 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.js @@ -0,0 +1,125 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.detectRawTransactionType = exports.detectTransactionType = exports.defaultTransactionTypeParser = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +// undefined is treated as null for JSON schema validator +const transactionType0x0Schema = { + type: 'object', + properties: { + accessList: { + type: 'null', + }, + maxFeePerGas: { + type: 'null', + }, + maxPriorityFeePerGas: { + type: 'null', + }, + }, +}; +const transactionType0x1Schema = { + type: 'object', + properties: { + maxFeePerGas: { + type: 'null', + }, + maxPriorityFeePerGas: { + type: 'null', + }, + }, +}; +const transactionType0x2Schema = { + type: 'object', + properties: { + gasPrice: { + type: 'null', + }, + }, +}; +const validateTxTypeAndHandleErrors = (txSchema, tx, txType) => { + try { + web3_validator_1.validator.validateJSONSchema(txSchema, tx); + } + catch (error) { + if (error instanceof web3_validator_1.Web3ValidatorError) + // Erroneously reported error + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + throw new web3_errors_1.InvalidPropertiesForTransactionTypeError(error.errors, txType); + throw error; + } +}; +const defaultTransactionTypeParser = (transaction) => { + var _a, _b; + const tx = transaction; + if (!(0, web3_validator_1.isNullish)(tx.type)) { + let txSchema; + switch (tx.type) { + case '0x0': + txSchema = transactionType0x0Schema; + break; + case '0x1': + txSchema = transactionType0x1Schema; + break; + case '0x2': + txSchema = transactionType0x2Schema; + break; + default: + return (0, web3_utils_1.format)({ format: 'uint' }, tx.type, web3_types_1.ETH_DATA_FORMAT); + } + validateTxTypeAndHandleErrors(txSchema, tx, tx.type); + return (0, web3_utils_1.format)({ format: 'uint' }, tx.type, web3_types_1.ETH_DATA_FORMAT); + } + if (!(0, web3_validator_1.isNullish)(tx.maxFeePerGas) || !(0, web3_validator_1.isNullish)(tx.maxPriorityFeePerGas)) { + validateTxTypeAndHandleErrors(transactionType0x2Schema, tx, '0x2'); + return '0x2'; + } + if (!(0, web3_validator_1.isNullish)(tx.accessList)) { + validateTxTypeAndHandleErrors(transactionType0x1Schema, tx, '0x1'); + return '0x1'; + } + const givenHardfork = (_a = tx.hardfork) !== null && _a !== void 0 ? _a : (_b = tx.common) === null || _b === void 0 ? void 0 : _b.hardfork; + if (!(0, web3_validator_1.isNullish)(givenHardfork)) { + const hardforkIndex = Object.keys(web3_types_1.HardforksOrdered).indexOf(givenHardfork); + // givenHardfork is London or later, so EIP-2718 is supported + if (hardforkIndex >= Object.keys(web3_types_1.HardforksOrdered).indexOf('london')) + return !(0, web3_validator_1.isNullish)(tx.gasPrice) ? '0x0' : '0x2'; + // givenHardfork is Berlin, tx.accessList is undefined, assume type is 0x0 + if (hardforkIndex === Object.keys(web3_types_1.HardforksOrdered).indexOf('berlin')) + return '0x0'; + } + // gasprice is defined + if (!(0, web3_validator_1.isNullish)(tx.gasPrice)) { + validateTxTypeAndHandleErrors(transactionType0x0Schema, tx, '0x0'); + return '0x0'; + } + // no transaction type can be inferred from properties, use default transaction type + return undefined; +}; +exports.defaultTransactionTypeParser = defaultTransactionTypeParser; +const detectTransactionType = (transaction, web3Context) => { + var _a; + return ((_a = web3Context === null || web3Context === void 0 ? void 0 : web3Context.transactionTypeParser) !== null && _a !== void 0 ? _a : exports.defaultTransactionTypeParser)(transaction); +}; +exports.detectTransactionType = detectTransactionType; +const detectRawTransactionType = (transaction) => transaction[0] > 0x7f ? '0x0' : (0, web3_utils_1.toHex)(transaction[0]); +exports.detectRawTransactionType = detectRawTransactionType; +//# sourceMappingURL=detect_transaction_type.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.js.map new file mode 100644 index 0000000..70a05a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/detect_transaction_type.js.map @@ -0,0 +1 @@ +{"version":3,"file":"detect_transaction_type.js","sourceRoot":"","sources":["../../../src/utils/detect_transaction_type.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAA2C;AAE3C,2CAA6F;AAC7F,mDAA0E;AAC1E,6CAAuE;AAIvE,yDAAyD;AACzD,MAAM,wBAAwB,GAAG;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,UAAU,EAAE;YACX,IAAI,EAAE,MAAM;SACZ;QACD,YAAY,EAAE;YACb,IAAI,EAAE,MAAM;SACZ;QACD,oBAAoB,EAAE;YACrB,IAAI,EAAE,MAAM;SACZ;KACD;CACD,CAAC;AACF,MAAM,wBAAwB,GAAG;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,YAAY,EAAE;YACb,IAAI,EAAE,MAAM;SACZ;QACD,oBAAoB,EAAE;YACrB,IAAI,EAAE,MAAM;SACZ;KACD;CACD,CAAC;AACF,MAAM,wBAAwB,GAAG;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,QAAQ,EAAE;YACT,IAAI,EAAE,MAAM;SACZ;KACD;CACD,CAAC;AAEF,MAAM,6BAA6B,GAAG,CACrC,QAAgB,EAChB,EAAe,EACf,MAA6B,EAC5B,EAAE;IACH,IAAI;QACH,0BAAS,CAAC,kBAAkB,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;KAC3C;IAAC,OAAO,KAAK,EAAE;QACf,IAAI,KAAK,YAAY,mCAAkB;YACtC,6BAA6B;YAC7B,6DAA6D;YAC7D,MAAM,IAAI,sDAAwC,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAE1E,MAAM,KAAK,CAAC;KACZ;AACF,CAAC,CAAC;AAEK,MAAM,4BAA4B,GAA0B,CAClE,WAAW,EACV,EAAE;;IACH,MAAM,EAAE,GAAG,WAAqC,CAAC;IACjD,IAAI,CAAC,IAAA,0BAAS,EA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,CAAC;QAE3E,6DAA6D;QAC7D,IAAI,aAAa,IAAI,MAAM,CAAC,IAAI,CAAC,6BAAgB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC;YACnE,OAAO,CAAC,IAAA,0BAAS,EAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;QAEhD,0EAA0E;QAC1E,IAAI,aAAa,KAAK,MAAM,CAAC,IAAI,CAAC,6BAAgB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;KACpF;IAED,sBAAsB;IACtB,IAAI,CAAC,IAAA,0BAAS,EAAC,EAAE,CAAC,QAAQ,CAAC,EAAE;QAC5B,6BAA6B,CAAC,wBAAwB,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO,KAAK,CAAC;KACb;IAED,oFAAoF;IACpF,OAAO,SAAS,CAAC;AAClB,CAAC,CAAC;AAzDW,QAAA,4BAA4B,gCAyDvC;AAEK,MAAM,qBAAqB,GAAG,CACpC,WAAgC,EAChC,WAA0C,EACzC,EAAE;;IACH,OAAA,CAAC,MAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,qBAAqB,mCAAI,oCAA4B,CAAC,CACnE,WAAiD,CACjD,CAAA;CAAA,CAAC;AANU,QAAA,qBAAqB,yBAM/B;AAEI,MAAM,wBAAwB,GAAG,CAAC,WAAuB,EAAE,EAAE,CACnE,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,kBAAK,EAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;AAD1C,QAAA,wBAAwB,4BACkB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.d.ts new file mode 100644 index 0000000..9b0c845 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.d.ts @@ -0,0 +1,7 @@ +import { Transaction, DataFormat, DEFAULT_RETURN_FORMAT, FormatType } from 'web3-types'; +import { ValidationSchemaInput } from 'web3-validator'; +import { transactionSchema } from '../schemas.js'; +export declare function formatTransaction(transaction: TransactionType, returnFormat?: ReturnFormat, options?: { + transactionSchema?: ValidationSchemaInput | typeof transactionSchema; + fillInputAndData?: boolean; +}): FormatType; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.js new file mode 100644 index 0000000..0e7c710 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.js @@ -0,0 +1,61 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatTransaction = void 0; +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +const schemas_js_1 = require("../schemas.js"); +function formatTransaction(transaction, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT, options = { + transactionSchema: schemas_js_1.transactionInfoSchema, + fillInputAndData: false, +}) { + var _a, _b; + let formattedTransaction = (0, web3_utils_1.mergeDeep)({}, transaction); + if (!(0, web3_validator_1.isNullish)(transaction === null || transaction === void 0 ? void 0 : transaction.common)) { + formattedTransaction.common = Object.assign({}, transaction.common); + if (!(0, web3_validator_1.isNullish)((_a = transaction.common) === null || _a === void 0 ? void 0 : _a.customChain)) + formattedTransaction.common.customChain = Object.assign({}, transaction.common.customChain); + } + formattedTransaction = (0, web3_utils_1.format)((_b = options.transactionSchema) !== null && _b !== void 0 ? _b : schemas_js_1.transactionInfoSchema, formattedTransaction, returnFormat); + if (!(0, web3_validator_1.isNullish)(formattedTransaction.data) && + !(0, web3_validator_1.isNullish)(formattedTransaction.input) && + // Converting toHex is accounting for data and input being Uint8Arrays + // since comparing Uint8Array is not as straightforward as comparing strings + (0, web3_utils_1.toHex)(formattedTransaction.data) !== (0, web3_utils_1.toHex)(formattedTransaction.input)) + throw new web3_errors_1.TransactionDataAndInputError({ + data: (0, web3_utils_1.bytesToHex)(formattedTransaction.data), + input: (0, web3_utils_1.bytesToHex)(formattedTransaction.input), + }); + if (options.fillInputAndData) { + if (!(0, web3_validator_1.isNullish)(formattedTransaction.data)) { + formattedTransaction.input = formattedTransaction.data; + } + else if (!(0, web3_validator_1.isNullish)(formattedTransaction.input)) { + formattedTransaction.data = formattedTransaction.input; + } + } + if (!(0, web3_validator_1.isNullish)(formattedTransaction.gasLimit)) { + formattedTransaction.gas = formattedTransaction.gasLimit; + delete formattedTransaction.gasLimit; + } + return formattedTransaction; +} +exports.formatTransaction = formatTransaction; +//# sourceMappingURL=format_transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.js.map new file mode 100644 index 0000000..1e7faab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/format_transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"format_transaction.js","sourceRoot":"","sources":["../../../src/utils/format_transaction.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAwF;AACxF,mDAAkE;AAClE,2CAAkE;AAClE,6CAA2D;AAE3D,8CAAyE;AAEzE,SAAgB,iBAAiB,CAIhC,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I,CAAC;SACvD;aAAM,IAAI,CAAC,IAAA,0BAAS,EAAC,oBAAoB,CAAC,KAAK,CAAC,EAAE;YAClD,oBAAoB,CAAC,IAAI,GAAG,oBAAoB,CAAC,KAAK,CAAC;SACvD;KACD;IAED,IAAI,CAAC,IAAA,0BAAS,EAAC,oBAAoB,CAAC,QAAQ,CAAC,EAAE;QAC9C,oBAAoB,CAAC,GAAG,GAAG,oBAAoB,CAAC,QAAQ,CAAC;QACzD,OAAO,oBAAoB,CAAC,QAAQ,CAAC;KACrC;IAED,OAAO,oBAAiE,CAAC;AAC1E,CAAC;AAnDD,8CAmDC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.d.ts new file mode 100644 index 0000000..cb8e54a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.d.ts @@ -0,0 +1,12 @@ +import { Web3Context } from 'web3-core'; +import { ContractAbi, DataFormat, DEFAULT_RETURN_FORMAT, EthExecutionAPI, TransactionCall } from 'web3-types'; +import { RevertReason, RevertReasonWithCustomError } from '../types.js'; +export declare const parseTransactionError: (error: unknown, contractAbi?: ContractAbi) => string | RevertReason; +/** + * Returns the revert reason generated by the EVM if the transaction were to be executed. + * + * @param web3Context - ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @returns `undefined` if no revert reason was given, a revert reason object, a revert reason string, or an `unknown` error + */ +export declare function getRevertReason(web3Context: Web3Context, transaction: TransactionCall, contractAbi?: ContractAbi, returnFormat?: ReturnFormat): Promise; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.js new file mode 100644 index 0000000..f692ad2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.js @@ -0,0 +1,83 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRevertReason = exports.parseTransactionError = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_eth_abi_1 = require("web3-eth-abi"); +const web3_types_1 = require("web3-types"); +// eslint-disable-next-line import/no-cycle +const rpc_method_wrappers_js_1 = require("../rpc_method_wrappers.js"); +const parseTransactionError = (error, contractAbi) => { + var _a, _b, _c, _d; + if (error instanceof web3_errors_1.ContractExecutionError && + error.innerError instanceof web3_errors_1.Eip838ExecutionError) { + if (contractAbi !== undefined) { + const errorsAbi = contractAbi.filter(abi => (0, web3_eth_abi_1.isAbiErrorFragment)(abi)); + (0, web3_eth_abi_1.decodeContractErrorData)(errorsAbi, error.innerError); + return { + reason: error.innerError.message, + signature: (_a = error.innerError.data) === null || _a === void 0 ? void 0 : _a.slice(0, 10), + data: (_b = error.innerError.data) === null || _b === void 0 ? void 0 : _b.substring(10), + customErrorName: error.innerError.errorName, + customErrorDecodedSignature: error.innerError.errorSignature, + customErrorArguments: error.innerError.errorArgs, + }; + } + return { + reason: error.innerError.message, + signature: (_c = error.innerError.data) === null || _c === void 0 ? void 0 : _c.slice(0, 10), + data: (_d = error.innerError.data) === null || _d === void 0 ? void 0 : _d.substring(10), + }; + } + if (error instanceof web3_errors_1.InvalidResponseError && + !Array.isArray(error.innerError) && + error.innerError !== undefined) { + return error.innerError.message; + } + throw error; +}; +exports.parseTransactionError = parseTransactionError; +/** + * Returns the revert reason generated by the EVM if the transaction were to be executed. + * + * @param web3Context - ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @returns `undefined` if no revert reason was given, a revert reason object, a revert reason string, or an `unknown` error + */ +function getRevertReason(web3Context, transaction, contractAbi, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield (0, rpc_method_wrappers_js_1.call)(web3Context, transaction, web3Context.defaultBlock, returnFormat); + return undefined; + } + catch (error) { + return (0, exports.parseTransactionError)(error, contractAbi); + } + }); +} +exports.getRevertReason = getRevertReason; +//# sourceMappingURL=get_revert_reason.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.js.map new file mode 100644 index 0000000..e5c6856 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_revert_reason.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_revert_reason.js","sourceRoot":"","sources":["../../../src/utils/get_revert_reason.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAGF,6CAAiG;AACjG,+CAA2E;AAC3E,2CAOoB;AAEpB,2CA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AC,OAAO,CAAC;KAChC;IAED,MAAM,KAAK,CAAC;AACb,CAAC,CAAC;AArCW,QAAA,qBAAqB,yBAqChC;AAEF;;;;;;GAMG;AACH,SAAsB,eAAe,CAGpC,WAAyC,EACzC,WAA4B,EAC5B,WAAyB,EACzB,eAA6B,kCAAqC;;QAElE,IAAI;YACH,MAAM,IAAA,6BAAI,EAAC,WAAW,EAAE,WAAW,EAAE,WAAW,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;YAC7E,OAAO,SAAS,CAAC;SACjB;QAAC,OAAO,KAAK,EAAE;YACf,OAAO,IAAA,6BAAqB,EAAC,KAAK,EAAE,WAAW,CAAC,CAAC;SACjD;IACF,CAAC;CAAA;AAdD,0CAcC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.d.ts new file mode 100644 index 0000000..9964e28 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.d.ts @@ -0,0 +1,152 @@ +import { Web3Context } from 'web3-core'; +import { TransactionRevertedWithoutReasonError, TransactionRevertInstructionError, TransactionRevertWithCustomError } from 'web3-errors'; +import { DataFormat, FormatType, ContractAbi, TransactionCall, TransactionReceipt } from 'web3-types'; +import { RevertReason, RevertReasonWithCustomError } from '../types.js'; +export declare function getTransactionError(web3Context: Web3Context, transactionFormatted?: TransactionCall, transactionReceiptFormatted?: FormatType, receivedError?: unknown, contractAbi?: ContractAbi, knownReason?: string | RevertReason | RevertReasonWithCustomError): Promise | TransactionRevertInstructionError<{ + readonly transactionHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly blockHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly blockNumber: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly from: string; + readonly to: string; + readonly cumulativeGasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly effectiveGasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly contractAddress?: string | undefined; + readonly logs: { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; + }[]; + readonly logsBloom: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly root: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly status: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + events?: { + [x: string]: { + readonly event: string; + readonly id?: string | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: string | undefined; + readonly blockHash?: string | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address: string; + readonly topics: string[]; + readonly data: string; + readonly raw?: { + data: string; + topics: unknown[]; + } | undefined; + readonly returnValues: { + [x: string]: unknown; + }; + readonly signature?: string | undefined; + }; + } | undefined; +}> | TransactionRevertWithCustomError<{ + readonly transactionHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly blockHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly blockNumber: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly from: string; + readonly to: string; + readonly cumulativeGasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly effectiveGasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly contractAddress?: string | undefined; + readonly logs: { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; + }[]; + readonly logsBloom: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly root: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly status: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + events?: { + [x: string]: { + readonly event: string; + readonly id?: string | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: string | undefined; + readonly blockHash?: string | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address: string; + readonly topics: string[]; + readonly data: string; + readonly raw?: { + data: string; + topics: unknown[]; + } | undefined; + readonly returnValues: { + [x: string]: unknown; + }; + readonly signature?: string | undefined; + }; + } | undefined; +}>>; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.js new file mode 100644 index 0000000..fe9752a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.js @@ -0,0 +1,63 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTransactionError = void 0; +const web3_errors_1 = require("web3-errors"); +// eslint-disable-next-line import/no-cycle +const get_revert_reason_js_1 = require("./get_revert_reason.js"); +function getTransactionError(web3Context, transactionFormatted, transactionReceiptFormatted, receivedError, contractAbi, knownReason) { + return __awaiter(this, void 0, void 0, function* () { + let _reason = knownReason; + if (_reason === undefined) { + if (receivedError !== undefined) { + _reason = (0, get_revert_reason_js_1.parseTransactionError)(receivedError); + } + else if (web3Context.handleRevert && transactionFormatted !== undefined) { + _reason = yield (0, get_revert_reason_js_1.getRevertReason)(web3Context, transactionFormatted, contractAbi); + } + } + let error; + if (_reason === undefined) { + error = new web3_errors_1.TransactionRevertedWithoutReasonError(transactionReceiptFormatted); + } + else if (typeof _reason === 'string') { + error = new web3_errors_1.TransactionRevertInstructionError(_reason, undefined, transactionReceiptFormatted); + } + else if (_reason.customErrorName !== undefined && + _reason.customErrorDecodedSignature !== undefined && + _reason.customErrorArguments !== undefined) { + const reasonWithCustomError = _reason; + error = new web3_errors_1.TransactionRevertWithCustomError(reasonWithCustomError.reason, reasonWithCustomError.customErrorName, reasonWithCustomError.customErrorDecodedSignature, reasonWithCustomError.customErrorArguments, reasonWithCustomError.signature, transactionReceiptFormatted, reasonWithCustomError.data); + } + else { + error = new web3_errors_1.TransactionRevertInstructionError(_reason.reason, _reason.signature, transactionReceiptFormatted, _reason.data); + } + return error; + }); +} +exports.getTransactionError = getTransactionError; +//# sourceMappingURL=get_transaction_error.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.js.map new file mode 100644 index 0000000..de4f64f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_transaction_error.js","sourceRoot":"","sources":["../../../src/utils/get_transaction_error.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAGF,6CAIqB;AASrB,2CAA2C;AAC3C,iEAAgF;AAEhF,SAAsB,mBAAmB,CACxC,WAAwB,EACxB,oBAAsC,EACtC,2BAA0E,EAC1E,aAAuB,EACvB,WAAyB,EACzB,WAAiE;;QAEjE,IAAI,OAAO,GAAoE,WAAW,CAAC;QAE3F,IAAI,OAAO,KAAK,SAAS,EAAE;YAC1B,IAAI,aAAa,KAAK,SAAS,EAAE;gBAChC,OAAO,GAAG,IAAA,4CAAqB,EAAC,aAAa,CAAC,CAAC;aAC/C;iBAAM,IAAI,WAAW,CAAC,YAAY,IAAI,oBAAoB,KAAK,SAAS,EAAE;gBAC1E,OAAO,GAAG,MAAM,IAAA,sCAAe,EAAC,WAAW,EAAE,oBAAoB,EAAE,WAAW,CAAC,CAAC;aAChF;SACD;QAED,IAAI,KAG6E,CAAC;QAClF,IAAI,OAAO,KAAK,SAAS,EAAE;YAC1B,KAAK,GAAG,IAAI,mDAAqC,CAE/C,2BAA2B,CAAC,CAAC;SAC/B;aAAM,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YACvC,KAAK,GAAG,IAAI,+CAAiC,CAC5C,OAAO,EACP,SAAS,EACT,2BAA2B,CAC3B,CAAC;SACF;aAAM,IACL,OAAuC,CAAC,eAAe,KAAK,SAAS;YACrE,OAAuC,CAAC,2BAA2B,KAAK,SAAS;YACjF,OAAuC,CAAC,oBAAoB,KAAK,SAAS,EAC1E;YACD,MAAM,qBAAqB,GAC1B,OAAsC,CAAC;YACxC,KAAK,GAAG,IAAI,8CAAgC,CAC3C,qBAAqB,CAAC,MAAM,EAC5B,qBAAqB,CAAC,eAAe,EACrC,qBAAqB,CAAC,2BAA2B,EACjD,qBAAqB,CAAC,oBAAoB,EAC1C,qBAAqB,CAAC,SAAS,EAC/B,2BAA2B,EAC3B,qBAAqB,CAAC,IAAI,CAC1B,CAAC;SACF;aAAM;YACN,KAAK,GAAG,IAAI,+CAAiC,CAC5C,OAAO,CAAC,MAAM,EACd,OAAO,CAAC,SAAS,EACjB,2BAA2B,EAC3B,OAAO,CAAC,IAAI,CACZ,CAAC;SACF;QAED,OAAO,KAAK,CAAC;IACd,CAAC;CAAA;AA1DD,kDA0DC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.d.ts new file mode 100644 index 0000000..b7b40a9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.d.ts @@ -0,0 +1,8 @@ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Numbers, DataFormat, FormatType } from 'web3-types'; +import { InternalTransaction } from '../types.js'; +export declare function getTransactionGasPricing(transaction: InternalTransaction, web3Context: Web3Context, returnFormat: ReturnFormat): Promise | undefined>; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.js new file mode 100644 index 0000000..3e9e85a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.js @@ -0,0 +1,80 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTransactionGasPricing = void 0; +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +// eslint-disable-next-line import/no-cycle +const rpc_method_wrappers_js_1 = require("../rpc_method_wrappers.js"); +// eslint-disable-next-line import/no-cycle +const transaction_builder_js_1 = require("./transaction_builder.js"); +function getEip1559GasPricing(transaction, web3Context, returnFormat) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const block = yield (0, rpc_method_wrappers_js_1.getBlock)(web3Context, web3Context.defaultBlock, false, returnFormat); + if ((0, web3_validator_1.isNullish)(block.baseFeePerGas)) + throw new web3_errors_1.Eip1559NotSupportedError(); + if (!(0, web3_validator_1.isNullish)(transaction.gasPrice)) { + const convertedTransactionGasPrice = (0, web3_utils_1.format)({ format: 'uint' }, transaction.gasPrice, returnFormat); + return { + maxPriorityFeePerGas: convertedTransactionGasPrice, + maxFeePerGas: convertedTransactionGasPrice, + }; + } + return { + maxPriorityFeePerGas: (0, web3_utils_1.format)({ format: 'uint' }, (_a = transaction.maxPriorityFeePerGas) !== null && _a !== void 0 ? _a : web3Context.defaultMaxPriorityFeePerGas, returnFormat), + maxFeePerGas: (0, web3_utils_1.format)({ format: 'uint' }, ((_b = transaction.maxFeePerGas) !== null && _b !== void 0 ? _b : BigInt(block.baseFeePerGas) * BigInt(2) + + BigInt((_c = transaction.maxPriorityFeePerGas) !== null && _c !== void 0 ? _c : web3Context.defaultMaxPriorityFeePerGas)), returnFormat), + }; + }); +} +function getTransactionGasPricing(transaction, web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionType = (0, transaction_builder_js_1.getTransactionType)(transaction, web3Context); + if (!(0, web3_validator_1.isNullish)(transactionType)) { + if (transactionType.startsWith('-')) + throw new web3_errors_1.UnsupportedTransactionTypeError(transactionType); + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2718.md#transactions + if (Number(transactionType) < 0 || Number(transactionType) > 127) + throw new web3_errors_1.UnsupportedTransactionTypeError(transactionType); + if ((0, web3_validator_1.isNullish)(transaction.gasPrice) && + (transactionType === '0x0' || transactionType === '0x1')) + return { + gasPrice: yield (0, rpc_method_wrappers_js_1.getGasPrice)(web3Context, returnFormat), + maxPriorityFeePerGas: undefined, + maxFeePerGas: undefined, + }; + if (transactionType === '0x2') { + return Object.assign({ gasPrice: undefined }, (yield getEip1559GasPricing(transaction, web3Context, returnFormat))); + } + } + return undefined; + }); +} +exports.getTransactionGasPricing = getTransactionGasPricing; +//# sourceMappingURL=get_transaction_gas_pricing.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.js.map new file mode 100644 index 0000000..19de481 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/get_transaction_gas_pricing.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_transaction_gas_pricing.js","sourceRoot":"","sources":["../../../src/utils/get_transaction_gas_pricing.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAWF,mDAA2C;AAC3C,6CAAwF;AACxF,2CAAoC;AACpC,2CAA2C;AAC3C,sEAAkE;AAElE,2CAA2C;AAC3C,qEAA8D;AAE9D,SAAe,oBAAoB,CAClC,WAA4D,EAC5D,WAAyC,EACzC,YAA0B;;;QAE1B,MAAM,KAAK,GAAG,MAAM,IAAA,iCAAQ,EAAC,WAAW,EAAE,WAAW,CAAC,YAAY,EAAE,KAAK,EAAE,YAAY,CAAC,CAAC;QAEzF,IAAI,IAAA,0BAAS,EAAC,KAAK,CAAC,aAAa,CAAC;YAAE,MAAM,IAAI,sCAAwB,EAAE,CAAC;QAEzE,IAAI,CAAC,IAAA,0BAAS,EAAC,WAAW,CAAC,QAAQ,CAAC,EAAE;YACrC,MAAM,4BAA4B,GAAG,IAAA,mBAAM,EAC1C,EAAE,MAAM,EAAE,MAAM,EAAE,EAClB,WAAW,CAAC,QAAmB,EAC/B,YAAY,CACZ,CAAC;YAEF,OAAO;gBACN,oBAAoB,EAAE,4BAA4B;gBAClD,YAAY,EAAE,4BAA4B;aAC1C,CAAC;SACF;QACD,OAAO;YACN,oBAAoB,EAAE,IAAA,mBAAM,EAC3B,EAA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EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,EACtE;aACF;SACD;QAED,OAAO,SAAS,CAAC;IAClB,CAAC;CAAA;AAvCD,4DAuCC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.d.ts new file mode 100644 index 0000000..81bd658 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.d.ts @@ -0,0 +1,4 @@ +export * from './detect_transaction_type.js'; +export * from './format_transaction.js'; +export * from './prepare_transaction_for_signing.js'; +export * from './transaction_builder.js'; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.js new file mode 100644 index 0000000..eefcc97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.js @@ -0,0 +1,37 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./detect_transaction_type.js"), exports); +__exportStar(require("./format_transaction.js"), exports); +__exportStar(require("./prepare_transaction_for_signing.js"), exports); +__exportStar(require("./transaction_builder.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.js.map new file mode 100644 index 0000000..fe8b410 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF,+DAA6C;AAC7C,0DAAwC;AACxC,uEAAqD;AACrD,2DAAyC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.d.ts new file mode 100644 index 0000000..d4ef49b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.d.ts @@ -0,0 +1,3 @@ +import { EthExecutionAPI, HexString, Transaction } from 'web3-types'; +import { Web3Context } from 'web3-core'; +export declare const prepareTransactionForSigning: (transaction: Transaction, web3Context: Web3Context, privateKey?: HexString | Uint8Array, fillGasPrice?: boolean, fillGasLimit?: boolean) => Promise; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.js new file mode 100644 index 0000000..3aa8af1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.js @@ -0,0 +1,111 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prepareTransactionForSigning = void 0; +const web3_types_1 = require("web3-types"); +const web3_utils_1 = require("web3-utils"); +const web3_eth_accounts_1 = require("web3-eth-accounts"); +const web3_validator_1 = require("web3-validator"); +const validation_js_1 = require("../validation.js"); +const format_transaction_js_1 = require("./format_transaction.js"); +const transaction_builder_js_1 = require("./transaction_builder.js"); +const getEthereumjsTxDataFromTransaction = (transaction) => { + var _a, _b; + return ({ + nonce: transaction.nonce, + gasPrice: transaction.gasPrice, + gasLimit: (_a = transaction.gasLimit) !== null && _a !== void 0 ? _a : transaction.gas, + to: transaction.to, + value: transaction.value, + data: (_b = transaction.data) !== null && _b !== void 0 ? _b : transaction.input, + type: transaction.type, + chainId: transaction.chainId, + accessList: transaction.accessList, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); +}; +const getEthereumjsTransactionOptions = (transaction, web3Context) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; + const hasTransactionSigningOptions = (!(0, web3_validator_1.isNullish)(transaction.chain) && !(0, web3_validator_1.isNullish)(transaction.hardfork)) || + !(0, web3_validator_1.isNullish)(transaction.common); + let common; + if (!hasTransactionSigningOptions) { + // if defaultcommon is specified, use that. + if (web3Context.defaultCommon) { + common = web3Context.defaultCommon; + if ((0, web3_validator_1.isNullish)(common.hardfork)) + common.hardfork = (_a = transaction.hardfork) !== null && _a !== void 0 ? _a : web3Context.defaultHardfork; + if ((0, web3_validator_1.isNullish)(common.baseChain)) + common.baseChain = web3Context.defaultChain; + } + else { + common = web3_eth_accounts_1.Common.custom({ + name: 'custom-network', + chainId: (0, web3_utils_1.toNumber)(transaction.chainId), + networkId: !(0, web3_validator_1.isNullish)(transaction.networkId) + ? (0, web3_utils_1.toNumber)(transaction.networkId) + : undefined, + defaultHardfork: (_b = transaction.hardfork) !== null && _b !== void 0 ? _b : web3Context.defaultHardfork, + }, { + baseChain: web3Context.defaultChain, + }); + } + } + else { + const name = (_f = (_e = (_d = (_c = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _c === void 0 ? void 0 : _c.customChain) === null || _d === void 0 ? void 0 : _d.name) !== null && _e !== void 0 ? _e : transaction.chain) !== null && _f !== void 0 ? _f : 'custom-network'; + const chainId = (0, web3_utils_1.toNumber)((_j = (_h = (_g = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _g === void 0 ? void 0 : _g.customChain) === null || _h === void 0 ? void 0 : _h.chainId) !== null && _j !== void 0 ? _j : transaction === null || transaction === void 0 ? void 0 : transaction.chainId); + const networkId = (0, web3_utils_1.toNumber)((_m = (_l = (_k = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _k === void 0 ? void 0 : _k.customChain) === null || _l === void 0 ? void 0 : _l.networkId) !== null && _m !== void 0 ? _m : transaction === null || transaction === void 0 ? void 0 : transaction.networkId); + const defaultHardfork = (_q = (_p = (_o = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _o === void 0 ? void 0 : _o.hardfork) !== null && _p !== void 0 ? _p : transaction === null || transaction === void 0 ? void 0 : transaction.hardfork) !== null && _q !== void 0 ? _q : web3Context.defaultHardfork; + const baseChain = (_t = (_s = (_r = transaction.common) === null || _r === void 0 ? void 0 : _r.baseChain) !== null && _s !== void 0 ? _s : transaction.chain) !== null && _t !== void 0 ? _t : web3Context.defaultChain; + if (chainId && networkId && name) { + common = web3_eth_accounts_1.Common.custom({ + name, + chainId, + networkId, + defaultHardfork, + }, { + baseChain, + }); + } + } + return { common }; +}; +const prepareTransactionForSigning = (transaction, web3Context, privateKey, fillGasPrice = false, fillGasLimit = true) => __awaiter(void 0, void 0, void 0, function* () { + const populatedTransaction = (yield (0, transaction_builder_js_1.transactionBuilder)({ + transaction, + web3Context, + privateKey, + fillGasPrice, + fillGasLimit, + })); + const formattedTransaction = (0, format_transaction_js_1.formatTransaction)(populatedTransaction, web3_types_1.ETH_DATA_FORMAT); + (0, validation_js_1.validateTransactionForSigning)(formattedTransaction); + return web3_eth_accounts_1.TransactionFactory.fromTxData(getEthereumjsTxDataFromTransaction(formattedTransaction), getEthereumjsTransactionOptions(formattedTransaction, web3Context)); +}); +exports.prepareTransactionForSigning = prepareTransactionForSigning; +//# sourceMappingURL=prepare_transaction_for_signing.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.js.map new file mode 100644 index 0000000..331b11e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/prepare_transaction_for_signing.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prepare_transaction_for_signing.js","sourceRoot":"","sources":["../../../src/utils/prepare_transaction_for_signing.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAUoB;AAEpB,2CAAsC;AACtC,yDAA0E;AAC1E,mDAA2C;AAC3C,oDAAiE;AACjE,mEAA4D;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F,MAAM,SAAS,GACd,MAAA,MAAA,MAAA,WAAW,CAAC,MAAM,0CAAE,SAAS,mCAAI,WAAW,CAAC,KAAK,mCAAI,WAAW,CAAC,YAAY,CAAC;QAEhF,IAAI,OAAO,IAAI,SAAS,IAAI,IAAI,EAAE;YACjC,MAAM,GAAG,0BAAM,CAAC,MAAM,CACrB;gBACC,IAAI;gBACJ,OAAO;gBACP,SAAS;gBACT,eAAe;aACf,EACD;gBACC,SAAS;aACT,CACD,CAAC;SACF;KACD;IACD,OAAO,EAAE,MAAM,EAAe,CAAC;AAChC,CAAC,CAAC;AAEK,MAAM,4BAA4B,GAAG,CAC3C,WAAwB,EACxB,WAAyC,EACzC,UAAmC,EACnC,YAAY,GAAG,KAAK,EACpB,YAAY,GAAG,IAAI,EAClB,EAAE;IACH,MAAM,oBAAoB,GAAG,CAAC,MAAM,IAAA,2CAAkB,EAAC;QACtD,WAAW;QACX,WAAW;QACX,UAAU;QACV,YAAY;QACZ,YAAY;KACZ,CAAC,CAA4C,CAAC;IAC/C,MAAM,oBAAoB,GAAG,IAAA,yCAAiB,EAC7C,oBAAoB,EACpB,4BAAe,CACgE,CAAC;IACjF,IAAA,6CAA6B,EAC5B,oBAAkF,CAClF,CAAC;IAEF,OAAO,sCAAkB,CAAC,UAAU,CACnC,kCAAkC,CAAC,oBAAoB,CAAC,EACxD,+BAA+B,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAClE,CAAC;AACH,CAAC,CAAA,CAAC;AA1BW,QAAA,4BAA4B,gCA0BvC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.d.ts new file mode 100644 index 0000000..02ce639 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.d.ts @@ -0,0 +1,6 @@ +import { EthExecutionAPI, Bytes } from 'web3-types'; +import { Web3Context } from 'web3-core'; +export interface ResourceCleaner { + clean: () => void; +} +export declare function rejectIfBlockTimeout(web3Context: Web3Context, transactionHash?: Bytes): Promise<[Promise, ResourceCleaner]>; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.js new file mode 100644 index 0000000..c3834e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.js @@ -0,0 +1,138 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rejectIfBlockTimeout = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +const constants_js_1 = require("../constants.js"); +// eslint-disable-next-line import/no-cycle +const rpc_method_wrappers_js_1 = require("../rpc_method_wrappers.js"); +function resolveByPolling(web3Context, starterBlockNumber, transactionHash) { + const pollingInterval = web3Context.transactionPollingInterval; + const [intervalId, promiseToError] = (0, web3_utils_1.rejectIfConditionAtInterval)(() => __awaiter(this, void 0, void 0, function* () { + let lastBlockNumber; + try { + lastBlockNumber = yield (0, rpc_method_wrappers_js_1.getBlockNumber)(web3Context, constants_js_1.NUMBER_DATA_FORMAT); + } + catch (error) { + console.warn('An error happen while trying to get the block number', error); + return undefined; + } + const numberOfBlocks = lastBlockNumber - starterBlockNumber; + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + return new web3_errors_1.TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + }); + } + return undefined; + }), pollingInterval); + const clean = () => { + clearInterval(intervalId); + }; + return [promiseToError, { clean }]; +} +function resolveBySubscription(web3Context, starterBlockNumber, transactionHash) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + // The following variable will stay true except if the data arrived, + // or if watching started after an error had occurred. + let needToWatchLater = true; + let subscription; + let resourceCleaner; + // internal helper function + function revertToPolling(reject, previousError) { + if (previousError) { + console.warn('error happened at subscription. So revert to polling...', previousError); + } + resourceCleaner.clean(); + needToWatchLater = false; + const [promiseToError, newResourceCleaner] = resolveByPolling(web3Context, starterBlockNumber, transactionHash); + resourceCleaner.clean = newResourceCleaner.clean; + promiseToError.catch(error => reject(error)); + } + try { + subscription = (yield ((_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.subscribe('newHeads'))); + resourceCleaner = { + clean: () => { + var _a; + // Remove the subscription, if it was not removed somewhere + // else by calling, for example, subscriptionManager.clear() + if (subscription.id) { + (_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.removeSubscription(subscription).then(() => { + // Subscription ended successfully + }).catch(() => { + // An error happened while ending subscription. But no need to take any action. + }); + } + }, + }; + } + catch (error) { + return resolveByPolling(web3Context, starterBlockNumber, transactionHash); + } + const promiseToError = new Promise((_, reject) => { + try { + subscription.on('data', (lastBlockHeader) => { + needToWatchLater = false; + if (!(lastBlockHeader === null || lastBlockHeader === void 0 ? void 0 : lastBlockHeader.number)) { + return; + } + const numberOfBlocks = Number(BigInt(lastBlockHeader.number) - BigInt(starterBlockNumber)); + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + // Transaction Block Timeout is known to be reached by subscribing to new heads + reject(new web3_errors_1.TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + })); + } + }); + subscription.on('error', error => { + revertToPolling(reject, error); + }); + } + catch (error) { + revertToPolling(reject, error); + } + // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds] + setTimeout(() => { + if (needToWatchLater) { + revertToPolling(reject); + } + }, web3Context.blockHeaderTimeout * 1000); + }); + return [promiseToError, resourceCleaner]; + }); +} +/* TODO: After merge, there will be constant block mining time (exactly 12 second each block, except slot missed that currently happens in <1% of slots. ) so we can optimize following function +for POS NWs, we can skip checking getBlockNumber(); after interval and calculate only based on time that certain num of blocked are mined after that for internal double check, can do one getBlockNumber() call and timeout. +*/ +function rejectIfBlockTimeout(web3Context, transactionHash) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const { provider } = web3Context.requestManager; + let callingRes; + const starterBlockNumber = yield (0, rpc_method_wrappers_js_1.getBlockNumber)(web3Context, constants_js_1.NUMBER_DATA_FORMAT); + // TODO: once https://github.com/web3/web3.js/issues/5521 is implemented, remove checking for `enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout` + if (((_b = (_a = provider).supportsSubscriptions) === null || _b === void 0 ? void 0 : _b.call(_a)) && + web3Context.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout) { + callingRes = yield resolveBySubscription(web3Context, starterBlockNumber, transactionHash); + } + else { + callingRes = resolveByPolling(web3Context, starterBlockNumber, transactionHash); + } + return callingRes; + }); +} +exports.rejectIfBlockTimeout = rejectIfBlockTimeout; +//# sourceMappingURL=reject_if_block_timeout.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.js.map new file mode 100644 index 0000000..c6e4f22 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/reject_if_block_timeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"reject_if_block_timeout.js","sourceRoot":"","sources":["../../../src/utils/reject_if_block_timeout.ts"],"names":[],"mappings":";;;;;;;;;;;;AAkBA,2CAAyD;AAEzD,6CAA2D;AAC3D,kDAAqD;AACrD,2CAA2C;AAC3C,sEAA2D;A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CAAC,CAAC;SAChF;QACD,OAAO,UAAU,CAAC;;CAClB;AAjBD,oDAiBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.d.ts new file mode 100644 index 0000000..13049aa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.d.ts @@ -0,0 +1,41 @@ +import { FormatType, DataFormat, EthExecutionAPI, Web3BaseWalletAccount, HexString, TransactionReceipt, Transaction, TransactionCall, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, TransactionHash } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { SendSignedTransactionEvents, SendTransactionEvents, SendTransactionOptions } from '../types.js'; +export declare class SendTxHelper, TxType = Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex> { + private readonly web3Context; + private readonly promiEvent; + private readonly options; + private readonly returnFormat; + constructor({ options, web3Context, promiEvent, returnFormat, }: { + web3Context: Web3Context; + options: SendTransactionOptions; + promiEvent: Web3PromiEvent | SendTransactionEvents>; + returnFormat: ReturnFormat; + }); + getReceiptWithEvents(data: TransactionReceipt): ResolveType; + checkRevertBeforeSending(tx: TransactionCall): Promise; + emitSending(tx: TxType | HexString): void; + populateGasPrice({ transactionFormatted, transaction, }: { + transactionFormatted: TxType; + transaction: TxType; + }): Promise; + signAndSend({ wallet, tx, }: { + wallet: Web3BaseWalletAccount | undefined; + tx: TxType; + }): Promise; + emitSent(tx: TxType | HexString): void; + emitTransactionHash(hash: string & Uint8Array): void; + emitReceipt(receipt: ResolveType): void; + handleError({ error, tx }: { + error: unknown; + tx: TransactionCall; + }): Promise; + emitConfirmation({ receipt, transactionHash, }: { + receipt: ResolveType; + transactionHash: TransactionHash; + }): void; + handleResolve({ receipt, tx }: { + receipt: ResolveType; + tx: TransactionCall; + }): Promise; +} diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.js new file mode 100644 index 0000000..4b54e0b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.js @@ -0,0 +1,172 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SendTxHelper = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const web3_rpc_methods_1 = require("web3-rpc-methods"); +// eslint-disable-next-line import/no-cycle +const get_transaction_gas_pricing_js_1 = require("./get_transaction_gas_pricing.js"); +// eslint-disable-next-line import/no-cycle +const try_send_transaction_js_1 = require("./try_send_transaction.js"); +// eslint-disable-next-line import/no-cycle +const watch_transaction_for_confirmations_js_1 = require("./watch_transaction_for_confirmations.js"); +const constants_js_1 = require("../constants.js"); +// eslint-disable-next-line import/no-cycle +const get_transaction_error_js_1 = require("./get_transaction_error.js"); +// eslint-disable-next-line import/no-cycle +const get_revert_reason_js_1 = require("./get_revert_reason.js"); +const decoding_js_1 = require("./decoding.js"); +class SendTxHelper { + constructor({ options, web3Context, promiEvent, returnFormat, }) { + this.options = { + checkRevertBeforeSending: true, + }; + this.options = options; + this.web3Context = web3Context; + this.promiEvent = promiEvent; + this.returnFormat = returnFormat; + } + getReceiptWithEvents(data) { + var _a, _b; + const result = Object.assign({}, (data !== null && data !== void 0 ? data : {})); + if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.contractAbi) && result.logs && result.logs.length > 0) { + result.events = {}; + for (const log of result.logs) { + const event = (0, decoding_js_1.decodeEventABI)(constants_js_1.ALL_EVENTS_ABI, log, (_b = this.options) === null || _b === void 0 ? void 0 : _b.contractAbi, this.returnFormat); + if (event.event) { + result.events[event.event] = event; + } + } + } + return result; + } + checkRevertBeforeSending(tx) { + return __awaiter(this, void 0, void 0, function* () { + if (this.options.checkRevertBeforeSending !== false) { + const reason = yield (0, get_revert_reason_js_1.getRevertReason)(this.web3Context, tx, this.options.contractAbi); + if (reason !== undefined) { + throw yield (0, get_transaction_error_js_1.getTransactionError)(this.web3Context, tx, undefined, undefined, this.options.contractAbi, reason); + } + } + }); + } + emitSending(tx) { + if (this.promiEvent.listenerCount('sending') > 0) { + this.promiEvent.emit('sending', tx); + } + } + populateGasPrice({ transactionFormatted, transaction, }) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + let result = transactionFormatted; + if (!((_a = this.options) === null || _a === void 0 ? void 0 : _a.ignoreGasPricing) && + (0, web3_validator_1.isNullish)(transactionFormatted.gasPrice) && + ((0, web3_validator_1.isNullish)(transaction.maxPriorityFeePerGas) || + (0, web3_validator_1.isNullish)(transaction.maxFeePerGas))) { + result = Object.assign(Object.assign({}, transactionFormatted), (yield (0, get_transaction_gas_pricing_js_1.getTransactionGasPricing)(transactionFormatted, this.web3Context, web3_types_1.ETH_DATA_FORMAT))); + } + return result; + }); + } + signAndSend({ wallet, tx, }) { + return __awaiter(this, void 0, void 0, function* () { + if (wallet) { + const signedTransaction = yield wallet.signTransaction(tx); + return (0, try_send_transaction_js_1.trySendTransaction)(this.web3Context, () => __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.sendRawTransaction(this.web3Context.requestManager, signedTransaction.rawTransaction); + }), signedTransaction.transactionHash); + } + return (0, try_send_transaction_js_1.trySendTransaction)(this.web3Context, () => __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.sendTransaction(this.web3Context.requestManager, tx); + })); + }); + } + emitSent(tx) { + if (this.promiEvent.listenerCount('sent') > 0) { + this.promiEvent.emit('sent', tx); + } + } + emitTransactionHash(hash) { + if (this.promiEvent.listenerCount('transactionHash') > 0) { + this.promiEvent.emit('transactionHash', hash); + } + } + emitReceipt(receipt) { + if (this.promiEvent.listenerCount('receipt') > 0) { + this.promiEvent.emit('receipt', + // @ts-expect-error unknown type fix + receipt); + } + } + handleError({ error, tx }) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + let _error = error; + if (_error instanceof web3_errors_1.ContractExecutionError && this.web3Context.handleRevert) { + _error = yield (0, get_transaction_error_js_1.getTransactionError)(this.web3Context, tx, undefined, undefined, (_a = this.options) === null || _a === void 0 ? void 0 : _a.contractAbi); + } + if ((_error instanceof web3_errors_1.InvalidResponseError || + _error instanceof web3_errors_1.ContractExecutionError || + _error instanceof web3_errors_1.TransactionRevertWithCustomError || + _error instanceof web3_errors_1.TransactionRevertedWithoutReasonError || + _error instanceof web3_errors_1.TransactionRevertInstructionError) && + this.promiEvent.listenerCount('error') > 0) { + this.promiEvent.emit('error', _error); + } + return _error; + }); + } + emitConfirmation({ receipt, transactionHash, }) { + if (this.promiEvent.listenerCount('confirmation') > 0) { + (0, watch_transaction_for_confirmations_js_1.watchTransactionForConfirmations)(this.web3Context, this.promiEvent, receipt, transactionHash, this.returnFormat); + } + } + handleResolve({ receipt, tx }) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.transactionResolver) { + return (_b = this.options) === null || _b === void 0 ? void 0 : _b.transactionResolver(receipt); + } + if (receipt.status === BigInt(0)) { + const error = yield (0, get_transaction_error_js_1.getTransactionError)(this.web3Context, tx, + // @ts-expect-error unknown type fix + receipt, undefined, (_c = this.options) === null || _c === void 0 ? void 0 : _c.contractAbi); + if (this.promiEvent.listenerCount('error') > 0) { + this.promiEvent.emit('error', error); + } + throw error; + } + else { + return receipt; + } + }); + } +} +exports.SendTxHelper = SendTxHelper; +//# sourceMappingURL=send_tx_helper.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.js.map new file mode 100644 index 0000000..c69c4cb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/send_tx_helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"send_tx_helper.js","sourceRoot":"","sources":["../../../src/utils/send_tx_helper.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,2CAiBoB;AAEpB,mDAA2C;AAC3C,6CAMqB;AACrB,uDAAiD;AAOjD,2CAA2C;AAC3C,qFAA4E;AAC5E,2CAA2C;AAC3C,uEAA+D;AAC/D,2CAA2C;AAC3C,qGAA4F;AAC5F,kDAAiD;AACjD,2CAA2C;AAC3C,yEAAiE;AACjE,2CAA2C;AAC3C,iEAAyD;AACzD,+CAA+C;AAE/C,MAAa,YAAY;IAkBxB,YAAmB,EAClB,OAAO,EACP,WAAW,EACX,UAAU,EACV,YAAY,GASZ;QAjBgB,YAAO,GAAwC;YAC/D,wBAAwB,EAAE,IAAI;SAC9B,CAAC;QAgBD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,WAAW,GAAG,WAAW,CAA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AAC;aACtC;YAED,OAAO,MAAM,CAAC;;KACd;IAEM,gBAAgB,CAAC,EACvB,OAAO,EACP,eAAe,GAIf;QACA,IAAI,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;YACtD,IAAA,yEAAgC,EAK/B,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,UAAU,EACf,OAAwC,EACxC,eAAe,EACf,IAAI,CAAC,YAAY,CACjB,CAAC;SACF;IACF,CAAC;IAEY,aAAa,CAAC,EAAE,OAAO,EAAE,EAAE,EAAiD;;;YACxF,IAAI,MAAA,IAAI,CAAC,OAAO,0CAAE,mBAAmB,EAAE;gBACtC,OAAO,MAAA,IAAI,CAAC,OAAO,0CAAE,mBAAmB,CAAC,OAAwC,CAAC,CAAC;aACnF;YACD,IAAK,OAAyC,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE;gBACpE,MAAM,KAAK,GAAG,MAAM,IAAA,8CAAmB,EACtC,IAAI,CAAC,WAAW,EAChB,EAAE;gBACF,oCAAoC;gBACpC,OAAO,EACP,SAAS,EACT,MAAA,IAAI,CAAC,OAAO,0CAAE,WAAW,CACzB,CAAC;gBACF,IAAI,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;oBAC/C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;iBACrC;gBAED,MAAM,KAAK,CAAC;aACZ;iBAAM;gBACN,OAAO,OAAO,CAAC;aACf;;KACD;CACD;AA3OD,oCA2OC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.d.ts new file mode 100644 index 0000000..f2582c6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.d.ts @@ -0,0 +1,19 @@ +import { EthExecutionAPI, Address, HexString, Transaction, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, Web3NetAPI, DataFormat, FormatType, ETH_DATA_FORMAT } from 'web3-types'; +import { Web3Context } from 'web3-core'; +export declare const getTransactionFromOrToAttr: (attr: 'from' | 'to', web3Context: Web3Context, transaction?: Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex, privateKey?: HexString | Uint8Array) => Address | undefined; +export declare const getTransactionNonce: (web3Context: Web3Context, address?: Address, returnFormat?: ReturnFormat) => Promise; +export declare const getTransactionType: (transaction: FormatType, web3Context: Web3Context) => string | undefined; +export declare function defaultTransactionBuilder(options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; + fillGasLimit?: boolean; +}): Promise; +export declare const transactionBuilder: (options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; + fillGasLimit?: boolean; +}) => Promise; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.js new file mode 100644 index 0000000..83a9afb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.js @@ -0,0 +1,171 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.transactionBuilder = exports.defaultTransactionBuilder = exports.getTransactionType = exports.getTransactionNonce = exports.getTransactionFromOrToAttr = void 0; +const web3_types_1 = require("web3-types"); +const web3_eth_accounts_1 = require("web3-eth-accounts"); +const web3_net_1 = require("web3-net"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const constants_js_1 = require("../constants.js"); +// eslint-disable-next-line import/no-cycle +const rpc_method_wrappers_js_1 = require("../rpc_method_wrappers.js"); +const detect_transaction_type_js_1 = require("./detect_transaction_type.js"); +const schemas_js_1 = require("../schemas.js"); +// eslint-disable-next-line import/no-cycle +const get_transaction_gas_pricing_js_1 = require("./get_transaction_gas_pricing.js"); +const getTransactionFromOrToAttr = (attr, web3Context, transaction, privateKey) => { + if (transaction !== undefined && attr in transaction && transaction[attr] !== undefined) { + if (typeof transaction[attr] === 'string' && (0, web3_validator_1.isAddress)(transaction[attr])) { + return transaction[attr]; + } + if (!(0, web3_validator_1.isHexStrict)(transaction[attr]) && (0, web3_validator_1.isNumber)(transaction[attr])) { + if (web3Context.wallet) { + const account = web3Context.wallet.get((0, web3_utils_1.format)({ format: 'uint' }, transaction[attr], constants_js_1.NUMBER_DATA_FORMAT)); + if (!(0, web3_validator_1.isNullish)(account)) { + return account.address; + } + throw new web3_errors_1.LocalWalletNotAvailableError(); + } + throw new web3_errors_1.LocalWalletNotAvailableError(); + } + else { + throw attr === 'from' + ? new web3_errors_1.InvalidTransactionWithSender(transaction.from) + : // eslint-disable-next-line @typescript-eslint/no-unsafe-call + new web3_errors_1.InvalidTransactionWithReceiver(transaction.to); + } + } + if (attr === 'from') { + if (!(0, web3_validator_1.isNullish)(privateKey)) + return (0, web3_eth_accounts_1.privateKeyToAddress)(privateKey); + if (!(0, web3_validator_1.isNullish)(web3Context.defaultAccount)) + return web3Context.defaultAccount; + } + return undefined; +}; +exports.getTransactionFromOrToAttr = getTransactionFromOrToAttr; +const getTransactionNonce = (web3Context, address, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) => __awaiter(void 0, void 0, void 0, function* () { + if ((0, web3_validator_1.isNullish)(address)) { + // TODO if (web3.eth.accounts.wallet) use address from local wallet + throw new web3_errors_1.UnableToPopulateNonceError(); + } + return (0, rpc_method_wrappers_js_1.getTransactionCount)(web3Context, address, web3Context.defaultBlock, returnFormat); +}); +exports.getTransactionNonce = getTransactionNonce; +const getTransactionType = (transaction, web3Context) => { + const inferredType = (0, detect_transaction_type_js_1.detectTransactionType)(transaction, web3Context); + if (!(0, web3_validator_1.isNullish)(inferredType)) + return inferredType; + if (!(0, web3_validator_1.isNullish)(web3Context.defaultTransactionType)) + return (0, web3_utils_1.format)({ format: 'uint' }, web3Context.defaultTransactionType, web3_types_1.ETH_DATA_FORMAT); + return undefined; +}; +exports.getTransactionType = getTransactionType; +// Keep in mind that the order the properties of populateTransaction get populated matters +// as some of the properties are dependent on others +function defaultTransactionBuilder(options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let populatedTransaction = (0, web3_utils_1.format)(schemas_js_1.transactionSchema, options.transaction, web3_types_1.DEFAULT_RETURN_FORMAT); + if ((0, web3_validator_1.isNullish)(populatedTransaction.from)) { + populatedTransaction.from = (0, exports.getTransactionFromOrToAttr)('from', options.web3Context, undefined, options.privateKey); + } + // TODO: Debug why need to typecase getTransactionNonce + if ((0, web3_validator_1.isNullish)(populatedTransaction.nonce)) { + populatedTransaction.nonce = yield (0, exports.getTransactionNonce)(options.web3Context, populatedTransaction.from, web3_types_1.ETH_DATA_FORMAT); + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.value)) { + populatedTransaction.value = '0x0'; + } + if (!(0, web3_validator_1.isNullish)(populatedTransaction.data)) { + if (!(0, web3_validator_1.isNullish)(populatedTransaction.input) && + populatedTransaction.data !== populatedTransaction.input) + throw new web3_errors_1.TransactionDataAndInputError({ + data: (0, web3_utils_1.bytesToHex)(populatedTransaction.data), + input: (0, web3_utils_1.bytesToHex)(populatedTransaction.input), + }); + if (!populatedTransaction.data.startsWith('0x')) + populatedTransaction.data = `0x${populatedTransaction.data}`; + } + else if (!(0, web3_validator_1.isNullish)(populatedTransaction.input)) { + if (!populatedTransaction.input.startsWith('0x')) + populatedTransaction.input = `0x${populatedTransaction.input}`; + } + else { + populatedTransaction.input = '0x'; + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.common)) { + if (options.web3Context.defaultCommon) { + const common = options.web3Context.defaultCommon; + const chainId = common.customChain.chainId; + const networkId = common.customChain.networkId; + const name = common.customChain.name; + populatedTransaction.common = Object.assign(Object.assign({}, common), { customChain: { chainId, networkId, name } }); + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.chain)) { + populatedTransaction.chain = options.web3Context.defaultChain; + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.hardfork)) { + populatedTransaction.hardfork = options.web3Context.defaultHardfork; + } + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.chainId) && + (0, web3_validator_1.isNullish)((_a = populatedTransaction.common) === null || _a === void 0 ? void 0 : _a.customChain.chainId)) { + populatedTransaction.chainId = yield (0, rpc_method_wrappers_js_1.getChainId)(options.web3Context, web3_types_1.ETH_DATA_FORMAT); + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.networkId)) { + populatedTransaction.networkId = + (_b = options.web3Context.defaultNetworkId) !== null && _b !== void 0 ? _b : (yield (0, web3_net_1.getId)(options.web3Context, web3_types_1.ETH_DATA_FORMAT)); + } + if ((0, web3_validator_1.isNullish)(populatedTransaction.gasLimit) && !(0, web3_validator_1.isNullish)(populatedTransaction.gas)) { + populatedTransaction.gasLimit = populatedTransaction.gas; + } + populatedTransaction.type = (0, exports.getTransactionType)(populatedTransaction, options.web3Context); + if ((0, web3_validator_1.isNullish)(populatedTransaction.accessList) && + (populatedTransaction.type === '0x1' || populatedTransaction.type === '0x2')) { + populatedTransaction.accessList = []; + } + if (options.fillGasPrice) + populatedTransaction = Object.assign(Object.assign({}, populatedTransaction), (yield (0, get_transaction_gas_pricing_js_1.getTransactionGasPricing)(populatedTransaction, options.web3Context, web3_types_1.ETH_DATA_FORMAT))); + if ((0, web3_validator_1.isNullish)(populatedTransaction.gas) && + (0, web3_validator_1.isNullish)(populatedTransaction.gasLimit) && + options.fillGasLimit) { + const fillGasLimit = yield (0, rpc_method_wrappers_js_1.estimateGas)(options.web3Context, populatedTransaction, 'latest', web3_types_1.ETH_DATA_FORMAT); + populatedTransaction = Object.assign(Object.assign({}, populatedTransaction), { gas: (0, web3_utils_1.format)({ format: 'uint' }, fillGasLimit, web3_types_1.ETH_DATA_FORMAT) }); + } + return populatedTransaction; + }); +} +exports.defaultTransactionBuilder = defaultTransactionBuilder; +const transactionBuilder = (options) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + return ((_a = options.web3Context.transactionBuilder) !== null && _a !== void 0 ? _a : defaultTransactionBuilder)(Object.assign(Object.assign({}, options), { transaction: options.transaction })); +}); +exports.transactionBuilder = transactionBuilder; +//# sourceMappingURL=transaction_builder.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.js.map new file mode 100644 index 0000000..1365052 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/transaction_builder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction_builder.js","sourceRoot":"","sources":["../../../src/utils/transaction_builder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAiB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GACzE,CAAC;SACF;QACD,OAAO,oBAAkC,CAAC;;CAC1C;AA5HD,8DA4HC;AAEM,MAAM,kBAAkB,GAAG,CACjC,OAMC,EAEA,EAAE;;IACH,OAAA,CAAC,MAAA,OAAO,CAAC,WAAW,CAAC,kBAAkB,mCAAI,yBAAyB,CAAC,iCACjE,OAAO,KACV,WAAW,EAAE,OAAO,CAAC,WAAW,IACN,CAAA;EAAA,CAAC;AAbhB,QAAA,kBAAkB,sBAaF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.d.ts new file mode 100644 index 0000000..962ca2e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.d.ts @@ -0,0 +1,11 @@ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Bytes } from 'web3-types'; +import { AsyncFunction } from 'web3-utils'; +/** + * An internal function to send a transaction or throws if sending did not finish during the timeout during the blocks-timeout. + * @param web3Context - the context to read the configurations from + * @param sendTransactionFunc - the function that will send the transaction (could be sendTransaction or sendRawTransaction) + * @param transactionHash - to be used inside the exception message if there will be any exceptions. + * @returns the Promise returned by the `sendTransactionFunc`. + */ +export declare function trySendTransaction(web3Context: Web3Context, sendTransactionFunc: AsyncFunction, transactionHash?: Bytes): Promise; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.js new file mode 100644 index 0000000..bb34167 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.js @@ -0,0 +1,46 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.trySendTransaction = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +// eslint-disable-next-line import/no-cycle +const reject_if_block_timeout_js_1 = require("./reject_if_block_timeout.js"); +/** + * An internal function to send a transaction or throws if sending did not finish during the timeout during the blocks-timeout. + * @param web3Context - the context to read the configurations from + * @param sendTransactionFunc - the function that will send the transaction (could be sendTransaction or sendRawTransaction) + * @param transactionHash - to be used inside the exception message if there will be any exceptions. + * @returns the Promise returned by the `sendTransactionFunc`. + */ +function trySendTransaction(web3Context, sendTransactionFunc, transactionHash) { + return __awaiter(this, void 0, void 0, function* () { + const [timeoutId, rejectOnTimeout] = (0, web3_utils_1.rejectIfTimeout)(web3Context.transactionSendTimeout, new web3_errors_1.TransactionSendTimeoutError({ + numberOfSeconds: web3Context.transactionSendTimeout / 1000, + transactionHash, + })); + const [rejectOnBlockTimeout, blockTimeoutResourceCleaner] = yield (0, reject_if_block_timeout_js_1.rejectIfBlockTimeout)(web3Context, transactionHash); + try { + // If an error happened here, do not catch it, just clear the resources before raising it to the caller function. + return yield Promise.race([ + sendTransactionFunc(), + rejectOnTimeout, + rejectOnBlockTimeout, // this will throw an error on Transaction Block Timeout + ]); + } + finally { + clearTimeout(timeoutId); + blockTimeoutResourceCleaner.clean(); + } + }); +} +exports.trySendTransaction = trySendTransaction; +//# sourceMappingURL=try_send_transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.js.map new file mode 100644 index 0000000..23e5db4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/try_send_transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"try_send_transaction.js","sourceRoot":"","sources":["../../../src/utils/try_send_transaction.ts"],"names":[],"mappings":";;;;;;;;;;;;AAkBA,2CAA4D;AAC5D,6CAA0D;AAE1D,2CAA2C;AAC3C,6EAAoE;AAEpE;;;;;;GAMG;AACH,SAAsB,kBAAkB,CACvC,WAAyC,EACzC,mBAA0C,EAC1C,eAAuB;;QAEvB,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,GAAG,IAAA,4BAAe,EACnD,WAAW,CAAC,sBAAsB,EAClC,IAAI,yCAA2B,CAAC;YAC/B,eAAe,EAAE,WAAW,CAAC,sBAAsB,GAAG,IAAI;YAC1D,eAAe;SACf,CAAC,CACF,CAAC;QAEF,MAAM,CAAC,oBAAoB,EAAE,2BAA2B,CAAC,GAAG,MAAM,IAAA,iDAAoB,EACrF,WAAW,EACX,eAAe,CACf,CAAC;QAEF,IAAI;YACH,iHAAiH;YACjH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;gBACzB,mBAAmB,EAAE;gBACrB,eAAe;gBACf,oBAAoB,EAAE,wDAAwD;aAC9E,CAAC,CAAC;SACH;gBAAS;YACT,YAAY,CAAC,SAAS,CAAC,CAAC;YACxB,2BAA2B,CAAC,KAAK,EAAE,CAAC;SACpC;IACF,CAAC;CAAA;AA7BD,gDA6BC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.d.ts new file mode 100644 index 0000000..1c928d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.d.ts @@ -0,0 +1,3 @@ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Bytes, TransactionReceipt, DataFormat } from 'web3-types'; +export declare function waitForTransactionReceipt(web3Context: Web3Context, transactionHash: Bytes, returnFormat: ReturnFormat): Promise; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.js new file mode 100644 index 0000000..edd79a4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.js @@ -0,0 +1,72 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.waitForTransactionReceipt = void 0; +const web3_errors_1 = require("web3-errors"); +// eslint-disable-next-line import/no-cycle +const web3_utils_1 = require("web3-utils"); +// eslint-disable-next-line import/no-cycle +const reject_if_block_timeout_js_1 = require("./reject_if_block_timeout.js"); +// eslint-disable-next-line import/no-cycle +const rpc_method_wrappers_js_1 = require("../rpc_method_wrappers.js"); +function waitForTransactionReceipt(web3Context, transactionHash, returnFormat) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const pollingInterval = (_a = web3Context.transactionReceiptPollingInterval) !== null && _a !== void 0 ? _a : web3Context.transactionPollingInterval; + const [awaitableTransactionReceipt, IntervalId] = (0, web3_utils_1.pollTillDefinedAndReturnIntervalId)(() => __awaiter(this, void 0, void 0, function* () { + try { + return (0, rpc_method_wrappers_js_1.getTransactionReceipt)(web3Context, transactionHash, returnFormat); + } + catch (error) { + console.warn('An error happen while trying to get the transaction receipt', error); + return undefined; + } + }), pollingInterval); + const [timeoutId, rejectOnTimeout] = (0, web3_utils_1.rejectIfTimeout)(web3Context.transactionPollingTimeout, new web3_errors_1.TransactionPollingTimeoutError({ + numberOfSeconds: web3Context.transactionPollingTimeout / 1000, + transactionHash, + })); + const [rejectOnBlockTimeout, blockTimeoutResourceCleaner] = yield (0, reject_if_block_timeout_js_1.rejectIfBlockTimeout)(web3Context, transactionHash); + try { + // If an error happened here, do not catch it, just clear the resources before raising it to the caller function. + return yield Promise.race([ + awaitableTransactionReceipt, + rejectOnTimeout, + rejectOnBlockTimeout, // this will throw an error on Transaction Block Timeout + ]); + } + finally { + if (timeoutId) + clearTimeout(timeoutId); + if (IntervalId) + clearInterval(IntervalId); + blockTimeoutResourceCleaner.clean(); + } + }); +} +exports.waitForTransactionReceipt = waitForTransactionReceipt; +//# sourceMappingURL=wait_for_transaction_receipt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.js.map new file mode 100644 index 0000000..b34e796 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/wait_for_transaction_receipt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wait_for_transaction_receipt.js","sourceRoot":"","sources":["../../../src/utils/wait_for_transaction_receipt.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAGF,6CAA6D;AAG7D,2CAA2C;AAC3C,2CAAiF;AACjF,2CAA2C;AAC3C,6EAAoE;AACpE,2CAA2C;AAC3C,sEAAkE;AAElE,SAAsB,yBAAyB,CAC9C,WAAyC,EACzC,eAAsB,EACtB,YAA0B;;;QAG1B,MAAM,eAAe,GACpB,MAAA,WAAW,CAAC,iCAAiC,mCAAI,WAAW,CAAC,0BAA0B,CAAC;QAEzF,MAAM,CAAC,2BAA2B,EAAE,UAAU,CAAC,GAAG,IAAA,+CAAkC,EAAC,GAAS,EAAE;YAC/F,IAAI;gBACH,OAAO,IAAA,8CAAqB,EAAC,WAAW,EAAE,eAAe,EAAE,YAAY,CAAC,CAAC;aACzE;YAAC,OAAO,KAAK,EAAE;gBACf,OAAO,CAAC,IAAI,CAAC,6DAA6D,EAAE,KAAK,CAAC,CAAC;gBACnF,OAAO,SAAS,CAAC;aACjB;QACF,CAAC,CAAA,EAAE,eAAe,CAAC,CAAC;QAEpB,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,GAAG,IAAA,4BAAe,EACnD,WAAW,CAAC,yBAAyB,EACrC,IAAI,4CAA8B,CAAC;YAClC,eAAe,EAAE,WAAW,CAAC,yBAAyB,GAAG,IAAI;YAC7D,eAAe;SACf,CAAC,CACF,CAAC;QAEF,MAAM,CAAC,oBAAoB,EAAE,2BAA2B,CAAC,GAAG,MAAM,IAAA,iDAAoB,EACrF,WAAW,EACX,eAAe,CACf,CAAC;QAEF,IAAI;YACH,iHAAiH;YACjH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;gBACzB,2BAA2B;gBAC3B,eAAe;gBACf,oBAAoB,EAAE,wDAAwD;aAC9E,CAAC,CAAC;SACH;gBAAS;YACT,IAAG,SAAS;gBACX,YAAY,CAAC,SAAS,CAAC,CAAC;YACzB,IAAG,UAAU;gBACZ,aAAa,CAAC,UAAU,CAAC,CAAC;YAC3B,2BAA2B,CAAC,KAAK,EAAE,CAAC;SACpC;;CACD;AA7CD,8DA6CC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.d.ts new file mode 100644 index 0000000..d1165c9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.d.ts @@ -0,0 +1,17 @@ +import { EthExecutionAPI, TransactionReceipt } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { DataFormat } from 'web3-types'; +import { SendSignedTransactionEvents, SendTransactionEvents } from '../types.js'; +export declare type Web3PromiEventEventTypeBase = SendTransactionEvents | SendSignedTransactionEvents; +export declare type WaitProps = { + web3Context: Web3Context; + transactionReceipt: TransactionReceipt; + transactionPromiEvent: Web3PromiEvent>; + returnFormat: ReturnFormat; +}; +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider does not support subscription. + * And it is also used by `watchTransactionBySubscription`, as a fallback, if the subscription failed for any reason. + */ +export declare const watchTransactionByPolling: ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }: WaitProps) => void; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.js new file mode 100644 index 0000000..a3c78c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.js @@ -0,0 +1,43 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.watchTransactionByPolling = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_rpc_methods_1 = require("web3-rpc-methods"); +const schemas_js_1 = require("../schemas.js"); +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider does not support subscription. + * And it is also used by `watchTransactionBySubscription`, as a fallback, if the subscription failed for any reason. + */ +const watchTransactionByPolling = ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }) => { + var _a; + // Having a transactionReceipt means that the transaction has already been included + // in at least one block, so we start with 1 + let confirmations = 1; + const intervalId = setInterval(() => { + (() => __awaiter(void 0, void 0, void 0, function* () { + if (confirmations >= web3Context.transactionConfirmationBlocks) + clearInterval(intervalId); + const nextBlock = yield web3_rpc_methods_1.ethRpcMethods.getBlockByNumber(web3Context.requestManager, (0, web3_utils_1.numberToHex)(BigInt(transactionReceipt.blockNumber) + BigInt(confirmations)), false); + if (nextBlock === null || nextBlock === void 0 ? void 0 : nextBlock.hash) { + confirmations += 1; + transactionPromiEvent.emit('confirmation', { + confirmations: (0, web3_utils_1.format)({ format: 'uint' }, confirmations, returnFormat), + receipt: (0, web3_utils_1.format)(schemas_js_1.transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: (0, web3_utils_1.format)({ format: 'bytes32' }, nextBlock.hash, returnFormat), + }); + } + }))(); + }, (_a = web3Context.transactionReceiptPollingInterval) !== null && _a !== void 0 ? _a : web3Context.transactionPollingInterval); +}; +exports.watchTransactionByPolling = watchTransactionByPolling; +//# sourceMappingURL=watch_transaction_by_pooling.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.js.map new file mode 100644 index 0000000..dd48996 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_pooling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_by_pooling.js","sourceRoot":"","sources":["../../../src/utils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CW,QAAA,yBAAyB,6BAsCpC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.d.ts new file mode 100644 index 0000000..a23d903 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.d.ts @@ -0,0 +1,8 @@ +import { TransactionReceipt } from 'web3-types'; +import { DataFormat } from 'web3-types'; +import { WaitProps } from './watch_transaction_by_pooling.js'; +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider supports subscription. + */ +export declare const watchTransactionBySubscription: ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }: WaitProps) => void; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.js new file mode 100644 index 0000000..990615c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.js @@ -0,0 +1,84 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.watchTransactionBySubscription = void 0; +const web3_utils_1 = require("web3-utils"); +const schemas_js_1 = require("../schemas.js"); +const watch_transaction_by_pooling_js_1 = require("./watch_transaction_by_pooling.js"); +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider supports subscription. + */ +const watchTransactionBySubscription = ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }) => { + // The following variable will stay true except if the data arrived, + // or if watching started after an error had occurred. + let needToWatchLater = true; + let lastCaughtBlockHash; + setImmediate(() => { + var _a; + (_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.subscribe('newHeads').then((subscription) => { + subscription.on('data', (newBlockHeader) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + needToWatchLater = false; + if (!(newBlockHeader === null || newBlockHeader === void 0 ? void 0 : newBlockHeader.number) || + // For some cases, the on-data event is fired couple times for the same block! + // This needs investigation but seems to be because of multiple `subscription.on('data'...)` even this should not cause that. + lastCaughtBlockHash === (newBlockHeader === null || newBlockHeader === void 0 ? void 0 : newBlockHeader.parentHash)) { + return; + } + lastCaughtBlockHash = newBlockHeader === null || newBlockHeader === void 0 ? void 0 : newBlockHeader.parentHash; + const confirmations = BigInt(newBlockHeader.number) - + BigInt(transactionReceipt.blockNumber) + + BigInt(1); + transactionPromiEvent.emit('confirmation', { + confirmations: (0, web3_utils_1.format)({ format: 'uint' }, confirmations, returnFormat), + receipt: (0, web3_utils_1.format)(schemas_js_1.transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: (0, web3_utils_1.format)({ format: 'bytes32' }, newBlockHeader.parentHash, returnFormat), + }); + if (confirmations >= web3Context.transactionConfirmationBlocks) { + yield ((_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.removeSubscription(subscription)); + } + })); + subscription.on('error', () => __awaiter(void 0, void 0, void 0, function* () { + var _b; + yield ((_b = web3Context.subscriptionManager) === null || _b === void 0 ? void 0 : _b.removeSubscription(subscription)); + needToWatchLater = false; + (0, watch_transaction_by_pooling_js_1.watchTransactionByPolling)({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + })); + }).catch(() => { + needToWatchLater = false; + (0, watch_transaction_by_pooling_js_1.watchTransactionByPolling)({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + }); + }); + // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds] + setTimeout(() => { + if (needToWatchLater) { + (0, watch_transaction_by_pooling_js_1.watchTransactionByPolling)({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } + }, web3Context.blockHeaderTimeout * 1000); +}; +exports.watchTransactionBySubscription = watchTransactionBySubscription; +//# sourceMappingURL=watch_transaction_by_subscription.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.js.map new file mode 100644 index 0000000..fd69135 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_by_subscription.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_by_subscription.js","sourceRoot":"","sources":["../../../src/utils/watch_transaction_by_subscription.ts"],"names":[],"mappings":";;;;;;;;;;;;AAiBA,2CAAoC;AAIpC,8CAAyD;AACzD,uFAAyF;AAEzF;;;GAGG;AACI,MAAM,8BAA8B,GAAG,CAG5C,EACD,WAAW,EACX,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,GAC0B,EAAE,EAAE;IAC1C,oEAAoE;IACpE,sDAAsD;IACtD,IAAI,gBAAgB,GAAG,IAAI,CAAC;IAC5B,IAAI,mBAA2B,CAAC;IAChC,YAAY,CAAC,GAAG,EAAE;;QACjB,MAAA,WAAW,CAAC,mBAAmB,0CAC5B,SAAS,CAAC,UAAU,EACrB,IAAI,CAAC,CAAC,YAAkC,EAAE,EAAE;YAC5C,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,CAAO,cAAiC,EAAE,EAAE;;gBACnE,gBAAgB,GAAG,KAAK,CAAC;gBACzB,IACC,CAAC,CAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,MAAM,CAAA;oBACvB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X,gBAAgB,GAAG,KAAK,CAAC;YACzB,IAAA,2DAAyB,EAAC;gBACzB,WAAW;gBACX,kBAAkB;gBAClB,qBAAqB;gBACrB,YAAY;aACZ,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,wFAAwF;IACxF,UAAU,CAAC,GAAG,EAAE;QACf,IAAI,gBAAgB,EAAE;YACrB,IAAA,2DAAyB,EAAC;gBACzB,WAAW;gBACX,kBAAkB;gBAClB,qBAAqB;gBACrB,YAAY;aACZ,CAAC,CAAC;SACH;IACF,CAAC,EAAE,WAAW,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;AAC3C,CAAC,CAAC;AArFW,QAAA,8BAA8B,kCAqFzC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.d.ts new file mode 100644 index 0000000..7ceb3e6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.d.ts @@ -0,0 +1,5 @@ +import { Bytes, EthExecutionAPI, TransactionReceipt } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { DataFormat } from 'web3-types'; +import { Web3PromiEventEventTypeBase } from './watch_transaction_by_pooling.js'; +export declare function watchTransactionForConfirmations, ResolveType = TransactionReceipt>(web3Context: Web3Context, transactionPromiEvent: Web3PromiEvent, transactionReceipt: TransactionReceipt, transactionHash: Bytes, returnFormat: ReturnFormat): void; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.js new file mode 100644 index 0000000..c9b76b0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.watchTransactionForConfirmations = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const schemas_js_1 = require("../schemas.js"); +const watch_transaction_by_pooling_js_1 = require("./watch_transaction_by_pooling.js"); +const watch_transaction_by_subscription_js_1 = require("./watch_transaction_by_subscription.js"); +function watchTransactionForConfirmations(web3Context, transactionPromiEvent, transactionReceipt, transactionHash, returnFormat) { + if ((0, web3_validator_1.isNullish)(transactionReceipt) || (0, web3_validator_1.isNullish)(transactionReceipt.blockHash)) + throw new web3_errors_1.TransactionMissingReceiptOrBlockHashError({ + receipt: transactionReceipt, + blockHash: (0, web3_utils_1.format)({ format: 'bytes32' }, transactionReceipt === null || transactionReceipt === void 0 ? void 0 : transactionReceipt.blockHash, returnFormat), + transactionHash: (0, web3_utils_1.format)({ format: 'bytes32' }, transactionHash, returnFormat), + }); + if (!transactionReceipt.blockNumber) + throw new web3_errors_1.TransactionReceiptMissingBlockNumberError({ receipt: transactionReceipt }); + // As we have the receipt, it's the first confirmation that tx is accepted. + transactionPromiEvent.emit('confirmation', { + confirmations: (0, web3_utils_1.format)({ format: 'uint' }, 1, returnFormat), + receipt: (0, web3_utils_1.format)(schemas_js_1.transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: (0, web3_utils_1.format)({ format: 'bytes32' }, transactionReceipt.blockHash, returnFormat), + }); + // so a subscription for newBlockHeaders can be made instead of polling + const provider = web3Context.requestManager.provider; + if (provider && 'supportsSubscriptions' in provider && provider.supportsSubscriptions()) { + (0, watch_transaction_by_subscription_js_1.watchTransactionBySubscription)({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } + else { + (0, watch_transaction_by_pooling_js_1.watchTransactionByPolling)({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } +} +exports.watchTransactionForConfirmations = watchTransactionForConfirmations; +//# sourceMappingURL=watch_transaction_for_confirmations.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.js.map new file mode 100644 index 0000000..2cc8fd3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/utils/watch_transaction_for_confirmations.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_for_confirmations.js","sourceRoot":"","sources":["../../../src/utils/watch_transaction_for_confirmations.ts"],"names":[],"mappings":";;;AAkBA,2CAAoC;AACpC,mDAA2C;AAE3C,6CAGqB;AAErB,8CAAyD;AACzD,uFAG2C;AAC3C,iGAAwF;AAExF,SAAgB,gCAAgC,CAK/C,WAAyC,EACzC,qBAA2E,EAC3E,kBAAsC,EACtC,eAAsB,EACtB,YAA0B;IAE1B,IAAI,IAAA,0BAAS,EAAC,kBAAkB,CAAC,IAAI,IAAA,0BAAS,EAAC,kBAAkB,CAAC,SAAS,CAAC;QAC3E,MAAM,IAAI,uDAAyC,CAAC;YACnD,OAAO,EAAE,kBAAkB;YAC3B,SAAS,EAAE,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAE,SAAS,EAAE,YAAY,CAAC;YACrF,eAAe,EAAE,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,eAAe,EAAE,YAAY,CAAC;SAC7E,CAAC,CAAC;IAEJ,IAAI,CAAC,kBAAkB,CAAC,WAAW;QAClC,MAAM,IAAI,uDAAyC,CAAC,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAEtF,2EAA2E;IAC3E,qBAAqB,CAAC,IAAI,CAAC,cAAc,EAAE;QAC1C,aAAa,EAAE,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,YAAY,CAAC;QAC1D,OAAO,EAAE,IAAA,mBAAM,EAAC,qCAAwB,EAAE,kBAAkB,EAAE,YAAY,CAAC;QAC3E,eAAe,EAAE,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,kBAAkB,CAAC,SAAS,EAAE,YAAY,CAAC;KAC1F,CAAC,CAAC;IAEH,uEAAuE;IACvE,MAAM,QAAQ,GAAqB,WAAW,CAAC,cAAc,CAAC,QAA4B,CAAC;IAC3F,IAAI,QAAQ,IAAI,uBAAuB,IAAI,QAAQ,IAAI,QAAQ,CAAC,qBAAqB,EAAE,EAAE;QACxF,IAAA,qEAA8B,EAAC;YAC9B,WAAW;YACX,kBAAkB;YAClB,qBAAqB;YACrB,YAAY;SACZ,CAAC,CAAC;KACH;SAAM;QACN,IAAA,2DAAyB,EAAC;YACzB,WAAW;YACX,kBAAkB;YAClB,qBAAqB;YACrB,YAAY;SACZ,CAAC,CAAC;KACH;AACF,CAAC;AA7CD,4EA6CC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.d.ts new file mode 100644 index 0000000..3c9549b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.d.ts @@ -0,0 +1,24 @@ +import { AccessList, AccessListEntry, BaseTransactionAPI, Transaction1559UnsignedAPI, Transaction2930UnsignedAPI, TransactionCall, TransactionLegacyUnsignedAPI, TransactionWithSenderAPI } from 'web3-types'; +import { InternalTransaction } from './types.js'; +export declare function isBaseTransaction(value: BaseTransactionAPI): boolean; +export declare function isAccessListEntry(value: AccessListEntry): boolean; +export declare function isAccessList(value: AccessList): boolean; +export declare function isTransaction1559Unsigned(value: Transaction1559UnsignedAPI): boolean; +export declare function isTransaction2930Unsigned(value: Transaction2930UnsignedAPI): boolean; +export declare function isTransactionLegacyUnsigned(value: TransactionLegacyUnsignedAPI): boolean; +export declare function isTransactionWithSender(value: TransactionWithSenderAPI): boolean; +export declare function validateTransactionWithSender(value: TransactionWithSenderAPI): void; +export declare function isTransactionCall(value: TransactionCall): boolean; +export declare function validateTransactionCall(value: TransactionCall): void; +export declare const validateCustomChainInfo: (transaction: InternalTransaction) => void; +export declare const validateChainInfo: (transaction: InternalTransaction) => void; +export declare const validateBaseChain: (transaction: InternalTransaction) => void; +export declare const validateHardfork: (transaction: InternalTransaction) => void; +export declare const validateLegacyGas: (transaction: InternalTransaction) => void; +export declare const validateFeeMarketGas: (transaction: InternalTransaction) => void; +/** + * This method checks if all required gas properties are present for either + * legacy gas (type 0x0 and 0x1) OR fee market transactions (0x2) + */ +export declare const validateGas: (transaction: InternalTransaction) => void; +export declare const validateTransactionForSigning: (transaction: InternalTransaction, overrideMethod?: ((transaction: InternalTransaction) => void) | undefined) => void; diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.js new file mode 100644 index 0000000..2e815f6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.js @@ -0,0 +1,279 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateTransactionForSigning = exports.validateGas = exports.validateFeeMarketGas = exports.validateLegacyGas = exports.validateHardfork = exports.validateBaseChain = exports.validateChainInfo = exports.validateCustomChainInfo = exports.validateTransactionCall = exports.isTransactionCall = exports.validateTransactionWithSender = exports.isTransactionWithSender = exports.isTransactionLegacyUnsigned = exports.isTransaction2930Unsigned = exports.isTransaction1559Unsigned = exports.isAccessList = exports.isAccessListEntry = exports.isBaseTransaction = void 0; +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const format_transaction_js_1 = require("./utils/format_transaction.js"); +function isBaseTransaction(value) { + if (!(0, web3_validator_1.isNullish)(value.to) && !(0, web3_validator_1.isAddress)(value.to)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.type) && !(0, web3_validator_1.isNullish)(value.type) && value.type.length !== 2) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.nonce)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.gas)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.value)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.input)) + return false; + if (value.chainId && !(0, web3_validator_1.isHexStrict)(value.chainId)) + return false; + return true; +} +exports.isBaseTransaction = isBaseTransaction; +function isAccessListEntry(value) { + if (!(0, web3_validator_1.isNullish)(value.address) && !(0, web3_validator_1.isAddress)(value.address)) + return false; + if (!(0, web3_validator_1.isNullish)(value.storageKeys) && + !value.storageKeys.every(storageKey => (0, web3_validator_1.isHexString32Bytes)(storageKey))) + return false; + return true; +} +exports.isAccessListEntry = isAccessListEntry; +function isAccessList(value) { + if (!Array.isArray(value) || + !value.every(accessListEntry => isAccessListEntry(accessListEntry))) + return false; + return true; +} +exports.isAccessList = isAccessList; +function isTransaction1559Unsigned(value) { + if (!isBaseTransaction(value)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.maxFeePerGas)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.maxPriorityFeePerGas)) + return false; + if (!isAccessList(value.accessList)) + return false; + return true; +} +exports.isTransaction1559Unsigned = isTransaction1559Unsigned; +function isTransaction2930Unsigned(value) { + if (!isBaseTransaction(value)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.gasPrice)) + return false; + if (!isAccessList(value.accessList)) + return false; + return true; +} +exports.isTransaction2930Unsigned = isTransaction2930Unsigned; +function isTransactionLegacyUnsigned(value) { + if (!isBaseTransaction(value)) + return false; + if (!(0, web3_validator_1.isHexStrict)(value.gasPrice)) + return false; + return true; +} +exports.isTransactionLegacyUnsigned = isTransactionLegacyUnsigned; +function isTransactionWithSender(value) { + if (!(0, web3_validator_1.isAddress)(value.from)) + return false; + if (!isBaseTransaction(value)) + return false; + if (!isTransaction1559Unsigned(value) && + !isTransaction2930Unsigned(value) && + !isTransactionLegacyUnsigned(value)) + return false; + return true; +} +exports.isTransactionWithSender = isTransactionWithSender; +function validateTransactionWithSender(value) { + if (!isTransactionWithSender(value)) + throw new web3_errors_1.InvalidTransactionWithSender(value); +} +exports.validateTransactionWithSender = validateTransactionWithSender; +function isTransactionCall(value) { + if (!(0, web3_validator_1.isNullish)(value.from) && !(0, web3_validator_1.isAddress)(value.from)) + return false; + if (!(0, web3_validator_1.isAddress)(value.to)) + return false; + if (!(0, web3_validator_1.isNullish)(value.gas) && !(0, web3_validator_1.isHexStrict)(value.gas)) + return false; + if (!(0, web3_validator_1.isNullish)(value.gasPrice) && !(0, web3_validator_1.isHexStrict)(value.gasPrice)) + return false; + if (!(0, web3_validator_1.isNullish)(value.value) && !(0, web3_validator_1.isHexStrict)(value.value)) + return false; + if (!(0, web3_validator_1.isNullish)(value.data) && !(0, web3_validator_1.isHexStrict)(value.data)) + return false; + if (!(0, web3_validator_1.isNullish)(value.input) && !(0, web3_validator_1.isHexStrict)(value.input)) + return false; + if (!(0, web3_validator_1.isNullish)(value.type)) + return false; + if (isTransaction1559Unsigned(value)) + return false; + if (isTransaction2930Unsigned(value)) + return false; + return true; +} +exports.isTransactionCall = isTransactionCall; +function validateTransactionCall(value) { + if (!isTransactionCall(value)) + throw new web3_errors_1.InvalidTransactionCall(value); +} +exports.validateTransactionCall = validateTransactionCall; +const validateCustomChainInfo = (transaction) => { + if (!(0, web3_validator_1.isNullish)(transaction.common)) { + if ((0, web3_validator_1.isNullish)(transaction.common.customChain)) + throw new web3_errors_1.MissingCustomChainError(); + if ((0, web3_validator_1.isNullish)(transaction.common.customChain.chainId)) + throw new web3_errors_1.MissingCustomChainIdError(); + if (!(0, web3_validator_1.isNullish)(transaction.chainId) && + transaction.chainId !== transaction.common.customChain.chainId) + throw new web3_errors_1.ChainIdMismatchError({ + txChainId: transaction.chainId, + customChainId: transaction.common.customChain.chainId, + }); + } +}; +exports.validateCustomChainInfo = validateCustomChainInfo; +const validateChainInfo = (transaction) => { + if (!(0, web3_validator_1.isNullish)(transaction.common) && + !(0, web3_validator_1.isNullish)(transaction.chain) && + !(0, web3_validator_1.isNullish)(transaction.hardfork)) { + throw new web3_errors_1.CommonOrChainAndHardforkError(); + } + if ((!(0, web3_validator_1.isNullish)(transaction.chain) && (0, web3_validator_1.isNullish)(transaction.hardfork)) || + (!(0, web3_validator_1.isNullish)(transaction.hardfork) && (0, web3_validator_1.isNullish)(transaction.chain))) + throw new web3_errors_1.MissingChainOrHardforkError({ + chain: transaction.chain, + hardfork: transaction.hardfork, + }); +}; +exports.validateChainInfo = validateChainInfo; +const validateBaseChain = (transaction) => { + if (!(0, web3_validator_1.isNullish)(transaction.common)) + if (!(0, web3_validator_1.isNullish)(transaction.common.baseChain)) + if (!(0, web3_validator_1.isNullish)(transaction.chain) && + transaction.chain !== transaction.common.baseChain) { + throw new web3_errors_1.ChainMismatchError({ + txChain: transaction.chain, + baseChain: transaction.common.baseChain, + }); + } +}; +exports.validateBaseChain = validateBaseChain; +const validateHardfork = (transaction) => { + if (!(0, web3_validator_1.isNullish)(transaction.common)) + if (!(0, web3_validator_1.isNullish)(transaction.common.hardfork)) + if (!(0, web3_validator_1.isNullish)(transaction.hardfork) && + transaction.hardfork !== transaction.common.hardfork) { + throw new web3_errors_1.HardforkMismatchError({ + txHardfork: transaction.hardfork, + commonHardfork: transaction.common.hardfork, + }); + } +}; +exports.validateHardfork = validateHardfork; +const validateLegacyGas = (transaction) => { + if ( + // This check is verifying gas and gasPrice aren't less than 0. + (0, web3_validator_1.isNullish)(transaction.gas) || + !(0, web3_validator_1.isUInt)(transaction.gas) || + (0, web3_validator_1.isNullish)(transaction.gasPrice) || + !(0, web3_validator_1.isUInt)(transaction.gasPrice)) + throw new web3_errors_1.InvalidGasOrGasPrice({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + }); + if (!(0, web3_validator_1.isNullish)(transaction.maxFeePerGas) || !(0, web3_validator_1.isNullish)(transaction.maxPriorityFeePerGas)) + throw new web3_errors_1.UnsupportedFeeMarketError({ + maxFeePerGas: transaction.maxFeePerGas, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + }); +}; +exports.validateLegacyGas = validateLegacyGas; +const validateFeeMarketGas = (transaction) => { + // These errors come from 1.x, so they must be checked before + // InvalidMaxPriorityFeePerGasOrMaxFeePerGas to throw the same error + // for the same code executing in 1.x + if (!(0, web3_validator_1.isNullish)(transaction.gasPrice) && transaction.type === '0x2') + throw new web3_errors_1.Eip1559GasPriceError(transaction.gasPrice); + if (transaction.type === '0x0' || transaction.type === '0x1') + throw new web3_errors_1.UnsupportedFeeMarketError({ + maxFeePerGas: transaction.maxFeePerGas, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + }); + if ((0, web3_validator_1.isNullish)(transaction.maxFeePerGas) || + !(0, web3_validator_1.isUInt)(transaction.maxFeePerGas) || + (0, web3_validator_1.isNullish)(transaction.maxPriorityFeePerGas) || + !(0, web3_validator_1.isUInt)(transaction.maxPriorityFeePerGas)) + throw new web3_errors_1.InvalidMaxPriorityFeePerGasOrMaxFeePerGas({ + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); +}; +exports.validateFeeMarketGas = validateFeeMarketGas; +/** + * This method checks if all required gas properties are present for either + * legacy gas (type 0x0 and 0x1) OR fee market transactions (0x2) + */ +const validateGas = (transaction) => { + const gasPresent = !(0, web3_validator_1.isNullish)(transaction.gas) || !(0, web3_validator_1.isNullish)(transaction.gasLimit); + const legacyGasPresent = gasPresent && !(0, web3_validator_1.isNullish)(transaction.gasPrice); + const feeMarketGasPresent = gasPresent && + !(0, web3_validator_1.isNullish)(transaction.maxPriorityFeePerGas) && + !(0, web3_validator_1.isNullish)(transaction.maxFeePerGas); + if (!legacyGasPresent && !feeMarketGasPresent) + throw new web3_errors_1.MissingGasError({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); + if (legacyGasPresent && feeMarketGasPresent) + throw new web3_errors_1.TransactionGasMismatchError({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); + (legacyGasPresent ? exports.validateLegacyGas : exports.validateFeeMarketGas)(transaction); + (!(0, web3_validator_1.isNullish)(transaction.type) && transaction.type > '0x1' + ? exports.validateFeeMarketGas + : exports.validateLegacyGas)(transaction); +}; +exports.validateGas = validateGas; +const validateTransactionForSigning = (transaction, overrideMethod) => { + if (!(0, web3_validator_1.isNullish)(overrideMethod)) { + overrideMethod(transaction); + return; + } + if (typeof transaction !== 'object' || (0, web3_validator_1.isNullish)(transaction)) + throw new web3_errors_1.InvalidTransactionObjectError(transaction); + (0, exports.validateCustomChainInfo)(transaction); + (0, exports.validateChainInfo)(transaction); + (0, exports.validateBaseChain)(transaction); + (0, exports.validateHardfork)(transaction); + const formattedTransaction = (0, format_transaction_js_1.formatTransaction)(transaction, web3_types_1.ETH_DATA_FORMAT); + (0, exports.validateGas)(formattedTransaction); + if ((0, web3_validator_1.isNullish)(formattedTransaction.nonce) || + (0, web3_validator_1.isNullish)(formattedTransaction.chainId) || + formattedTransaction.nonce.startsWith('-') || + formattedTransaction.chainId.startsWith('-')) + throw new web3_errors_1.InvalidNonceOrChainIdError({ + nonce: transaction.nonce, + chainId: transaction.chainId, + }); +}; +exports.validateTransactionForSigning = validateTransactionForSigning; +//# sourceMappingURL=validation.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.js.map new file mode 100644 index 0000000..aa69bf5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/validation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/validation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAWoB;AACpB,mDAA+F;AAC/F,6CAkBqB;AACrB,yEAAkE;AAGlE,SAAgB,iBAAiB,CAAC,KAAyB;IAC1D,IAAI,CAAC,IAAA,0BAAS,EAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC,IAAA,0BAAS,EAAC,KAAK,CAAC,EAAE,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/D,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAA,0BAAS,EAAC,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAChG,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IAC1C,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,KAAK,CAAC,OAAO,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAE/D,OAAO,IAAI,CAAC;AACb,CAAC;AAVD,8CAUC;AAED,S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.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.d.ts new file mode 100644 index 0000000..2988afc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.d.ts @@ -0,0 +1,1597 @@ +import { SupportedProviders, Address, Bytes, Filter, HexString32Bytes, HexString8Bytes, Numbers, BlockNumberOrTag, Transaction, TransactionCall, Web3EthExecutionAPI, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, TransactionForAccessList, DataFormat, DEFAULT_RETURN_FORMAT, Eip712TypedData } from 'web3-types'; +import { Web3Context, Web3ContextInitOptions } from 'web3-core'; +import { SendTransactionOptions } from './types.js'; +import { LogsSubscription, NewPendingTransactionsSubscription, NewHeadsSubscription, SyncingSubscription } from './web3_subscriptions.js'; +export declare type RegisteredSubscription = { + logs: typeof LogsSubscription; + newPendingTransactions: typeof NewPendingTransactionsSubscription; + pendingTransactions: typeof NewPendingTransactionsSubscription; + newHeads: typeof NewHeadsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; + syncing: typeof SyncingSubscription; +}; +export declare const registeredSubscriptions: { + logs: typeof LogsSubscription; + newPendingTransactions: typeof NewPendingTransactionsSubscription; + newHeads: typeof NewHeadsSubscription; + syncing: typeof SyncingSubscription; + pendingTransactions: typeof NewPendingTransactionsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; +}; +export declare class Web3Eth extends Web3Context { + constructor(providerOrContext?: SupportedProviders | Web3ContextInitOptions | string); + /** + * @returns Returns the ethereum protocol version of the node. + * + * ```ts + * web3.eth.getProtocolVersion().then(console.log); + * > "63" + * ``` + */ + getProtocolVersion(): Promise; + /** + * Checks if the node is currently syncing. + * + * @returns Either a {@link SyncingStatusAPI}, or `false`. + * + * ```ts + * web3.eth.isSyncing().then(console.log); + * > { + * startingBlock: 100, + * currentBlock: 312, + * highestBlock: 512, + * knownStates: 234566, + * pulledStates: 123455 + * } + * ``` + */ + isSyncing(): Promise; + /** + * @returns Returns the coinbase address to which mining rewards will go. + * + * ```ts + * web3.eth.getCoinbase().then(console.log); + * > "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" + * ``` + */ + getCoinbase(): Promise; + /** + * Checks whether the node is mining or not. + * + * @returns `true` if the node is mining, otherwise `false`. + * + * ```ts + * web3.eth.isMining().then(console.log); + * > true + * ``` + */ + isMining(): Promise; + /** + * @deprecated Will be removed in the future, please use {@link Web3Eth.getHashRate} method instead. + * + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashrate().then(console.log); + * > 493736n + * + * web3.eth.getHashrate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashrate(returnFormat?: ReturnFormat): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashRate().then(console.log); + * > 493736n + * + * web3.eth.getHashRate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashRate(returnFormat?: ReturnFormat): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The gas price determined by the last few blocks median gas price. + * + * ```ts + * web3.eth.getGasPrice().then(console.log); + * > 20000000000n + * + * web3.eth.getGasPrice({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x4a817c800" + * ``` + */ + getGasPrice(returnFormat?: ReturnFormat): Promise; + /** + * @returns A list of accounts the node controls (addresses are checksummed). + * + * ```ts + * web3.eth.getAccounts().then(console.log); + * > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"] + * ``` + */ + getAccounts(): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current block number. + * + * ```ts + * web3.eth.getBlockNumber().then(console.log); + * > 2744n + * + * web3.eth.getBlockNumber({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0xab8" + * ``` + */ + getBlockNumber(returnFormat?: ReturnFormat): Promise; + /** + * Get the balance of an address at a given block. + * + * @param address The address to get the balance of. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the balance query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current balance for the given address in `wei`. + * + * ```ts + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1000000000000n + * + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > "0xe8d4a51000" + * ``` + */ + getBalance(address: Address, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Get the storage at a specific position of an address. + * + * @param address The address to get the storage from. + * @param storageSlot The index position of the storage. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the storage query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The value in storage at the given position. + * + * ```ts + * web3.eth.getStorageAt("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", 0).then(console.log); + * > "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234" + * + * web3.eth.getStorageAt( + * "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", + * 0, + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(31) [ + * 3, 52, 86, 115, 33, 35, 255, 255, + * 35, 66, 52, 45, 209, 35, 66, 67, + * 67, 36, 35, 66, 52, 253, 35, 79, + * 210, 63, 212, 242, 61, 66, 52 + * ] + * ``` + */ + getStorageAt(address: Address, storageSlot: Numbers, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Get the code at a specific address. + * + * @param address The address to get the code from. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the code query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The [data](https://ethereum.org/en/developers/docs/transactions/#the-data-field) at the provided `address`. + * + * ```ts + * web3.eth.getCode("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234").then(console.log); + * > "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056" + * + * web3.eth.getCode( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(50) [ + * 96, 1, 96, 0, 128, 53, 129, 26, 129, 129, 129, + * 20, 96, 18, 87, 131, 1, 0, 91, 96, 27, 96, + * 1, 53, 96, 37, 86, 91, 128, 96, 0, 82, 96, + * 32, 96, 0, 242, 91, 96, 0, 96, 7, 130, 2, + * 144, 80, 145, 144, 80, 86 + * ] + * ``` + */ + getCode(address: Address, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Retrieves a {@link Block} matching the provided block number, block hash or block tag. + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param hydrated If specified `true`, the returned block will contain all transactions as objects. If `false` it will only contain transaction hashes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted (does not format transaction objects or hashes). + * @returns A {@link Block} object matching the provided block number or block hash. + * + * ```ts + * web3.eth.getBlock(0).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getBlock( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * false, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getBlock(block?: HexString32Bytes | BlockNumberOrTag, hydrated?: boolean, returnFormat?: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }>; + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions in the provided block. + * + * ```ts + * web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockTransactionCount(block?: HexString32Bytes | BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of [uncles](https://ethereum.org/en/glossary/#ommer) in the provided block. + * + * ```ts + * web3.eth.getBlockUncleCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockUncleCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockUncleCount(block?: HexString32Bytes | BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param uncleIndex The index position of the uncle. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A blocks [uncle](https://ethereum.org/en/glossary/#ommer) by a given uncle index position. + * + * ```ts + * web3.eth.getUncle(0, 1).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getUncle( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * 1, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getUncle(block: BlockNumberOrTag | undefined, uncleIndex: Numbers, returnFormat?: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }>; + /** + * @param transactionHash The hash of the desired transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransaction('0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc').then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransaction( + * web3.utils.hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransaction(transactionHash: Bytes, returnFormat?: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + }>; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A list of pending transactions. + * + * ```ts + * web3.eth.getPendingTransactions().then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0n, + * nonce: 1n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2710n, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * + * * web3.eth.getPendingTransactions({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0, + * nonce: 1, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2710, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * ``` + */ + getPendingTransactions(returnFormat?: ReturnFormat): Promise<{ + from?: string | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]>; + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param transactionIndex The index position of the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransactionFromBlock('0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', 0).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransactionFromBlock( + * hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * 0, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransactionFromBlock(block: BlockNumberOrTag | undefined, transactionIndex: Numbers, returnFormat?: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | undefined>; + /** + * @param transactionHash Hash of the transaction to retrieve the receipt for. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired {@link TransactionReceipt} object. + * + * ```ts + * web3.eth.getTransactionReceipt("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f").then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * + * web3.eth.getTransactionReceipt( + * "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0, + * blockNumber: 2, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000, + * gasUsed: 21000, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1, + * effectiveGasPrice: 2000000000, + * type: 0n + * } + * ``` + */ + getTransactionReceipt(transactionHash: Bytes, returnFormat?: ReturnFormat): Promise; + /** + * @param address The address to get the number of transactions for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions sent from the provided address. + * + * ```ts + * web3.eth.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getTransactionCount(address: Address, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * @param transaction The {@link Transaction}, {@link TransactionWithFromLocalWalletIndex}, {@link TransactionWithToLocalWalletIndex} or {@link TransactionWithFromAndToLocalWalletIndex} to send. __Note:__ In the `to` and `from` fields when hex strings are used, it is assumed they are addresses, for any other form (number, string number, etc.) it is assumed they are wallet indexes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @param options A configuration object used to change the behavior of the `sendTransaction` method. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const transaction = { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1' + * } + * + * const transactionHash = await web3.eth.sendTransaction(transaction); + * console.log(transactionHash); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).catch(console.log); + * > + * + * // Example using options.ignoreGasPricing = true + * web3.eth.sendTransaction(transaction, undefined, { ignoreGasPricing: true }).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendTransaction(transaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `sent` + * ```ts + * web3.eth.sendTransaction(transaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendTransaction(transaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * - `receipt` + * ```ts + * web3.eth.sendTransaction(transaction).on('receipt', receipt => console.log(receipt)); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendTransaction(transaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * transactionHash: '0xb4a3a35ae0f3e77ef0ff7be42010d948d011b21a4e341072ee18717b67e99ab8', + * transactionIndex: 0n, + * blockNumber: 5n, + * blockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * }, + * latestBlockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendTransaction(transaction).on('error', error => console.log); + * > + * ``` + */ + sendTransaction(transaction: Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex, returnFormat?: ReturnFormat, options?: SendTransactionOptions): import("web3-core").Web3PromiEvent>; + /** + * @param transaction Signed transaction in one of the valid {@link Bytes} format. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const signedTransaction = "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * + * const transactionHash = await web3.eth.sendSignedTransaction(signedTransaction); + * console.log(transactionHash); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).then(console.log); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).catch(console.log); + * > + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `sent` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * ``` + * - `receipt` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('receipt', receipt => console.log(receipt)); + * > { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * }, + * latestBlockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('error', error => console.log(error)); + * > + * ``` + */ + sendSignedTransaction(transaction: Bytes, returnFormat?: ReturnFormat, options?: SendTransactionOptions): import("web3-core").Web3PromiEvent>; + /** + * @param message Data to sign in one of the valid {@link Bytes} format. + * @param address Address to sign data with, can be an address or the index of a local wallet. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The signed `message`. + * + * ```ts + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + * + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.UINT8ARRAY }).then(console.log); + * > Uint8Array(65) [ + * 48, 117, 94, 214, 83, 150, 250, 207, 134, 197, 62, + * 98, 23, 197, 43, 77, 174, 190, 114, 170, 73, 65, + * 216, 150, 53, 64, 157, 228, 201, 199, 249, 70, 109, + * 78, 154, 174, 199, 151, 127, 5, 233, 35, 136, 155, + * 51, 192, 208, 221, 39, 215, 34, 107, 110, 111, 86, + * 206, 115, 116, 101, 197, 207, 208, 75, 228, 0 + * ] + * ``` + * + * // Using an indexed account managed by local Web3 wallet + * web3.eth.sign("0x48656c6c6f20776f726c64", 0).then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + */ + sign(message: Bytes, address: Address, returnFormat?: ReturnFormat): Promise<{ + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + } | import("web3-types").ByteTypes[ReturnFormat["bytes"]]>; + /** + * @param transaction The transaction object to sign. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * gas: '21000', + * gasPrice: await web3Eth.getGasPrice(), + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.signTransaction(transaction).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0n, + * nonce: 1n, + * gasPrice: 1000000001n, + * gas: 21000n, + * value: 1n, + * v: 2710n, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * + * web3.eth.signTransaction(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0, + * nonce: 1, + * gasPrice: 1000000001, + * gas: 21000, + * value: 1, + * v: 2710, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * ``` + */ + signTransaction(transaction: Transaction, returnFormat?: ReturnFormat): Promise; + /** + * Executes a message call within the EVM without creating a transaction. + * It does not publish anything to the blockchain and does not consume any gas. + * + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The returned data of the call, e.g. a smart contract function's return value. + */ + call(transaction: TransactionCall, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Simulates the transaction within the EVM to estimate the amount of gas to be used by the transaction. + * The transaction will not be added to the blockchain, and actual gas usage can vary when interacting + * with a contract as a result of updating the contract's state. + * + * @param transaction The {@link Transaction} object to estimate the gas for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The used gas for the simulated transaction execution. + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.estimateGas(transaction).then(console.log); + * > 21000n + * + * web3.eth.estimateGas(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 21000 + * ``` + */ + estimateGas(transaction: Transaction, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Gets past logs, matching the provided `filter`. + * + * @param filter A {@link Filter} object containing the properties for the desired logs. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns {@link FilterResultsAPI}, an array of {@link Log} objects. + * + * ```ts + * web3.eth.getPastLogs({ + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0n, + * transactionIndex: 0n, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234n, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * + * web3.eth.getPastLogs( + * { + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * ``` + */ + getPastLogs(filter: Filter, returnFormat?: ReturnFormat): Promise<(string | { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; + })[]>; + /** + * Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ('target'). + * + * @returns The mining work as an array of strings with the following structure: + * + * String 32 Bytes - at index 0: current block header pow-hash + * String 32 Bytes - at index 1: the seed hash used for the DAG. + * String 32 Bytes - at index 2: the boundary condition ('target'), 2^256 / difficulty. + * + * ```ts + * web3.eth.getWork().then(console.log); + * > [ + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0x5EED00000000000000000000000000005EED0000000000000000000000000000", + * "0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000" + * ] + * ``` + */ + getWork(): Promise<[string, string, string]>; + /** + * Used for submitting a proof-of-work solution. + * + * @param nonce The nonce found (8 bytes). + * @param hash The header’s pow-hash (32 bytes). + * @param digest The mix digest (32 bytes). + * @returns Returns `true` if the provided solution is valid, otherwise `false`. + * + * ```ts + * web3.eth.submitWork([ + * "0x0000000000000001", + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000" + * ]).then(console.log); + * > true + * ``` + */ + submitWork(nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes): Promise; + /** + * This method will request/enable the accounts from the current environment and for supporting [EIP 1102](https://eips.ethereum.org/EIPS/eip-1102) + * This method will only work if you’re using the injected provider from a application like Metamask, Status or TrustWallet. + * It doesn’t work if you’re connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvider and IpcProvider). + * For more information about the behavior of this method please read [EIP-1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md): Opt-in account exposure. + * + * @returns An array of enabled accounts. + * + * ```ts + * web3.eth.requestAccounts().then(console.log); + * > ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'] + * ``` + */ + requestAccounts(): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The chain ID of the current connected node as described in the [EIP-695](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md). + * + * ```ts + * web3.eth.getChainId().then(console.log); + * > 61n + * + * web3.eth.getChainId({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 61 + * ``` + */ + getChainId(returnFormat?: ReturnFormat): Promise; + /** + * @returns The current client version. + * + * ```ts + * web3.eth.getNodeInfo().then(console.log); + * > "Mist/v0.9.3/darwin/go1.4.1" + * ``` + */ + getNodeInfo(): Promise; + /** + * @param address The Address of the account or contract. + * @param storageKeys Array of storage-keys which should be proofed and included. See {@link web3.getStorageAt}. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The account and storage-values of the specified account including the Merkle-proof as described in [EIP-1186](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md). + * + * ```ts + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * "latest" + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0n, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0n, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0n, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0n, + * "proof": [] + * } + * ] + * } + * + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0, + * "proof": [] + * } + * ] + * } + * ``` + */ + getProof(address: Address, storageKeys: Bytes[], blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise<{ + readonly balance: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly codeHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly storageHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly accountProof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + readonly storageProof: { + readonly key: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly value: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly proof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + }[]; + }>; + /** + * @param blockCount Number of blocks in the requested range. Between `1` and `1024` blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. + * @param newestBlock Highest number block of the requested range. + * @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `['0', '25', '50', '75', '100']` or `['0', '0.5', '1', '1.5', '3', '80']` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available. + * The range between `headBlock - 4` and `headBlock` is guaranteed to be available while retrieving data from the `pending` block and older history are optional to support. + * For pre-EIP-1559 blocks the `gasPrice`s are returned as `rewards` and zeroes are returned for the `baseFeePerGas`. + * + * ```ts + * web3.eth.getFeeHistory(4, 'pending', [0, 25, 75, 100]).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621n, + * 21417903463n, + * 19989260230n, + * 17770954829n, + * 18850641304n + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343n, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * + * web3.eth.getFeeHistory(4, BlockTags.LATEST, [0, 25, 75, 100], { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621, + * 21417903463, + * 19989260230, + * 17770954829, + * 18850641304 + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * ``` + */ + getFeeHistory(blockCount: Numbers, newestBlock: BlockNumberOrTag | undefined, rewardPercentiles: Numbers[], returnFormat?: ReturnFormat): Promise<{ + readonly oldestBlock: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly reward: import("web3-types").NumberTypes[ReturnFormat["number"]][][]; + readonly gasUsedRatio: import("web3-types").NumberTypes[ReturnFormat["number"]][]; + }>; + /** + * This method generates an access list for a transaction. + * + * @param transaction - A transaction object where all properties are optional except `from`, however it's recommended to include the `to` property. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the createAccessList should be formatted. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * @example + * ```ts + * web3.eth.createAccessList({ + * from: '0xDe95305a63302C3aa4d3A9B42654659AeA72b694', + * data: '0x9a67c8b100000000000000000000000000000000000000000000000000000000000004d0', + * gasPrice: '0x3b9aca00', + * gas: '0x3d0900', + * to: '0x940b25304947ae863568B3804434EC77E2160b87' + * }) + * .then(console.log); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList(transaction: TransactionForAccessList, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise<{ + readonly accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + readonly gasUsed?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + }>; + /** + * This method sends EIP-712 typed data to the RPC provider to be signed. + * + * @param address The address that corresponds with the private key used to sign the typed data. + * @param typedData The EIP-712 typed data object. + * @param useLegacy A boolean flag determining whether the RPC call uses the legacy method `eth_signTypedData` or the newer method `eth_signTypedData_v4` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the signed typed data should be formatted. + * @returns The signed typed data. + */ + signTypedData(address: Address, typedData: Eip712TypedData, useLegacy?: boolean, returnFormat?: ReturnFormat): Promise; + /** + * Lets you subscribe to specific events in the blockchain. + * + * @param name - The subscription you want to subscribe to. + * @param args - Optional additional parameters, depending on the subscription type. + * @returns A subscription object of type {@link RegisteredSubscription}. The object contains: + * - subscription.id: The subscription id, used to identify and unsubscribing the subscription. + * - subscription.subscribe(): Can be used to re-subscribe with the same parameters. + * - subscription.unsubscribe(): Unsubscribes the subscription and returns TRUE in the callback if successful. + * - subscription.args: The subscription arguments, used when re-subscribing. + * + * + * You can use the subscription object to listen on: + * + * - on("data") - Fires on each incoming log with the log object as argument. + * - on("changed") - Fires on each log which was removed from the blockchain. The log will have the additional property "removed: true". + * - on("error") - Fires when an error in the subscription occurs. + * - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id. + * + * @example **Subscribe to Smart Contract events** + * ```ts + * // Subscribe to `logs` + * const logSubscription = web3.eth.subscribe('logs', { + * address: '0x1234567890123456789012345678901234567890', + * topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234'] + * }); + * logSubscription.on('data', (data: any) => console.log(data)); + * logSubscription.on('error', (error: any) => console.log(error)); + * + * ``` + * + * @example **Subscribe to new block headers** + * ```ts + * // Subscribe to `newBlockHeaders` + * const newBlocksSubscription = await web3.eth.subscribe('newBlockHeaders'); + * + * newBlocksSubscription.on('data', async blockhead => { + * console.log('New block header: ', blockhead); + * + * // You do not need the next line, if you like to keep notified for every new block + * await newBlocksSubscription.unsubscribe(); + * console.log('Unsubscribed from new block headers.'); + * }); + * newBlocksSubscription.on('error', error => + * console.log('Error when subscribing to New block header: ', error), + * ); + * ``` + */ + subscribe(name: T, args?: ConstructorParameters[0], returnFormat?: ReturnType): Promise>; + private static shouldClearSubscription; + /** + * Resets subscriptions. + * + * @param notClearSyncing If `true` it keeps the `syncing` subscription. + * @returns A promise to an array of subscription ids that were cleared. + * + * ```ts + * web3.eth.clearSubscriptions().then(console.log); + * > [...] An array of subscription ids that were cleared + * ``` + */ + clearSubscriptions(notClearSyncing?: boolean): Promise | undefined; +} diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.js new file mode 100644 index 0000000..17208ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.js @@ -0,0 +1,1530 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3Eth = exports.registeredSubscriptions = void 0; +// Disabling because returnTypes must be last param to match 1.x params +/* eslint-disable default-param-last */ +const web3_types_1 = require("web3-types"); +const web3_core_1 = require("web3-core"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const web3_rpc_methods_1 = require("web3-rpc-methods"); +const rpcMethodsWrappers = __importStar(require("./rpc_method_wrappers.js")); +const web3_subscriptions_js_1 = require("./web3_subscriptions.js"); +exports.registeredSubscriptions = { + logs: web3_subscriptions_js_1.LogsSubscription, + newPendingTransactions: web3_subscriptions_js_1.NewPendingTransactionsSubscription, + newHeads: web3_subscriptions_js_1.NewHeadsSubscription, + syncing: web3_subscriptions_js_1.SyncingSubscription, + pendingTransactions: web3_subscriptions_js_1.NewPendingTransactionsSubscription, + newBlockHeaders: web3_subscriptions_js_1.NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x +}; +class Web3Eth extends web3_core_1.Web3Context { + constructor(providerOrContext) { + if (typeof providerOrContext === 'string' || + (0, web3_core_1.isSupportedProvider)(providerOrContext)) { + super({ + provider: providerOrContext, + registeredSubscriptions: exports.registeredSubscriptions, + }); + return; + } + if (providerOrContext.registeredSubscriptions) { + super(providerOrContext); + return; + } + super(Object.assign(Object.assign({}, providerOrContext), { registeredSubscriptions: exports.registeredSubscriptions })); + } + /** + * @returns Returns the ethereum protocol version of the node. + * + * ```ts + * web3.eth.getProtocolVersion().then(console.log); + * > "63" + * ``` + */ + getProtocolVersion() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.getProtocolVersion(this.requestManager); + }); + } + // TODO Add returnFormat parameter + /** + * Checks if the node is currently syncing. + * + * @returns Either a {@link SyncingStatusAPI}, or `false`. + * + * ```ts + * web3.eth.isSyncing().then(console.log); + * > { + * startingBlock: 100, + * currentBlock: 312, + * highestBlock: 512, + * knownStates: 234566, + * pulledStates: 123455 + * } + * ``` + */ + isSyncing() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.getSyncing(this.requestManager); + }); + } + // TODO consider adding returnFormat parameter (to format address as bytes) + /** + * @returns Returns the coinbase address to which mining rewards will go. + * + * ```ts + * web3.eth.getCoinbase().then(console.log); + * > "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" + * ``` + */ + getCoinbase() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.getCoinbase(this.requestManager); + }); + } + /** + * Checks whether the node is mining or not. + * + * @returns `true` if the node is mining, otherwise `false`. + * + * ```ts + * web3.eth.isMining().then(console.log); + * > true + * ``` + */ + isMining() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.getMining(this.requestManager); + }); + } + /** + * @deprecated Will be removed in the future, please use {@link Web3Eth.getHashRate} method instead. + * + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashrate().then(console.log); + * > 493736n + * + * web3.eth.getHashrate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashrate(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return this.getHashRate(returnFormat); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashRate().then(console.log); + * > 493736n + * + * web3.eth.getHashRate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashRate(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getHashRate(this, returnFormat); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The gas price determined by the last few blocks median gas price. + * + * ```ts + * web3.eth.getGasPrice().then(console.log); + * > 20000000000n + * + * web3.eth.getGasPrice({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x4a817c800" + * ``` + */ + getGasPrice(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getGasPrice(this, returnFormat); + }); + } + /** + * @returns A list of accounts the node controls (addresses are checksummed). + * + * ```ts + * web3.eth.getAccounts().then(console.log); + * > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"] + * ``` + */ + getAccounts() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const hexAddresses = (_a = (yield web3_rpc_methods_1.ethRpcMethods.getAccounts(this.requestManager))) !== null && _a !== void 0 ? _a : []; + return hexAddresses.map(address => (0, web3_utils_1.toChecksumAddress)(address)); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current block number. + * + * ```ts + * web3.eth.getBlockNumber().then(console.log); + * > 2744n + * + * web3.eth.getBlockNumber({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0xab8" + * ``` + */ + getBlockNumber(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlockNumber(this, returnFormat); + }); + } + /** + * Get the balance of an address at a given block. + * + * @param address The address to get the balance of. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the balance query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current balance for the given address in `wei`. + * + * ```ts + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1000000000000n + * + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > "0xe8d4a51000" + * ``` + */ + getBalance(address, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBalance(this, address, blockNumber, returnFormat); + }); + } + /** + * Get the storage at a specific position of an address. + * + * @param address The address to get the storage from. + * @param storageSlot The index position of the storage. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the storage query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The value in storage at the given position. + * + * ```ts + * web3.eth.getStorageAt("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", 0).then(console.log); + * > "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234" + * + * web3.eth.getStorageAt( + * "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", + * 0, + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(31) [ + * 3, 52, 86, 115, 33, 35, 255, 255, + * 35, 66, 52, 45, 209, 35, 66, 67, + * 67, 36, 35, 66, 52, 253, 35, 79, + * 210, 63, 212, 242, 61, 66, 52 + * ] + * ``` + */ + getStorageAt(address, storageSlot, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getStorageAt(this, address, storageSlot, blockNumber, returnFormat); + }); + } + /** + * Get the code at a specific address. + * + * @param address The address to get the code from. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the code query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The [data](https://ethereum.org/en/developers/docs/transactions/#the-data-field) at the provided `address`. + * + * ```ts + * web3.eth.getCode("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234").then(console.log); + * > "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056" + * + * web3.eth.getCode( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(50) [ + * 96, 1, 96, 0, 128, 53, 129, 26, 129, 129, 129, + * 20, 96, 18, 87, 131, 1, 0, 91, 96, 27, 96, + * 1, 53, 96, 37, 86, 91, 128, 96, 0, 82, 96, + * 32, 96, 0, 242, 91, 96, 0, 96, 7, 130, 2, + * 144, 80, 145, 144, 80, 86 + * ] + * ``` + */ + getCode(address, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getCode(this, address, blockNumber, returnFormat); + }); + } + /** + * Retrieves a {@link Block} matching the provided block number, block hash or block tag. + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param hydrated If specified `true`, the returned block will contain all transactions as objects. If `false` it will only contain transaction hashes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted (does not format transaction objects or hashes). + * @returns A {@link Block} object matching the provided block number or block hash. + * + * ```ts + * web3.eth.getBlock(0).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getBlock( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * false, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getBlock(block = this.defaultBlock, hydrated = false, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlock(this, block, hydrated, returnFormat); + }); + } + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions in the provided block. + * + * ```ts + * web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockTransactionCount(block = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlockTransactionCount(this, block, returnFormat); + }); + } + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of [uncles](https://ethereum.org/en/glossary/#ommer) in the provided block. + * + * ```ts + * web3.eth.getBlockUncleCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockUncleCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockUncleCount(block = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlockUncleCount(this, block, returnFormat); + }); + } + /** + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param uncleIndex The index position of the uncle. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A blocks [uncle](https://ethereum.org/en/glossary/#ommer) by a given uncle index position. + * + * ```ts + * web3.eth.getUncle(0, 1).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getUncle( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * 1, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getUncle(block = this.defaultBlock, uncleIndex, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getUncle(this, block, uncleIndex, returnFormat); + }); + } + /** + * @param transactionHash The hash of the desired transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransaction('0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc').then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransaction( + * web3.utils.hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransaction(transactionHash, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield rpcMethodsWrappers.getTransaction(this, transactionHash, returnFormat); + if (!response) + throw new web3_errors_1.TransactionNotFound(); + return response; + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A list of pending transactions. + * + * ```ts + * web3.eth.getPendingTransactions().then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0n, + * nonce: 1n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2710n, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * + * * web3.eth.getPendingTransactions({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0, + * nonce: 1, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2710, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * ``` + */ + getPendingTransactions(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getPendingTransactions(this, returnFormat); + }); + } + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param transactionIndex The index position of the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransactionFromBlock('0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', 0).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransactionFromBlock( + * hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * 0, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransactionFromBlock(block = this.defaultBlock, transactionIndex, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getTransactionFromBlock(this, block, transactionIndex, returnFormat); + }); + } + /** + * @param transactionHash Hash of the transaction to retrieve the receipt for. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired {@link TransactionReceipt} object. + * + * ```ts + * web3.eth.getTransactionReceipt("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f").then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * + * web3.eth.getTransactionReceipt( + * "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0, + * blockNumber: 2, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000, + * gasUsed: 21000, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1, + * effectiveGasPrice: 2000000000, + * type: 0n + * } + * ``` + */ + getTransactionReceipt(transactionHash, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield rpcMethodsWrappers.getTransactionReceipt(this, transactionHash, returnFormat); + if (!response) + throw new web3_errors_1.TransactionNotFound(); + return response; + }); + } + /** + * @param address The address to get the number of transactions for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions sent from the provided address. + * + * ```ts + * web3.eth.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getTransactionCount(address, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getTransactionCount(this, address, blockNumber, returnFormat); + }); + } + /** + * @param transaction The {@link Transaction}, {@link TransactionWithFromLocalWalletIndex}, {@link TransactionWithToLocalWalletIndex} or {@link TransactionWithFromAndToLocalWalletIndex} to send. __Note:__ In the `to` and `from` fields when hex strings are used, it is assumed they are addresses, for any other form (number, string number, etc.) it is assumed they are wallet indexes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @param options A configuration object used to change the behavior of the `sendTransaction` method. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const transaction = { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1' + * } + * + * const transactionHash = await web3.eth.sendTransaction(transaction); + * console.log(transactionHash); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).catch(console.log); + * > + * + * // Example using options.ignoreGasPricing = true + * web3.eth.sendTransaction(transaction, undefined, { ignoreGasPricing: true }).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendTransaction(transaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `sent` + * ```ts + * web3.eth.sendTransaction(transaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendTransaction(transaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * - `receipt` + * ```ts + * web3.eth.sendTransaction(transaction).on('receipt', receipt => console.log(receipt)); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendTransaction(transaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * transactionHash: '0xb4a3a35ae0f3e77ef0ff7be42010d948d011b21a4e341072ee18717b67e99ab8', + * transactionIndex: 0n, + * blockNumber: 5n, + * blockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * }, + * latestBlockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendTransaction(transaction).on('error', error => console.log); + * > + * ``` + */ + sendTransaction(transaction, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT, options) { + return rpcMethodsWrappers.sendTransaction(this, transaction, returnFormat, options); + } + /** + * @param transaction Signed transaction in one of the valid {@link Bytes} format. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const signedTransaction = "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * + * const transactionHash = await web3.eth.sendSignedTransaction(signedTransaction); + * console.log(transactionHash); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).then(console.log); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).catch(console.log); + * > + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `sent` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * ``` + * - `receipt` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('receipt', receipt => console.log(receipt)); + * > { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * }, + * latestBlockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('error', error => console.log(error)); + * > + * ``` + */ + sendSignedTransaction(transaction, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT, options) { + return rpcMethodsWrappers.sendSignedTransaction(this, transaction, returnFormat, options); + } + /** + * @param message Data to sign in one of the valid {@link Bytes} format. + * @param address Address to sign data with, can be an address or the index of a local wallet. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The signed `message`. + * + * ```ts + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + * + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.UINT8ARRAY }).then(console.log); + * > Uint8Array(65) [ + * 48, 117, 94, 214, 83, 150, 250, 207, 134, 197, 62, + * 98, 23, 197, 43, 77, 174, 190, 114, 170, 73, 65, + * 216, 150, 53, 64, 157, 228, 201, 199, 249, 70, 109, + * 78, 154, 174, 199, 151, 127, 5, 233, 35, 136, 155, + * 51, 192, 208, 221, 39, 215, 34, 107, 110, 111, 86, + * 206, 115, 116, 101, 197, 207, 208, 75, 228, 0 + * ] + * ``` + * + * // Using an indexed account managed by local Web3 wallet + * web3.eth.sign("0x48656c6c6f20776f726c64", 0).then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + */ + sign(message, address, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.sign(this, message, address, returnFormat); + }); + } + /** + * @param transaction The transaction object to sign. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * gas: '21000', + * gasPrice: await web3Eth.getGasPrice(), + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.signTransaction(transaction).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0n, + * nonce: 1n, + * gasPrice: 1000000001n, + * gas: 21000n, + * value: 1n, + * v: 2710n, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * + * web3.eth.signTransaction(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0, + * nonce: 1, + * gasPrice: 1000000001, + * gas: 21000, + * value: 1, + * v: 2710, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * ``` + */ + signTransaction(transaction, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.signTransaction(this, transaction, returnFormat); + }); + } + // TODO Decide what to do with transaction.to + // https://github.com/ChainSafe/web3.js/pull/4525#issuecomment-982330076 + /** + * Executes a message call within the EVM without creating a transaction. + * It does not publish anything to the blockchain and does not consume any gas. + * + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The returned data of the call, e.g. a smart contract function's return value. + */ + call(transaction, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.call(this, transaction, blockNumber, returnFormat); + }); + } + /** + * Simulates the transaction within the EVM to estimate the amount of gas to be used by the transaction. + * The transaction will not be added to the blockchain, and actual gas usage can vary when interacting + * with a contract as a result of updating the contract's state. + * + * @param transaction The {@link Transaction} object to estimate the gas for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The used gas for the simulated transaction execution. + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.estimateGas(transaction).then(console.log); + * > 21000n + * + * web3.eth.estimateGas(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 21000 + * ``` + */ + estimateGas(transaction, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.estimateGas(this, transaction, blockNumber, returnFormat); + }); + } + /** + * Gets past logs, matching the provided `filter`. + * + * @param filter A {@link Filter} object containing the properties for the desired logs. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns {@link FilterResultsAPI}, an array of {@link Log} objects. + * + * ```ts + * web3.eth.getPastLogs({ + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0n, + * transactionIndex: 0n, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234n, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * + * web3.eth.getPastLogs( + * { + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * ``` + */ + getPastLogs(filter, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getLogs(this, filter, returnFormat); + }); + } + /** + * Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ('target'). + * + * @returns The mining work as an array of strings with the following structure: + * + * String 32 Bytes - at index 0: current block header pow-hash + * String 32 Bytes - at index 1: the seed hash used for the DAG. + * String 32 Bytes - at index 2: the boundary condition ('target'), 2^256 / difficulty. + * + * ```ts + * web3.eth.getWork().then(console.log); + * > [ + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0x5EED00000000000000000000000000005EED0000000000000000000000000000", + * "0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000" + * ] + * ``` + */ + getWork() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.getWork(this.requestManager); + }); + } + /** + * Used for submitting a proof-of-work solution. + * + * @param nonce The nonce found (8 bytes). + * @param hash The header’s pow-hash (32 bytes). + * @param digest The mix digest (32 bytes). + * @returns Returns `true` if the provided solution is valid, otherwise `false`. + * + * ```ts + * web3.eth.submitWork([ + * "0x0000000000000001", + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000" + * ]).then(console.log); + * > true + * ``` + */ + submitWork(nonce, hash, digest) { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.submitWork(this.requestManager, nonce, hash, digest); + }); + } + // TODO - Format addresses + /** + * This method will request/enable the accounts from the current environment and for supporting [EIP 1102](https://eips.ethereum.org/EIPS/eip-1102) + * This method will only work if you’re using the injected provider from a application like Metamask, Status or TrustWallet. + * It doesn’t work if you’re connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvider and IpcProvider). + * For more information about the behavior of this method please read [EIP-1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md): Opt-in account exposure. + * + * @returns An array of enabled accounts. + * + * ```ts + * web3.eth.requestAccounts().then(console.log); + * > ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'] + * ``` + */ + requestAccounts() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.requestAccounts(this.requestManager); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The chain ID of the current connected node as described in the [EIP-695](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md). + * + * ```ts + * web3.eth.getChainId().then(console.log); + * > 61n + * + * web3.eth.getChainId({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 61 + * ``` + */ + getChainId(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getChainId(this, returnFormat); + }); + } + /** + * @returns The current client version. + * + * ```ts + * web3.eth.getNodeInfo().then(console.log); + * > "Mist/v0.9.3/darwin/go1.4.1" + * ``` + */ + getNodeInfo() { + return __awaiter(this, void 0, void 0, function* () { + return web3_rpc_methods_1.ethRpcMethods.getNodeInfo(this.requestManager); + }); + } + /** + * @param address The Address of the account or contract. + * @param storageKeys Array of storage-keys which should be proofed and included. See {@link web3.getStorageAt}. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The account and storage-values of the specified account including the Merkle-proof as described in [EIP-1186](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md). + * + * ```ts + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * "latest" + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0n, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0n, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0n, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0n, + * "proof": [] + * } + * ] + * } + * + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0, + * "proof": [] + * } + * ] + * } + * ``` + */ + getProof(address, storageKeys, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getProof(this, address, storageKeys, blockNumber, returnFormat); + }); + } + // TODO Throwing an error with Geth, but not Infura + // TODO gasUsedRatio and reward not formatting + /** + * @param blockCount Number of blocks in the requested range. Between `1` and `1024` blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. + * @param newestBlock Highest number block of the requested range. + * @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `['0', '25', '50', '75', '100']` or `['0', '0.5', '1', '1.5', '3', '80']` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available. + * The range between `headBlock - 4` and `headBlock` is guaranteed to be available while retrieving data from the `pending` block and older history are optional to support. + * For pre-EIP-1559 blocks the `gasPrice`s are returned as `rewards` and zeroes are returned for the `baseFeePerGas`. + * + * ```ts + * web3.eth.getFeeHistory(4, 'pending', [0, 25, 75, 100]).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621n, + * 21417903463n, + * 19989260230n, + * 17770954829n, + * 18850641304n + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343n, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * + * web3.eth.getFeeHistory(4, BlockTags.LATEST, [0, 25, 75, 100], { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621, + * 21417903463, + * 19989260230, + * 17770954829, + * 18850641304 + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * ``` + */ + getFeeHistory(blockCount, newestBlock = this.defaultBlock, rewardPercentiles, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getFeeHistory(this, blockCount, newestBlock, rewardPercentiles, returnFormat); + }); + } + /** + * This method generates an access list for a transaction. + * + * @param transaction - A transaction object where all properties are optional except `from`, however it's recommended to include the `to` property. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the createAccessList should be formatted. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * @example + * ```ts + * web3.eth.createAccessList({ + * from: '0xDe95305a63302C3aa4d3A9B42654659AeA72b694', + * data: '0x9a67c8b100000000000000000000000000000000000000000000000000000000000004d0', + * gasPrice: '0x3b9aca00', + * gas: '0x3d0900', + * to: '0x940b25304947ae863568B3804434EC77E2160b87' + * }) + * .then(console.log); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList(transaction, blockNumber = this.defaultBlock, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.createAccessList(this, transaction, blockNumber, returnFormat); + }); + } + /** + * This method sends EIP-712 typed data to the RPC provider to be signed. + * + * @param address The address that corresponds with the private key used to sign the typed data. + * @param typedData The EIP-712 typed data object. + * @param useLegacy A boolean flag determining whether the RPC call uses the legacy method `eth_signTypedData` or the newer method `eth_signTypedData_v4` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the signed typed data should be formatted. + * @returns The signed typed data. + */ + signTypedData(address, typedData, useLegacy = false, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.signTypedData(this, address, typedData, useLegacy, returnFormat); + }); + } + /** + * Lets you subscribe to specific events in the blockchain. + * + * @param name - The subscription you want to subscribe to. + * @param args - Optional additional parameters, depending on the subscription type. + * @returns A subscription object of type {@link RegisteredSubscription}. The object contains: + * - subscription.id: The subscription id, used to identify and unsubscribing the subscription. + * - subscription.subscribe(): Can be used to re-subscribe with the same parameters. + * - subscription.unsubscribe(): Unsubscribes the subscription and returns TRUE in the callback if successful. + * - subscription.args: The subscription arguments, used when re-subscribing. + * + * + * You can use the subscription object to listen on: + * + * - on("data") - Fires on each incoming log with the log object as argument. + * - on("changed") - Fires on each log which was removed from the blockchain. The log will have the additional property "removed: true". + * - on("error") - Fires when an error in the subscription occurs. + * - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id. + * + * @example **Subscribe to Smart Contract events** + * ```ts + * // Subscribe to `logs` + * const logSubscription = web3.eth.subscribe('logs', { + * address: '0x1234567890123456789012345678901234567890', + * topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234'] + * }); + * logSubscription.on('data', (data: any) => console.log(data)); + * logSubscription.on('error', (error: any) => console.log(error)); + * + * ``` + * + * @example **Subscribe to new block headers** + * ```ts + * // Subscribe to `newBlockHeaders` + * const newBlocksSubscription = await web3.eth.subscribe('newBlockHeaders'); + * + * newBlocksSubscription.on('data', async blockhead => { + * console.log('New block header: ', blockhead); + * + * // You do not need the next line, if you like to keep notified for every new block + * await newBlocksSubscription.unsubscribe(); + * console.log('Unsubscribed from new block headers.'); + * }); + * newBlocksSubscription.on('error', error => + * console.log('Error when subscribing to New block header: ', error), + * ); + * ``` + */ + subscribe(name, args, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const subscription = yield ((_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.subscribe(name, args, returnFormat)); + if (subscription instanceof web3_subscriptions_js_1.LogsSubscription && + name === 'logs' && + typeof args === 'object' && + !(0, web3_utils_1.isNullish)(args.fromBlock) && + Number.isFinite(Number(args.fromBlock))) { + setImmediate(() => { + this.getPastLogs(args) + .then(logs => { + for (const log of logs) { + subscription._processSubscriptionResult(log); + } + }) + .catch(e => { + subscription._processSubscriptionError(e); + }); + }); + } + return subscription; + }); + } + static shouldClearSubscription({ sub }) { + return !(sub instanceof web3_subscriptions_js_1.SyncingSubscription); + } + /** + * Resets subscriptions. + * + * @param notClearSyncing If `true` it keeps the `syncing` subscription. + * @returns A promise to an array of subscription ids that were cleared. + * + * ```ts + * web3.eth.clearSubscriptions().then(console.log); + * > [...] An array of subscription ids that were cleared + * ``` + */ + clearSubscriptions(notClearSyncing = false) { + var _a; + return (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.unsubscribe( + // eslint-disable-next-line + notClearSyncing ? Web3Eth.shouldClearSubscription : undefined); + } +} +exports.Web3Eth = Web3Eth; +//# sourceMappingURL=web3_eth.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.js.map new file mode 100644 index 0000000..75f485b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_eth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eth.js","sourceRoot":"","sources":["../../src/web3_eth.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,uEAAuE;AACvE,uCAAuC;AAEvC,2CAoBoB;AACpB,yCAAqF;AACrF,6CAAkD;AAClD,2CAA0D;AAC1D,uDAAiD;AAEjD,6EAA+D;AAE/D,mEAKiC;AAWpB,QAAA,uBAAuB,GAAG;IACt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3_subscriptions.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.d.ts new file mode 100644 index 0000000..860889e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.d.ts @@ -0,0 +1,117 @@ +import { SyncOutput, Address, BlockNumberOrTag, HexString, Topic, BlockHeaderOutput, LogsOutput } from 'web3-types'; +import { Web3Subscription } from 'web3-core'; +/** + * ## subscribe('logs') + * Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, web3.js will retrieve logs beginning from this point, backfilling the response as necessary. + * + * You can subscribe to logs matching a given filter object, which can take the following parameters: + * - `fromBlock`: (optional, default: 'latest') Integer block number, or `'latest'` for the last mined block or `'pending'`, `'earliest'` for not yet mined transactions. + * - `address`: (optional) Contract address or a list of addresses from which logs should originate. + * - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with `or` options. + * + */ +export declare class LogsSubscription extends Web3Subscription<{ + data: LogsOutput; +}, { + readonly fromBlock?: BlockNumberOrTag; + readonly address?: Address | Address[]; + readonly topics?: Topic[]; +}> { + protected _buildSubscriptionParams(): (string | { + readonly fromBlock?: BlockNumberOrTag | undefined; + readonly address?: string | string[] | undefined; + readonly topics?: string[] | undefined; + })[]; + protected formatSubscriptionResult(data: LogsOutput): { + readonly id?: string | undefined; + readonly removed: boolean; + readonly logIndex?: string | number | bigint | undefined; + readonly transactionIndex?: string | number | bigint | undefined; + readonly transactionHash?: string | undefined; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | number | bigint | undefined; + readonly address: string; + readonly topics: string[]; + readonly data: string; + }; +} +/** + * ## subscribe('pendingTransactions') + * Subscribes to incoming pending transactions. + * + * You can subscribe to pending transactions by calling web3.eth.subscribe('pendingTransactions'). + * @example + * ```ts + * (await web3.eth.subscribe('pendingTransactions')).on('data', console.log); + * ``` + */ +export declare class NewPendingTransactionsSubscription extends Web3Subscription<{ + data: HexString; +}> { + protected _buildSubscriptionParams(): string[]; + protected formatSubscriptionResult(data: string): string; +} +/** + * ## subscribe('newHeads') ( same as subscribe('newBlockHeaders')) + * + * Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain. + * + * The structure of a returned block header is {@link BlockHeaderOutput}: + * @example + * ```ts + * (await web3.eth.subscribe('newHeads')).on( // 'newBlockHeaders' would work as well + * 'data', + * console.log + * ); + * >{ + * parentHash: '0x9e746a1d906b299def98c75b06f714d62dacadd567c7515d76eeaa8c8074c738', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0xe0f04b04861ecfa95e82a9310d6a7ef7aef8d7417f5209c182582bfb98a8e307', + * transactionsRoot: '0x31ab4ea571a9e10d3a19aaed07d190595b1dfa34e03960c04293fec565dea536', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 2n, + * number: 21n, + * gasLimit: 11738125n, + * gasUsed: 830006n, + * timestamp: 1678797237n, + * extraData: '0xd883010b02846765746888676f312e32302e31856c696e757800000000000000e0a6e93cf40e2e71a72e493272210c3f43738ccc7e7d7b14ffd51833797d896c09117e8dc4fbcbc969bd21b42e5af3e276a911524038c001b2109b63b8e0352601', + * nonce: 0n + * } + * ``` + */ +export declare class NewHeadsSubscription extends Web3Subscription<{ + data: BlockHeaderOutput; +}> { + protected _buildSubscriptionParams(): string[]; + protected formatSubscriptionResult(data: BlockHeaderOutput): BlockHeaderOutput; +} +/** + * ## subscribe('syncing') + * + * Subscribe to syncing events. This will return `true` when the node is syncing and when it’s finished syncing will return `false`, for the `changed` event. + * @example + * ```ts + * (await web3.eth.subscribe('syncing')).on('changed', console.log); + * > `true` // when syncing + * + * (await web3.eth.subscribe('syncing')).on('data', console.log); + * > { + * startingBlock: 0, + * currentBlock: 0, + * highestBlock: 0, + * pulledStates: 0, + * knownStates: 0 + * } + * ``` + */ +export declare class SyncingSubscription extends Web3Subscription<{ + data: SyncOutput; + changed: boolean; +}> { + protected _buildSubscriptionParams(): string[]; + _processSubscriptionResult(data: { + syncing: boolean; + status: SyncOutput; + } | boolean): void; +} diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.js b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.js new file mode 100644 index 0000000..6294f1b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.js @@ -0,0 +1,141 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SyncingSubscription = exports.NewHeadsSubscription = exports.NewPendingTransactionsSubscription = exports.LogsSubscription = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable-next-line max-classes-per-file */ +const web3_utils_1 = require("web3-utils"); +const web3_core_1 = require("web3-core"); +const schemas_js_1 = require("./schemas.js"); +/** + * ## subscribe('logs') + * Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, web3.js will retrieve logs beginning from this point, backfilling the response as necessary. + * + * You can subscribe to logs matching a given filter object, which can take the following parameters: + * - `fromBlock`: (optional, default: 'latest') Integer block number, or `'latest'` for the last mined block or `'pending'`, `'earliest'` for not yet mined transactions. + * - `address`: (optional) Contract address or a list of addresses from which logs should originate. + * - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with `or` options. + * + */ +class LogsSubscription extends web3_core_1.Web3Subscription { + _buildSubscriptionParams() { + return ['logs', this.args]; + } + formatSubscriptionResult(data) { + return (0, web3_utils_1.format)(schemas_js_1.logSchema, data, super.returnFormat); + } +} +exports.LogsSubscription = LogsSubscription; +/** + * ## subscribe('pendingTransactions') + * Subscribes to incoming pending transactions. + * + * You can subscribe to pending transactions by calling web3.eth.subscribe('pendingTransactions'). + * @example + * ```ts + * (await web3.eth.subscribe('pendingTransactions')).on('data', console.log); + * ``` + */ +class NewPendingTransactionsSubscription extends web3_core_1.Web3Subscription { + // eslint-disable-next-line + _buildSubscriptionParams() { + return ['newPendingTransactions']; + } + formatSubscriptionResult(data) { + return (0, web3_utils_1.format)({ format: 'string' }, data, super.returnFormat); + } +} +exports.NewPendingTransactionsSubscription = NewPendingTransactionsSubscription; +/** + * ## subscribe('newHeads') ( same as subscribe('newBlockHeaders')) + * + * Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain. + * + * The structure of a returned block header is {@link BlockHeaderOutput}: + * @example + * ```ts + * (await web3.eth.subscribe('newHeads')).on( // 'newBlockHeaders' would work as well + * 'data', + * console.log + * ); + * >{ + * parentHash: '0x9e746a1d906b299def98c75b06f714d62dacadd567c7515d76eeaa8c8074c738', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0xe0f04b04861ecfa95e82a9310d6a7ef7aef8d7417f5209c182582bfb98a8e307', + * transactionsRoot: '0x31ab4ea571a9e10d3a19aaed07d190595b1dfa34e03960c04293fec565dea536', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 2n, + * number: 21n, + * gasLimit: 11738125n, + * gasUsed: 830006n, + * timestamp: 1678797237n, + * extraData: '0xd883010b02846765746888676f312e32302e31856c696e757800000000000000e0a6e93cf40e2e71a72e493272210c3f43738ccc7e7d7b14ffd51833797d896c09117e8dc4fbcbc969bd21b42e5af3e276a911524038c001b2109b63b8e0352601', + * nonce: 0n + * } + * ``` + */ +class NewHeadsSubscription extends web3_core_1.Web3Subscription { + // eslint-disable-next-line + _buildSubscriptionParams() { + return ['newHeads']; + } + formatSubscriptionResult(data) { + return (0, web3_utils_1.format)(schemas_js_1.blockHeaderSchema, data, super.returnFormat); + } +} +exports.NewHeadsSubscription = NewHeadsSubscription; +/** + * ## subscribe('syncing') + * + * Subscribe to syncing events. This will return `true` when the node is syncing and when it’s finished syncing will return `false`, for the `changed` event. + * @example + * ```ts + * (await web3.eth.subscribe('syncing')).on('changed', console.log); + * > `true` // when syncing + * + * (await web3.eth.subscribe('syncing')).on('data', console.log); + * > { + * startingBlock: 0, + * currentBlock: 0, + * highestBlock: 0, + * pulledStates: 0, + * knownStates: 0 + * } + * ``` + */ +class SyncingSubscription extends web3_core_1.Web3Subscription { + // eslint-disable-next-line + _buildSubscriptionParams() { + return ['syncing']; + } + _processSubscriptionResult(data) { + if (typeof data === 'boolean') { + this.emit('changed', data); + } + else { + const mappedData = Object.fromEntries(Object.entries(data.status).map(([key, value]) => [ + key.charAt(0).toLowerCase() + key.substring(1), + value, + ])); + this.emit('changed', data.syncing); + this.emit('data', (0, web3_utils_1.format)(schemas_js_1.syncSchema, mappedData, super.returnFormat)); + } + } +} +exports.SyncingSubscription = SyncingSubscription; +//# sourceMappingURL=web3_subscriptions.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.js.map b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.js.map new file mode 100644 index 0000000..9a9fe27 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/commonjs/web3_subscriptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscriptions.js","sourceRoot":"","sources":["../../src/web3_subscriptions.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,mDAAmD;AACnD,2CAAoC;AAWpC,yCAA6C;AAC7C,6CAAwE;AAExE;;;;;;;;;GASG;AACH,MAAa,gBAAiB,SAAQ,4BASrC;IACU,wBAAwB;QACjC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAES,wBAAwB,CAAC,IAAgB;QAClD,OAAO,IAAA,mBAAM,EAAC,sBAAS,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IACpD,CAAC;CACD;AAjBD,4CAiBC;AAED;;;;;;;;;GASG;AACH,MAAa,kCAAmC,SAAQ,4BAEtD;IACD,2BAA2B;IACjB,wBAAwB;QACjC,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACnC,CAAC;IAES,wBAAwB,CAAC,IAAY;QAC9C,OAAO,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/D,CAAC;CACD;AAXD,gFAWC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,oBAAqB,SAAQ,4BAExC;IACD,2BAA2B;IACjB,wBAAwB;QACjC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrB,CAAC;IAES,wBAAwB,CAAC,IAAuB;QACzD,OAAO,IAAA,mBAAM,EAAC,8BAAiB,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5D,CAAC;CACD;AAXD,oDAWC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,mBAAoB,SAAQ,4BAGvC;IACD,2BAA2B;IACjB,wBAAwB;QACjC,OAAO,CAAC,SAAS,CAAC,CAAC;IACpB,CAAC;IAEM,0BAA0B,CAChC,IAKU;QAEV,IAAI,OAAO,IAAI,KAAK,SAAS,EAAE;YAC9B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;SAC3B;aAAM;YACN,MAAM,UAAU,GAAe,MAAM,CAAC,WAAW,CAChD,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;gBACjD,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;gBAC9C,KAAK;aACL,CAAC,CACY,CAAC;YAEhB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YACnC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAA,mBAAM,EAAC,uBAAU,EAAE,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC;SACtE;IACF,CAAC;CACD;AA/BD,kDA+BC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/constants.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/constants.js new file mode 100644 index 0000000..25ba999 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/constants.js @@ -0,0 +1,26 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { FMT_BYTES, FMT_NUMBER } from 'web3-types'; +export const ALL_EVENTS = 'ALLEVENTS'; +export const ALL_EVENTS_ABI = { + name: ALL_EVENTS, + signature: '', + type: 'event', + inputs: [], +}; +export const NUMBER_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.NUMBER }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/constants.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/constants.js.map new file mode 100644 index 0000000..8c29355 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAoB,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAErE,MAAM,CAAC,MAAM,UAAU,GAAG,WAAW,CAAC;AACtC,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B,IAAI,EAAE,UAAU;IAChB,SAAS,EAAE,EAAE;IACb,IAAI,EAAE,OAAO;IACb,MAAM,EAAE,EAAE;CACkC,CAAC;AAE9C,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAW,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/index.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/index.js new file mode 100644 index 0000000..006afcf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/index.js @@ -0,0 +1,65 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The `web3-eth` package allows you to interact with an Ethereum blockchain and Ethereum smart contracts. + * + * To use this package standalone and use its methods use: + * ```ts + * import { Web3Context } from 'web3-core'; + * import { BlockTags } from 'web3-types'; + * import { DEFAULT_RETURN_FORMAT } from 'web3-types'; + * import { getBalance} from 'web3-eth'; + * + * getBalance( + * new Web3Context('http://127.0.0.1:8545'), + * '0x407d73d8a49eeb85d32cf465507dd71d507100c1', + * BlockTags.LATEST, + * DEFAULT_RETURN_FORMAT + * ).then(console.log); + * > 1000000000000n + * ``` + * + * To use this package within the `web3` object use: + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * web3.eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1').then(console.log); + * > 1000000000000n + *``` + * + * With `web3-eth` you can also subscribe (if supported by provider) to events in the Ethereum Blockchain, using the `subscribe` function. See more at the {@link Web3Eth.subscribe} function. + */ +/** + * + */ +import 'setimmediate'; +import { Web3Eth } from './web3_eth.js'; +export * from './web3_eth.js'; +export * from './utils/decoding.js'; +export * from './schemas.js'; +export * from './constants.js'; +export * from './types.js'; +export * from './validation.js'; +export * from './rpc_method_wrappers.js'; +export * from './utils/format_transaction.js'; +export * from './utils/prepare_transaction_for_signing.js'; +export * from './web3_subscriptions.js'; +export { detectTransactionType } from './utils/detect_transaction_type.js'; +export { transactionBuilder } from './utils/transaction_builder.js'; +export default Web3Eth; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/index.js.map new file mode 100644 index 0000000..10adb3e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH;;GAEG;AACH,OAAO,cAAc,CAAC;AAEtB,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,4CAA4C,CAAC;AAC3D,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEpE,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/package.json b/test/merkletreejs/node_modules/web3-eth/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/rpc_method_wrappers.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/rpc_method_wrappers.js new file mode 100644 index 0000000..2a2d8fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/rpc_method_wrappers.js @@ -0,0 +1,592 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +// Disabling because returnTypes must be last param to match 1.x params +/* eslint-disable default-param-last */ +import { ETH_DATA_FORMAT, DEFAULT_RETURN_FORMAT, } from 'web3-types'; +import { Web3PromiEvent } from 'web3-core'; +import { format, hexToBytes, bytesToUint8Array, numberToHex } from 'web3-utils'; +import { TransactionFactory } from 'web3-eth-accounts'; +import { isBlockTag, isBytes, isNullish, isString } from 'web3-validator'; +import { SignatureError } from 'web3-errors'; +import { ethRpcMethods } from 'web3-rpc-methods'; +import { decodeSignedTransaction } from './utils/decode_signed_transaction.js'; +import { accountSchema, blockSchema, feeHistorySchema, logSchema, transactionReceiptSchema, accessListResultSchema, SignatureObjectSchema, } from './schemas.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionFromOrToAttr } from './utils/transaction_builder.js'; +import { formatTransaction } from './utils/format_transaction.js'; +// eslint-disable-next-line import/no-cycle +import { trySendTransaction } from './utils/try_send_transaction.js'; +// eslint-disable-next-line import/no-cycle +import { waitForTransactionReceipt } from './utils/wait_for_transaction_receipt.js'; +import { NUMBER_DATA_FORMAT } from './constants.js'; +// eslint-disable-next-line import/no-cycle +import { SendTxHelper } from './utils/send_tx_helper.js'; +/** + * View additional documentations here: {@link Web3Eth.getProtocolVersion} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const getProtocolVersion = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return ethRpcMethods.getProtocolVersion(web3Context.requestManager); }); +// TODO Add returnFormat parameter +/** + * View additional documentations here: {@link Web3Eth.isSyncing} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const isSyncing = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return ethRpcMethods.getSyncing(web3Context.requestManager); }); +// TODO consider adding returnFormat parameter (to format address as bytes) +/** + * View additional documentations here: {@link Web3Eth.getCoinbase} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const getCoinbase = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return ethRpcMethods.getCoinbase(web3Context.requestManager); }); +/** + * View additional documentations here: {@link Web3Eth.isMining} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const isMining = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return ethRpcMethods.getMining(web3Context.requestManager); }); +/** + * View additional documentations here: {@link Web3Eth.getHashRate} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getHashRate(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.getHashRate(web3Context.requestManager); + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getGasPrice} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getGasPrice(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.getGasPrice(web3Context.requestManager); + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getBlockNumber} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getBlockNumber(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.getBlockNumber(web3Context.requestManager); + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getBalance} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getBalance(web3Context, address, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.getBalance(web3Context.requestManager, address, blockNumberFormatted); + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getStorageAt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getStorageAt(web3Context, address, storageSlot, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const storageSlotFormatted = format({ format: 'uint' }, storageSlot, ETH_DATA_FORMAT); + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.getStorageAt(web3Context.requestManager, address, storageSlotFormatted, blockNumberFormatted); + return format({ format: 'bytes' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getCode} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getCode(web3Context, address, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.getCode(web3Context.requestManager, address, blockNumberFormatted); + return format({ format: 'bytes' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getBlock(web3Context, block = web3Context.defaultBlock, hydrated = false, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getBlockByHash(web3Context.requestManager, blockHashFormatted, hydrated); + } + else { + const blockNumberFormatted = isBlockTag(block) + ? block + : format({ format: 'uint' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getBlockByNumber(web3Context.requestManager, blockNumberFormatted, hydrated); + } + return format(blockSchema, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getBlockTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getBlockTransactionCount(web3Context, block = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getBlockTransactionCountByHash(web3Context.requestManager, blockHashFormatted); + } + else { + const blockNumberFormatted = isBlockTag(block) + ? block + : format({ format: 'uint' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getBlockTransactionCountByNumber(web3Context.requestManager, blockNumberFormatted); + } + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getBlockUncleCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getBlockUncleCount(web3Context, block = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getUncleCountByBlockHash(web3Context.requestManager, blockHashFormatted); + } + else { + const blockNumberFormatted = isBlockTag(block) + ? block + : format({ format: 'uint' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getUncleCountByBlockNumber(web3Context.requestManager, blockNumberFormatted); + } + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getUncle} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getUncle(web3Context, block = web3Context.defaultBlock, uncleIndex, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const uncleIndexFormatted = format({ format: 'uint' }, uncleIndex, ETH_DATA_FORMAT); + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getUncleByBlockHashAndIndex(web3Context.requestManager, blockHashFormatted, uncleIndexFormatted); + } + else { + const blockNumberFormatted = isBlockTag(block) + ? block + : format({ format: 'uint' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getUncleByBlockNumberAndIndex(web3Context.requestManager, blockNumberFormatted, uncleIndexFormatted); + } + return format(blockSchema, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getTransaction(web3Context, transactionHash, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionHashFormatted = format({ format: 'bytes32' }, transactionHash, DEFAULT_RETURN_FORMAT); + const response = yield ethRpcMethods.getTransactionByHash(web3Context.requestManager, transactionHashFormatted); + return isNullish(response) + ? response + : formatTransaction(response, returnFormat, { fillInputAndData: true }); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getPendingTransactions} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getPendingTransactions(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.getPendingTransactions(web3Context.requestManager); + return response.map(transaction => formatTransaction(transaction, returnFormat, { + fillInputAndData: true, + })); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getTransactionFromBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getTransactionFromBlock(web3Context, block = web3Context.defaultBlock, transactionIndex, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionIndexFormatted = format({ format: 'uint' }, transactionIndex, ETH_DATA_FORMAT); + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getTransactionByBlockHashAndIndex(web3Context.requestManager, blockHashFormatted, transactionIndexFormatted); + } + else { + const blockNumberFormatted = isBlockTag(block) + ? block + : format({ format: 'uint' }, block, ETH_DATA_FORMAT); + response = yield ethRpcMethods.getTransactionByBlockNumberAndIndex(web3Context.requestManager, blockNumberFormatted, transactionIndexFormatted); + } + return isNullish(response) + ? response + : formatTransaction(response, returnFormat, { fillInputAndData: true }); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getTransactionReceipt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getTransactionReceipt(web3Context, transactionHash, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionHashFormatted = format({ format: 'bytes32' }, transactionHash, DEFAULT_RETURN_FORMAT); + const response = yield ethRpcMethods.getTransactionReceipt(web3Context.requestManager, transactionHashFormatted); + return isNullish(response) + ? response + : format(transactionReceiptSchema, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getTransactionCount(web3Context, address, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.getTransactionCount(web3Context.requestManager, address, blockNumberFormatted); + return format({ format: 'uint' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.sendTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function sendTransaction(web3Context, transaction, returnFormat, options = { checkRevertBeforeSending: true }) { + const promiEvent = new Web3PromiEvent((resolve, reject) => { + setImmediate(() => { + (() => __awaiter(this, void 0, void 0, function* () { + const sendTxHelper = new SendTxHelper({ + web3Context, + promiEvent, + options, + returnFormat, + }); + let transactionFormatted = formatTransaction(Object.assign(Object.assign({}, transaction), { from: getTransactionFromOrToAttr('from', web3Context, transaction), to: getTransactionFromOrToAttr('to', web3Context, transaction) }), ETH_DATA_FORMAT); + try { + transactionFormatted = yield sendTxHelper.populateGasPrice({ + transaction, + transactionFormatted, + }); + yield sendTxHelper.checkRevertBeforeSending(transactionFormatted); + sendTxHelper.emitSending(transactionFormatted); + let wallet; + if (web3Context.wallet && !isNullish(transactionFormatted.from)) { + wallet = web3Context.wallet.get(transactionFormatted.from); + } + const transactionHash = yield sendTxHelper.signAndSend({ + wallet, + tx: transactionFormatted, + }); + const transactionHashFormatted = format({ format: 'bytes32' }, transactionHash, returnFormat); + sendTxHelper.emitSent(transactionFormatted); + sendTxHelper.emitTransactionHash(transactionHashFormatted); + const transactionReceipt = yield waitForTransactionReceipt(web3Context, transactionHash, returnFormat); + const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents(format(transactionReceiptSchema, transactionReceipt, returnFormat)); + sendTxHelper.emitReceipt(transactionReceiptFormatted); + resolve(yield sendTxHelper.handleResolve({ + receipt: transactionReceiptFormatted, + tx: transactionFormatted, + })); + sendTxHelper.emitConfirmation({ + receipt: transactionReceiptFormatted, + transactionHash, + }); + } + catch (error) { + reject(yield sendTxHelper.handleError({ + error, + tx: transactionFormatted, + })); + } + }))(); + }); + }); + return promiEvent; +} +/** + * View additional documentations here: {@link Web3Eth.sendSignedTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function sendSignedTransaction(web3Context, signedTransaction, returnFormat, options = { checkRevertBeforeSending: true }) { + // TODO - Promise returned in function argument where a void return was expected + // eslint-disable-next-line @typescript-eslint/no-misused-promises + const promiEvent = new Web3PromiEvent((resolve, reject) => { + setImmediate(() => { + (() => __awaiter(this, void 0, void 0, function* () { + const sendTxHelper = new SendTxHelper({ + web3Context, + promiEvent, + options, + returnFormat, + }); + // Formatting signedTransaction to be send to RPC endpoint + const signedTransactionFormattedHex = format({ format: 'bytes' }, signedTransaction, ETH_DATA_FORMAT); + const unSerializedTransaction = TransactionFactory.fromSerializedData(bytesToUint8Array(hexToBytes(signedTransactionFormattedHex))); + const unSerializedTransactionWithFrom = Object.assign(Object.assign({}, unSerializedTransaction.toJSON()), { + // Some providers will default `from` to address(0) causing the error + // reported from `eth_call` to not be the reason the user's tx failed + // e.g. `eth_call` will return an Out of Gas error for a failed + // smart contract execution contract, because the sender, address(0), + // has no balance to pay for the gas of the transaction execution + from: unSerializedTransaction.getSenderAddress().toString() }); + try { + const { v, r, s } = unSerializedTransactionWithFrom, txWithoutSigParams = __rest(unSerializedTransactionWithFrom, ["v", "r", "s"]); + yield sendTxHelper.checkRevertBeforeSending(txWithoutSigParams); + sendTxHelper.emitSending(signedTransactionFormattedHex); + const transactionHash = yield trySendTransaction(web3Context, () => __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.sendRawTransaction(web3Context.requestManager, signedTransactionFormattedHex); + })); + sendTxHelper.emitSent(signedTransactionFormattedHex); + const transactionHashFormatted = format({ format: 'bytes32' }, transactionHash, returnFormat); + sendTxHelper.emitTransactionHash(transactionHashFormatted); + const transactionReceipt = yield waitForTransactionReceipt(web3Context, transactionHash, returnFormat); + const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents(format(transactionReceiptSchema, transactionReceipt, returnFormat)); + sendTxHelper.emitReceipt(transactionReceiptFormatted); + resolve(yield sendTxHelper.handleResolve({ + receipt: transactionReceiptFormatted, + tx: unSerializedTransactionWithFrom, + })); + sendTxHelper.emitConfirmation({ + receipt: transactionReceiptFormatted, + transactionHash, + }); + } + catch (error) { + reject(yield sendTxHelper.handleError({ + error, + tx: unSerializedTransactionWithFrom, + })); + } + }))(); + }); + }); + return promiEvent; +} +/** + * View additional documentations here: {@link Web3Eth.sign} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function sign(web3Context, message, addressOrIndex, returnFormat) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const messageFormatted = format({ format: 'bytes' }, message, DEFAULT_RETURN_FORMAT); + if ((_a = web3Context.wallet) === null || _a === void 0 ? void 0 : _a.get(addressOrIndex)) { + const wallet = web3Context.wallet.get(addressOrIndex); + const signed = wallet.sign(messageFormatted); + return format(SignatureObjectSchema, signed, returnFormat); + } + if (typeof addressOrIndex === 'number') { + throw new SignatureError(message, 'RPC method "eth_sign" does not support index signatures'); + } + const response = yield ethRpcMethods.sign(web3Context.requestManager, addressOrIndex, messageFormatted); + return format({ format: 'bytes' }, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.signTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function signTransaction(web3Context, transaction, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.signTransaction(web3Context.requestManager, formatTransaction(transaction, ETH_DATA_FORMAT)); + // Some clients only return the encoded signed transaction (e.g. Ganache) + // while clients such as Geth return the desired SignedTransactionInfoAPI object + return isString(response) + ? decodeSignedTransaction(response, returnFormat, { + fillInputAndData: true, + }) + : { + raw: format({ format: 'bytes' }, response.raw, returnFormat), + tx: formatTransaction(response.tx, returnFormat, { + fillInputAndData: true, + }), + }; + }); +} +// TODO Decide what to do with transaction.to +// https://github.com/ChainSafe/web3.js/pull/4525#issuecomment-982330076 +/** + * View additional documentations here: {@link Web3Eth.call} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function call(web3Context, transaction, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.call(web3Context.requestManager, formatTransaction(transaction, ETH_DATA_FORMAT), blockNumberFormatted); + return format({ format: 'bytes' }, response, returnFormat); + }); +} +// TODO - Investigate whether response is padded as 1.x docs suggest +/** + * View additional documentations here: {@link Web3Eth.estimateGas} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function estimateGas(web3Context, transaction, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionFormatted = formatTransaction(transaction, ETH_DATA_FORMAT); + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.estimateGas(web3Context.requestManager, transactionFormatted, blockNumberFormatted); + return format({ format: 'uint' }, response, returnFormat); + }); +} +// TODO - Add input formatting to filter +/** + * View additional documentations here: {@link Web3Eth.getPastLogs} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getLogs(web3Context, filter, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + // format type bigint or number toBlock and fromBlock to hexstring. + let { toBlock, fromBlock } = filter; + if (!isNullish(toBlock)) { + if (typeof toBlock === 'number' || typeof toBlock === 'bigint') { + toBlock = numberToHex(toBlock); + } + } + if (!isNullish(fromBlock)) { + if (typeof fromBlock === 'number' || typeof fromBlock === 'bigint') { + fromBlock = numberToHex(fromBlock); + } + } + const formattedFilter = Object.assign(Object.assign({}, filter), { fromBlock, toBlock }); + const response = yield ethRpcMethods.getLogs(web3Context.requestManager, formattedFilter); + const result = response.map(res => { + if (typeof res === 'string') { + return res; + } + return format(logSchema, res, returnFormat); + }); + return result; + }); +} +/** + * View additional documentations here: {@link Web3Eth.getChainId} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getChainId(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.getChainId(web3Context.requestManager); + return format({ format: 'uint' }, + // Response is number in hex formatted string + response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.getProof} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getProof(web3Context, address, storageKeys, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const storageKeysFormatted = storageKeys.map(storageKey => format({ format: 'bytes' }, storageKey, ETH_DATA_FORMAT)); + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = yield ethRpcMethods.getProof(web3Context.requestManager, address, storageKeysFormatted, blockNumberFormatted); + return format(accountSchema, response, returnFormat); + }); +} +// TODO Throwing an error with Geth, but not Infura +// TODO gasUsedRatio and reward not formatting +/** + * View additional documentations here: {@link Web3Eth.getFeeHistory} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function getFeeHistory(web3Context, blockCount, newestBlock = web3Context.defaultBlock, rewardPercentiles, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockCountFormatted = format({ format: 'uint' }, blockCount, ETH_DATA_FORMAT); + const newestBlockFormatted = isBlockTag(newestBlock) + ? newestBlock + : format({ format: 'uint' }, newestBlock, ETH_DATA_FORMAT); + const rewardPercentilesFormatted = format({ + type: 'array', + items: { + format: 'uint', + }, + }, rewardPercentiles, NUMBER_DATA_FORMAT); + const response = yield ethRpcMethods.getFeeHistory(web3Context.requestManager, blockCountFormatted, newestBlockFormatted, rewardPercentilesFormatted); + return format(feeHistorySchema, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.createAccessList} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function createAccessList(web3Context, transaction, blockNumber = web3Context.defaultBlock, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const blockNumberFormatted = isBlockTag(blockNumber) + ? blockNumber + : format({ format: 'uint' }, blockNumber, ETH_DATA_FORMAT); + const response = (yield ethRpcMethods.createAccessList(web3Context.requestManager, formatTransaction(transaction, ETH_DATA_FORMAT), blockNumberFormatted)); + return format(accessListResultSchema, response, returnFormat); + }); +} +/** + * View additional documentations here: {@link Web3Eth.signTypedData} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function signTypedData(web3Context, address, typedData, useLegacy, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield ethRpcMethods.signTypedData(web3Context.requestManager, address, typedData, useLegacy); + return format({ format: 'bytes' }, response, returnFormat); + }); +} +//# sourceMappingURL=rpc_method_wrappers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/rpc_method_wrappers.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/rpc_method_wrappers.js.map new file mode 100644 index 0000000..b6e1c53 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/rpc_method_wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.js","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;AAEF,uEAAuE;AACvE,uCAAuC;AACvC,OAAO,EACN,eAAe,EAGf,qBAAqB,GA0BrB,MA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AE,YAAY,CAAC,CAAC;IAClF,CAAC;CAAA;AAED;;;GAGG;AACH,MAAM,UAAgB,gBAAgB,CACrC,WAAyC,EACzC,WAAqC,EACrC,cAAgC,WAAW,CAAC,YAAY,EACxD,YAA0B;;QAE1B,MAAM,oBAAoB,GAAG,UAAU,CAAC,WAAqB,CAAC;YAC7D,CAAC,CAAE,WAAwB;YAC3B,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,WAAsB,EAAE,eAAe,CAAC,CAAC;QAEvE,MAAM,QAAQ,GAAG,CAAC,MAAM,aAAa,CAAC,gBAAgB,CACrD,WAAW,CAAC,cAAc,EAC1B,iBAAiB,CAAC,WAAW,EAAE,eAAe,CAAC,EAC/C,oBAAoB,CACpB,CAAgC,CAAC;QAElC,OAAO,MAAM,CAAC,sBAAsB,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;IAC/D,CAAC;CAAA;AAED;;;GAGG;AACH,MAAM,UAAgB,aAAa,CAClC,WAAyC,EACzC,OAAgB,EAChB,SAA0B,EAC1B,SAAkB,EAClB,YAA0B;;QAE1B,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC,aAAa,CACjD,WAAW,CAAC,cAAc,EAC1B,OAAO,EACP,SAAS,EACT,SAAS,CACT,CAAC;QAEF,OAAO,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;IAC5D,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/schemas.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/schemas.js new file mode 100644 index 0000000..6a5f26d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/schemas.js @@ -0,0 +1,584 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export const accessListItemSchema = { + type: 'object', + properties: { + address: { + format: 'address', + }, + storageKeys: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +export const accessListSchema = { + type: 'array', + items: Object.assign({}, accessListItemSchema), +}; +export const accessListResultSchema = { + type: 'object', + properties: { + accessList: Object.assign({}, accessListSchema), + gasUsed: { + type: 'string', + }, + }, +}; +export const chainSchema = { + type: 'string', + enum: ['goerli', 'kovan', 'mainnet', 'rinkeby', 'ropsten', 'sepolia'], +}; +export const hardforkSchema = { + type: 'string', + enum: [ + 'arrowGlacier', + 'berlin', + 'byzantium', + 'chainstart', + 'constantinople', + 'dao', + 'homestead', + 'istanbul', + 'london', + 'merge', + 'muirGlacier', + 'petersburg', + 'shanghai', + 'spuriousDragon', + 'tangerineWhistle', + ], +}; +export const customChainSchema = { + type: 'object', + properties: { + name: { + format: 'string', + }, + networkId: { + format: 'uint', + }, + chainId: { + format: 'uint', + }, + }, +}; +export const transactionSchema = { + type: 'object', + properties: { + from: { + format: 'address', + }, + to: { + oneOf: [{ format: 'address' }, { type: 'null' }], + }, + value: { + format: 'uint', + }, + gas: { + format: 'uint', + }, + gasPrice: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + type: { + format: 'uint', + }, + maxFeePerGas: { + format: 'uint', + }, + maxPriorityFeePerGas: { + format: 'uint', + }, + accessList: Object.assign({}, accessListSchema), + data: { + format: 'bytes', + }, + input: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + chain: Object.assign({}, chainSchema), + hardfork: Object.assign({}, hardforkSchema), + chainId: { + format: 'uint', + }, + networkId: { + format: 'uint', + }, + common: { + type: 'object', + properties: { + customChain: Object.assign({}, customChainSchema), + baseChain: Object.assign({}, chainSchema), + hardfork: Object.assign({}, hardforkSchema), + }, + }, + gasLimit: { + format: 'uint', + }, + v: { + format: 'uint', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + }, +}; +export const transactionInfoSchema = { + type: 'object', + properties: Object.assign(Object.assign({}, transactionSchema.properties), { blockHash: { + format: 'bytes32', + }, blockNumber: { + format: 'uint', + }, hash: { + format: 'bytes32', + }, transactionIndex: { + format: 'uint', + }, from: { + format: 'address', + }, to: { + oneOf: [{ format: 'address' }, { type: 'null' }], + }, value: { + format: 'uint', + }, gas: { + format: 'uint', + }, gasPrice: { + format: 'uint', + }, effectiveGasPrice: { + format: 'uint', + }, type: { + format: 'uint', + }, maxFeePerGas: { + format: 'uint', + }, maxPriorityFeePerGas: { + format: 'uint', + }, accessList: Object.assign({}, accessListSchema), data: { + format: 'bytes', + }, input: { + format: 'bytes', + }, nonce: { + format: 'uint', + }, gasLimit: { + format: 'uint', + }, v: { + format: 'uint', + }, r: { + format: 'bytes32', + }, s: { + format: 'bytes32', + } }), +}; +export const blockSchema = { + type: 'object', + properties: { + parentHash: { + format: 'bytes32', + }, + sha3Uncles: { + format: 'bytes32', + }, + miner: { + format: 'bytes', + }, + stateRoot: { + format: 'bytes32', + }, + transactionsRoot: { + format: 'bytes32', + }, + receiptsRoot: { + format: 'bytes32', + }, + logsBloom: { + format: 'bytes256', + }, + difficulty: { + format: 'uint', + }, + number: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + timestamp: { + format: 'uint', + }, + extraData: { + format: 'bytes', + }, + mixHash: { + format: 'bytes32', + }, + nonce: { + format: 'uint', + }, + totalDifficulty: { + format: 'uint', + }, + baseFeePerGas: { + format: 'uint', + }, + size: { + format: 'uint', + }, + transactions: { + oneOf: [ + { + type: 'array', + items: Object.assign({}, transactionInfoSchema), + }, + { + type: 'array', + items: { + format: 'bytes32', + }, + }, + ], + }, + uncles: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + hash: { + format: 'bytes32', + }, + }, +}; +export const withdrawalsSchema = { + type: 'object', + properties: { + index: { + format: 'uint', + }, + validatorIndex: { + format: 'uint', + }, + address: { + format: 'address', + }, + amount: { + format: 'uint', + }, + }, +}; +export const blockHeaderSchema = { + type: 'object', + properties: { + author: { + format: 'bytes32', + }, + hash: { + format: 'bytes32', + }, + parentHash: { + format: 'bytes32', + }, + receiptsRoot: { + format: 'bytes32', + }, + miner: { + format: 'bytes', + }, + stateRoot: { + format: 'bytes32', + }, + transactionsRoot: { + format: 'bytes32', + }, + withdrawalsRoot: { + format: 'bytes32', + }, + logsBloom: { + format: 'bytes256', + }, + difficulty: { + format: 'uint', + }, + totalDifficulty: { + format: 'uint', + }, + number: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + timestamp: { + format: 'uint', + }, + extraData: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + sha3Uncles: { + format: 'bytes32', + }, + size: { + format: 'uint', + }, + baseFeePerGas: { + format: 'uint', + }, + excessDataGas: { + format: 'uint', + }, + mixHash: { + format: 'bytes32', + }, + transactions: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + uncles: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + withdrawals: { + type: 'array', + items: Object.assign({}, withdrawalsSchema), + }, + }, +}; +export const logSchema = { + type: 'object', + properties: { + removed: { + format: 'bool', + }, + logIndex: { + format: 'uint', + }, + transactionIndex: { + format: 'uint', + }, + transactionHash: { + format: 'bytes32', + }, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + address: { + format: 'address', + }, + data: { + format: 'bytes', + }, + topics: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +export const syncSchema = { + type: 'object', + properties: { + startingBlock: { + format: 'string', + }, + currentBlock: { + format: 'string', + }, + highestBlock: { + format: 'string', + }, + knownStates: { + format: 'string', + }, + pulledStates: { + format: 'string', + }, + }, +}; +export const transactionReceiptSchema = { + type: 'object', + properties: { + transactionHash: { + format: 'bytes32', + }, + transactionIndex: { + format: 'uint', + }, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + from: { + format: 'address', + }, + to: { + format: 'address', + }, + cumulativeGasUsed: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + contractAddress: { + format: 'address', + }, + logs: { + type: 'array', + items: Object.assign({}, logSchema), + }, + logsBloom: { + format: 'bytes', + }, + root: { + format: 'bytes', + }, + status: { + format: 'uint', + }, + type: { + format: 'uint', + }, + }, +}; +export const SignatureObjectSchema = { + type: 'object', + properties: { + messageHash: { + format: 'bytes', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + v: { + format: 'bytes', + }, + message: { + format: 'bytes', + }, + signature: { + format: 'bytes', + }, + }, +}; +export const feeHistorySchema = { + type: 'object', + properties: { + oldestBlock: { + format: 'uint', + }, + baseFeePerGas: { + type: 'array', + items: { + format: 'uint', + }, + }, + reward: { + type: 'array', + items: { + type: 'array', + items: { + format: 'uint', + }, + }, + }, + gasUsedRatio: { + type: 'array', + items: { + type: 'number', + }, + }, + }, +}; +export const storageProofSchema = { + type: 'object', + properties: { + key: { + format: 'bytes32', + }, + value: { + format: 'uint', + }, + proof: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +export const accountSchema = { + type: 'object', + properties: { + balance: { + format: 'uint', + }, + codeHash: { + format: 'bytes32', + }, + nonce: { + format: 'uint', + }, + storageHash: { + format: 'bytes32', + }, + accountProof: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + storageProof: { + type: 'array', + items: Object.assign({}, storageProofSchema), + }, + }, +}; +//# sourceMappingURL=schemas.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/schemas.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/schemas.js.map new file mode 100644 index 0000000..2b4d9b2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/schemas.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,MAAM,CAAC,MAAM,oBAAoB,GAAG;IACnC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,OAAO,EAAE;YACR,MAAM,EAAE,SAAS;SACjB;QACD,WAAW,EAAE;YACZ,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,SAAS;aACjB;SACD;KACD;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC/B,IAAI,EAAE,OAAO;IACb,KAAK,oBACD,oBAAoB,CACvB;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACrC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,UAAU,oBACN,gBAAgB,CACnB;QACD,OAAO,EAAE;YACR,IAAI,EAAE,QAAQ;SACd;KACD;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,WAAW,GAAG;IAC1B,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC;CACrE,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE;QACL,cAAc;QACd,QAAQ;QACR,WAAW;QACX,YAAY;QACZ,gBAAgB;QAChB,KAAK;QACL,WAAW;QACX,UAAU;QACV,QAAQ;QACR,OAAO;QACP,aAAa;QACb,YAAY;QACZ,UAAU;QACV,gBAAgB;QAChB,kBAAkB;KAClB;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,IAAI,EAAE;YACL,MAAM,EAAE,QAAQ;SAChB;QACD,SAAS,EAAE;YACV,MAAM,E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F,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC/B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,WAAW,EAAE;YACZ,MAAM,EAAE,MAAM;SACd;QACD,aAAa,EAAE;YACd,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,MAAM;aACd;SACD;QACD,MAAM,EAAE;YACP,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,IAAI,EAAE,OAAO;gBACb,KAAK,EAAE;oBACN,MAAM,EAAE,MAAM;iBACd;aACD;SACD;QACD,YAAY,EAAE;YACb,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,IAAI,EAAE,QAAQ;aACd;SACD;KACD;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAG;IACjC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,GAAG,EAAE;YACJ,MAAM,EAAE,SAAS;SACjB;QACD,KAAK,EAAE;YACN,MAAM,EAAE,MAAM;SACd;QACD,KAAK,EAAE;YACN,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,SAAS;aACjB;SACD;KACD;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,OAAO,EAAE;YACR,MAAM,EAAE,MAAM;SACd;QACD,QAAQ,EAAE;YACT,MAAM,EAAE,SAAS;SACjB;QACD,KAAK,EAAE;YACN,MAAM,EAAE,MAAM;SACd;QACD,WAAW,EAAE;YACZ,MAAM,EAAE,SAAS;SACjB;QACD,YAAY,EAAE;YACb,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,MAAM,EAAE,SAAS;aACjB;SACD;QACD,YAAY,EAAE;YACb,IAAI,EAAE,OAAO;YACb,KAAK,oBACD,kBAAkB,CACrB;SACD;KACD;CACD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/types.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decode_signed_transaction.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decode_signed_transaction.js new file mode 100644 index 0000000..2e3f0ce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decode_signed_transaction.js @@ -0,0 +1,18 @@ +import { bytesToHex, format, hexToBytes, keccak256 } from 'web3-utils'; +import { TransactionFactory } from 'web3-eth-accounts'; +import { detectRawTransactionType } from './detect_transaction_type.js'; +import { formatTransaction } from './format_transaction.js'; +/** + * Decodes an [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded transaction. + * + * @param encodedSignedTransaction The RLP encoded transaction. + * @param returnFormat ({@link DataFormat} Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the RLP encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + */ +export function decodeSignedTransaction(encodedSignedTransaction, returnFormat, options = { fillInputAndData: false }) { + return { + raw: format({ format: 'bytes' }, encodedSignedTransaction, returnFormat), + tx: formatTransaction(Object.assign(Object.assign({}, TransactionFactory.fromSerializedData(hexToBytes(encodedSignedTransaction)).toJSON()), { hash: bytesToHex(keccak256(hexToBytes(encodedSignedTransaction))), type: detectRawTransactionType(hexToBytes(encodedSignedTransaction)) }), returnFormat, { fillInputAndData: options.fillInputAndData }), + }; +} +//# sourceMappingURL=decode_signed_transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decode_signed_transaction.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decode_signed_transaction.js.map new file mode 100644 index 0000000..b4dc2f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decode_signed_transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_signed_transaction.js","sourceRoot":"","sources":["../../../src/utils/decode_signed_transaction.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CACtC,wBAAwC,EACxC,YAA0B,EAC1B,UAA0C,EAAE,gBAAgB,EAAE,KAAK,EAAE;IAErE,OAAO;QACN,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,wBAAwB,EAAE,YAAY,CAAC;QACxE,EAAE,EAAE,iBAAiB,CACpB,gCACI,kBAAkB,CAAC,kBAAkB,CACvC,UAAU,CAAC,wBAAwB,CAAC,CACpC,CAAC,MAAM,EAAE,KACV,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,wBAAwB,CAAC,CAAC,CAAC,EACjE,IAAI,EAAE,wBAAwB,CAAC,UAAU,CAAC,wBAAwB,CAAC,CAAC,GAC5C,EACzB,YAAY,EACZ,EAAE,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,EAAE,CAC9C;KACD,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decoding.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decoding.js new file mode 100644 index 0000000..368ccd8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decoding.js @@ -0,0 +1,60 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { format } from 'web3-utils'; +import { DEFAULT_RETURN_FORMAT, } from 'web3-types'; +import { decodeLog } from 'web3-eth-abi'; +import { logSchema } from '../schemas.js'; +import { ALL_EVENTS } from '../constants.js'; +export const decodeEventABI = (event, data, jsonInterface, returnFormat = DEFAULT_RETURN_FORMAT) => { + var _a, _b, _c, _d, _e; + let modifiedEvent = Object.assign({}, event); + const result = format(logSchema, data, returnFormat); + // if allEvents get the right event + if ([ALL_EVENTS, 'allEvents'].includes(modifiedEvent.name)) { + const matchedEvent = jsonInterface.find(j => j.signature === data.topics[0]); + if (matchedEvent) { + modifiedEvent = matchedEvent; + } + else { + modifiedEvent = { anonymous: true }; + } + } + // create empty inputs if none are present (e.g. anonymous events on allEvents) + modifiedEvent.inputs = (_b = (_a = modifiedEvent.inputs) !== null && _a !== void 0 ? _a : event.inputs) !== null && _b !== void 0 ? _b : []; + // Handle case where an event signature shadows the current ABI with non-identical + // arg indexing. If # of topics doesn't match, event is anon. + if (!modifiedEvent.anonymous) { + let indexedInputs = 0; + ((_c = modifiedEvent.inputs) !== null && _c !== void 0 ? _c : []).forEach(input => { + if (input.indexed) { + indexedInputs += 1; + } + }); + if (indexedInputs > 0 && (data === null || data === void 0 ? void 0 : data.topics) && (data === null || data === void 0 ? void 0 : data.topics.length) !== indexedInputs + 1) { + // checks if event is anonymous + modifiedEvent = Object.assign(Object.assign({}, modifiedEvent), { anonymous: true, inputs: [] }); + } + } + const argTopics = modifiedEvent.anonymous ? data.topics : ((_d = data.topics) !== null && _d !== void 0 ? _d : []).slice(1); + return Object.assign(Object.assign({}, result), { returnValues: decodeLog([...((_e = modifiedEvent.inputs) !== null && _e !== void 0 ? _e : [])], data.data, argTopics), event: modifiedEvent.name, signature: modifiedEvent.anonymous || !data.topics || data.topics.length === 0 || !data.topics[0] + ? undefined + : data.topics[0], raw: { + data: data.data, + topics: data.topics, + } }); +}; +//# sourceMappingURL=decoding.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decoding.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decoding.js.map new file mode 100644 index 0000000..521eaab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/decoding.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding.js","sourceRoot":"","sources":["../../../src/utils/decoding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEpC,OAAO,EAIN,qBAAqB,GAGrB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CA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AAM,CAAC,MAAM,MAAK,aAAa,GAAG,CAAC,EAAE;YACnF,+BAA+B;YAC/B,aAAa,mCACT,aAAa,KAChB,SAAS,EAAE,IAAI,EACf,MAAM,EAAE,EAAE,GACV,CAAC;SACF;KACD;IAED,MAAM,SAAS,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAA,IAAI,CAAC,MAAM,mCAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAEvF,uCACI,MAAM,KACT,YAAY,EAAE,SAAS,CAAC,CAAC,GAAG,CAAC,MAAA,aAAa,CAAC,MAAM,mCAAI,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,EAChF,KAAK,EAAE,aAAa,CAAC,IAAI,EACzB,SAAS,EACR,aAAa,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;YACrF,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAElB,GAAG,EAAE;YACJ,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM,EAAE,IAAI,CAAC,MAAM;SACnB,IACA;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/detect_transaction_type.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/detect_transaction_type.js new file mode 100644 index 0000000..1e8e497 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/detect_transaction_type.js @@ -0,0 +1,119 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { format, toHex } from 'web3-utils'; +import { HardforksOrdered, ETH_DATA_FORMAT } from 'web3-types'; +import { Web3ValidatorError, isNullish, validator } from 'web3-validator'; +import { InvalidPropertiesForTransactionTypeError } from 'web3-errors'; +// undefined is treated as null for JSON schema validator +const transactionType0x0Schema = { + type: 'object', + properties: { + accessList: { + type: 'null', + }, + maxFeePerGas: { + type: 'null', + }, + maxPriorityFeePerGas: { + type: 'null', + }, + }, +}; +const transactionType0x1Schema = { + type: 'object', + properties: { + maxFeePerGas: { + type: 'null', + }, + maxPriorityFeePerGas: { + type: 'null', + }, + }, +}; +const transactionType0x2Schema = { + type: 'object', + properties: { + gasPrice: { + type: 'null', + }, + }, +}; +const validateTxTypeAndHandleErrors = (txSchema, tx, txType) => { + try { + validator.validateJSONSchema(txSchema, tx); + } + catch (error) { + if (error instanceof Web3ValidatorError) + // Erroneously reported error + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + throw new InvalidPropertiesForTransactionTypeError(error.errors, txType); + throw error; + } +}; +export const defaultTransactionTypeParser = (transaction) => { + var _a, _b; + const tx = transaction; + if (!isNullish(tx.type)) { + let txSchema; + switch (tx.type) { + case '0x0': + txSchema = transactionType0x0Schema; + break; + case '0x1': + txSchema = transactionType0x1Schema; + break; + case '0x2': + txSchema = transactionType0x2Schema; + break; + default: + return format({ format: 'uint' }, tx.type, ETH_DATA_FORMAT); + } + validateTxTypeAndHandleErrors(txSchema, tx, tx.type); + return format({ format: 'uint' }, tx.type, ETH_DATA_FORMAT); + } + if (!isNullish(tx.maxFeePerGas) || !isNullish(tx.maxPriorityFeePerGas)) { + validateTxTypeAndHandleErrors(transactionType0x2Schema, tx, '0x2'); + return '0x2'; + } + if (!isNullish(tx.accessList)) { + validateTxTypeAndHandleErrors(transactionType0x1Schema, tx, '0x1'); + return '0x1'; + } + const givenHardfork = (_a = tx.hardfork) !== null && _a !== void 0 ? _a : (_b = tx.common) === null || _b === void 0 ? void 0 : _b.hardfork; + if (!isNullish(givenHardfork)) { + const hardforkIndex = Object.keys(HardforksOrdered).indexOf(givenHardfork); + // givenHardfork is London or later, so EIP-2718 is supported + if (hardforkIndex >= Object.keys(HardforksOrdered).indexOf('london')) + return !isNullish(tx.gasPrice) ? '0x0' : '0x2'; + // givenHardfork is Berlin, tx.accessList is undefined, assume type is 0x0 + if (hardforkIndex === Object.keys(HardforksOrdered).indexOf('berlin')) + return '0x0'; + } + // gasprice is defined + if (!isNullish(tx.gasPrice)) { + validateTxTypeAndHandleErrors(transactionType0x0Schema, tx, '0x0'); + return '0x0'; + } + // no transaction type can be inferred from properties, use default transaction type + return undefined; +}; +export const detectTransactionType = (transaction, web3Context) => { + var _a; + return ((_a = web3Context === null || web3Context === void 0 ? void 0 : web3Context.transactionTypeParser) !== null && _a !== void 0 ? _a : defaultTransactionTypeParser)(transaction); +}; +export const detectRawTransactionType = (transaction) => transaction[0] > 0x7f ? '0x0' : toHex(transaction[0]); +//# sourceMappingURL=detect_transaction_type.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/detect_transaction_type.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/detect_transaction_type.js.map new file mode 100644 index 0000000..da06f90 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/detect_transaction_type.js.map @@ -0,0 +1 @@ +{"version":3,"file":"detect_transaction_type.js","sourceRoot":"","sources":["../../../src/utils/detect_transaction_type.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAE3C,OAAO,EAAmB,gBAAgB,EAAe,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7F,OAAO,EAAE,kBAAkB,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C,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;QAEhD,0EAA0E;QAC1E,IAAI,aAAa,KAAK,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;KACpF;IAED,sBAAsB;IACtB,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE;QAC5B,6BAA6B,CAAC,wBAAwB,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO,KAAK,CAAC;KACb;IAED,oFAAoF;IACpF,OAAO,SAAS,CAAC;AAClB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACpC,WAAgC,EAChC,WAA0C,EACzC,EAAE;;IACH,OAAA,CAAC,MAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,qBAAqB,mCAAI,4BAA4B,CAAC,CACnE,WAAiD,CACjD,CAAA;CAAA,CAAC;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,WAAuB,EAAE,EAAE,CACnE,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/format_transaction.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/format_transaction.js new file mode 100644 index 0000000..7f133cb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/format_transaction.js @@ -0,0 +1,57 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { isNullish } from 'web3-validator'; +import { mergeDeep, format, bytesToHex, toHex } from 'web3-utils'; +import { TransactionDataAndInputError } from 'web3-errors'; +import { transactionInfoSchema } from '../schemas.js'; +export function formatTransaction(transaction, returnFormat = DEFAULT_RETURN_FORMAT, options = { + transactionSchema: transactionInfoSchema, + fillInputAndData: false, +}) { + var _a, _b; + let formattedTransaction = mergeDeep({}, transaction); + if (!isNullish(transaction === null || transaction === void 0 ? void 0 : transaction.common)) { + formattedTransaction.common = Object.assign({}, transaction.common); + if (!isNullish((_a = transaction.common) === null || _a === void 0 ? void 0 : _a.customChain)) + formattedTransaction.common.customChain = Object.assign({}, transaction.common.customChain); + } + formattedTransaction = format((_b = options.transactionSchema) !== null && _b !== void 0 ? _b : transactionInfoSchema, formattedTransaction, returnFormat); + if (!isNullish(formattedTransaction.data) && + !isNullish(formattedTransaction.input) && + // Converting toHex is accounting for data and input being Uint8Arrays + // since comparing Uint8Array is not as straightforward as comparing strings + toHex(formattedTransaction.data) !== toHex(formattedTransaction.input)) + throw new TransactionDataAndInputError({ + data: bytesToHex(formattedTransaction.data), + input: bytesToHex(formattedTransaction.input), + }); + if (options.fillInputAndData) { + if (!isNullish(formattedTransaction.data)) { + formattedTransaction.input = formattedTransaction.data; + } + else if (!isNullish(formattedTransaction.input)) { + formattedTransaction.data = formattedTransaction.input; + } + } + if (!isNullish(formattedTransaction.gasLimit)) { + formattedTransaction.gas = formattedTransaction.gasLimit; + delete formattedTransaction.gasLimit; + } + return formattedTransaction; +} +//# sourceMappingURL=format_transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/format_transaction.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/format_transaction.js.map new file mode 100644 index 0000000..f37d673 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/format_transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"format_transaction.js","sourceRoot":"","sources":["../../../src/utils/format_transaction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAA2B,qBAAqB,EAAc,MAAM,YAAY,CAAC;AACxF,OAAO,EAAE,SAAS,EAAyB,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAClE,OAAO,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAC;AAE3D,OAAO,EAAE,qBAAqB,EAAqB,MAAM,eAAe,CAAC;AAEzE,MAAM,UAAU,iBAAiB,CAIhC,WAA4B,EAC5B,eAA6B,qBAAqC,EAClE,UAGI;IACH,iBAAiB,EAAE,qBAAqB;IACxC,gBAAgB,EAAE,KAAK;CACvB;;IAED,IAAI,oBAAoB,GAAG,SAAS,CAAC,EAAE,EAAE,WAAsC,CAAgB,CAAC;IAChG,IAAI,CAAC,SAAS,CAAC,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,MAAM,CAAC,EAAE;QACpC,oBAAoB,CAAC,MAAM,qBAAQ,WAAW,CAAC,MAAM,CAAE,CAAC;QACxD,IAAI,CAAC,SAAS,CAAC,MAAA,WAAW,CAAC,MAAM,0CAAE,WAAW,CAAC;YAC9C,oBAAoB,CAAC,MAAM,CAAC,WAAW,qBAAQ,WAAW,CAAC,MAAM,CAAC,WAAW,CAAE,CAAC;KACjF;IACD,oBAAoB,GAAG,MAAM,CAC5B,MAAA,OAAO,CAAC,iBAAiB,mCAAI,qBAAqB,EAClD,oBAAoB,EACpB,YAAY,CACZ,CAAC;IACF,IACC,CAAC,SAAS,CAAC,oBAAoB,CAAC,IAAI,CAAC;QACrC,CAAC,SAAS,CAAC,oBAAoB,CAAC,KAAK,CAAC;QACtC,sEAAsE;QACtE,4EAA4E;QAC5E,KAAK,CAAC,oBAAoB,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,oBAAoB,CAAC,KAAK,CAAC;QAEtE,MAAM,IAAI,4BAA4B,CAAC;YACtC,IAAI,EAAE,UAAU,CAAC,oBAAoB,CAAC,IAAI,CAAC;YAC3C,KAAK,EAAE,UAAU,CAAC,oBAAoB,CAAC,KAAK,CAAC;SAC7C,CAAC,CAAC;IAEJ,IAAI,OAAO,CAAC,gBAAgB,EAAE;QAC7B,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,IAAI,CAAC,EAAE;YAC1C,oBAAoB,CAAC,KAAK,GAAG,oBAAoB,CAAC,IAAI,CAAC;SACvD;aAAM,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,KAAK,CAAC,EAAE;YAClD,oBAAoB,CAAC,IAAI,GAAG,oBAAoB,CAAC,KAAK,CAAC;SACvD;KACD;IAED,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,QAAQ,CAAC,EAAE;QAC9C,oBAAoB,CAAC,GAAG,GAAG,oBAAoB,CAAC,QAAQ,CAAC;QACzD,OAAO,oBAAoB,CAAC,QAAQ,CAAC;KACrC;IAED,OAAO,oBAAiE,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_revert_reason.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_revert_reason.js new file mode 100644 index 0000000..ce323ef --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_revert_reason.js @@ -0,0 +1,78 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { ContractExecutionError, Eip838ExecutionError, InvalidResponseError } from 'web3-errors'; +import { decodeContractErrorData, isAbiErrorFragment } from 'web3-eth-abi'; +import { DEFAULT_RETURN_FORMAT, } from 'web3-types'; +// eslint-disable-next-line import/no-cycle +import { call } from '../rpc_method_wrappers.js'; +export const parseTransactionError = (error, contractAbi) => { + var _a, _b, _c, _d; + if (error instanceof ContractExecutionError && + error.innerError instanceof Eip838ExecutionError) { + if (contractAbi !== undefined) { + const errorsAbi = contractAbi.filter(abi => isAbiErrorFragment(abi)); + decodeContractErrorData(errorsAbi, error.innerError); + return { + reason: error.innerError.message, + signature: (_a = error.innerError.data) === null || _a === void 0 ? void 0 : _a.slice(0, 10), + data: (_b = error.innerError.data) === null || _b === void 0 ? void 0 : _b.substring(10), + customErrorName: error.innerError.errorName, + customErrorDecodedSignature: error.innerError.errorSignature, + customErrorArguments: error.innerError.errorArgs, + }; + } + return { + reason: error.innerError.message, + signature: (_c = error.innerError.data) === null || _c === void 0 ? void 0 : _c.slice(0, 10), + data: (_d = error.innerError.data) === null || _d === void 0 ? void 0 : _d.substring(10), + }; + } + if (error instanceof InvalidResponseError && + !Array.isArray(error.innerError) && + error.innerError !== undefined) { + return error.innerError.message; + } + throw error; +}; +/** + * Returns the revert reason generated by the EVM if the transaction were to be executed. + * + * @param web3Context - ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @returns `undefined` if no revert reason was given, a revert reason object, a revert reason string, or an `unknown` error + */ +export function getRevertReason(web3Context, transaction, contractAbi, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield call(web3Context, transaction, web3Context.defaultBlock, returnFormat); + return undefined; + } + catch (error) { + return parseTransactionError(error, contractAbi); + } + }); +} +//# sourceMappingURL=get_revert_reason.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_revert_reason.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_revert_reason.js.map new file mode 100644 index 0000000..2563fc0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_revert_reason.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_revert_reason.js","sourceRoot":"","sources":["../../../src/utils/get_revert_reason.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAGF,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAIN,qBAAqB,GAGrB,MAAM,YAAY,CAAC;AAEpB,2CAA2C;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,2BAA2B,CAAC;AAGjD,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,KAAc,EAAE,WAAyB,EAAE,EAAE;;IAClF,IACC,KAAK,YAAY,sBAAsB;QACvC,KAAK,CAAC,UAAU,YAAY,oBAAoB,EAC/C;QACD,IAAI,WAAW,KAAK,SAAS,EAAE;YAC9B,MAAM,SAAS,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAC1C,kBAAkB,CAAC,GAAG,CAAC,CACU,CAAC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AE;YACf,OAAO,qBAAqB,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;SACjD;IACF,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_error.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_error.js new file mode 100644 index 0000000..8538eeb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_error.js @@ -0,0 +1,59 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { TransactionRevertedWithoutReasonError, TransactionRevertInstructionError, TransactionRevertWithCustomError, } from 'web3-errors'; +// eslint-disable-next-line import/no-cycle +import { getRevertReason, parseTransactionError } from './get_revert_reason.js'; +export function getTransactionError(web3Context, transactionFormatted, transactionReceiptFormatted, receivedError, contractAbi, knownReason) { + return __awaiter(this, void 0, void 0, function* () { + let _reason = knownReason; + if (_reason === undefined) { + if (receivedError !== undefined) { + _reason = parseTransactionError(receivedError); + } + else if (web3Context.handleRevert && transactionFormatted !== undefined) { + _reason = yield getRevertReason(web3Context, transactionFormatted, contractAbi); + } + } + let error; + if (_reason === undefined) { + error = new TransactionRevertedWithoutReasonError(transactionReceiptFormatted); + } + else if (typeof _reason === 'string') { + error = new TransactionRevertInstructionError(_reason, undefined, transactionReceiptFormatted); + } + else if (_reason.customErrorName !== undefined && + _reason.customErrorDecodedSignature !== undefined && + _reason.customErrorArguments !== undefined) { + const reasonWithCustomError = _reason; + error = new TransactionRevertWithCustomError(reasonWithCustomError.reason, reasonWithCustomError.customErrorName, reasonWithCustomError.customErrorDecodedSignature, reasonWithCustomError.customErrorArguments, reasonWithCustomError.signature, transactionReceiptFormatted, reasonWithCustomError.data); + } + else { + error = new TransactionRevertInstructionError(_reason.reason, _reason.signature, transactionReceiptFormatted, _reason.data); + } + return error; + }); +} +//# sourceMappingURL=get_transaction_error.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_error.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_error.js.map new file mode 100644 index 0000000..d9cd549 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_transaction_error.js","sourceRoot":"","sources":["../../../src/utils/get_transaction_error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAGF,OAAO,EACN,qCAAqC,EACrC,iCAAiC,EACjC,gCAAgC,GAChC,MAAM,aAAa,CAAC;AASrB,2CAA2C;AAC3C,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEhF,MAAM,UAAgB,mBAAmB,CACxC,WAAwB,EACxB,oBAAsC,EACtC,2BAA0E,EAC1E,aAAuB,EACvB,WAAyB,EACzB,WAAiE;;QAEjE,IAAI,OAAO,GAAoE,WAAW,CAAC;QAE3F,IAAI,OAAO,KAAK,SAAS,EAAE;YAC1B,IAAI,aAAa,KAAK,SAAS,EAAE;gBAChC,OAAO,GAAG,qBAAqB,CAAC,aAAa,CAAC,CAAC;aAC/C;iBAAM,IAAI,WAAW,CAAC,YAAY,IAAI,oBAAoB,KAAK,SAAS,EAAE;gBAC1E,OAAO,GAAG,MAAM,eAAe,CAAC,WAAW,EAAE,oBAAoB,EAAE,WAAW,CAAC,CAAC;aAChF;SACD;QAED,IAAI,KAG6E,CAAC;QAClF,IAAI,OAAO,KAAK,SAAS,EAAE;YAC1B,KAAK,GAAG,IAAI,qCAAqC,CAE/C,2BAA2B,CAAC,CAAC;SAC/B;aAAM,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YACvC,KAAK,GAAG,IAAI,iCAAiC,CAC5C,OAAO,EACP,SAAS,EACT,2BAA2B,CAC3B,CAAC;SACF;aAAM,IACL,OAAuC,CAAC,eAAe,KAAK,SAAS;YACrE,OAAuC,CAAC,2BAA2B,KAAK,SAAS;YACjF,OAAuC,CAAC,oBAAoB,KAAK,SAAS,EAC1E;YACD,MAAM,qBAAqB,GAC1B,OAAsC,CAAC;YACxC,KAAK,GAAG,IAAI,gCAAgC,CAC3C,qBAAqB,CAAC,MAAM,EAC5B,qBAAqB,CAAC,eAAe,EACrC,qBAAqB,CAAC,2BAA2B,EACjD,qBAAqB,CAAC,oBAAoB,EAC1C,qBAAqB,CAAC,SAAS,EAC/B,2BAA2B,EAC3B,qBAAqB,CAAC,IAAI,CAC1B,CAAC;SACF;aAAM;YACN,KAAK,GAAG,IAAI,iCAAiC,CAC5C,OAAO,CAAC,MAAM,EACd,OAAO,CAAC,SAAS,EACjB,2BAA2B,EAC3B,OAAO,CAAC,IAAI,CACZ,CAAC;SACF;QAED,OAAO,KAAK,CAAC;IACd,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_gas_pricing.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_gas_pricing.js new file mode 100644 index 0000000..bd5b124 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_gas_pricing.js @@ -0,0 +1,76 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { isNullish } from 'web3-validator'; +import { Eip1559NotSupportedError, UnsupportedTransactionTypeError } from 'web3-errors'; +import { format } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { getBlock, getGasPrice } from '../rpc_method_wrappers.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionType } from './transaction_builder.js'; +function getEip1559GasPricing(transaction, web3Context, returnFormat) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const block = yield getBlock(web3Context, web3Context.defaultBlock, false, returnFormat); + if (isNullish(block.baseFeePerGas)) + throw new Eip1559NotSupportedError(); + if (!isNullish(transaction.gasPrice)) { + const convertedTransactionGasPrice = format({ format: 'uint' }, transaction.gasPrice, returnFormat); + return { + maxPriorityFeePerGas: convertedTransactionGasPrice, + maxFeePerGas: convertedTransactionGasPrice, + }; + } + return { + maxPriorityFeePerGas: format({ format: 'uint' }, (_a = transaction.maxPriorityFeePerGas) !== null && _a !== void 0 ? _a : web3Context.defaultMaxPriorityFeePerGas, returnFormat), + maxFeePerGas: format({ format: 'uint' }, ((_b = transaction.maxFeePerGas) !== null && _b !== void 0 ? _b : BigInt(block.baseFeePerGas) * BigInt(2) + + BigInt((_c = transaction.maxPriorityFeePerGas) !== null && _c !== void 0 ? _c : web3Context.defaultMaxPriorityFeePerGas)), returnFormat), + }; + }); +} +export function getTransactionGasPricing(transaction, web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const transactionType = getTransactionType(transaction, web3Context); + if (!isNullish(transactionType)) { + if (transactionType.startsWith('-')) + throw new UnsupportedTransactionTypeError(transactionType); + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2718.md#transactions + if (Number(transactionType) < 0 || Number(transactionType) > 127) + throw new UnsupportedTransactionTypeError(transactionType); + if (isNullish(transaction.gasPrice) && + (transactionType === '0x0' || transactionType === '0x1')) + return { + gasPrice: yield getGasPrice(web3Context, returnFormat), + maxPriorityFeePerGas: undefined, + maxFeePerGas: undefined, + }; + if (transactionType === '0x2') { + return Object.assign({ gasPrice: undefined }, (yield getEip1559GasPricing(transaction, web3Context, returnFormat))); + } + } + return undefined; + }); +} +//# sourceMappingURL=get_transaction_gas_pricing.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_gas_pricing.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_gas_pricing.js.map new file mode 100644 index 0000000..f8c89c4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/get_transaction_gas_pricing.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_transaction_gas_pricing.js","sourceRoot":"","sources":["../../../src/utils/get_transaction_gas_pricing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAWF,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,wBAAwB,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AACxF,OAAO,EAAE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AM,eAAe,GAAG,kBAAkB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;QACrE,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,EAAE;YAChC,IAAI,eAAe,CAAC,UAAU,CAAC,GAAG,CAAC;gBAClC,MAAM,IAAI,+BAA+B,CAAC,eAAe,CAAC,CAAC;YAE5D,6EAA6E;YAC7E,IAAI,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,eAAe,CAAC,GAAG,GAAG;gBAC/D,MAAM,IAAI,+BAA+B,CAAC,eAAe,CAAC,CAAC;YAE5D,IACC,SAAS,CAAC,WAAW,CAAC,QAAQ,CAAC;gBAC/B,CAAC,eAAe,KAAK,KAAK,IAAI,eAAe,KAAK,KAAK,CAAC;gBAExD,OAAO;oBACN,QAAQ,EAAE,MAAM,WAAW,CAAC,WAAW,EAAE,YAAY,CAAC;oBACtD,oBAAoB,EAAE,SAAS;oBAC/B,YAAY,EAAE,SAAS;iBACvB,CAAC;YAEH,IAAI,eAAe,KAAK,KAAK,EAAE;gBAC9B,uBACC,QAAQ,EAAE,SAAS,IAChB,CAAC,MAAM,oBAAoB,CAAC,WAAW,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,EACtE;aACF;SACD;QAED,OAAO,SAAS,CAAC;IAClB,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/index.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/index.js new file mode 100644 index 0000000..2ac90d8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/index.js @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './detect_transaction_type.js'; +export * from './format_transaction.js'; +export * from './prepare_transaction_for_signing.js'; +export * from './transaction_builder.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/index.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/index.js.map new file mode 100644 index 0000000..d0fc57f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,8BAA8B,CAAC;AAC7C,cAAc,yBAAyB,CAAC;AACxC,cAAc,sCAAsC,CAAC;AACrD,cAAc,0BAA0B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/prepare_transaction_for_signing.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/prepare_transaction_for_signing.js new file mode 100644 index 0000000..052ae23 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/prepare_transaction_for_signing.js @@ -0,0 +1,107 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { ETH_DATA_FORMAT, } from 'web3-types'; +import { toNumber } from 'web3-utils'; +import { TransactionFactory, Common } from 'web3-eth-accounts'; +import { isNullish } from 'web3-validator'; +import { validateTransactionForSigning } from '../validation.js'; +import { formatTransaction } from './format_transaction.js'; +import { transactionBuilder } from './transaction_builder.js'; +const getEthereumjsTxDataFromTransaction = (transaction) => { + var _a, _b; + return ({ + nonce: transaction.nonce, + gasPrice: transaction.gasPrice, + gasLimit: (_a = transaction.gasLimit) !== null && _a !== void 0 ? _a : transaction.gas, + to: transaction.to, + value: transaction.value, + data: (_b = transaction.data) !== null && _b !== void 0 ? _b : transaction.input, + type: transaction.type, + chainId: transaction.chainId, + accessList: transaction.accessList, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); +}; +const getEthereumjsTransactionOptions = (transaction, web3Context) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; + const hasTransactionSigningOptions = (!isNullish(transaction.chain) && !isNullish(transaction.hardfork)) || + !isNullish(transaction.common); + let common; + if (!hasTransactionSigningOptions) { + // if defaultcommon is specified, use that. + if (web3Context.defaultCommon) { + common = web3Context.defaultCommon; + if (isNullish(common.hardfork)) + common.hardfork = (_a = transaction.hardfork) !== null && _a !== void 0 ? _a : web3Context.defaultHardfork; + if (isNullish(common.baseChain)) + common.baseChain = web3Context.defaultChain; + } + else { + common = Common.custom({ + name: 'custom-network', + chainId: toNumber(transaction.chainId), + networkId: !isNullish(transaction.networkId) + ? toNumber(transaction.networkId) + : undefined, + defaultHardfork: (_b = transaction.hardfork) !== null && _b !== void 0 ? _b : web3Context.defaultHardfork, + }, { + baseChain: web3Context.defaultChain, + }); + } + } + else { + const name = (_f = (_e = (_d = (_c = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _c === void 0 ? void 0 : _c.customChain) === null || _d === void 0 ? void 0 : _d.name) !== null && _e !== void 0 ? _e : transaction.chain) !== null && _f !== void 0 ? _f : 'custom-network'; + const chainId = toNumber((_j = (_h = (_g = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _g === void 0 ? void 0 : _g.customChain) === null || _h === void 0 ? void 0 : _h.chainId) !== null && _j !== void 0 ? _j : transaction === null || transaction === void 0 ? void 0 : transaction.chainId); + const networkId = toNumber((_m = (_l = (_k = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _k === void 0 ? void 0 : _k.customChain) === null || _l === void 0 ? void 0 : _l.networkId) !== null && _m !== void 0 ? _m : transaction === null || transaction === void 0 ? void 0 : transaction.networkId); + const defaultHardfork = (_q = (_p = (_o = transaction === null || transaction === void 0 ? void 0 : transaction.common) === null || _o === void 0 ? void 0 : _o.hardfork) !== null && _p !== void 0 ? _p : transaction === null || transaction === void 0 ? void 0 : transaction.hardfork) !== null && _q !== void 0 ? _q : web3Context.defaultHardfork; + const baseChain = (_t = (_s = (_r = transaction.common) === null || _r === void 0 ? void 0 : _r.baseChain) !== null && _s !== void 0 ? _s : transaction.chain) !== null && _t !== void 0 ? _t : web3Context.defaultChain; + if (chainId && networkId && name) { + common = Common.custom({ + name, + chainId, + networkId, + defaultHardfork, + }, { + baseChain, + }); + } + } + return { common }; +}; +export const prepareTransactionForSigning = (transaction, web3Context, privateKey, fillGasPrice = false, fillGasLimit = true) => __awaiter(void 0, void 0, void 0, function* () { + const populatedTransaction = (yield transactionBuilder({ + transaction, + web3Context, + privateKey, + fillGasPrice, + fillGasLimit, + })); + const formattedTransaction = formatTransaction(populatedTransaction, ETH_DATA_FORMAT); + validateTransactionForSigning(formattedTransaction); + return TransactionFactory.fromTxData(getEthereumjsTxDataFromTransaction(formattedTransaction), getEthereumjsTransactionOptions(formattedTransaction, web3Context)); +}); +//# sourceMappingURL=prepare_transaction_for_signing.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/prepare_transaction_for_signing.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/prepare_transaction_for_signing.js.map new file mode 100644 index 0000000..f95bb3c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/prepare_transaction_for_signing.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prepare_transaction_for_signing.js","sourceRoot":"","sources":["../../../src/utils/prepare_transaction_for_signing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EASN,eAAe,GACf,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAa,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE9D,MAAM,kCAAkC,GAAG,CAC1C,WAA6E,EAC5E,EAAE;;IAAC,OAAA,CAAC;QACL,KAAK,EAAE,WAAW,CAAC,KAAK;QACxB,QAAQ,EAAE,WAAW,CAAC,QAAQ;QAC9B,QAAQ,EAAE,MAAA,WAAW,CAAC,QAAQ,mCAAI,WAAW,CAAC,GAAG;QACjD,EAAE,EAAE,WAAW,CAAC,EAAE;QAClB,KAAK,EAAE,WAAW,CAAC,KAAK;QACxB,IAAI,EAAE,MAAA,WAAW,CAAC,IAAI,mCAAI,WAAW,CAAC,KAAK;QAC3C,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,OAAO,EAAE,WAAW,CAAC,OAAO;QAC5B,UAAU,EACT,WACA,CAAC,UAA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AC;QACtD,WAAW;QACX,WAAW;QACX,UAAU;QACV,YAAY;QACZ,YAAY;KACZ,CAAC,CAA4C,CAAC;IAC/C,MAAM,oBAAoB,GAAG,iBAAiB,CAC7C,oBAAoB,EACpB,eAAe,CACgE,CAAC;IACjF,6BAA6B,CAC5B,oBAAkF,CAClF,CAAC;IAEF,OAAO,kBAAkB,CAAC,UAAU,CACnC,kCAAkC,CAAC,oBAAoB,CAAC,EACxD,+BAA+B,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAClE,CAAC;AACH,CAAC,CAAA,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/reject_if_block_timeout.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/reject_if_block_timeout.js new file mode 100644 index 0000000..b089dae --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/reject_if_block_timeout.js @@ -0,0 +1,134 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { rejectIfConditionAtInterval } from 'web3-utils'; +import { TransactionBlockTimeoutError } from 'web3-errors'; +import { NUMBER_DATA_FORMAT } from '../constants.js'; +// eslint-disable-next-line import/no-cycle +import { getBlockNumber } from '../rpc_method_wrappers.js'; +function resolveByPolling(web3Context, starterBlockNumber, transactionHash) { + const pollingInterval = web3Context.transactionPollingInterval; + const [intervalId, promiseToError] = rejectIfConditionAtInterval(() => __awaiter(this, void 0, void 0, function* () { + let lastBlockNumber; + try { + lastBlockNumber = yield getBlockNumber(web3Context, NUMBER_DATA_FORMAT); + } + catch (error) { + console.warn('An error happen while trying to get the block number', error); + return undefined; + } + const numberOfBlocks = lastBlockNumber - starterBlockNumber; + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + return new TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + }); + } + return undefined; + }), pollingInterval); + const clean = () => { + clearInterval(intervalId); + }; + return [promiseToError, { clean }]; +} +function resolveBySubscription(web3Context, starterBlockNumber, transactionHash) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + // The following variable will stay true except if the data arrived, + // or if watching started after an error had occurred. + let needToWatchLater = true; + let subscription; + let resourceCleaner; + // internal helper function + function revertToPolling(reject, previousError) { + if (previousError) { + console.warn('error happened at subscription. So revert to polling...', previousError); + } + resourceCleaner.clean(); + needToWatchLater = false; + const [promiseToError, newResourceCleaner] = resolveByPolling(web3Context, starterBlockNumber, transactionHash); + resourceCleaner.clean = newResourceCleaner.clean; + promiseToError.catch(error => reject(error)); + } + try { + subscription = (yield ((_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.subscribe('newHeads'))); + resourceCleaner = { + clean: () => { + var _a; + // Remove the subscription, if it was not removed somewhere + // else by calling, for example, subscriptionManager.clear() + if (subscription.id) { + (_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.removeSubscription(subscription).then(() => { + // Subscription ended successfully + }).catch(() => { + // An error happened while ending subscription. But no need to take any action. + }); + } + }, + }; + } + catch (error) { + return resolveByPolling(web3Context, starterBlockNumber, transactionHash); + } + const promiseToError = new Promise((_, reject) => { + try { + subscription.on('data', (lastBlockHeader) => { + needToWatchLater = false; + if (!(lastBlockHeader === null || lastBlockHeader === void 0 ? void 0 : lastBlockHeader.number)) { + return; + } + const numberOfBlocks = Number(BigInt(lastBlockHeader.number) - BigInt(starterBlockNumber)); + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + // Transaction Block Timeout is known to be reached by subscribing to new heads + reject(new TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + })); + } + }); + subscription.on('error', error => { + revertToPolling(reject, error); + }); + } + catch (error) { + revertToPolling(reject, error); + } + // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds] + setTimeout(() => { + if (needToWatchLater) { + revertToPolling(reject); + } + }, web3Context.blockHeaderTimeout * 1000); + }); + return [promiseToError, resourceCleaner]; + }); +} +/* TODO: After merge, there will be constant block mining time (exactly 12 second each block, except slot missed that currently happens in <1% of slots. ) so we can optimize following function +for POS NWs, we can skip checking getBlockNumber(); after interval and calculate only based on time that certain num of blocked are mined after that for internal double check, can do one getBlockNumber() call and timeout. +*/ +export function rejectIfBlockTimeout(web3Context, transactionHash) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const { provider } = web3Context.requestManager; + let callingRes; + const starterBlockNumber = yield getBlockNumber(web3Context, NUMBER_DATA_FORMAT); + // TODO: once https://github.com/web3/web3.js/issues/5521 is implemented, remove checking for `enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout` + if (((_b = (_a = provider).supportsSubscriptions) === null || _b === void 0 ? void 0 : _b.call(_a)) && + web3Context.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout) { + callingRes = yield resolveBySubscription(web3Context, starterBlockNumber, transactionHash); + } + else { + callingRes = resolveByPolling(web3Context, starterBlockNumber, transactionHash); + } + return callingRes; + }); +} +//# sourceMappingURL=reject_if_block_timeout.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/reject_if_block_timeout.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/reject_if_block_timeout.js.map new file mode 100644 index 0000000..fabcaff --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/reject_if_block_timeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"reject_if_block_timeout.js","sourceRoot":"","sources":["../../../src/utils/reject_if_block_timeout.ts"],"names":[],"mappings":";;;;;;;;;AAkBA,OAAO,EAAE,2BAA2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A0B,CAAC,uCAAuC,EAC7E;YACD,UAAU,GAAG,MAAM,qBAAqB,CAAC,WAAW,EAAE,kBAAkB,EAAE,eAAe,CAAC,CAAC;SAC3F;aAAM;YACN,UAAU,GAAG,gBAAgB,CAAC,WAAW,EAAE,kBAAkB,EAAE,eAAe,CAAC,CAAC;SAChF;QACD,OAAO,UAAU,CAAC;;CAClB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/send_tx_helper.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/send_tx_helper.js new file mode 100644 index 0000000..cd42200 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/send_tx_helper.js @@ -0,0 +1,168 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ETH_DATA_FORMAT, } from 'web3-types'; +import { isNullish } from 'web3-validator'; +import { ContractExecutionError, InvalidResponseError, TransactionRevertedWithoutReasonError, TransactionRevertInstructionError, TransactionRevertWithCustomError, } from 'web3-errors'; +import { ethRpcMethods } from 'web3-rpc-methods'; +// eslint-disable-next-line import/no-cycle +import { getTransactionGasPricing } from './get_transaction_gas_pricing.js'; +// eslint-disable-next-line import/no-cycle +import { trySendTransaction } from './try_send_transaction.js'; +// eslint-disable-next-line import/no-cycle +import { watchTransactionForConfirmations } from './watch_transaction_for_confirmations.js'; +import { ALL_EVENTS_ABI } from '../constants.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionError } from './get_transaction_error.js'; +// eslint-disable-next-line import/no-cycle +import { getRevertReason } from './get_revert_reason.js'; +import { decodeEventABI } from './decoding.js'; +export class SendTxHelper { + constructor({ options, web3Context, promiEvent, returnFormat, }) { + this.options = { + checkRevertBeforeSending: true, + }; + this.options = options; + this.web3Context = web3Context; + this.promiEvent = promiEvent; + this.returnFormat = returnFormat; + } + getReceiptWithEvents(data) { + var _a, _b; + const result = Object.assign({}, (data !== null && data !== void 0 ? data : {})); + if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.contractAbi) && result.logs && result.logs.length > 0) { + result.events = {}; + for (const log of result.logs) { + const event = decodeEventABI(ALL_EVENTS_ABI, log, (_b = this.options) === null || _b === void 0 ? void 0 : _b.contractAbi, this.returnFormat); + if (event.event) { + result.events[event.event] = event; + } + } + } + return result; + } + checkRevertBeforeSending(tx) { + return __awaiter(this, void 0, void 0, function* () { + if (this.options.checkRevertBeforeSending !== false) { + const reason = yield getRevertReason(this.web3Context, tx, this.options.contractAbi); + if (reason !== undefined) { + throw yield getTransactionError(this.web3Context, tx, undefined, undefined, this.options.contractAbi, reason); + } + } + }); + } + emitSending(tx) { + if (this.promiEvent.listenerCount('sending') > 0) { + this.promiEvent.emit('sending', tx); + } + } + populateGasPrice({ transactionFormatted, transaction, }) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + let result = transactionFormatted; + if (!((_a = this.options) === null || _a === void 0 ? void 0 : _a.ignoreGasPricing) && + isNullish(transactionFormatted.gasPrice) && + (isNullish(transaction.maxPriorityFeePerGas) || + isNullish(transaction.maxFeePerGas))) { + result = Object.assign(Object.assign({}, transactionFormatted), (yield getTransactionGasPricing(transactionFormatted, this.web3Context, ETH_DATA_FORMAT))); + } + return result; + }); + } + signAndSend({ wallet, tx, }) { + return __awaiter(this, void 0, void 0, function* () { + if (wallet) { + const signedTransaction = yield wallet.signTransaction(tx); + return trySendTransaction(this.web3Context, () => __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.sendRawTransaction(this.web3Context.requestManager, signedTransaction.rawTransaction); + }), signedTransaction.transactionHash); + } + return trySendTransaction(this.web3Context, () => __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.sendTransaction(this.web3Context.requestManager, tx); + })); + }); + } + emitSent(tx) { + if (this.promiEvent.listenerCount('sent') > 0) { + this.promiEvent.emit('sent', tx); + } + } + emitTransactionHash(hash) { + if (this.promiEvent.listenerCount('transactionHash') > 0) { + this.promiEvent.emit('transactionHash', hash); + } + } + emitReceipt(receipt) { + if (this.promiEvent.listenerCount('receipt') > 0) { + this.promiEvent.emit('receipt', + // @ts-expect-error unknown type fix + receipt); + } + } + handleError({ error, tx }) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + let _error = error; + if (_error instanceof ContractExecutionError && this.web3Context.handleRevert) { + _error = yield getTransactionError(this.web3Context, tx, undefined, undefined, (_a = this.options) === null || _a === void 0 ? void 0 : _a.contractAbi); + } + if ((_error instanceof InvalidResponseError || + _error instanceof ContractExecutionError || + _error instanceof TransactionRevertWithCustomError || + _error instanceof TransactionRevertedWithoutReasonError || + _error instanceof TransactionRevertInstructionError) && + this.promiEvent.listenerCount('error') > 0) { + this.promiEvent.emit('error', _error); + } + return _error; + }); + } + emitConfirmation({ receipt, transactionHash, }) { + if (this.promiEvent.listenerCount('confirmation') > 0) { + watchTransactionForConfirmations(this.web3Context, this.promiEvent, receipt, transactionHash, this.returnFormat); + } + } + handleResolve({ receipt, tx }) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.transactionResolver) { + return (_b = this.options) === null || _b === void 0 ? void 0 : _b.transactionResolver(receipt); + } + if (receipt.status === BigInt(0)) { + const error = yield getTransactionError(this.web3Context, tx, + // @ts-expect-error unknown type fix + receipt, undefined, (_c = this.options) === null || _c === void 0 ? void 0 : _c.contractAbi); + if (this.promiEvent.listenerCount('error') > 0) { + this.promiEvent.emit('error', error); + } + throw error; + } + else { + return receipt; + } + }); + } +} +//# sourceMappingURL=send_tx_helper.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/send_tx_helper.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/send_tx_helper.js.map new file mode 100644 index 0000000..d1c98db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/send_tx_helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"send_tx_helper.js","sourceRoot":"","sources":["../../../src/utils/send_tx_helper.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EACN,eAAe,GAgBf,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EACN,sBAAsB,EACtB,oBAAoB,EACpB,qCAAqC,EACrC,iCAAiC,EACjC,gCAAgC,GAChC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAOjD,2CAA2C;AAC3C,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,2CAA2C;AAC3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,2CAA2C;AAC3C,OAAO,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,2CAA2C;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,2CAA2C;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC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esm/utils/transaction_builder.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/transaction_builder.js new file mode 100644 index 0000000..1851e2c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/transaction_builder.js @@ -0,0 +1,163 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, } from 'web3-types'; +import { privateKeyToAddress } from 'web3-eth-accounts'; +import { getId } from 'web3-net'; +import { isNullish, isNumber, isHexStrict, isAddress } from 'web3-validator'; +import { InvalidTransactionWithSender, InvalidTransactionWithReceiver, LocalWalletNotAvailableError, TransactionDataAndInputError, UnableToPopulateNonceError, } from 'web3-errors'; +import { bytesToHex, format } from 'web3-utils'; +import { NUMBER_DATA_FORMAT } from '../constants.js'; +// eslint-disable-next-line import/no-cycle +import { getChainId, getTransactionCount, estimateGas } from '../rpc_method_wrappers.js'; +import { detectTransactionType } from './detect_transaction_type.js'; +import { transactionSchema } from '../schemas.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionGasPricing } from './get_transaction_gas_pricing.js'; +export const getTransactionFromOrToAttr = (attr, web3Context, transaction, privateKey) => { + if (transaction !== undefined && attr in transaction && transaction[attr] !== undefined) { + if (typeof transaction[attr] === 'string' && isAddress(transaction[attr])) { + return transaction[attr]; + } + if (!isHexStrict(transaction[attr]) && isNumber(transaction[attr])) { + if (web3Context.wallet) { + const account = web3Context.wallet.get(format({ format: 'uint' }, transaction[attr], NUMBER_DATA_FORMAT)); + if (!isNullish(account)) { + return account.address; + } + throw new LocalWalletNotAvailableError(); + } + throw new LocalWalletNotAvailableError(); + } + else { + throw attr === 'from' + ? new InvalidTransactionWithSender(transaction.from) + : // eslint-disable-next-line @typescript-eslint/no-unsafe-call + new InvalidTransactionWithReceiver(transaction.to); + } + } + if (attr === 'from') { + if (!isNullish(privateKey)) + return privateKeyToAddress(privateKey); + if (!isNullish(web3Context.defaultAccount)) + return web3Context.defaultAccount; + } + return undefined; +}; +export const getTransactionNonce = (web3Context, address, returnFormat = DEFAULT_RETURN_FORMAT) => __awaiter(void 0, void 0, void 0, function* () { + if (isNullish(address)) { + // TODO if (web3.eth.accounts.wallet) use address from local wallet + throw new UnableToPopulateNonceError(); + } + return getTransactionCount(web3Context, address, web3Context.defaultBlock, returnFormat); +}); +export const getTransactionType = (transaction, web3Context) => { + const inferredType = detectTransactionType(transaction, web3Context); + if (!isNullish(inferredType)) + return inferredType; + if (!isNullish(web3Context.defaultTransactionType)) + return format({ format: 'uint' }, web3Context.defaultTransactionType, ETH_DATA_FORMAT); + return undefined; +}; +// Keep in mind that the order the properties of populateTransaction get populated matters +// as some of the properties are dependent on others +export function defaultTransactionBuilder(options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let populatedTransaction = format(transactionSchema, options.transaction, DEFAULT_RETURN_FORMAT); + if (isNullish(populatedTransaction.from)) { + populatedTransaction.from = getTransactionFromOrToAttr('from', options.web3Context, undefined, options.privateKey); + } + // TODO: Debug why need to typecase getTransactionNonce + if (isNullish(populatedTransaction.nonce)) { + populatedTransaction.nonce = yield getTransactionNonce(options.web3Context, populatedTransaction.from, ETH_DATA_FORMAT); + } + if (isNullish(populatedTransaction.value)) { + populatedTransaction.value = '0x0'; + } + if (!isNullish(populatedTransaction.data)) { + if (!isNullish(populatedTransaction.input) && + populatedTransaction.data !== populatedTransaction.input) + throw new TransactionDataAndInputError({ + data: bytesToHex(populatedTransaction.data), + input: bytesToHex(populatedTransaction.input), + }); + if (!populatedTransaction.data.startsWith('0x')) + populatedTransaction.data = `0x${populatedTransaction.data}`; + } + else if (!isNullish(populatedTransaction.input)) { + if (!populatedTransaction.input.startsWith('0x')) + populatedTransaction.input = `0x${populatedTransaction.input}`; + } + else { + populatedTransaction.input = '0x'; + } + if (isNullish(populatedTransaction.common)) { + if (options.web3Context.defaultCommon) { + const common = options.web3Context.defaultCommon; + const chainId = common.customChain.chainId; + const networkId = common.customChain.networkId; + const name = common.customChain.name; + populatedTransaction.common = Object.assign(Object.assign({}, common), { customChain: { chainId, networkId, name } }); + } + if (isNullish(populatedTransaction.chain)) { + populatedTransaction.chain = options.web3Context.defaultChain; + } + if (isNullish(populatedTransaction.hardfork)) { + populatedTransaction.hardfork = options.web3Context.defaultHardfork; + } + } + if (isNullish(populatedTransaction.chainId) && + isNullish((_a = populatedTransaction.common) === null || _a === void 0 ? void 0 : _a.customChain.chainId)) { + populatedTransaction.chainId = yield getChainId(options.web3Context, ETH_DATA_FORMAT); + } + if (isNullish(populatedTransaction.networkId)) { + populatedTransaction.networkId = + (_b = options.web3Context.defaultNetworkId) !== null && _b !== void 0 ? _b : (yield getId(options.web3Context, ETH_DATA_FORMAT)); + } + if (isNullish(populatedTransaction.gasLimit) && !isNullish(populatedTransaction.gas)) { + populatedTransaction.gasLimit = populatedTransaction.gas; + } + populatedTransaction.type = getTransactionType(populatedTransaction, options.web3Context); + if (isNullish(populatedTransaction.accessList) && + (populatedTransaction.type === '0x1' || populatedTransaction.type === '0x2')) { + populatedTransaction.accessList = []; + } + if (options.fillGasPrice) + populatedTransaction = Object.assign(Object.assign({}, populatedTransaction), (yield getTransactionGasPricing(populatedTransaction, options.web3Context, ETH_DATA_FORMAT))); + if (isNullish(populatedTransaction.gas) && + isNullish(populatedTransaction.gasLimit) && + options.fillGasLimit) { + const fillGasLimit = yield estimateGas(options.web3Context, populatedTransaction, 'latest', ETH_DATA_FORMAT); + populatedTransaction = Object.assign(Object.assign({}, populatedTransaction), { gas: format({ format: 'uint' }, fillGasLimit, ETH_DATA_FORMAT) }); + } + return populatedTransaction; + }); +} +export const transactionBuilder = (options) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + return ((_a = options.web3Context.transactionBuilder) !== null && _a !== void 0 ? _a : defaultTransactionBuilder)(Object.assign(Object.assign({}, options), { transaction: options.transaction })); +}); +//# sourceMappingURL=transaction_builder.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/transaction_builder.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/transaction_builder.js.map new file mode 100644 index 0000000..f429407 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/transaction_builder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction_builder.js","sourceRoot":"","sources":["../../../src/utils/transaction_builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAcN,qBAAqB,EAErB,eAAe,GACf,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EACN,4BAA4B,EAC5B,8BAA8B,EAC9B,4BAA4B,EAC5B,4BAA4B,EAC5B,0BAA0B,GAC1B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,YAAY,CA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AAW,EAAE,OAAO,CAAC,WAAW,IACN,CAAA;EAAA,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/try_send_transaction.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/try_send_transaction.js new file mode 100644 index 0000000..1e03c8d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/try_send_transaction.js @@ -0,0 +1,42 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { rejectIfTimeout } from 'web3-utils'; +import { TransactionSendTimeoutError } from 'web3-errors'; +// eslint-disable-next-line import/no-cycle +import { rejectIfBlockTimeout } from './reject_if_block_timeout.js'; +/** + * An internal function to send a transaction or throws if sending did not finish during the timeout during the blocks-timeout. + * @param web3Context - the context to read the configurations from + * @param sendTransactionFunc - the function that will send the transaction (could be sendTransaction or sendRawTransaction) + * @param transactionHash - to be used inside the exception message if there will be any exceptions. + * @returns the Promise returned by the `sendTransactionFunc`. + */ +export function trySendTransaction(web3Context, sendTransactionFunc, transactionHash) { + return __awaiter(this, void 0, void 0, function* () { + const [timeoutId, rejectOnTimeout] = rejectIfTimeout(web3Context.transactionSendTimeout, new TransactionSendTimeoutError({ + numberOfSeconds: web3Context.transactionSendTimeout / 1000, + transactionHash, + })); + const [rejectOnBlockTimeout, blockTimeoutResourceCleaner] = yield rejectIfBlockTimeout(web3Context, transactionHash); + try { + // If an error happened here, do not catch it, just clear the resources before raising it to the caller function. + return yield Promise.race([ + sendTransactionFunc(), + rejectOnTimeout, + rejectOnBlockTimeout, // this will throw an error on Transaction Block Timeout + ]); + } + finally { + clearTimeout(timeoutId); + blockTimeoutResourceCleaner.clean(); + } + }); +} +//# sourceMappingURL=try_send_transaction.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/try_send_transaction.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/try_send_transaction.js.map new file mode 100644 index 0000000..505445b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/try_send_transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"try_send_transaction.js","sourceRoot":"","sources":["../../../src/utils/try_send_transaction.ts"],"names":[],"mappings":";;;;;;;;;AAkBA,OAAO,EAAiB,eAAe,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAE1D,2CAA2C;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,UAAgB,kBAAkB,CACvC,WAAyC,EACzC,mBAA0C,EAC1C,eAAuB;;QAEvB,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,GAAG,eAAe,CACnD,WAAW,CAAC,sBAAsB,EAClC,IAAI,2BAA2B,CAAC;YAC/B,eAAe,EAAE,WAAW,CAAC,sBAAsB,GAAG,IAAI;YAC1D,eAAe;SACf,CAAC,CACF,CAAC;QAEF,MAAM,CAAC,oBAAoB,EAAE,2BAA2B,CAAC,GAAG,MAAM,oBAAoB,CACrF,WAAW,EACX,eAAe,CACf,CAAC;QAEF,IAAI;YACH,iHAAiH;YACjH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;gBACzB,mBAAmB,EAAE;gBACrB,eAAe;gBACf,oBAAoB,EAAE,wDAAwD;aAC9E,CAAC,CAAC;SACH;gBAAS;YACT,YAAY,CAAC,SAAS,CAAC,CAAC;YACxB,2BAA2B,CAAC,KAAK,EAAE,CAAC;SACpC;IACF,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/wait_for_transaction_receipt.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/wait_for_transaction_receipt.js new file mode 100644 index 0000000..3133a64 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/wait_for_transaction_receipt.js @@ -0,0 +1,68 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { TransactionPollingTimeoutError } from 'web3-errors'; +// eslint-disable-next-line import/no-cycle +import { pollTillDefinedAndReturnIntervalId, rejectIfTimeout } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { rejectIfBlockTimeout } from './reject_if_block_timeout.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionReceipt } from '../rpc_method_wrappers.js'; +export function waitForTransactionReceipt(web3Context, transactionHash, returnFormat) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const pollingInterval = (_a = web3Context.transactionReceiptPollingInterval) !== null && _a !== void 0 ? _a : web3Context.transactionPollingInterval; + const [awaitableTransactionReceipt, IntervalId] = pollTillDefinedAndReturnIntervalId(() => __awaiter(this, void 0, void 0, function* () { + try { + return getTransactionReceipt(web3Context, transactionHash, returnFormat); + } + catch (error) { + console.warn('An error happen while trying to get the transaction receipt', error); + return undefined; + } + }), pollingInterval); + const [timeoutId, rejectOnTimeout] = rejectIfTimeout(web3Context.transactionPollingTimeout, new TransactionPollingTimeoutError({ + numberOfSeconds: web3Context.transactionPollingTimeout / 1000, + transactionHash, + })); + const [rejectOnBlockTimeout, blockTimeoutResourceCleaner] = yield rejectIfBlockTimeout(web3Context, transactionHash); + try { + // If an error happened here, do not catch it, just clear the resources before raising it to the caller function. + return yield Promise.race([ + awaitableTransactionReceipt, + rejectOnTimeout, + rejectOnBlockTimeout, // this will throw an error on Transaction Block Timeout + ]); + } + finally { + if (timeoutId) + clearTimeout(timeoutId); + if (IntervalId) + clearInterval(IntervalId); + blockTimeoutResourceCleaner.clean(); + } + }); +} +//# sourceMappingURL=wait_for_transaction_receipt.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/wait_for_transaction_receipt.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/wait_for_transaction_receipt.js.map new file mode 100644 index 0000000..b8dc22b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/wait_for_transaction_receipt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wait_for_transaction_receipt.js","sourceRoot":"","sources":["../../../src/utils/wait_for_transaction_receipt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAGF,OAAO,EAAE,8BAA8B,EAAE,MAAM,aAAa,CAAC;AAG7D,2CAA2C;AAC3C,OAAO,EAAE,kCAAkC,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACjF,2CAA2C;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,2CAA2C;AAC3C,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAElE,MAAM,UAAgB,yBAAyB,CAC9C,WAAyC,EACzC,eAAsB,EACtB,YAA0B;;;QAG1B,MAAM,eAAe,GACpB,MAAA,WAAW,CAAC,iCAAiC,mCAAI,WAAW,CAAC,0BAA0B,CAAC;QAEzF,MAAM,CAAC,2BAA2B,EAAE,UAAU,CAAC,GAAG,kCAAkC,CAAC,GAAS,EAAE;YAC/F,IAAI;gBACH,OAAO,qBAAqB,CAAC,WAAW,EAAE,eAAe,EAAE,YAAY,CAAC,CAAC;aACzE;YAAC,OAAO,KAAK,EAAE;gBACf,OAAO,CAAC,IAAI,CAAC,6DAA6D,EAAE,KAAK,CAAC,CAAC;gBACnF,OAAO,SAAS,CAAC;aACjB;QACF,CAAC,CAAA,EAAE,eAAe,CAAC,CAAC;QAEpB,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,GAAG,eAAe,CACnD,WAAW,CAAC,yBAAyB,EACrC,IAAI,8BAA8B,CAAC;YAClC,eAAe,EAAE,WAAW,CAAC,yBAAyB,GAAG,IAAI;YAC7D,eAAe;SACf,CAAC,CACF,CAAC;QAEF,MAAM,CAAC,oBAAoB,EAAE,2BAA2B,CAAC,GAAG,MAAM,oBAAoB,CACrF,WAAW,EACX,eAAe,CACf,CAAC;QAEF,IAAI;YACH,iHAAiH;YACjH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;gBACzB,2BAA2B;gBAC3B,eAAe;gBACf,oBAAoB,EAAE,wDAAwD;aAC9E,CAAC,CAAC;SACH;gBAAS;YACT,IAAG,SAAS;gBACX,YAAY,CAAC,SAAS,CAAC,CAAC;YACzB,IAAG,UAAU;gBACZ,aAAa,CAAC,UAAU,CAAC,CAAC;YAC3B,2BAA2B,CAAC,KAAK,EAAE,CAAC;SACpC;;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_pooling.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_pooling.js new file mode 100644 index 0000000..2ce3349 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_pooling.js @@ -0,0 +1,39 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { format, numberToHex } from 'web3-utils'; +import { ethRpcMethods } from 'web3-rpc-methods'; +import { transactionReceiptSchema } from '../schemas.js'; +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider does not support subscription. + * And it is also used by `watchTransactionBySubscription`, as a fallback, if the subscription failed for any reason. + */ +export const watchTransactionByPolling = ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }) => { + var _a; + // Having a transactionReceipt means that the transaction has already been included + // in at least one block, so we start with 1 + let confirmations = 1; + const intervalId = setInterval(() => { + (() => __awaiter(void 0, void 0, void 0, function* () { + if (confirmations >= web3Context.transactionConfirmationBlocks) + clearInterval(intervalId); + const nextBlock = yield ethRpcMethods.getBlockByNumber(web3Context.requestManager, numberToHex(BigInt(transactionReceipt.blockNumber) + BigInt(confirmations)), false); + if (nextBlock === null || nextBlock === void 0 ? void 0 : nextBlock.hash) { + confirmations += 1; + transactionPromiEvent.emit('confirmation', { + confirmations: format({ format: 'uint' }, confirmations, returnFormat), + receipt: format(transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: format({ format: 'bytes32' }, nextBlock.hash, returnFormat), + }); + } + }))(); + }, (_a = web3Context.transactionReceiptPollingInterval) !== null && _a !== void 0 ? _a : web3Context.transactionPollingInterval); +}; +//# sourceMappingURL=watch_transaction_by_pooling.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_pooling.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_pooling.js.map new file mode 100644 index 0000000..16b2c4b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_pooling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_by_pooling.js","sourceRoot":"","sources":["../../../src/utils/watch_transaction_by_pooling.ts"],"names":[],"mappings":";;;;;;;;;AAkBA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAIjD,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAazD;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAGvC,EACD,WAAW,EACX,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,GAC0B,EAAE,EAAE;;IAC1C,mFAAmF;IACnF,4CAA4C;IAC5C,IAAI,aAAa,GAAG,CAAC,CAAC;IACtB,MAAM,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE;QACnC,CAAC,GAAS,EAAE;YACX,IAAI,aAAa,IAAI,WAAW,CAAC,6BAA6B;gBAC7D,aAAa,CAAC,UAAU,CAAC,CAAC;YAE3B,MAAM,SAAS,GAAG,MAAM,aAAa,CAAC,gBAAgB,CACrD,WAAW,CAAC,cAAc,EAC1B,WAAW,CAAC,MAAM,CAAC,kBAAkB,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC,EAC3E,KAAK,CACL,CAAC;YAEF,IAAI,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,IAAI,EAAE;gBACpB,aAAa,IAAI,CAAC,CAAC;gBAEnB,qBAAqB,CAAC,IAAI,CAAC,cAAc,EAAE;oBAC1C,aAAa,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,YAAY,CAAC;oBACtE,OAAO,EAAE,MAAM,CAAC,wBAAwB,EAAE,kBAAkB,EAAE,YAAY,CAAC;oBAC3E,eAAe,EAAE,MAAM,CACtB,EAAE,MAAM,EAAE,SAAS,EAAE,EACrB,SAAS,CAAC,IAAa,EACvB,YAAY,CACZ;iBACD,CAAC,CAAC;aACH;QACF,CAAC,CAAA,CAAC,EAAa,CAAC;IACjB,CAAC,EAAE,MAAA,WAAW,CAAC,iCAAiC,mCAAI,WAAW,CAAC,0BAA0B,CAAC,CAAC;AAC7F,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_subscription.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_subscription.js new file mode 100644 index 0000000..d0169a2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_subscription.js @@ -0,0 +1,80 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { format } from 'web3-utils'; +import { transactionReceiptSchema } from '../schemas.js'; +import { watchTransactionByPolling } from './watch_transaction_by_pooling.js'; +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider supports subscription. + */ +export const watchTransactionBySubscription = ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }) => { + // The following variable will stay true except if the data arrived, + // or if watching started after an error had occurred. + let needToWatchLater = true; + let lastCaughtBlockHash; + setImmediate(() => { + var _a; + (_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.subscribe('newHeads').then((subscription) => { + subscription.on('data', (newBlockHeader) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + needToWatchLater = false; + if (!(newBlockHeader === null || newBlockHeader === void 0 ? void 0 : newBlockHeader.number) || + // For some cases, the on-data event is fired couple times for the same block! + // This needs investigation but seems to be because of multiple `subscription.on('data'...)` even this should not cause that. + lastCaughtBlockHash === (newBlockHeader === null || newBlockHeader === void 0 ? void 0 : newBlockHeader.parentHash)) { + return; + } + lastCaughtBlockHash = newBlockHeader === null || newBlockHeader === void 0 ? void 0 : newBlockHeader.parentHash; + const confirmations = BigInt(newBlockHeader.number) - + BigInt(transactionReceipt.blockNumber) + + BigInt(1); + transactionPromiEvent.emit('confirmation', { + confirmations: format({ format: 'uint' }, confirmations, returnFormat), + receipt: format(transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: format({ format: 'bytes32' }, newBlockHeader.parentHash, returnFormat), + }); + if (confirmations >= web3Context.transactionConfirmationBlocks) { + yield ((_a = web3Context.subscriptionManager) === null || _a === void 0 ? void 0 : _a.removeSubscription(subscription)); + } + })); + subscription.on('error', () => __awaiter(void 0, void 0, void 0, function* () { + var _b; + yield ((_b = web3Context.subscriptionManager) === null || _b === void 0 ? void 0 : _b.removeSubscription(subscription)); + needToWatchLater = false; + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + })); + }).catch(() => { + needToWatchLater = false; + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + }); + }); + // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds] + setTimeout(() => { + if (needToWatchLater) { + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } + }, web3Context.blockHeaderTimeout * 1000); +}; +//# sourceMappingURL=watch_transaction_by_subscription.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_subscription.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_subscription.js.map new file mode 100644 index 0000000..3b6685c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_by_subscription.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_by_subscription.js","sourceRoot":"","sources":["../../../src/utils/watch_transaction_by_subscription.ts"],"names":[],"mappings":";;;;;;;;;AAiBA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAIpC,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAa,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAEzF;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAG5C,EACD,WAAW,EACX,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,GAC0B,EAAE,EAAE;IAC1C,oEAAoE;IACpE,sDAAsD;IACtD,IAAI,gBAAgB,GAAG,IAAI,CAAC;IAC5B,IAAI,mBAA2B,CAAC;IAChC,YAAY,CAAC,GAAG,EAAE;;QACjB,MAAA,WAAW,CAAC,mBAAmB,0CAC5B,SAAS,CAAC,UAAU,EACrB,IAAI,CAAC,CAAC,YAAkC,EAAE,EAAE;YAC5C,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,CAAO,cAAiC,EAAE,EAAE;;gBACnE,gBAAgB,GAAG,KAAK,CAAC;gBACzB,IACC,CAAC,CAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,MAAM,CAAA;oBACvB,8EAA8E;oBAC9E,6HAA6H;oBAC7H,mBAAmB,MAAK,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,UAAU,CAAA,EACjD;oBACD,OAAO;iBACP;gBACD,mBAAmB,GAAG,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,UAAoB,CAAC;gBAE3D,MAAM,aAAa,GAClB,MAAM,CAAC,cAAc,CAAC,MA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gBACX,kBAAkB;gBAClB,qBAAqB;gBACrB,YAAY;aACZ,CAAC,CAAC;SACH;IACF,CAAC,EAAE,WAAW,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;AAC3C,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_for_confirmations.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_for_confirmations.js new file mode 100644 index 0000000..446bf07 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_for_confirmations.js @@ -0,0 +1,41 @@ +import { format } from 'web3-utils'; +import { isNullish } from 'web3-validator'; +import { TransactionMissingReceiptOrBlockHashError, TransactionReceiptMissingBlockNumberError, } from 'web3-errors'; +import { transactionReceiptSchema } from '../schemas.js'; +import { watchTransactionByPolling, } from './watch_transaction_by_pooling.js'; +import { watchTransactionBySubscription } from './watch_transaction_by_subscription.js'; +export function watchTransactionForConfirmations(web3Context, transactionPromiEvent, transactionReceipt, transactionHash, returnFormat) { + if (isNullish(transactionReceipt) || isNullish(transactionReceipt.blockHash)) + throw new TransactionMissingReceiptOrBlockHashError({ + receipt: transactionReceipt, + blockHash: format({ format: 'bytes32' }, transactionReceipt === null || transactionReceipt === void 0 ? void 0 : transactionReceipt.blockHash, returnFormat), + transactionHash: format({ format: 'bytes32' }, transactionHash, returnFormat), + }); + if (!transactionReceipt.blockNumber) + throw new TransactionReceiptMissingBlockNumberError({ receipt: transactionReceipt }); + // As we have the receipt, it's the first confirmation that tx is accepted. + transactionPromiEvent.emit('confirmation', { + confirmations: format({ format: 'uint' }, 1, returnFormat), + receipt: format(transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: format({ format: 'bytes32' }, transactionReceipt.blockHash, returnFormat), + }); + // so a subscription for newBlockHeaders can be made instead of polling + const provider = web3Context.requestManager.provider; + if (provider && 'supportsSubscriptions' in provider && provider.supportsSubscriptions()) { + watchTransactionBySubscription({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } + else { + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } +} +//# sourceMappingURL=watch_transaction_for_confirmations.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_for_confirmations.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_for_confirmations.js.map new file mode 100644 index 0000000..7163766 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/utils/watch_transaction_for_confirmations.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_for_confirmations.js","sourceRoot":"","sources":["../../../src/utils/watch_transaction_for_confirmations.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EACN,yCAAyC,EACzC,yCAAyC,GACzC,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EACN,yBAAyB,GAEzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAExF,MAAM,UAAU,gCAAgC,CAK/C,WAAyC,EACzC,qBAA2E,EAC3E,kBAAsC,EACtC,eAAsB,EACtB,YAA0B;IAE1B,IAAI,SAAS,CAAC,kBAAkB,CAAC,IAAI,SAAS,CAAC,kBAAkB,CAAC,SAAS,CAAC;QAC3E,MAAM,IAAI,yCAAyC,CAAC;YACnD,OAAO,EAAE,kBAAkB;YAC3B,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAE,SAAS,EAAE,YAAY,CAAC;YACrF,eAAe,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,eAAe,EAAE,YAAY,CAAC;SAC7E,CAAC,CAAC;IAEJ,IAAI,CAAC,kBAAkB,CAAC,WAAW;QAClC,MAAM,IAAI,yCAAyC,CAAC,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAEtF,2EAA2E;IAC3E,qBAAqB,CAAC,IAAI,CAAC,cAAc,EAAE;QAC1C,aAAa,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,YAAY,CAAC;QAC1D,OAAO,EAAE,MAAM,CAAC,wBAAwB,EAAE,kBAAkB,EAAE,YAAY,CAAC;QAC3E,eAAe,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,kBAAkB,CAAC,SAAS,EAAE,YAAY,CAAC;KAC1F,CAAC,CAAC;IAEH,uEAAuE;IACvE,MAAM,QAAQ,GAAqB,WAAW,CAAC,cAAc,CAAC,QAA4B,CAAC;IAC3F,IAAI,QAAQ,IAAI,uBAAuB,IAAI,QAAQ,IAAI,QAAQ,CAAC,qBAAqB,EAAE,EAAE;QACxF,8BAA8B,CAAC;YAC9B,WAAW;YACX,kBAAkB;YAClB,qBAAqB;YACrB,YAAY;SACZ,CAAC,CAAC;KACH;SAAM;QACN,yBAAyB,CAAC;YACzB,WAAW;YACX,kBAAkB;YAClB,qBAAqB;YACrB,YAAY;SACZ,CAAC,CAAC;KACH;AACF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/validation.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/validation.js new file mode 100644 index 0000000..b899443 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/validation.js @@ -0,0 +1,258 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { ETH_DATA_FORMAT, } from 'web3-types'; +import { isAddress, isHexStrict, isHexString32Bytes, isNullish, isUInt } from 'web3-validator'; +import { ChainMismatchError, HardforkMismatchError, ChainIdMismatchError, CommonOrChainAndHardforkError, Eip1559GasPriceError, InvalidGasOrGasPrice, InvalidMaxPriorityFeePerGasOrMaxFeePerGas, InvalidNonceOrChainIdError, InvalidTransactionCall, InvalidTransactionObjectError, InvalidTransactionWithSender, MissingChainOrHardforkError, MissingCustomChainError, MissingCustomChainIdError, MissingGasError, TransactionGasMismatchError, UnsupportedFeeMarketError, } from 'web3-errors'; +import { formatTransaction } from './utils/format_transaction.js'; +export function isBaseTransaction(value) { + if (!isNullish(value.to) && !isAddress(value.to)) + return false; + if (!isHexStrict(value.type) && !isNullish(value.type) && value.type.length !== 2) + return false; + if (!isHexStrict(value.nonce)) + return false; + if (!isHexStrict(value.gas)) + return false; + if (!isHexStrict(value.value)) + return false; + if (!isHexStrict(value.input)) + return false; + if (value.chainId && !isHexStrict(value.chainId)) + return false; + return true; +} +export function isAccessListEntry(value) { + if (!isNullish(value.address) && !isAddress(value.address)) + return false; + if (!isNullish(value.storageKeys) && + !value.storageKeys.every(storageKey => isHexString32Bytes(storageKey))) + return false; + return true; +} +export function isAccessList(value) { + if (!Array.isArray(value) || + !value.every(accessListEntry => isAccessListEntry(accessListEntry))) + return false; + return true; +} +export function isTransaction1559Unsigned(value) { + if (!isBaseTransaction(value)) + return false; + if (!isHexStrict(value.maxFeePerGas)) + return false; + if (!isHexStrict(value.maxPriorityFeePerGas)) + return false; + if (!isAccessList(value.accessList)) + return false; + return true; +} +export function isTransaction2930Unsigned(value) { + if (!isBaseTransaction(value)) + return false; + if (!isHexStrict(value.gasPrice)) + return false; + if (!isAccessList(value.accessList)) + return false; + return true; +} +export function isTransactionLegacyUnsigned(value) { + if (!isBaseTransaction(value)) + return false; + if (!isHexStrict(value.gasPrice)) + return false; + return true; +} +export function isTransactionWithSender(value) { + if (!isAddress(value.from)) + return false; + if (!isBaseTransaction(value)) + return false; + if (!isTransaction1559Unsigned(value) && + !isTransaction2930Unsigned(value) && + !isTransactionLegacyUnsigned(value)) + return false; + return true; +} +export function validateTransactionWithSender(value) { + if (!isTransactionWithSender(value)) + throw new InvalidTransactionWithSender(value); +} +export function isTransactionCall(value) { + if (!isNullish(value.from) && !isAddress(value.from)) + return false; + if (!isAddress(value.to)) + return false; + if (!isNullish(value.gas) && !isHexStrict(value.gas)) + return false; + if (!isNullish(value.gasPrice) && !isHexStrict(value.gasPrice)) + return false; + if (!isNullish(value.value) && !isHexStrict(value.value)) + return false; + if (!isNullish(value.data) && !isHexStrict(value.data)) + return false; + if (!isNullish(value.input) && !isHexStrict(value.input)) + return false; + if (!isNullish(value.type)) + return false; + if (isTransaction1559Unsigned(value)) + return false; + if (isTransaction2930Unsigned(value)) + return false; + return true; +} +export function validateTransactionCall(value) { + if (!isTransactionCall(value)) + throw new InvalidTransactionCall(value); +} +export const validateCustomChainInfo = (transaction) => { + if (!isNullish(transaction.common)) { + if (isNullish(transaction.common.customChain)) + throw new MissingCustomChainError(); + if (isNullish(transaction.common.customChain.chainId)) + throw new MissingCustomChainIdError(); + if (!isNullish(transaction.chainId) && + transaction.chainId !== transaction.common.customChain.chainId) + throw new ChainIdMismatchError({ + txChainId: transaction.chainId, + customChainId: transaction.common.customChain.chainId, + }); + } +}; +export const validateChainInfo = (transaction) => { + if (!isNullish(transaction.common) && + !isNullish(transaction.chain) && + !isNullish(transaction.hardfork)) { + throw new CommonOrChainAndHardforkError(); + } + if ((!isNullish(transaction.chain) && isNullish(transaction.hardfork)) || + (!isNullish(transaction.hardfork) && isNullish(transaction.chain))) + throw new MissingChainOrHardforkError({ + chain: transaction.chain, + hardfork: transaction.hardfork, + }); +}; +export const validateBaseChain = (transaction) => { + if (!isNullish(transaction.common)) + if (!isNullish(transaction.common.baseChain)) + if (!isNullish(transaction.chain) && + transaction.chain !== transaction.common.baseChain) { + throw new ChainMismatchError({ + txChain: transaction.chain, + baseChain: transaction.common.baseChain, + }); + } +}; +export const validateHardfork = (transaction) => { + if (!isNullish(transaction.common)) + if (!isNullish(transaction.common.hardfork)) + if (!isNullish(transaction.hardfork) && + transaction.hardfork !== transaction.common.hardfork) { + throw new HardforkMismatchError({ + txHardfork: transaction.hardfork, + commonHardfork: transaction.common.hardfork, + }); + } +}; +export const validateLegacyGas = (transaction) => { + if ( + // This check is verifying gas and gasPrice aren't less than 0. + isNullish(transaction.gas) || + !isUInt(transaction.gas) || + isNullish(transaction.gasPrice) || + !isUInt(transaction.gasPrice)) + throw new InvalidGasOrGasPrice({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + }); + if (!isNullish(transaction.maxFeePerGas) || !isNullish(transaction.maxPriorityFeePerGas)) + throw new UnsupportedFeeMarketError({ + maxFeePerGas: transaction.maxFeePerGas, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + }); +}; +export const validateFeeMarketGas = (transaction) => { + // These errors come from 1.x, so they must be checked before + // InvalidMaxPriorityFeePerGasOrMaxFeePerGas to throw the same error + // for the same code executing in 1.x + if (!isNullish(transaction.gasPrice) && transaction.type === '0x2') + throw new Eip1559GasPriceError(transaction.gasPrice); + if (transaction.type === '0x0' || transaction.type === '0x1') + throw new UnsupportedFeeMarketError({ + maxFeePerGas: transaction.maxFeePerGas, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + }); + if (isNullish(transaction.maxFeePerGas) || + !isUInt(transaction.maxFeePerGas) || + isNullish(transaction.maxPriorityFeePerGas) || + !isUInt(transaction.maxPriorityFeePerGas)) + throw new InvalidMaxPriorityFeePerGasOrMaxFeePerGas({ + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); +}; +/** + * This method checks if all required gas properties are present for either + * legacy gas (type 0x0 and 0x1) OR fee market transactions (0x2) + */ +export const validateGas = (transaction) => { + const gasPresent = !isNullish(transaction.gas) || !isNullish(transaction.gasLimit); + const legacyGasPresent = gasPresent && !isNullish(transaction.gasPrice); + const feeMarketGasPresent = gasPresent && + !isNullish(transaction.maxPriorityFeePerGas) && + !isNullish(transaction.maxFeePerGas); + if (!legacyGasPresent && !feeMarketGasPresent) + throw new MissingGasError({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); + if (legacyGasPresent && feeMarketGasPresent) + throw new TransactionGasMismatchError({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); + (legacyGasPresent ? validateLegacyGas : validateFeeMarketGas)(transaction); + (!isNullish(transaction.type) && transaction.type > '0x1' + ? validateFeeMarketGas + : validateLegacyGas)(transaction); +}; +export const validateTransactionForSigning = (transaction, overrideMethod) => { + if (!isNullish(overrideMethod)) { + overrideMethod(transaction); + return; + } + if (typeof transaction !== 'object' || isNullish(transaction)) + throw new InvalidTransactionObjectError(transaction); + validateCustomChainInfo(transaction); + validateChainInfo(transaction); + validateBaseChain(transaction); + validateHardfork(transaction); + const formattedTransaction = formatTransaction(transaction, ETH_DATA_FORMAT); + validateGas(formattedTransaction); + if (isNullish(formattedTransaction.nonce) || + isNullish(formattedTransaction.chainId) || + formattedTransaction.nonce.startsWith('-') || + formattedTransaction.chainId.startsWith('-')) + throw new InvalidNonceOrChainIdError({ + nonce: transaction.nonce, + chainId: transaction.chainId, + }); +}; +//# sourceMappingURL=validation.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/validation.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/validation.js.map new file mode 100644 index 0000000..0de086c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/l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M,IAAI,6BAA6B,CAAC,WAAW,CAAC,CAAC;IAEtD,uBAAuB,CAAC,WAAW,CAAC,CAAC;IACrC,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAC/B,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAC/B,gBAAgB,CAAC,WAAW,CAAC,CAAC;IAE9B,MAAM,oBAAoB,GAAG,iBAAiB,CAAC,WAA0B,EAAE,eAAe,CAAC,CAAC;IAC5F,WAAW,CAAC,oBAAoB,CAAC,CAAC;IAElC,IACC,SAAS,CAAC,oBAAoB,CAAC,KAAK,CAAC;QACrC,SAAS,CAAC,oBAAoB,CAAC,OAAO,CAAC;QACvC,oBAAoB,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;QAC1C,oBAAoB,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QAE5C,MAAM,IAAI,0BAA0B,CAAC;YACpC,KAAK,EAAE,WAAW,CAAC,KAAK;YACxB,OAAO,EAAE,WAAW,CAAC,OAAO;SAC5B,CAAC,CAAC;AACL,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_eth.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_eth.js new file mode 100644 index 0000000..c6a1aa8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_eth.js @@ -0,0 +1,1503 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +// Disabling because returnTypes must be last param to match 1.x params +/* eslint-disable default-param-last */ +import { DEFAULT_RETURN_FORMAT, } from 'web3-types'; +import { isSupportedProvider, Web3Context } from 'web3-core'; +import { TransactionNotFound } from 'web3-errors'; +import { toChecksumAddress, isNullish } from 'web3-utils'; +import { ethRpcMethods } from 'web3-rpc-methods'; +import * as rpcMethodsWrappers from './rpc_method_wrappers.js'; +import { LogsSubscription, NewPendingTransactionsSubscription, NewHeadsSubscription, SyncingSubscription, } from './web3_subscriptions.js'; +export const registeredSubscriptions = { + logs: LogsSubscription, + newPendingTransactions: NewPendingTransactionsSubscription, + newHeads: NewHeadsSubscription, + syncing: SyncingSubscription, + pendingTransactions: NewPendingTransactionsSubscription, + newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x +}; +export class Web3Eth extends Web3Context { + constructor(providerOrContext) { + if (typeof providerOrContext === 'string' || + isSupportedProvider(providerOrContext)) { + super({ + provider: providerOrContext, + registeredSubscriptions, + }); + return; + } + if (providerOrContext.registeredSubscriptions) { + super(providerOrContext); + return; + } + super(Object.assign(Object.assign({}, providerOrContext), { registeredSubscriptions })); + } + /** + * @returns Returns the ethereum protocol version of the node. + * + * ```ts + * web3.eth.getProtocolVersion().then(console.log); + * > "63" + * ``` + */ + getProtocolVersion() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.getProtocolVersion(this.requestManager); + }); + } + // TODO Add returnFormat parameter + /** + * Checks if the node is currently syncing. + * + * @returns Either a {@link SyncingStatusAPI}, or `false`. + * + * ```ts + * web3.eth.isSyncing().then(console.log); + * > { + * startingBlock: 100, + * currentBlock: 312, + * highestBlock: 512, + * knownStates: 234566, + * pulledStates: 123455 + * } + * ``` + */ + isSyncing() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.getSyncing(this.requestManager); + }); + } + // TODO consider adding returnFormat parameter (to format address as bytes) + /** + * @returns Returns the coinbase address to which mining rewards will go. + * + * ```ts + * web3.eth.getCoinbase().then(console.log); + * > "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" + * ``` + */ + getCoinbase() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.getCoinbase(this.requestManager); + }); + } + /** + * Checks whether the node is mining or not. + * + * @returns `true` if the node is mining, otherwise `false`. + * + * ```ts + * web3.eth.isMining().then(console.log); + * > true + * ``` + */ + isMining() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.getMining(this.requestManager); + }); + } + /** + * @deprecated Will be removed in the future, please use {@link Web3Eth.getHashRate} method instead. + * + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashrate().then(console.log); + * > 493736n + * + * web3.eth.getHashrate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashrate(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return this.getHashRate(returnFormat); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashRate().then(console.log); + * > 493736n + * + * web3.eth.getHashRate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashRate(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getHashRate(this, returnFormat); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The gas price determined by the last few blocks median gas price. + * + * ```ts + * web3.eth.getGasPrice().then(console.log); + * > 20000000000n + * + * web3.eth.getGasPrice({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x4a817c800" + * ``` + */ + getGasPrice(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getGasPrice(this, returnFormat); + }); + } + /** + * @returns A list of accounts the node controls (addresses are checksummed). + * + * ```ts + * web3.eth.getAccounts().then(console.log); + * > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"] + * ``` + */ + getAccounts() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const hexAddresses = (_a = (yield ethRpcMethods.getAccounts(this.requestManager))) !== null && _a !== void 0 ? _a : []; + return hexAddresses.map(address => toChecksumAddress(address)); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current block number. + * + * ```ts + * web3.eth.getBlockNumber().then(console.log); + * > 2744n + * + * web3.eth.getBlockNumber({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0xab8" + * ``` + */ + getBlockNumber(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlockNumber(this, returnFormat); + }); + } + /** + * Get the balance of an address at a given block. + * + * @param address The address to get the balance of. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the balance query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current balance for the given address in `wei`. + * + * ```ts + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1000000000000n + * + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > "0xe8d4a51000" + * ``` + */ + getBalance(address, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBalance(this, address, blockNumber, returnFormat); + }); + } + /** + * Get the storage at a specific position of an address. + * + * @param address The address to get the storage from. + * @param storageSlot The index position of the storage. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the storage query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The value in storage at the given position. + * + * ```ts + * web3.eth.getStorageAt("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", 0).then(console.log); + * > "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234" + * + * web3.eth.getStorageAt( + * "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", + * 0, + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(31) [ + * 3, 52, 86, 115, 33, 35, 255, 255, + * 35, 66, 52, 45, 209, 35, 66, 67, + * 67, 36, 35, 66, 52, 253, 35, 79, + * 210, 63, 212, 242, 61, 66, 52 + * ] + * ``` + */ + getStorageAt(address, storageSlot, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getStorageAt(this, address, storageSlot, blockNumber, returnFormat); + }); + } + /** + * Get the code at a specific address. + * + * @param address The address to get the code from. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the code query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The [data](https://ethereum.org/en/developers/docs/transactions/#the-data-field) at the provided `address`. + * + * ```ts + * web3.eth.getCode("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234").then(console.log); + * > "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056" + * + * web3.eth.getCode( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(50) [ + * 96, 1, 96, 0, 128, 53, 129, 26, 129, 129, 129, + * 20, 96, 18, 87, 131, 1, 0, 91, 96, 27, 96, + * 1, 53, 96, 37, 86, 91, 128, 96, 0, 82, 96, + * 32, 96, 0, 242, 91, 96, 0, 96, 7, 130, 2, + * 144, 80, 145, 144, 80, 86 + * ] + * ``` + */ + getCode(address, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getCode(this, address, blockNumber, returnFormat); + }); + } + /** + * Retrieves a {@link Block} matching the provided block number, block hash or block tag. + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param hydrated If specified `true`, the returned block will contain all transactions as objects. If `false` it will only contain transaction hashes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted (does not format transaction objects or hashes). + * @returns A {@link Block} object matching the provided block number or block hash. + * + * ```ts + * web3.eth.getBlock(0).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getBlock( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * false, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getBlock(block = this.defaultBlock, hydrated = false, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlock(this, block, hydrated, returnFormat); + }); + } + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions in the provided block. + * + * ```ts + * web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockTransactionCount(block = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlockTransactionCount(this, block, returnFormat); + }); + } + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of [uncles](https://ethereum.org/en/glossary/#ommer) in the provided block. + * + * ```ts + * web3.eth.getBlockUncleCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockUncleCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockUncleCount(block = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getBlockUncleCount(this, block, returnFormat); + }); + } + /** + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param uncleIndex The index position of the uncle. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A blocks [uncle](https://ethereum.org/en/glossary/#ommer) by a given uncle index position. + * + * ```ts + * web3.eth.getUncle(0, 1).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getUncle( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * 1, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getUncle(block = this.defaultBlock, uncleIndex, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getUncle(this, block, uncleIndex, returnFormat); + }); + } + /** + * @param transactionHash The hash of the desired transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransaction('0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc').then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransaction( + * web3.utils.hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransaction(transactionHash, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield rpcMethodsWrappers.getTransaction(this, transactionHash, returnFormat); + if (!response) + throw new TransactionNotFound(); + return response; + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A list of pending transactions. + * + * ```ts + * web3.eth.getPendingTransactions().then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0n, + * nonce: 1n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2710n, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * + * * web3.eth.getPendingTransactions({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0, + * nonce: 1, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2710, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * ``` + */ + getPendingTransactions(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getPendingTransactions(this, returnFormat); + }); + } + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param transactionIndex The index position of the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransactionFromBlock('0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', 0).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransactionFromBlock( + * hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * 0, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransactionFromBlock(block = this.defaultBlock, transactionIndex, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getTransactionFromBlock(this, block, transactionIndex, returnFormat); + }); + } + /** + * @param transactionHash Hash of the transaction to retrieve the receipt for. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired {@link TransactionReceipt} object. + * + * ```ts + * web3.eth.getTransactionReceipt("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f").then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * + * web3.eth.getTransactionReceipt( + * "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0, + * blockNumber: 2, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000, + * gasUsed: 21000, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1, + * effectiveGasPrice: 2000000000, + * type: 0n + * } + * ``` + */ + getTransactionReceipt(transactionHash, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield rpcMethodsWrappers.getTransactionReceipt(this, transactionHash, returnFormat); + if (!response) + throw new TransactionNotFound(); + return response; + }); + } + /** + * @param address The address to get the number of transactions for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions sent from the provided address. + * + * ```ts + * web3.eth.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getTransactionCount(address, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getTransactionCount(this, address, blockNumber, returnFormat); + }); + } + /** + * @param transaction The {@link Transaction}, {@link TransactionWithFromLocalWalletIndex}, {@link TransactionWithToLocalWalletIndex} or {@link TransactionWithFromAndToLocalWalletIndex} to send. __Note:__ In the `to` and `from` fields when hex strings are used, it is assumed they are addresses, for any other form (number, string number, etc.) it is assumed they are wallet indexes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @param options A configuration object used to change the behavior of the `sendTransaction` method. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const transaction = { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1' + * } + * + * const transactionHash = await web3.eth.sendTransaction(transaction); + * console.log(transactionHash); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).catch(console.log); + * > + * + * // Example using options.ignoreGasPricing = true + * web3.eth.sendTransaction(transaction, undefined, { ignoreGasPricing: true }).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendTransaction(transaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `sent` + * ```ts + * web3.eth.sendTransaction(transaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendTransaction(transaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * - `receipt` + * ```ts + * web3.eth.sendTransaction(transaction).on('receipt', receipt => console.log(receipt)); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendTransaction(transaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * transactionHash: '0xb4a3a35ae0f3e77ef0ff7be42010d948d011b21a4e341072ee18717b67e99ab8', + * transactionIndex: 0n, + * blockNumber: 5n, + * blockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * }, + * latestBlockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendTransaction(transaction).on('error', error => console.log); + * > + * ``` + */ + sendTransaction(transaction, returnFormat = DEFAULT_RETURN_FORMAT, options) { + return rpcMethodsWrappers.sendTransaction(this, transaction, returnFormat, options); + } + /** + * @param transaction Signed transaction in one of the valid {@link Bytes} format. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const signedTransaction = "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * + * const transactionHash = await web3.eth.sendSignedTransaction(signedTransaction); + * console.log(transactionHash); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).then(console.log); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).catch(console.log); + * > + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `sent` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * ``` + * - `receipt` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('receipt', receipt => console.log(receipt)); + * > { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * }, + * latestBlockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('error', error => console.log(error)); + * > + * ``` + */ + sendSignedTransaction(transaction, returnFormat = DEFAULT_RETURN_FORMAT, options) { + return rpcMethodsWrappers.sendSignedTransaction(this, transaction, returnFormat, options); + } + /** + * @param message Data to sign in one of the valid {@link Bytes} format. + * @param address Address to sign data with, can be an address or the index of a local wallet. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The signed `message`. + * + * ```ts + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + * + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.UINT8ARRAY }).then(console.log); + * > Uint8Array(65) [ + * 48, 117, 94, 214, 83, 150, 250, 207, 134, 197, 62, + * 98, 23, 197, 43, 77, 174, 190, 114, 170, 73, 65, + * 216, 150, 53, 64, 157, 228, 201, 199, 249, 70, 109, + * 78, 154, 174, 199, 151, 127, 5, 233, 35, 136, 155, + * 51, 192, 208, 221, 39, 215, 34, 107, 110, 111, 86, + * 206, 115, 116, 101, 197, 207, 208, 75, 228, 0 + * ] + * ``` + * + * // Using an indexed account managed by local Web3 wallet + * web3.eth.sign("0x48656c6c6f20776f726c64", 0).then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + */ + sign(message, address, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.sign(this, message, address, returnFormat); + }); + } + /** + * @param transaction The transaction object to sign. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * gas: '21000', + * gasPrice: await web3Eth.getGasPrice(), + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.signTransaction(transaction).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0n, + * nonce: 1n, + * gasPrice: 1000000001n, + * gas: 21000n, + * value: 1n, + * v: 2710n, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * + * web3.eth.signTransaction(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0, + * nonce: 1, + * gasPrice: 1000000001, + * gas: 21000, + * value: 1, + * v: 2710, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * ``` + */ + signTransaction(transaction, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.signTransaction(this, transaction, returnFormat); + }); + } + // TODO Decide what to do with transaction.to + // https://github.com/ChainSafe/web3.js/pull/4525#issuecomment-982330076 + /** + * Executes a message call within the EVM without creating a transaction. + * It does not publish anything to the blockchain and does not consume any gas. + * + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The returned data of the call, e.g. a smart contract function's return value. + */ + call(transaction, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.call(this, transaction, blockNumber, returnFormat); + }); + } + /** + * Simulates the transaction within the EVM to estimate the amount of gas to be used by the transaction. + * The transaction will not be added to the blockchain, and actual gas usage can vary when interacting + * with a contract as a result of updating the contract's state. + * + * @param transaction The {@link Transaction} object to estimate the gas for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The used gas for the simulated transaction execution. + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.estimateGas(transaction).then(console.log); + * > 21000n + * + * web3.eth.estimateGas(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 21000 + * ``` + */ + estimateGas(transaction, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.estimateGas(this, transaction, blockNumber, returnFormat); + }); + } + /** + * Gets past logs, matching the provided `filter`. + * + * @param filter A {@link Filter} object containing the properties for the desired logs. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns {@link FilterResultsAPI}, an array of {@link Log} objects. + * + * ```ts + * web3.eth.getPastLogs({ + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0n, + * transactionIndex: 0n, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234n, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * + * web3.eth.getPastLogs( + * { + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * ``` + */ + getPastLogs(filter, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getLogs(this, filter, returnFormat); + }); + } + /** + * Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ('target'). + * + * @returns The mining work as an array of strings with the following structure: + * + * String 32 Bytes - at index 0: current block header pow-hash + * String 32 Bytes - at index 1: the seed hash used for the DAG. + * String 32 Bytes - at index 2: the boundary condition ('target'), 2^256 / difficulty. + * + * ```ts + * web3.eth.getWork().then(console.log); + * > [ + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0x5EED00000000000000000000000000005EED0000000000000000000000000000", + * "0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000" + * ] + * ``` + */ + getWork() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.getWork(this.requestManager); + }); + } + /** + * Used for submitting a proof-of-work solution. + * + * @param nonce The nonce found (8 bytes). + * @param hash The header’s pow-hash (32 bytes). + * @param digest The mix digest (32 bytes). + * @returns Returns `true` if the provided solution is valid, otherwise `false`. + * + * ```ts + * web3.eth.submitWork([ + * "0x0000000000000001", + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000" + * ]).then(console.log); + * > true + * ``` + */ + submitWork(nonce, hash, digest) { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.submitWork(this.requestManager, nonce, hash, digest); + }); + } + // TODO - Format addresses + /** + * This method will request/enable the accounts from the current environment and for supporting [EIP 1102](https://eips.ethereum.org/EIPS/eip-1102) + * This method will only work if you’re using the injected provider from a application like Metamask, Status or TrustWallet. + * It doesn’t work if you’re connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvider and IpcProvider). + * For more information about the behavior of this method please read [EIP-1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md): Opt-in account exposure. + * + * @returns An array of enabled accounts. + * + * ```ts + * web3.eth.requestAccounts().then(console.log); + * > ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'] + * ``` + */ + requestAccounts() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.requestAccounts(this.requestManager); + }); + } + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The chain ID of the current connected node as described in the [EIP-695](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md). + * + * ```ts + * web3.eth.getChainId().then(console.log); + * > 61n + * + * web3.eth.getChainId({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 61 + * ``` + */ + getChainId(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getChainId(this, returnFormat); + }); + } + /** + * @returns The current client version. + * + * ```ts + * web3.eth.getNodeInfo().then(console.log); + * > "Mist/v0.9.3/darwin/go1.4.1" + * ``` + */ + getNodeInfo() { + return __awaiter(this, void 0, void 0, function* () { + return ethRpcMethods.getNodeInfo(this.requestManager); + }); + } + /** + * @param address The Address of the account or contract. + * @param storageKeys Array of storage-keys which should be proofed and included. See {@link web3.getStorageAt}. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The account and storage-values of the specified account including the Merkle-proof as described in [EIP-1186](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md). + * + * ```ts + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * "latest" + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0n, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0n, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0n, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0n, + * "proof": [] + * } + * ] + * } + * + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0, + * "proof": [] + * } + * ] + * } + * ``` + */ + getProof(address, storageKeys, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getProof(this, address, storageKeys, blockNumber, returnFormat); + }); + } + // TODO Throwing an error with Geth, but not Infura + // TODO gasUsedRatio and reward not formatting + /** + * @param blockCount Number of blocks in the requested range. Between `1` and `1024` blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. + * @param newestBlock Highest number block of the requested range. + * @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `['0', '25', '50', '75', '100']` or `['0', '0.5', '1', '1.5', '3', '80']` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available. + * The range between `headBlock - 4` and `headBlock` is guaranteed to be available while retrieving data from the `pending` block and older history are optional to support. + * For pre-EIP-1559 blocks the `gasPrice`s are returned as `rewards` and zeroes are returned for the `baseFeePerGas`. + * + * ```ts + * web3.eth.getFeeHistory(4, 'pending', [0, 25, 75, 100]).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621n, + * 21417903463n, + * 19989260230n, + * 17770954829n, + * 18850641304n + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343n, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * + * web3.eth.getFeeHistory(4, BlockTags.LATEST, [0, 25, 75, 100], { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621, + * 21417903463, + * 19989260230, + * 17770954829, + * 18850641304 + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * ``` + */ + getFeeHistory(blockCount, newestBlock = this.defaultBlock, rewardPercentiles, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getFeeHistory(this, blockCount, newestBlock, rewardPercentiles, returnFormat); + }); + } + /** + * This method generates an access list for a transaction. + * + * @param transaction - A transaction object where all properties are optional except `from`, however it's recommended to include the `to` property. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the createAccessList should be formatted. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * @example + * ```ts + * web3.eth.createAccessList({ + * from: '0xDe95305a63302C3aa4d3A9B42654659AeA72b694', + * data: '0x9a67c8b100000000000000000000000000000000000000000000000000000000000004d0', + * gasPrice: '0x3b9aca00', + * gas: '0x3d0900', + * to: '0x940b25304947ae863568B3804434EC77E2160b87' + * }) + * .then(console.log); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList(transaction, blockNumber = this.defaultBlock, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.createAccessList(this, transaction, blockNumber, returnFormat); + }); + } + /** + * This method sends EIP-712 typed data to the RPC provider to be signed. + * + * @param address The address that corresponds with the private key used to sign the typed data. + * @param typedData The EIP-712 typed data object. + * @param useLegacy A boolean flag determining whether the RPC call uses the legacy method `eth_signTypedData` or the newer method `eth_signTypedData_v4` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the signed typed data should be formatted. + * @returns The signed typed data. + */ + signTypedData(address, typedData, useLegacy = false, returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.signTypedData(this, address, typedData, useLegacy, returnFormat); + }); + } + /** + * Lets you subscribe to specific events in the blockchain. + * + * @param name - The subscription you want to subscribe to. + * @param args - Optional additional parameters, depending on the subscription type. + * @returns A subscription object of type {@link RegisteredSubscription}. The object contains: + * - subscription.id: The subscription id, used to identify and unsubscribing the subscription. + * - subscription.subscribe(): Can be used to re-subscribe with the same parameters. + * - subscription.unsubscribe(): Unsubscribes the subscription and returns TRUE in the callback if successful. + * - subscription.args: The subscription arguments, used when re-subscribing. + * + * + * You can use the subscription object to listen on: + * + * - on("data") - Fires on each incoming log with the log object as argument. + * - on("changed") - Fires on each log which was removed from the blockchain. The log will have the additional property "removed: true". + * - on("error") - Fires when an error in the subscription occurs. + * - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id. + * + * @example **Subscribe to Smart Contract events** + * ```ts + * // Subscribe to `logs` + * const logSubscription = web3.eth.subscribe('logs', { + * address: '0x1234567890123456789012345678901234567890', + * topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234'] + * }); + * logSubscription.on('data', (data: any) => console.log(data)); + * logSubscription.on('error', (error: any) => console.log(error)); + * + * ``` + * + * @example **Subscribe to new block headers** + * ```ts + * // Subscribe to `newBlockHeaders` + * const newBlocksSubscription = await web3.eth.subscribe('newBlockHeaders'); + * + * newBlocksSubscription.on('data', async blockhead => { + * console.log('New block header: ', blockhead); + * + * // You do not need the next line, if you like to keep notified for every new block + * await newBlocksSubscription.unsubscribe(); + * console.log('Unsubscribed from new block headers.'); + * }); + * newBlocksSubscription.on('error', error => + * console.log('Error when subscribing to New block header: ', error), + * ); + * ``` + */ + subscribe(name, args, returnFormat = DEFAULT_RETURN_FORMAT) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const subscription = yield ((_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.subscribe(name, args, returnFormat)); + if (subscription instanceof LogsSubscription && + name === 'logs' && + typeof args === 'object' && + !isNullish(args.fromBlock) && + Number.isFinite(Number(args.fromBlock))) { + setImmediate(() => { + this.getPastLogs(args) + .then(logs => { + for (const log of logs) { + subscription._processSubscriptionResult(log); + } + }) + .catch(e => { + subscription._processSubscriptionError(e); + }); + }); + } + return subscription; + }); + } + static shouldClearSubscription({ sub }) { + return !(sub instanceof SyncingSubscription); + } + /** + * Resets subscriptions. + * + * @param notClearSyncing If `true` it keeps the `syncing` subscription. + * @returns A promise to an array of subscription ids that were cleared. + * + * ```ts + * web3.eth.clearSubscriptions().then(console.log); + * > [...] An array of subscription ids that were cleared + * ``` + */ + clearSubscriptions(notClearSyncing = false) { + var _a; + return (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.unsubscribe( + // eslint-disable-next-line + notClearSyncing ? Web3Eth.shouldClearSubscription : undefined); + } +} +//# sourceMappingURL=web3_eth.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_eth.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_eth.js.map new file mode 100644 index 0000000..b210437 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_eth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eth.js","sourceRoot":"","sources":["../../src/web3_eth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,uEAAuE;AACvE,uCAAuC;AAEvC,OAAO,EAkBN,qBAAqB,GAErB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAA0B,MAAM,WAAW,CAAC;AACrF,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,kBAAkB,MAAM,0BAA0B,CAAC;AAE/D,OAAO,EACN,gBAAgB,EAChB,kCAAkC,EAClC,oBAAoB,EACpB,mBAAmB,GACnB,MAAM,yBAAyB,CAAC;AAWjC,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,IAAI,EAAE,gBAAgB;IACtB,sBAAsB,EAAE,kCAAkC;IAC1D,QAAQ,EAAE,oBAAoB;IAC9B,OAAO,EAAE,mBAAmB;IAC5B,mBAAmB,EAAE,kCAAkC;IACvD,eAAe,EAAE,oBAAoB,EAAE,iEAAiE;CACxG,CAAC;AAEF,MAAM,OAAO,OAAQ,SAAQ,WAAwD;IACpF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C,IAAI,CAAC,SAAS,CAAC;gBAC1B,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,EACtC;gBACD,YAAY,CAAC,GAAG,EAAE;oBACjB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;yBACpB,IAAI,CAAC,IAAI,CAAC,EAAE;wBACZ,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;4BACvB,YAAY,CAAC,0BAA0B,CAAC,GAAiB,CAAC,CAAC;yBAC3D;oBACF,CAAC,CAAC;yBACD,KAAK,CAAC,CAAC,CAAC,EAAE;wBACV,YAAY,CAAC,yBAAyB,CAAC,CAAU,CAAC,CAAC;oBACpD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACH;YACD,OAAO,YAAY,CAAC;;KACpB;IAEO,MAAM,CAAC,uBAAuB,CAAC,EAAE,GAAG,EAAoB;QAC/D,OAAO,CAAC,CAAC,GAAG,YAAY,mBAAmB,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;;;;;;OAUG;IACI,kBAAkB,CAAC,eAAe,GAAG,KAAK;;QAChD,OAAO,MAAA,IAAI,CAAC,mBAAmB,0CAAE,WAAW;QAC3C,2BAA2B;QAC3B,eAAe,CAAC,CAAC,CAAC,OAAO,CAAC,uBAAuB,CAAC,CAAC,CAAC,SAAS,CAC7D,CAAC;IACH,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_subscriptions.js b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_subscriptions.js new file mode 100644 index 0000000..126f6a2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_subscriptions.js @@ -0,0 +1,134 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable-next-line max-classes-per-file */ +import { format } from 'web3-utils'; +import { Web3Subscription } from 'web3-core'; +import { blockHeaderSchema, logSchema, syncSchema } from './schemas.js'; +/** + * ## subscribe('logs') + * Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, web3.js will retrieve logs beginning from this point, backfilling the response as necessary. + * + * You can subscribe to logs matching a given filter object, which can take the following parameters: + * - `fromBlock`: (optional, default: 'latest') Integer block number, or `'latest'` for the last mined block or `'pending'`, `'earliest'` for not yet mined transactions. + * - `address`: (optional) Contract address or a list of addresses from which logs should originate. + * - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with `or` options. + * + */ +export class LogsSubscription extends Web3Subscription { + _buildSubscriptionParams() { + return ['logs', this.args]; + } + formatSubscriptionResult(data) { + return format(logSchema, data, super.returnFormat); + } +} +/** + * ## subscribe('pendingTransactions') + * Subscribes to incoming pending transactions. + * + * You can subscribe to pending transactions by calling web3.eth.subscribe('pendingTransactions'). + * @example + * ```ts + * (await web3.eth.subscribe('pendingTransactions')).on('data', console.log); + * ``` + */ +export class NewPendingTransactionsSubscription extends Web3Subscription { + // eslint-disable-next-line + _buildSubscriptionParams() { + return ['newPendingTransactions']; + } + formatSubscriptionResult(data) { + return format({ format: 'string' }, data, super.returnFormat); + } +} +/** + * ## subscribe('newHeads') ( same as subscribe('newBlockHeaders')) + * + * Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain. + * + * The structure of a returned block header is {@link BlockHeaderOutput}: + * @example + * ```ts + * (await web3.eth.subscribe('newHeads')).on( // 'newBlockHeaders' would work as well + * 'data', + * console.log + * ); + * >{ + * parentHash: '0x9e746a1d906b299def98c75b06f714d62dacadd567c7515d76eeaa8c8074c738', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0xe0f04b04861ecfa95e82a9310d6a7ef7aef8d7417f5209c182582bfb98a8e307', + * transactionsRoot: '0x31ab4ea571a9e10d3a19aaed07d190595b1dfa34e03960c04293fec565dea536', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 2n, + * number: 21n, + * gasLimit: 11738125n, + * gasUsed: 830006n, + * timestamp: 1678797237n, + * extraData: '0xd883010b02846765746888676f312e32302e31856c696e757800000000000000e0a6e93cf40e2e71a72e493272210c3f43738ccc7e7d7b14ffd51833797d896c09117e8dc4fbcbc969bd21b42e5af3e276a911524038c001b2109b63b8e0352601', + * nonce: 0n + * } + * ``` + */ +export class NewHeadsSubscription extends Web3Subscription { + // eslint-disable-next-line + _buildSubscriptionParams() { + return ['newHeads']; + } + formatSubscriptionResult(data) { + return format(blockHeaderSchema, data, super.returnFormat); + } +} +/** + * ## subscribe('syncing') + * + * Subscribe to syncing events. This will return `true` when the node is syncing and when it’s finished syncing will return `false`, for the `changed` event. + * @example + * ```ts + * (await web3.eth.subscribe('syncing')).on('changed', console.log); + * > `true` // when syncing + * + * (await web3.eth.subscribe('syncing')).on('data', console.log); + * > { + * startingBlock: 0, + * currentBlock: 0, + * highestBlock: 0, + * pulledStates: 0, + * knownStates: 0 + * } + * ``` + */ +export class SyncingSubscription extends Web3Subscription { + // eslint-disable-next-line + _buildSubscriptionParams() { + return ['syncing']; + } + _processSubscriptionResult(data) { + if (typeof data === 'boolean') { + this.emit('changed', data); + } + else { + const mappedData = Object.fromEntries(Object.entries(data.status).map(([key, value]) => [ + key.charAt(0).toLowerCase() + key.substring(1), + value, + ])); + this.emit('changed', data.syncing); + this.emit('data', format(syncSchema, mappedData, super.returnFormat)); + } + } +} +//# sourceMappingURL=web3_subscriptions.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_subscriptions.js.map b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_subscriptions.js.map new file mode 100644 index 0000000..4ff161a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/esm/web3_subscriptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscriptions.js","sourceRoot":"","sources":["../../src/web3_subscriptions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,mDAAmD;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAWpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAExE;;;;;;;;;GASG;AACH,MAAM,OAAO,gBAAiB,SAAQ,gBASrC;IACU,wBAAwB;QACjC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAES,wBAAwB,CAAC,IAAgB;QAClD,OAAO,MAAM,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IACpD,CAAC;CACD;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,kCAAmC,SAAQ,gBAEtD;IACD,2BAA2B;IACjB,wBAAwB;QACjC,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACnC,CAAC;IAES,wBAAwB,CAAC,IAAY;QAC9C,OAAO,MAAM,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/D,CAAC;CACD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,OAAO,oBAAqB,SAAQ,gBAExC;IACD,2BAA2B;IACjB,wBAAwB;QACjC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrB,CAAC;IAES,wBAAwB,CAAC,IAAuB;QACzD,OAAO,MAAM,CAAC,iBAAiB,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5D,CAAC;CACD;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,mBAAoB,SAAQ,gBAGvC;IACD,2BAA2B;IACjB,wBAAwB;QACjC,OAAO,CAAC,SAAS,CAAC,CAAC;IACpB,CAAC;IAEM,0BAA0B,CAChC,IAKU;QAEV,IAAI,OAAO,IAAI,KAAK,SAAS,EAAE;YAC9B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;SAC3B;aAAM;YACN,MAAM,UAAU,GAAe,MAAM,CAAC,WAAW,CAChD,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;gBACjD,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;gBAC9C,KAAK;aACL,CAAC,CACY,CAAC;YAEhB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YACnC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC;SACtE;IACF,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/constants.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/constants.d.ts new file mode 100644 index 0000000..f3eb3d5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/constants.d.ts @@ -0,0 +1,15 @@ +import { FMT_BYTES, FMT_NUMBER } from 'web3-types'; +export declare const ALL_EVENTS = "ALLEVENTS"; +export declare const ALL_EVENTS_ABI: import("web3-types").AbiBaseFragment & { + readonly name: string; + readonly type: string; + readonly inputs?: readonly import("web3-types").AbiParameter[] | undefined; + readonly anonymous?: boolean | undefined; +} & { + signature: string; +}; +export declare const NUMBER_DATA_FORMAT: { + readonly bytes: FMT_BYTES.HEX; + readonly number: FMT_NUMBER.NUMBER; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/constants.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/constants.d.ts.map new file mode 100644 index 0000000..0dfd34a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAoB,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAErE,eAAO,MAAM,UAAU,cAAc,CAAC;AACtC,eAAO,MAAM,cAAc;;;;;;eAKU,MAAM;CAAE,CAAC;AAE9C,eAAO,MAAM,kBAAkB;;;CAA+D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/index.d.ts new file mode 100644 index 0000000..8126e16 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/index.d.ts @@ -0,0 +1,49 @@ +/** + * The `web3-eth` package allows you to interact with an Ethereum blockchain and Ethereum smart contracts. + * + * To use this package standalone and use its methods use: + * ```ts + * import { Web3Context } from 'web3-core'; + * import { BlockTags } from 'web3-types'; + * import { DEFAULT_RETURN_FORMAT } from 'web3-types'; + * import { getBalance} from 'web3-eth'; + * + * getBalance( + * new Web3Context('http://127.0.0.1:8545'), + * '0x407d73d8a49eeb85d32cf465507dd71d507100c1', + * BlockTags.LATEST, + * DEFAULT_RETURN_FORMAT + * ).then(console.log); + * > 1000000000000n + * ``` + * + * To use this package within the `web3` object use: + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * web3.eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1').then(console.log); + * > 1000000000000n + *``` + * + * With `web3-eth` you can also subscribe (if supported by provider) to events in the Ethereum Blockchain, using the `subscribe` function. See more at the {@link Web3Eth.subscribe} function. + */ +/** + * + */ +import 'setimmediate'; +import { Web3Eth } from './web3_eth.js'; +export * from './web3_eth.js'; +export * from './utils/decoding.js'; +export * from './schemas.js'; +export * from './constants.js'; +export * from './types.js'; +export * from './validation.js'; +export * from './rpc_method_wrappers.js'; +export * from './utils/format_transaction.js'; +export * from './utils/prepare_transaction_for_signing.js'; +export * from './web3_subscriptions.js'; +export { detectTransactionType } from './utils/detect_transaction_type.js'; +export { transactionBuilder } from './utils/transaction_builder.js'; +export default Web3Eth; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/index.d.ts.map new file mode 100644 index 0000000..4932e39 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH;;GAEG;AACH,OAAO,cAAc,CAAC;AAEtB,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,4CAA4C,CAAC;AAC3D,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEpE,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/rpc_method_wrappers.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/rpc_method_wrappers.d.ts new file mode 100644 index 0000000..74e7c25 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/rpc_method_wrappers.d.ts @@ -0,0 +1,479 @@ +import { FormatType, DataFormat, EthExecutionAPI, SignedTransactionInfoAPI, Address, BlockNumberOrTag, Bytes, Filter, Numbers, TransactionReceipt, Transaction, TransactionCall, Web3EthExecutionAPI, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, TransactionForAccessList, Eip712TypedData } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { SendSignedTransactionEvents, SendSignedTransactionOptions, SendTransactionEvents, SendTransactionOptions } from './types.js'; +/** + * View additional documentations here: {@link Web3Eth.getProtocolVersion} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const getProtocolVersion: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.isSyncing} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const isSyncing: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.getCoinbase} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const getCoinbase: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.isMining} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare const isMining: (web3Context: Web3Context) => Promise; +/** + * View additional documentations here: {@link Web3Eth.getHashRate} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getHashRate(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getGasPrice} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getGasPrice(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBlockNumber} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlockNumber(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBalance} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBalance(web3Context: Web3Context, address: Address, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getStorageAt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getStorageAt(web3Context: Web3Context, address: Address, storageSlot: Numbers, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getCode} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getCode(web3Context: Web3Context, address: Address, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlock(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, hydrated: boolean | undefined, returnFormat: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; +}>; +/** + * View additional documentations here: {@link Web3Eth.getBlockTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlockTransactionCount(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getBlockUncleCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getBlockUncleCount(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getUncle} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getUncle(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, uncleIndex: Numbers, returnFormat: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; +}>; +/** + * View additional documentations here: {@link Web3Eth.getTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransaction(web3Context: Web3Context, transactionHash: Bytes, returnFormat: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | undefined>; +/** + * View additional documentations here: {@link Web3Eth.getPendingTransactions} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getPendingTransactions(web3Context: Web3Context, returnFormat: ReturnFormat): Promise<{ + from?: string | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; +}[]>; +/** + * View additional documentations here: {@link Web3Eth.getTransactionFromBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransactionFromBlock(web3Context: Web3Context, block: string | number | bigint | Uint8Array | undefined, transactionIndex: Numbers, returnFormat: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; +} | undefined>; +/** + * View additional documentations here: {@link Web3Eth.getTransactionReceipt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransactionReceipt(web3Context: Web3Context, transactionHash: Bytes, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getTransactionCount(web3Context: Web3Context, address: Address, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.sendTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function sendTransaction>(web3Context: Web3Context, transaction: Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex, returnFormat: ReturnFormat, options?: SendTransactionOptions): Web3PromiEvent>; +/** + * View additional documentations here: {@link Web3Eth.sendSignedTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function sendSignedTransaction>(web3Context: Web3Context, signedTransaction: Bytes, returnFormat: ReturnFormat, options?: SendSignedTransactionOptions): Web3PromiEvent>; +/** + * View additional documentations here: {@link Web3Eth.sign} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function sign(web3Context: Web3Context, message: Bytes, addressOrIndex: Address | number, returnFormat: ReturnFormat): Promise<{ + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; +} | import("web3-types").ByteTypes[ReturnFormat["bytes"]]>; +/** + * View additional documentations here: {@link Web3Eth.signTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function signTransaction(web3Context: Web3Context, transaction: Transaction, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.call} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function call(web3Context: Web3Context, transaction: TransactionCall, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.estimateGas} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function estimateGas(web3Context: Web3Context, transaction: Transaction, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getPastLogs} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getLogs(web3Context: Web3Context, filter: Filter, returnFormat: ReturnFormat): Promise<(string | { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; +})[]>; +/** + * View additional documentations here: {@link Web3Eth.getChainId} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getChainId(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +/** + * View additional documentations here: {@link Web3Eth.getProof} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getProof(web3Context: Web3Context, address: Address, storageKeys: Bytes[], blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise<{ + readonly balance: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly codeHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly storageHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly accountProof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + readonly storageProof: { + readonly key: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly value: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly proof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + }[]; +}>; +/** + * View additional documentations here: {@link Web3Eth.getFeeHistory} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function getFeeHistory(web3Context: Web3Context, blockCount: Numbers, newestBlock: BlockNumberOrTag | undefined, rewardPercentiles: Numbers[], returnFormat: ReturnFormat): Promise<{ + readonly oldestBlock: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly reward: import("web3-types").NumberTypes[ReturnFormat["number"]][][]; + readonly gasUsedRatio: import("web3-types").NumberTypes[ReturnFormat["number"]][]; +}>; +/** + * View additional documentations here: {@link Web3Eth.createAccessList} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function createAccessList(web3Context: Web3Context, transaction: TransactionForAccessList, blockNumber: BlockNumberOrTag | undefined, returnFormat: ReturnFormat): Promise<{ + readonly accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + readonly gasUsed?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; +}>; +/** + * View additional documentations here: {@link Web3Eth.signTypedData} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export declare function signTypedData(web3Context: Web3Context, address: Address, typedData: Eip712TypedData, useLegacy: boolean, returnFormat: ReturnFormat): Promise; +//# sourceMappingURL=rpc_method_wrappers.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/rpc_method_wrappers.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/rpc_method_wrappers.d.ts.map new file mode 100644 index 0000000..1b1f12c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/rpc_method_wrappers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.d.ts","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":"AAmBA,OAAO,EAEN,UAAU,EACV,UAAU,EAEV,eAAe,EACf,wBAAwB,EAExB,OAAO,EAEP,gBAAgB,EAChB,KAAK,EACL,MAAM,EAEN,OAAO,EAMP,kBAAkB,EAClB,WAAW,EACX,eAAe,EACf,mBAAmB,EACnB,mCAAmC,EACnC,iCAAiC,EACjC,wCAAwC,EACxC,wBAAwB,EAExB,eAAe,EACf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAiBxD,OAAO,EACN,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACrB,sBAAsB,EACtB,MAAM,YAAY,CAAC;AAYpB;;;GAGG;AACH,eAAO,MAAM,kBAAkB,gBAAuB,YAAY,eAAe,CAAC,oBACrB,CAAC;AAG9D;;;GAGG;AACH,eAAO,MAAM,SAAS,gBAAuB,YAAY,e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,EAClE,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,UAAU,EAAE,OAAO,EACnB,WAAW,8BAA6C,EACxD,iBAAiB,EAAE,OAAO,EAAE,EAC5B,YAAY,EAAE,YAAY;;;;;GA2B1B;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,YAAY,SAAS,UAAU,EACrE,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,WAAW,EAAE,wBAAwB,EACrC,WAAW,8BAA6C,EACxD,YAAY,EAAE,YAAY;;;;;;GAa1B;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,YAAY,SAAS,UAAU,EAClE,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,eAAe,EAC1B,SAAS,EAAE,OAAO,EAClB,YAAY,EAAE,YAAY,mBAU1B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/schemas.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/schemas.d.ts new file mode 100644 index 0000000..5fa5e9c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/schemas.d.ts @@ -0,0 +1,905 @@ +export declare const accessListItemSchema: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; +}; +export declare const accessListSchema: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; +}; +export declare const accessListResultSchema: { + type: string; + properties: { + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + gasUsed: { + type: string; + }; + }; +}; +export declare const chainSchema: { + type: string; + enum: string[]; +}; +export declare const hardforkSchema: { + type: string; + enum: string[]; +}; +export declare const customChainSchema: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; +}; +export declare const transactionSchema: { + type: string; + properties: { + from: { + format: string; + }; + to: { + oneOf: ({ + format: string; + type?: undefined; + } | { + type: string; + format?: undefined; + })[]; + }; + value: { + format: string; + }; + gas: { + format: string; + }; + gasPrice: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + type: { + format: string; + }; + maxFeePerGas: { + format: string; + }; + maxPriorityFeePerGas: { + format: string; + }; + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + data: { + format: string; + }; + input: { + format: string; + }; + nonce: { + format: string; + }; + chain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + chainId: { + format: string; + }; + networkId: { + format: string; + }; + common: { + type: string; + properties: { + customChain: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; + }; + baseChain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + }; + }; + gasLimit: { + format: string; + }; + v: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + }; +}; +export declare const transactionInfoSchema: { + type: string; + properties: { + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + hash: { + format: string; + }; + transactionIndex: { + format: string; + }; + from: { + format: string; + }; + to: { + oneOf: ({ + format: string; + type?: undefined; + } | { + type: string; + format?: undefined; + })[]; + }; + value: { + format: string; + }; + gas: { + format: string; + }; + gasPrice: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + type: { + format: string; + }; + maxFeePerGas: { + format: string; + }; + maxPriorityFeePerGas: { + format: string; + }; + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + data: { + format: string; + }; + input: { + format: string; + }; + nonce: { + format: string; + }; + gasLimit: { + format: string; + }; + v: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + chain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + chainId: { + format: string; + }; + networkId: { + format: string; + }; + common: { + type: string; + properties: { + customChain: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; + }; + baseChain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + }; + }; + }; +}; +export declare const blockSchema: { + type: string; + properties: { + parentHash: { + format: string; + }; + sha3Uncles: { + format: string; + }; + miner: { + format: string; + }; + stateRoot: { + format: string; + }; + transactionsRoot: { + format: string; + }; + receiptsRoot: { + format: string; + }; + logsBloom: { + format: string; + }; + difficulty: { + format: string; + }; + number: { + format: string; + }; + gasLimit: { + format: string; + }; + gasUsed: { + format: string; + }; + timestamp: { + format: string; + }; + extraData: { + format: string; + }; + mixHash: { + format: string; + }; + nonce: { + format: string; + }; + totalDifficulty: { + format: string; + }; + baseFeePerGas: { + format: string; + }; + size: { + format: string; + }; + transactions: { + oneOf: ({ + type: string; + items: { + type: string; + properties: { + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + hash: { + format: string; + }; + transactionIndex: { + format: string; + }; + from: { + format: string; + }; + to: { + oneOf: ({ + format: string; + type?: undefined; + } | { + type: string; + format?: undefined; + })[]; + }; + value: { + format: string; + }; + gas: { + format: string; + }; + gasPrice: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + type: { + format: string; + }; + maxFeePerGas: { + format: string; + }; + maxPriorityFeePerGas: { + format: string; + }; + accessList: { + type: string; + items: { + type: string; + properties: { + address: { + format: string; + }; + storageKeys: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + data: { + format: string; + }; + input: { + format: string; + }; + nonce: { + format: string; + }; + gasLimit: { + format: string; + }; + v: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + chain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + chainId: { + format: string; + }; + networkId: { + format: string; + }; + common: { + type: string; + properties: { + customChain: { + type: string; + properties: { + name: { + format: string; + }; + networkId: { + format: string; + }; + chainId: { + format: string; + }; + }; + }; + baseChain: { + type: string; + enum: string[]; + }; + hardfork: { + type: string; + enum: string[]; + }; + }; + }; + }; + format?: undefined; + }; + } | { + type: string; + items: { + format: string; + }; + })[]; + }; + uncles: { + type: string; + items: { + format: string; + }; + }; + hash: { + format: string; + }; + }; +}; +export declare const withdrawalsSchema: { + type: string; + properties: { + index: { + format: string; + }; + validatorIndex: { + format: string; + }; + address: { + format: string; + }; + amount: { + format: string; + }; + }; +}; +export declare const blockHeaderSchema: { + type: string; + properties: { + author: { + format: string; + }; + hash: { + format: string; + }; + parentHash: { + format: string; + }; + receiptsRoot: { + format: string; + }; + miner: { + format: string; + }; + stateRoot: { + format: string; + }; + transactionsRoot: { + format: string; + }; + withdrawalsRoot: { + format: string; + }; + logsBloom: { + format: string; + }; + difficulty: { + format: string; + }; + totalDifficulty: { + format: string; + }; + number: { + format: string; + }; + gasLimit: { + format: string; + }; + gasUsed: { + format: string; + }; + timestamp: { + format: string; + }; + extraData: { + format: string; + }; + nonce: { + format: string; + }; + sha3Uncles: { + format: string; + }; + size: { + format: string; + }; + baseFeePerGas: { + format: string; + }; + excessDataGas: { + format: string; + }; + mixHash: { + format: string; + }; + transactions: { + type: string; + items: { + format: string; + }; + }; + uncles: { + type: string; + items: { + format: string; + }; + }; + withdrawals: { + type: string; + items: { + type: string; + properties: { + index: { + format: string; + }; + validatorIndex: { + format: string; + }; + address: { + format: string; + }; + amount: { + format: string; + }; + }; + }; + }; + }; +}; +export declare const logSchema: { + type: string; + properties: { + removed: { + format: string; + }; + logIndex: { + format: string; + }; + transactionIndex: { + format: string; + }; + transactionHash: { + format: string; + }; + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + address: { + format: string; + }; + data: { + format: string; + }; + topics: { + type: string; + items: { + format: string; + }; + }; + }; +}; +export declare const syncSchema: { + type: string; + properties: { + startingBlock: { + format: string; + }; + currentBlock: { + format: string; + }; + highestBlock: { + format: string; + }; + knownStates: { + format: string; + }; + pulledStates: { + format: string; + }; + }; +}; +export declare const transactionReceiptSchema: { + type: string; + properties: { + transactionHash: { + format: string; + }; + transactionIndex: { + format: string; + }; + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + from: { + format: string; + }; + to: { + format: string; + }; + cumulativeGasUsed: { + format: string; + }; + gasUsed: { + format: string; + }; + effectiveGasPrice: { + format: string; + }; + contractAddress: { + format: string; + }; + logs: { + type: string; + items: { + type: string; + properties: { + removed: { + format: string; + }; + logIndex: { + format: string; + }; + transactionIndex: { + format: string; + }; + transactionHash: { + format: string; + }; + blockHash: { + format: string; + }; + blockNumber: { + format: string; + }; + address: { + format: string; + }; + data: { + format: string; + }; + topics: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + logsBloom: { + format: string; + }; + root: { + format: string; + }; + status: { + format: string; + }; + type: { + format: string; + }; + }; +}; +export declare const SignatureObjectSchema: { + type: string; + properties: { + messageHash: { + format: string; + }; + r: { + format: string; + }; + s: { + format: string; + }; + v: { + format: string; + }; + message: { + format: string; + }; + signature: { + format: string; + }; + }; +}; +export declare const feeHistorySchema: { + type: string; + properties: { + oldestBlock: { + format: string; + }; + baseFeePerGas: { + type: string; + items: { + format: string; + }; + }; + reward: { + type: string; + items: { + type: string; + items: { + format: string; + }; + }; + }; + gasUsedRatio: { + type: string; + items: { + type: string; + }; + }; + }; +}; +export declare const storageProofSchema: { + type: string; + properties: { + key: { + format: string; + }; + value: { + format: string; + }; + proof: { + type: string; + items: { + format: string; + }; + }; + }; +}; +export declare const accountSchema: { + type: string; + properties: { + balance: { + format: string; + }; + codeHash: { + format: string; + }; + nonce: { + format: string; + }; + storageHash: { + format: string; + }; + accountProof: { + type: string; + items: { + format: string; + }; + }; + storageProof: { + type: string; + items: { + type: string; + properties: { + key: { + format: string; + }; + value: { + format: string; + }; + proof: { + type: string; + items: { + format: string; + }; + }; + }; + }; + }; + }; +}; +//# sourceMappingURL=schemas.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/schemas.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/schemas.d.ts.map new file mode 100644 index 0000000..f3cca8a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/schemas.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/schemas.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;CAahC,CAAC;AAEF,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;CAK5B,CAAC;AAEF,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;CAUlC,CAAC;AAEF,eAAO,MAAM,WAAW;;;CAGvB,CAAC;AAEF,eAAO,MAAM,cAAc;;;CAmB1B,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;CAa7B,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2E7B,CAAC;AAEF,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoEjC,CAAC;AAEF,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmFvB,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;CAgB7B,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwF7B,CAAC;AAEF,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCrB,CAAC;AACF,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;CAmBtB,CAAC;AAEF,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDpC,CAAC;AAEF,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;CAsBjC,CAAC;AACF,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4B5B,CAAC;AAEF,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;CAgB9B,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BzB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/types.d.ts new file mode 100644 index 0000000..31b026b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/types.d.ts @@ -0,0 +1,40 @@ +import { ContractExecutionError, TransactionRevertedWithoutReasonError, TransactionRevertInstructionError, TransactionRevertWithCustomError, InvalidResponseError } from 'web3-errors'; +import { FormatType, ETH_DATA_FORMAT, DataFormat, Bytes, ContractAbi, HexString, Numbers, Transaction, TransactionReceipt } from 'web3-types'; +export declare type InternalTransaction = FormatType; +export declare type SendTransactionEventsBase = { + sending: FormatType; + sent: FormatType; + transactionHash: FormatType; + receipt: FormatType; + confirmation: { + confirmations: FormatType; + receipt: FormatType; + latestBlockHash: FormatType; + }; + error: TransactionRevertedWithoutReasonError> | TransactionRevertInstructionError> | TransactionRevertWithCustomError> | InvalidResponseError | ContractExecutionError; +}; +export declare type SendTransactionEvents = SendTransactionEventsBase; +export declare type SendSignedTransactionEvents = SendTransactionEventsBase; +export interface SendTransactionOptions { + ignoreGasPricing?: boolean; + transactionResolver?: (receipt: TransactionReceipt) => ResolveType; + contractAbi?: ContractAbi; + checkRevertBeforeSending?: boolean; + ignoreFillingGasLimit?: boolean; +} +export interface SendSignedTransactionOptions { + transactionResolver?: (receipt: TransactionReceipt) => ResolveType; + contractAbi?: ContractAbi; + checkRevertBeforeSending?: boolean; +} +export interface RevertReason { + reason: string; + signature?: HexString; + data?: HexString; +} +export interface RevertReasonWithCustomError extends RevertReason { + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/types.d.ts.map new file mode 100644 index 0000000..b6cf852 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,sBAAsB,EACtB,qCAAqC,EACrC,iCAAiC,EACjC,gCAAgC,EAChC,oBAAoB,EACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,UAAU,EACV,eAAe,EACf,UAAU,EACV,KAAK,EACL,WAAW,EACX,SAAS,EACT,OAAO,EACP,WAAW,EACX,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAEpB,oBAAY,mBAAmB,GAAG,UAAU,CAAC,WAAW,EAAE,OAAO,eAAe,CAAC,CAAC;AAElF,oBAAY,yBAAyB,CAAC,YAAY,SAAS,UAAU,EAAE,MAAM,IAAI;IA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,GAAG,kBAAkB;IAC7E,mBAAmB,CAAC,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,WAAW,CAAC;IACnE,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,wBAAwB,CAAC,EAAE,OAAO,CAAC;CACnC;AAED,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,IAAI,CAAC,EAAE,SAAS,CAAC;CACjB;AAED,MAAM,WAAW,2BAA4B,SAAQ,YAAY;IAChE,eAAe,EAAE,MAAM,CAAC;IACxB,2BAA2B,EAAE,MAAM,CAAC;IACpC,oBAAoB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC9C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decode_signed_transaction.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decode_signed_transaction.d.ts new file mode 100644 index 0000000..1b77ffe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decode_signed_transaction.d.ts @@ -0,0 +1,12 @@ +import { DataFormat, HexStringBytes, SignedTransactionInfoAPI } from 'web3-types'; +/** + * Decodes an [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded transaction. + * + * @param encodedSignedTransaction The RLP encoded transaction. + * @param returnFormat ({@link DataFormat} Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the RLP encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + */ +export declare function decodeSignedTransaction(encodedSignedTransaction: HexStringBytes, returnFormat: ReturnFormat, options?: { + fillInputAndData?: boolean; +}): SignedTransactionInfoAPI; +//# sourceMappingURL=decode_signed_transaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decode_signed_transaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decode_signed_transaction.d.ts.map new file mode 100644 index 0000000..06b91c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decode_signed_transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_signed_transaction.d.ts","sourceRoot":"","sources":["../../../src/utils/decode_signed_transaction.ts"],"names":[],"mappings":"AAgBA,OAAO,EACN,UAAU,EACV,cAAc,EACd,wBAAwB,EAExB,MAAM,YAAY,CAAC;AAMpB;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,YAAY,SAAS,UAAU,EACtE,wBAAwB,EAAE,cAAc,EACxC,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAgC,GACnE,wBAAwB,CAe1B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decoding.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decoding.d.ts new file mode 100644 index 0000000..dd275ad --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decoding.d.ts @@ -0,0 +1,5 @@ +import { AbiEventFragment, LogsInput, DataFormat, EventLog, ContractAbiWithSignature } from 'web3-types'; +export declare const decodeEventABI: (event: AbiEventFragment & { + signature: string; +}, data: LogsInput, jsonInterface: ContractAbiWithSignature, returnFormat?: DataFormat) => EventLog; +//# sourceMappingURL=decoding.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decoding.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decoding.d.ts.map new file mode 100644 index 0000000..97581bd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/decoding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding.d.ts","sourceRoot":"","sources":["../../../src/utils/decoding.ts"],"names":[],"mappings":"AAmBA,OAAO,EACN,gBAAgB,EAChB,SAAS,EACT,UAAU,EAEV,QAAQ,EACR,wBAAwB,EACxB,MAAM,YAAY,CAAC;AAOpB,eAAO,MAAM,cAAc,UACnB,gBAAgB,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,QACzC,SAAS,0DAED,UAAU,KACtB,QAwDF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/detect_transaction_type.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/detect_transaction_type.d.ts new file mode 100644 index 0000000..c20e0e1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/detect_transaction_type.d.ts @@ -0,0 +1,7 @@ +import { TransactionTypeParser, Web3Context } from 'web3-core'; +import { EthExecutionAPI } from 'web3-types'; +import { InternalTransaction } from '../types.js'; +export declare const defaultTransactionTypeParser: TransactionTypeParser; +export declare const detectTransactionType: (transaction: InternalTransaction, web3Context?: Web3Context) => string | undefined; +export declare const detectRawTransactionType: (transaction: Uint8Array) => string; +//# sourceMappingURL=detect_transaction_type.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/detect_transaction_type.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/detect_transaction_type.d.ts.map new file mode 100644 index 0000000..f6f21de --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/detect_transaction_type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"detect_transaction_type.d.ts","sourceRoot":"","sources":["../../../src/utils/detect_transaction_type.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAkD,MAAM,YAAY,CAAC;AAI7F,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAsDlD,eAAO,MAAM,4BAA4B,EAAE,qBAyD1C,CAAC;AAEF,eAAO,MAAM,qBAAqB,gBACpB,mBAAmB,gBAClB,YAAY,eAAe,CAAC,uBAIzC,CAAC;AAEH,eAAO,MAAM,wBAAwB,gBAAiB,UAAU,WACV,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/format_transaction.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/format_transaction.d.ts new file mode 100644 index 0000000..90a8329 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/format_transaction.d.ts @@ -0,0 +1,8 @@ +import { Transaction, DataFormat, DEFAULT_RETURN_FORMAT, FormatType } from 'web3-types'; +import { ValidationSchemaInput } from 'web3-validator'; +import { transactionSchema } from '../schemas.js'; +export declare function formatTransaction(transaction: TransactionType, returnFormat?: ReturnFormat, options?: { + transactionSchema?: ValidationSchemaInput | typeof transactionSchema; + fillInputAndData?: boolean; +}): FormatType; +//# sourceMappingURL=format_transaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/format_transaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/format_transaction.d.ts.map new file mode 100644 index 0000000..f02304a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/format_transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"format_transaction.d.ts","sourceRoot":"","sources":["../../../src/utils/format_transaction.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxF,OAAO,EAAa,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAIlE,OAAO,EAAyB,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEzE,wBAAgB,iBAAiB,CAChC,YAAY,SAAS,UAAU,GAAG,OAAO,qBAAqB,EAC9D,eAAe,SAAS,WAAW,GAAG,WAAW,EAEjD,WAAW,EAAE,eAAe,EAC5B,YAAY,GAAE,YAAoD,EAClE,OAAO,GAAE;IACR,iBAAiB,CAAC,EAAE,qBAAqB,GAAG,OAAO,iBAAiB,CAAC;IACrE,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAI3B,GACC,UAAU,CAAC,eAAe,EAAE,YAAY,CAAC,CAsC3C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_revert_reason.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_revert_reason.d.ts new file mode 100644 index 0000000..a01b7aa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_revert_reason.d.ts @@ -0,0 +1,13 @@ +import { Web3Context } from 'web3-core'; +import { ContractAbi, DataFormat, DEFAULT_RETURN_FORMAT, EthExecutionAPI, TransactionCall } from 'web3-types'; +import { RevertReason, RevertReasonWithCustomError } from '../types.js'; +export declare const parseTransactionError: (error: unknown, contractAbi?: ContractAbi) => string | RevertReason; +/** + * Returns the revert reason generated by the EVM if the transaction were to be executed. + * + * @param web3Context - ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @returns `undefined` if no revert reason was given, a revert reason object, a revert reason string, or an `unknown` error + */ +export declare function getRevertReason(web3Context: Web3Context, transaction: TransactionCall, contractAbi?: ContractAbi, returnFormat?: ReturnFormat): Promise; +//# sourceMappingURL=get_revert_reason.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_revert_reason.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_revert_reason.d.ts.map new file mode 100644 index 0000000..cdcf382 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_revert_reason.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"get_revert_reason.d.ts","sourceRoot":"","sources":["../../../src/utils/get_revert_reason.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAGxC,OAAO,EAEN,WAAW,EACX,UAAU,EACV,qBAAqB,EACrB,eAAe,EACf,eAAe,EACf,MAAM,YAAY,CAAC;AAIpB,OAAO,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAExE,eAAO,MAAM,qBAAqB,UAAW,OAAO,gBAAgB,WAAW,0BAqC9E,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,eAAe,CACpC,YAAY,SAAS,UAAU,GAAG,OAAO,qBAAqB,EAE9D,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,WAAW,EAAE,eAAe,EAC5B,WAAW,CAAC,EAAE,WAAW,EACzB,YAAY,GAAE,YAAoD,GAChE,OAAO,CAAC,SAAS,GAAG,YAAY,GAAG,2BAA2B,GAAG,MAAM,CAAC,CAO1E"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_error.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_error.d.ts new file mode 100644 index 0000000..ab3d9f4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_error.d.ts @@ -0,0 +1,153 @@ +import { Web3Context } from 'web3-core'; +import { TransactionRevertedWithoutReasonError, TransactionRevertInstructionError, TransactionRevertWithCustomError } from 'web3-errors'; +import { DataFormat, FormatType, ContractAbi, TransactionCall, TransactionReceipt } from 'web3-types'; +import { RevertReason, RevertReasonWithCustomError } from '../types.js'; +export declare function getTransactionError(web3Context: Web3Context, transactionFormatted?: TransactionCall, transactionReceiptFormatted?: FormatType, receivedError?: unknown, contractAbi?: ContractAbi, knownReason?: string | RevertReason | RevertReasonWithCustomError): Promise | TransactionRevertInstructionError<{ + readonly transactionHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly blockHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly blockNumber: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly from: string; + readonly to: string; + readonly cumulativeGasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly effectiveGasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly contractAddress?: string | undefined; + readonly logs: { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; + }[]; + readonly logsBloom: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly root: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly status: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + events?: { + [x: string]: { + readonly event: string; + readonly id?: string | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: string | undefined; + readonly blockHash?: string | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address: string; + readonly topics: string[]; + readonly data: string; + readonly raw?: { + data: string; + topics: unknown[]; + } | undefined; + readonly returnValues: { + [x: string]: unknown; + }; + readonly signature?: string | undefined; + }; + } | undefined; +}> | TransactionRevertWithCustomError<{ + readonly transactionHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly blockHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly blockNumber: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly from: string; + readonly to: string; + readonly cumulativeGasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly effectiveGasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly contractAddress?: string | undefined; + readonly logs: { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; + }[]; + readonly logsBloom: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly root: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly status: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + events?: { + [x: string]: { + readonly event: string; + readonly id?: string | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: string | undefined; + readonly blockHash?: string | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address: string; + readonly topics: string[]; + readonly data: string; + readonly raw?: { + data: string; + topics: unknown[]; + } | undefined; + readonly returnValues: { + [x: string]: unknown; + }; + readonly signature?: string | undefined; + }; + } | undefined; +}>>; +//# sourceMappingURL=get_transaction_error.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_error.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_error.d.ts.map new file mode 100644 index 0000000..2747507 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"get_transaction_error.d.ts","sourceRoot":"","sources":["../../../src/utils/get_transaction_error.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EACN,qCAAqC,EACrC,iCAAiC,EACjC,gCAAgC,EAChC,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,UAAU,EACV,UAAU,EACV,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAIxE,wBAAsB,mBAAmB,CAAC,YAAY,SAAS,UAAU,EACxE,WAAW,EAAE,WAAW,EACxB,oBAAoB,CAAC,EAAE,eAAe,EACtC,2BAA2B,CAAC,EAAE,UAAU,CAAC,kBAAkB,EAAE,YAAY,CAAC,EAC1E,aAAa,CAAC,EAAE,OAAO,EACvB,WAAW,CAAC,EAAE,WAAW,EACzB,WAAW,CAAC,EAAE,MAAM,GAAG,YAAY,GAAG,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoDjE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_gas_pricing.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_gas_pricing.d.ts new file mode 100644 index 0000000..8136a4a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_gas_pricing.d.ts @@ -0,0 +1,9 @@ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Numbers, DataFormat, FormatType } from 'web3-types'; +import { InternalTransaction } from '../types.js'; +export declare function getTransactionGasPricing(transaction: InternalTransaction, web3Context: Web3Context, returnFormat: ReturnFormat): Promise | undefined>; +//# sourceMappingURL=get_transaction_gas_pricing.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_gas_pricing.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_gas_pricing.d.ts.map new file mode 100644 index 0000000..71a91d4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/get_transaction_gas_pricing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"get_transaction_gas_pricing.d.ts","sourceRoot":"","sources":["../../../src/utils/get_transaction_gas_pricing.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EACN,eAAe,EACf,OAAO,EAEP,UAAU,EACV,UAAU,EAEV,MAAM,YAAY,CAAC;AAMpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AA2ClD,wBAAsB,wBAAwB,CAAC,YAAY,SAAS,UAAU,EAC7E,WAAW,EAAE,mBAAmB,EAChC,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,YAAY,EAAE,YAAY,GACxB,OAAO,CACP,UAAU,CACV;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,OAAO,CAAA;CAAE,EAC9E,YAAY,CACX,GACD,SAAS,CACX,CA6BA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/index.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/index.d.ts new file mode 100644 index 0000000..0d33436 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/index.d.ts @@ -0,0 +1,5 @@ +export * from './detect_transaction_type.js'; +export * from './format_transaction.js'; +export * from './prepare_transaction_for_signing.js'; +export * from './transaction_builder.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/index.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/index.d.ts.map new file mode 100644 index 0000000..e083513 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAiBA,cAAc,8BAA8B,CAAC;AAC7C,cAAc,yBAAyB,CAAC;AACxC,cAAc,sCAAsC,CAAC;AACrD,cAAc,0BAA0B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/prepare_transaction_for_signing.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/prepare_transaction_for_signing.d.ts new file mode 100644 index 0000000..f6f9651 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/prepare_transaction_for_signing.d.ts @@ -0,0 +1,4 @@ +import { EthExecutionAPI, HexString, Transaction } from 'web3-types'; +import { Web3Context } from 'web3-core'; +export declare const prepareTransactionForSigning: (transaction: Transaction, web3Context: Web3Context, privateKey?: HexString | Uint8Array, fillGasPrice?: boolean, fillGasLimit?: boolean) => Promise; +//# sourceMappingURL=prepare_transaction_for_signing.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/prepare_transaction_for_signing.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/prepare_transaction_for_signing.d.ts.map new file mode 100644 index 0000000..65da212 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/prepare_transaction_for_signing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prepare_transaction_for_signing.d.ts","sourceRoot":"","sources":["../../../src/utils/prepare_transaction_for_signing.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,eAAe,EACf,SAAS,EAIT,WAAW,EAIX,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AA8FxC,eAAO,MAAM,4BAA4B,gBAC3B,WAAW,eACX,YAAY,eAAe,CAAC,eAC5B,SAAS,GAAG,UAAU,0GAuBnC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/reject_if_block_timeout.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/reject_if_block_timeout.d.ts new file mode 100644 index 0000000..eadb224 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/reject_if_block_timeout.d.ts @@ -0,0 +1,7 @@ +import { EthExecutionAPI, Bytes } from 'web3-types'; +import { Web3Context } from 'web3-core'; +export interface ResourceCleaner { + clean: () => void; +} +export declare function rejectIfBlockTimeout(web3Context: Web3Context, transactionHash?: Bytes): Promise<[Promise, ResourceCleaner]>; +//# sourceMappingURL=reject_if_block_timeout.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/reject_if_block_timeout.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/reject_if_block_timeout.d.ts.map new file mode 100644 index 0000000..b89fe62 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/reject_if_block_timeout.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"reject_if_block_timeout.d.ts","sourceRoot":"","sources":["../../../src/utils/reject_if_block_timeout.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAuC,MAAM,YAAY,CAAC;AACzF,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AASxC,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,MAAM,IAAI,CAAC;CAClB;AAmID,wBAAsB,oBAAoB,CACzC,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,eAAe,CAAC,EAAE,KAAK,GACrB,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,eAAe,CAAC,CAAC,CAc5C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/send_tx_helper.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/send_tx_helper.d.ts new file mode 100644 index 0000000..d3ec3e9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/send_tx_helper.d.ts @@ -0,0 +1,42 @@ +import { FormatType, DataFormat, EthExecutionAPI, Web3BaseWalletAccount, HexString, TransactionReceipt, Transaction, TransactionCall, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, TransactionHash } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { SendSignedTransactionEvents, SendTransactionEvents, SendTransactionOptions } from '../types.js'; +export declare class SendTxHelper, TxType = Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex> { + private readonly web3Context; + private readonly promiEvent; + private readonly options; + private readonly returnFormat; + constructor({ options, web3Context, promiEvent, returnFormat, }: { + web3Context: Web3Context; + options: SendTransactionOptions; + promiEvent: Web3PromiEvent | SendTransactionEvents>; + returnFormat: ReturnFormat; + }); + getReceiptWithEvents(data: TransactionReceipt): ResolveType; + checkRevertBeforeSending(tx: TransactionCall): Promise; + emitSending(tx: TxType | HexString): void; + populateGasPrice({ transactionFormatted, transaction, }: { + transactionFormatted: TxType; + transaction: TxType; + }): Promise; + signAndSend({ wallet, tx, }: { + wallet: Web3BaseWalletAccount | undefined; + tx: TxType; + }): Promise; + emitSent(tx: TxType | HexString): void; + emitTransactionHash(hash: string & Uint8Array): void; + emitReceipt(receipt: ResolveType): void; + handleError({ error, tx }: { + error: unknown; + tx: TransactionCall; + }): Promise; + emitConfirmation({ receipt, transactionHash, }: { + receipt: ResolveType; + transactionHash: TransactionHash; + }): void; + handleResolve({ receipt, tx }: { + receipt: ResolveType; + tx: TransactionCall; + }): Promise; +} +//# sourceMappingURL=send_tx_helper.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/send_tx_helper.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/send_tx_helper.d.ts.map new file mode 100644 index 0000000..a633b64 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/send_tx_helper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"send_tx_helper.d.ts","sourceRoot":"","sources":["../../../src/utils/send_tx_helper.ts"],"names":[],"mappings":"AAgBA,OAAO,EAEN,UAAU,EACV,UAAU,EACV,eAAe,EAEf,qBAAqB,EACrB,SAAS,EACT,kBAAkB,EAClB,WAAW,EACX,eAAe,EACf,mCAAmC,EACnC,iCAAiC,EACjC,wCAAwC,EAExC,eAAe,EAEf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAoB,cAAc,EAAE,MAAM,WAAW,CAAC;AAW1E,OAAO,EACN,2BAA2B,EAC3B,qBAAqB,EACrB,sBAAsB,EACtB,MAAM,aAAa,CAAC;AAcrB,qBAAa,YAAY,CACxB,YAAY,SAAS,UAAU,EAC/B,WAAW,GAAG,UAAU,CAAC,kBAAkB,EAAE,YAAY,CAAC,EAC1D,MAAM,GACH,WAAW,GACX,mCAAmC,GACnC,iCAAiC,GACjC,wCAAwC;IAE3C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA+B;IAC3D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAGzB;IACF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IACF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AAO,EAAE,WAAW,CAAC;QAAC,EAAE,EAAE,eAAe,CAAA;KAAE;CAsBzF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/transaction_builder.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/transaction_builder.d.ts new file mode 100644 index 0000000..7acc1db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/transaction_builder.d.ts @@ -0,0 +1,20 @@ +import { EthExecutionAPI, Address, HexString, Transaction, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, Web3NetAPI, DataFormat, FormatType, ETH_DATA_FORMAT } from 'web3-types'; +import { Web3Context } from 'web3-core'; +export declare const getTransactionFromOrToAttr: (attr: 'from' | 'to', web3Context: Web3Context, transaction?: Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex, privateKey?: HexString | Uint8Array) => Address | undefined; +export declare const getTransactionNonce: (web3Context: Web3Context, address?: Address, returnFormat?: ReturnFormat) => Promise; +export declare const getTransactionType: (transaction: FormatType, web3Context: Web3Context) => string | undefined; +export declare function defaultTransactionBuilder(options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; + fillGasLimit?: boolean; +}): Promise; +export declare const transactionBuilder: (options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; + fillGasLimit?: boolean; +}) => Promise; +//# sourceMappingURL=transaction_builder.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/transaction_builder.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/transaction_builder.d.ts.map new file mode 100644 index 0000000..56b4f91 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/transaction_builder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction_builder.d.ts","sourceRoot":"","sources":["../../../src/utils/transaction_builder.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,eAAe,EACf,OAAO,EACP,SAAS,EAGT,WAAW,EACX,mCAAmC,EACnC,iCAAiC,EACjC,wCAAwC,EAExC,UAAU,EAEV,UAAU,EAEV,UAAU,EACV,eAAe,EACf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAqBxC,eAAO,MAAM,0BAA0B,SAChC,MAAM,GAAG,IAAI,eACN,YAAY,eAAe,CAAC,gBAEtC,WAAW,GACX,mCAAmC,GACnC,iCAAiC,GACjC,wCAAwC,eAC9B,SAAS,GAAG,UAAU,KACjC,OAAO,GAAG,SA+BZ,CAAC;AAEF,eAAO,MAAM,mBAAmB,iDAClB,YAAY,eAAe,CAAC,YAC/B,OAAO,mGASjB,CAAC;AAEF,eAAO,MAAM,kBAAkB,gBACjB,WAAW,WAAW,EAAE,sBAAsB,CAAC,eAC/C,YAAY,eAAe,CAAC,uBAQzC,CAAC;AAIF,wBAAsB,yBAAyB,CAAC,UAAU,GAAG,WAAW,EAAE,OAAO,EAAE;IAClF,WAAW,EAAE,WAAW,CAAC;IACzB,WAAW,EAAE,WAAW,CAAC,eAAe,GAAG,UAAU,CAAC,CAAC;IACvD,UAAU,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;IACpC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB,GAAG,OAAO,CAAC,UAAU,CAAC,CAsHtB;AAED,eAAO,MAAM,kBAAkB,wCACrB;IACR,WAAW,EAAE,WAAW,CAAC;IACzB,WAAW,EAAE,YAAY,eAAe,CAAC,CAAC;IAC1C,UAAU,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;IACpC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB,0BAM0B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/try_send_transaction.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/try_send_transaction.d.ts new file mode 100644 index 0000000..b5c5f6d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/try_send_transaction.d.ts @@ -0,0 +1,12 @@ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Bytes } from 'web3-types'; +import { AsyncFunction } from 'web3-utils'; +/** + * An internal function to send a transaction or throws if sending did not finish during the timeout during the blocks-timeout. + * @param web3Context - the context to read the configurations from + * @param sendTransactionFunc - the function that will send the transaction (could be sendTransaction or sendRawTransaction) + * @param transactionHash - to be used inside the exception message if there will be any exceptions. + * @returns the Promise returned by the `sendTransactionFunc`. + */ +export declare function trySendTransaction(web3Context: Web3Context, sendTransactionFunc: AsyncFunction, transactionHash?: Bytes): Promise; +//# sourceMappingURL=try_send_transaction.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/try_send_transaction.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/try_send_transaction.d.ts.map new file mode 100644 index 0000000..f8b9cd7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/try_send_transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"try_send_transaction.d.ts","sourceRoot":"","sources":["../../../src/utils/try_send_transaction.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,aAAa,EAAmB,MAAM,YAAY,CAAC;AAM5D;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACvC,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,mBAAmB,EAAE,aAAa,CAAC,MAAM,CAAC,EAC1C,eAAe,CAAC,EAAE,KAAK,GACrB,OAAO,CAAC,MAAM,CAAC,CAyBjB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/wait_for_transaction_receipt.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/wait_for_transaction_receipt.d.ts new file mode 100644 index 0000000..053e0cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/wait_for_transaction_receipt.d.ts @@ -0,0 +1,4 @@ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Bytes, TransactionReceipt, DataFormat } from 'web3-types'; +export declare function waitForTransactionReceipt(web3Context: Web3Context, transactionHash: Bytes, returnFormat: ReturnFormat): Promise; +//# sourceMappingURL=wait_for_transaction_receipt.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/wait_for_transaction_receipt.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/wait_for_transaction_receipt.d.ts.map new file mode 100644 index 0000000..d2458cc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/wait_for_transaction_receipt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wait_for_transaction_receipt.d.ts","sourceRoot":"","sources":["../../../src/utils/wait_for_transaction_receipt.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AASpF,wBAAsB,yBAAyB,CAAC,YAAY,SAAS,UAAU,EAC9E,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,eAAe,EAAE,KAAK,EACtB,YAAY,EAAE,YAAY,GACxB,OAAO,CAAC,kBAAkB,CAAC,CAyC7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_pooling.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_pooling.d.ts new file mode 100644 index 0000000..1b20fd4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_pooling.d.ts @@ -0,0 +1,18 @@ +import { EthExecutionAPI, TransactionReceipt } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { DataFormat } from 'web3-types'; +import { SendSignedTransactionEvents, SendTransactionEvents } from '../types.js'; +export declare type Web3PromiEventEventTypeBase = SendTransactionEvents | SendSignedTransactionEvents; +export declare type WaitProps = { + web3Context: Web3Context; + transactionReceipt: TransactionReceipt; + transactionPromiEvent: Web3PromiEvent>; + returnFormat: ReturnFormat; +}; +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider does not support subscription. + * And it is also used by `watchTransactionBySubscription`, as a fallback, if the subscription failed for any reason. + */ +export declare const watchTransactionByPolling: ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }: WaitProps) => void; +//# sourceMappingURL=watch_transaction_by_pooling.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_pooling.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_pooling.d.ts.map new file mode 100644 index 0000000..012d02c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_pooling.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_by_pooling.d.ts","sourceRoot":"","sources":["../../../src/utils/watch_transaction_by_pooling.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAS,eAAe,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAIxD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAGjF,oBAAY,2BAA2B,CAAC,YAAY,SAAS,UAAU,IACpE,qBAAqB,CAAC,YAAY,CAAC,GACnC,2BAA2B,CAAC,YAAY,CAAC,CAAC;AAE7C,oBAAY,SAAS,CAAC,YAAY,SAAS,UAAU,EAAE,WAAW,GAAG,kBAAkB,IAAI;IAC1F,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,CAAC;IAC1C,kBAAkB,EAAE,kBAAkB,CAAC;IACvC,qBAAqB,EAAE,cAAc,CAAC,WAAW,EAAE,2BAA2B,CAAC,YAAY,CAAC,CAAC,CAAC;IAC9F,YAAY,EAAE,YAAY,CAAC;CAC3B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,8LAsCrC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_subscription.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_subscription.d.ts new file mode 100644 index 0000000..efff22e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_subscription.d.ts @@ -0,0 +1,9 @@ +import { TransactionReceipt } from 'web3-types'; +import { DataFormat } from 'web3-types'; +import { WaitProps } from './watch_transaction_by_pooling.js'; +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider supports subscription. + */ +export declare const watchTransactionBySubscription: ({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat, }: WaitProps) => void; +//# sourceMappingURL=watch_transaction_by_subscription.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_subscription.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_subscription.d.ts.map new file mode 100644 index 0000000..cea2046 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_by_subscription.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_by_subscription.d.ts","sourceRoot":"","sources":["../../../src/utils/watch_transaction_by_subscription.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAqC,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAGnF,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAGxC,OAAO,EAAE,SAAS,EAA6B,MAAM,mCAAmC,CAAC;AAEzF;;;GAGG;AACH,eAAO,MAAM,8BAA8B,8LAqF1C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_for_confirmations.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_for_confirmations.d.ts new file mode 100644 index 0000000..6e6b509 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_for_confirmations.d.ts @@ -0,0 +1,6 @@ +import { Bytes, EthExecutionAPI, TransactionReceipt } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { DataFormat } from 'web3-types'; +import { Web3PromiEventEventTypeBase } from './watch_transaction_by_pooling.js'; +export declare function watchTransactionForConfirmations, ResolveType = TransactionReceipt>(web3Context: Web3Context, transactionPromiEvent: Web3PromiEvent, transactionReceipt: TransactionReceipt, transactionHash: Bytes, returnFormat: ReturnFormat): void; +//# sourceMappingURL=watch_transaction_for_confirmations.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_for_confirmations.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_for_confirmations.d.ts.map new file mode 100644 index 0000000..07e556c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/utils/watch_transaction_for_confirmations.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"watch_transaction_for_confirmations.d.ts","sourceRoot":"","sources":["../../../src/utils/watch_transaction_for_confirmations.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,EAAE,eAAe,EAAoB,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAQxD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,OAAO,EAEN,2BAA2B,EAC3B,MAAM,mCAAmC,CAAC;AAG3C,wBAAgB,gCAAgC,CAC/C,YAAY,SAAS,UAAU,EAC/B,uBAAuB,SAAS,2BAA2B,CAAC,YAAY,CAAC,EACzE,WAAW,GAAG,kBAAkB,EAEhC,WAAW,EAAE,WAAW,CAAC,eAAe,CAAC,EACzC,qBAAqB,EAAE,cAAc,CAAC,WAAW,EAAE,uBAAuB,CAAC,EAC3E,kBAAkB,EAAE,kBAAkB,EACtC,eAAe,EAAE,KAAK,EACtB,YAAY,EAAE,YAAY,QAoC1B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/validation.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/validation.d.ts new file mode 100644 index 0000000..446d586 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/validation.d.ts @@ -0,0 +1,25 @@ +import { AccessList, AccessListEntry, BaseTransactionAPI, Transaction1559UnsignedAPI, Transaction2930UnsignedAPI, TransactionCall, TransactionLegacyUnsignedAPI, TransactionWithSenderAPI } from 'web3-types'; +import { InternalTransaction } from './types.js'; +export declare function isBaseTransaction(value: BaseTransactionAPI): boolean; +export declare function isAccessListEntry(value: AccessListEntry): boolean; +export declare function isAccessList(value: AccessList): boolean; +export declare function isTransaction1559Unsigned(value: Transaction1559UnsignedAPI): boolean; +export declare function isTransaction2930Unsigned(value: Transaction2930UnsignedAPI): boolean; +export declare function isTransactionLegacyUnsigned(value: TransactionLegacyUnsignedAPI): boolean; +export declare function isTransactionWithSender(value: TransactionWithSenderAPI): boolean; +export declare function validateTransactionWithSender(value: TransactionWithSenderAPI): void; +export declare function isTransactionCall(value: TransactionCall): boolean; +export declare function validateTransactionCall(value: TransactionCall): void; +export declare const validateCustomChainInfo: (transaction: InternalTransaction) => void; +export declare const validateChainInfo: (transaction: InternalTransaction) => void; +export declare const validateBaseChain: (transaction: InternalTransaction) => void; +export declare const validateHardfork: (transaction: InternalTransaction) => void; +export declare const validateLegacyGas: (transaction: InternalTransaction) => void; +export declare const validateFeeMarketGas: (transaction: InternalTransaction) => void; +/** + * This method checks if all required gas properties are present for either + * legacy gas (type 0x0 and 0x1) OR fee market transactions (0x2) + */ +export declare const validateGas: (transaction: InternalTransaction) => void; +export declare const validateTransactionForSigning: (transaction: InternalTransaction, overrideMethod?: ((transaction: InternalTransaction) => void) | undefined) => void; +//# sourceMappingURL=validation.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/validation.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/validation.d.ts.map new file mode 100644 index 0000000..5a13840 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/validation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/validation.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,UAAU,EACV,eAAe,EACf,kBAAkB,EAClB,0BAA0B,EAC1B,0BAA0B,EAC1B,eAAe,EACf,4BAA4B,EAE5B,wBAAwB,EAExB,MAAM,YAAY,CAAC;AAsBpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAUpE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CASjE;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAQvD;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAOpF;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAMpF;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,4BAA4B,GAAG,OAAO,CAKxF;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAWhF;AAED,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,wBAAwB,QAE5E;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAajE;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,QAE7D;AAED,eAAO,MAAM,uBAAuB,gBAAiB,mBAAmB,SAcvE,CAAC;AACF,eAAO,MAAM,iBAAiB,gBAAiB,mBAAmB,SAgBjE,CAAC;AACF,eAAO,MAAM,iBAAiB,gBAAiB,mBAAmB,SAYjE,CAAC;AACF,eAAO,MAAM,gBAAgB,gBAAiB,mBAAmB,SAYhE,CAAC;AAEF,eAAO,MAAM,iBAAiB,gBAAiB,mBAAmB,SAiBjE,CAAC;AAEF,eAAO,MAAM,oBAAoB,gBAAiB,mBAAmB,SAsBpE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,gBAAiB,mBAAmB,SA4B3D,CAAC;AAEF,eAAO,MAAM,6BAA6B,gBAC5B,mBAAmB,kCACD,mBAAmB,KAAK,IAAI,sBA4B3D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/web3_eth.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_eth.d.ts new file mode 100644 index 0000000..9368191 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_eth.d.ts @@ -0,0 +1,1598 @@ +import { SupportedProviders, Address, Bytes, Filter, HexString32Bytes, HexString8Bytes, Numbers, BlockNumberOrTag, Transaction, TransactionCall, Web3EthExecutionAPI, TransactionWithFromLocalWalletIndex, TransactionWithToLocalWalletIndex, TransactionWithFromAndToLocalWalletIndex, TransactionForAccessList, DataFormat, DEFAULT_RETURN_FORMAT, Eip712TypedData } from 'web3-types'; +import { Web3Context, Web3ContextInitOptions } from 'web3-core'; +import { SendTransactionOptions } from './types.js'; +import { LogsSubscription, NewPendingTransactionsSubscription, NewHeadsSubscription, SyncingSubscription } from './web3_subscriptions.js'; +export declare type RegisteredSubscription = { + logs: typeof LogsSubscription; + newPendingTransactions: typeof NewPendingTransactionsSubscription; + pendingTransactions: typeof NewPendingTransactionsSubscription; + newHeads: typeof NewHeadsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; + syncing: typeof SyncingSubscription; +}; +export declare const registeredSubscriptions: { + logs: typeof LogsSubscription; + newPendingTransactions: typeof NewPendingTransactionsSubscription; + newHeads: typeof NewHeadsSubscription; + syncing: typeof SyncingSubscription; + pendingTransactions: typeof NewPendingTransactionsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; +}; +export declare class Web3Eth extends Web3Context { + constructor(providerOrContext?: SupportedProviders | Web3ContextInitOptions | string); + /** + * @returns Returns the ethereum protocol version of the node. + * + * ```ts + * web3.eth.getProtocolVersion().then(console.log); + * > "63" + * ``` + */ + getProtocolVersion(): Promise; + /** + * Checks if the node is currently syncing. + * + * @returns Either a {@link SyncingStatusAPI}, or `false`. + * + * ```ts + * web3.eth.isSyncing().then(console.log); + * > { + * startingBlock: 100, + * currentBlock: 312, + * highestBlock: 512, + * knownStates: 234566, + * pulledStates: 123455 + * } + * ``` + */ + isSyncing(): Promise; + /** + * @returns Returns the coinbase address to which mining rewards will go. + * + * ```ts + * web3.eth.getCoinbase().then(console.log); + * > "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" + * ``` + */ + getCoinbase(): Promise; + /** + * Checks whether the node is mining or not. + * + * @returns `true` if the node is mining, otherwise `false`. + * + * ```ts + * web3.eth.isMining().then(console.log); + * > true + * ``` + */ + isMining(): Promise; + /** + * @deprecated Will be removed in the future, please use {@link Web3Eth.getHashRate} method instead. + * + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashrate().then(console.log); + * > 493736n + * + * web3.eth.getHashrate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashrate(returnFormat?: ReturnFormat): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashRate().then(console.log); + * > 493736n + * + * web3.eth.getHashRate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + getHashRate(returnFormat?: ReturnFormat): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The gas price determined by the last few blocks median gas price. + * + * ```ts + * web3.eth.getGasPrice().then(console.log); + * > 20000000000n + * + * web3.eth.getGasPrice({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x4a817c800" + * ``` + */ + getGasPrice(returnFormat?: ReturnFormat): Promise; + /** + * @returns A list of accounts the node controls (addresses are checksummed). + * + * ```ts + * web3.eth.getAccounts().then(console.log); + * > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"] + * ``` + */ + getAccounts(): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current block number. + * + * ```ts + * web3.eth.getBlockNumber().then(console.log); + * > 2744n + * + * web3.eth.getBlockNumber({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0xab8" + * ``` + */ + getBlockNumber(returnFormat?: ReturnFormat): Promise; + /** + * Get the balance of an address at a given block. + * + * @param address The address to get the balance of. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the balance query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current balance for the given address in `wei`. + * + * ```ts + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1000000000000n + * + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > "0xe8d4a51000" + * ``` + */ + getBalance(address: Address, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Get the storage at a specific position of an address. + * + * @param address The address to get the storage from. + * @param storageSlot The index position of the storage. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the storage query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The value in storage at the given position. + * + * ```ts + * web3.eth.getStorageAt("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", 0).then(console.log); + * > "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234" + * + * web3.eth.getStorageAt( + * "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", + * 0, + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(31) [ + * 3, 52, 86, 115, 33, 35, 255, 255, + * 35, 66, 52, 45, 209, 35, 66, 67, + * 67, 36, 35, 66, 52, 253, 35, 79, + * 210, 63, 212, 242, 61, 66, 52 + * ] + * ``` + */ + getStorageAt(address: Address, storageSlot: Numbers, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Get the code at a specific address. + * + * @param address The address to get the code from. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the code query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The [data](https://ethereum.org/en/developers/docs/transactions/#the-data-field) at the provided `address`. + * + * ```ts + * web3.eth.getCode("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234").then(console.log); + * > "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056" + * + * web3.eth.getCode( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(50) [ + * 96, 1, 96, 0, 128, 53, 129, 26, 129, 129, 129, + * 20, 96, 18, 87, 131, 1, 0, 91, 96, 27, 96, + * 1, 53, 96, 37, 86, 91, 128, 96, 0, 82, 96, + * 32, 96, 0, 242, 91, 96, 0, 96, 7, 130, 2, + * 144, 80, 145, 144, 80, 86 + * ] + * ``` + */ + getCode(address: Address, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Retrieves a {@link Block} matching the provided block number, block hash or block tag. + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param hydrated If specified `true`, the returned block will contain all transactions as objects. If `false` it will only contain transaction hashes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted (does not format transaction objects or hashes). + * @returns A {@link Block} object matching the provided block number or block hash. + * + * ```ts + * web3.eth.getBlock(0).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getBlock( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * false, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getBlock(block?: HexString32Bytes | BlockNumberOrTag, hydrated?: boolean, returnFormat?: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }>; + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions in the provided block. + * + * ```ts + * web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockTransactionCount(block?: HexString32Bytes | BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of [uncles](https://ethereum.org/en/glossary/#ommer) in the provided block. + * + * ```ts + * web3.eth.getBlockUncleCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockUncleCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getBlockUncleCount(block?: HexString32Bytes | BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param uncleIndex The index position of the uncle. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A blocks [uncle](https://ethereum.org/en/glossary/#ommer) by a given uncle index position. + * + * ```ts + * web3.eth.getUncle(0, 1).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getUncle( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * 1, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + getUncle(block: BlockNumberOrTag | undefined, uncleIndex: Numbers, returnFormat?: ReturnFormat): Promise<{ + readonly parentHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly sha3Uncles: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly miner: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly stateRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly receiptsRoot: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly logsBloom?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly difficulty?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly number: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasLimit: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly gasUsed: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly timestamp: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly extraData: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly mixHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly totalDifficulty: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly size: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly transactions: string[] | { + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly from: string; + readonly hash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]; + readonly uncles: string[]; + readonly hash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }>; + /** + * @param transactionHash The hash of the desired transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransaction('0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc').then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransaction( + * web3.utils.hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransaction(transactionHash: Bytes, returnFormat?: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + }>; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A list of pending transactions. + * + * ```ts + * web3.eth.getPendingTransactions().then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0n, + * nonce: 1n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2710n, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * + * * web3.eth.getPendingTransactions({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0, + * nonce: 1, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2710, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * ``` + */ + getPendingTransactions(returnFormat?: ReturnFormat): Promise<{ + from?: string | undefined; + to?: string | null | undefined; + value?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + common?: { + customChain: { + name?: string | undefined; + networkId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + chainId: import("web3-types").NumberTypes[ReturnFormat["number"]]; + }; + baseChain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + } | undefined; + gas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasPrice?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + type?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + maxPriorityFeePerGas?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + input?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + nonce?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + chain?: import("web3-types").ValidChains | undefined; + hardfork?: "chainstart" | "frontier" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople" | "petersburg" | "istanbul" | "muirGlacier" | "berlin" | "london" | "altair" | "arrowGlacier" | "grayGlacier" | "bellatrix" | "merge" | "capella" | "shanghai" | undefined; + chainId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + networkId?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + gasLimit?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + yParity?: string | undefined; + v?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + r?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + s?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + }[]>; + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param transactionIndex The index position of the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransactionFromBlock('0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', 0).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransactionFromBlock( + * hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * 0, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + getTransactionFromBlock(block: BlockNumberOrTag | undefined, transactionIndex: Numbers, returnFormat?: ReturnFormat): Promise<{ + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly maxFeePerGas: string; + readonly maxPriorityFeePerGas: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly yParity: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly accessList: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[]; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | { + readonly v: string; + readonly r: string; + readonly s: string; + readonly gasPrice: string; + readonly to?: string | null | undefined; + readonly type: string; + readonly nonce: string; + readonly gas: string; + readonly value: string; + readonly input: string; + readonly data?: string | undefined; + readonly chainId?: string | undefined; + readonly hash: string; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | undefined; + readonly from: string; + readonly transactionIndex?: string | undefined; + } | undefined>; + /** + * @param transactionHash Hash of the transaction to retrieve the receipt for. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired {@link TransactionReceipt} object. + * + * ```ts + * web3.eth.getTransactionReceipt("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f").then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * + * web3.eth.getTransactionReceipt( + * "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0, + * blockNumber: 2, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000, + * gasUsed: 21000, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1, + * effectiveGasPrice: 2000000000, + * type: 0n + * } + * ``` + */ + getTransactionReceipt(transactionHash: Bytes, returnFormat?: ReturnFormat): Promise; + /** + * @param address The address to get the number of transactions for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions sent from the provided address. + * + * ```ts + * web3.eth.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + getTransactionCount(address: Address, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * @param transaction The {@link Transaction}, {@link TransactionWithFromLocalWalletIndex}, {@link TransactionWithToLocalWalletIndex} or {@link TransactionWithFromAndToLocalWalletIndex} to send. __Note:__ In the `to` and `from` fields when hex strings are used, it is assumed they are addresses, for any other form (number, string number, etc.) it is assumed they are wallet indexes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @param options A configuration object used to change the behavior of the `sendTransaction` method. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const transaction = { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1' + * } + * + * const transactionHash = await web3.eth.sendTransaction(transaction); + * console.log(transactionHash); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).catch(console.log); + * > + * + * // Example using options.ignoreGasPricing = true + * web3.eth.sendTransaction(transaction, undefined, { ignoreGasPricing: true }).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendTransaction(transaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `sent` + * ```ts + * web3.eth.sendTransaction(transaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendTransaction(transaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * - `receipt` + * ```ts + * web3.eth.sendTransaction(transaction).on('receipt', receipt => console.log(receipt)); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendTransaction(transaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * transactionHash: '0xb4a3a35ae0f3e77ef0ff7be42010d948d011b21a4e341072ee18717b67e99ab8', + * transactionIndex: 0n, + * blockNumber: 5n, + * blockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * }, + * latestBlockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendTransaction(transaction).on('error', error => console.log); + * > + * ``` + */ + sendTransaction(transaction: Transaction | TransactionWithFromLocalWalletIndex | TransactionWithToLocalWalletIndex | TransactionWithFromAndToLocalWalletIndex, returnFormat?: ReturnFormat, options?: SendTransactionOptions): import("web3-core").Web3PromiEvent>; + /** + * @param transaction Signed transaction in one of the valid {@link Bytes} format. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const signedTransaction = "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * + * const transactionHash = await web3.eth.sendSignedTransaction(signedTransaction); + * console.log(transactionHash); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).then(console.log); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).catch(console.log); + * > + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `sent` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * ``` + * - `receipt` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('receipt', receipt => console.log(receipt)); + * > { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * }, + * latestBlockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('error', error => console.log(error)); + * > + * ``` + */ + sendSignedTransaction(transaction: Bytes, returnFormat?: ReturnFormat, options?: SendTransactionOptions): import("web3-core").Web3PromiEvent>; + /** + * @param message Data to sign in one of the valid {@link Bytes} format. + * @param address Address to sign data with, can be an address or the index of a local wallet. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The signed `message`. + * + * ```ts + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + * + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.UINT8ARRAY }).then(console.log); + * > Uint8Array(65) [ + * 48, 117, 94, 214, 83, 150, 250, 207, 134, 197, 62, + * 98, 23, 197, 43, 77, 174, 190, 114, 170, 73, 65, + * 216, 150, 53, 64, 157, 228, 201, 199, 249, 70, 109, + * 78, 154, 174, 199, 151, 127, 5, 233, 35, 136, 155, + * 51, 192, 208, 221, 39, 215, 34, 107, 110, 111, 86, + * 206, 115, 116, 101, 197, 207, 208, 75, 228, 0 + * ] + * ``` + * + * // Using an indexed account managed by local Web3 wallet + * web3.eth.sign("0x48656c6c6f20776f726c64", 0).then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + */ + sign(message: Bytes, address: Address, returnFormat?: ReturnFormat): Promise<{ + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + } | import("web3-types").ByteTypes[ReturnFormat["bytes"]]>; + /** + * @param transaction The transaction object to sign. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * gas: '21000', + * gasPrice: await web3Eth.getGasPrice(), + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.signTransaction(transaction).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0n, + * nonce: 1n, + * gasPrice: 1000000001n, + * gas: 21000n, + * value: 1n, + * v: 2710n, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * + * web3.eth.signTransaction(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0, + * nonce: 1, + * gasPrice: 1000000001, + * gas: 21000, + * value: 1, + * v: 2710, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * ``` + */ + signTransaction(transaction: Transaction, returnFormat?: ReturnFormat): Promise; + /** + * Executes a message call within the EVM without creating a transaction. + * It does not publish anything to the blockchain and does not consume any gas. + * + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The returned data of the call, e.g. a smart contract function's return value. + */ + call(transaction: TransactionCall, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Simulates the transaction within the EVM to estimate the amount of gas to be used by the transaction. + * The transaction will not be added to the blockchain, and actual gas usage can vary when interacting + * with a contract as a result of updating the contract's state. + * + * @param transaction The {@link Transaction} object to estimate the gas for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The used gas for the simulated transaction execution. + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.estimateGas(transaction).then(console.log); + * > 21000n + * + * web3.eth.estimateGas(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 21000 + * ``` + */ + estimateGas(transaction: Transaction, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise; + /** + * Gets past logs, matching the provided `filter`. + * + * @param filter A {@link Filter} object containing the properties for the desired logs. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns {@link FilterResultsAPI}, an array of {@link Log} objects. + * + * ```ts + * web3.eth.getPastLogs({ + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0n, + * transactionIndex: 0n, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234n, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * + * web3.eth.getPastLogs( + * { + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * ``` + */ + getPastLogs(filter: Filter, returnFormat?: ReturnFormat): Promise<(string | { + readonly id?: string | undefined; + readonly removed?: boolean | undefined; + readonly logIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionIndex?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly transactionHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockHash?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly blockNumber?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + readonly address?: string | undefined; + readonly data?: import("web3-types").ByteTypes[ReturnFormat["bytes"]] | undefined; + readonly topics?: import("web3-types").ByteTypes[ReturnFormat["bytes"]][] | undefined; + })[]>; + /** + * Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ('target'). + * + * @returns The mining work as an array of strings with the following structure: + * + * String 32 Bytes - at index 0: current block header pow-hash + * String 32 Bytes - at index 1: the seed hash used for the DAG. + * String 32 Bytes - at index 2: the boundary condition ('target'), 2^256 / difficulty. + * + * ```ts + * web3.eth.getWork().then(console.log); + * > [ + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0x5EED00000000000000000000000000005EED0000000000000000000000000000", + * "0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000" + * ] + * ``` + */ + getWork(): Promise<[string, string, string]>; + /** + * Used for submitting a proof-of-work solution. + * + * @param nonce The nonce found (8 bytes). + * @param hash The header’s pow-hash (32 bytes). + * @param digest The mix digest (32 bytes). + * @returns Returns `true` if the provided solution is valid, otherwise `false`. + * + * ```ts + * web3.eth.submitWork([ + * "0x0000000000000001", + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000" + * ]).then(console.log); + * > true + * ``` + */ + submitWork(nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes): Promise; + /** + * This method will request/enable the accounts from the current environment and for supporting [EIP 1102](https://eips.ethereum.org/EIPS/eip-1102) + * This method will only work if you’re using the injected provider from a application like Metamask, Status or TrustWallet. + * It doesn’t work if you’re connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvider and IpcProvider). + * For more information about the behavior of this method please read [EIP-1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md): Opt-in account exposure. + * + * @returns An array of enabled accounts. + * + * ```ts + * web3.eth.requestAccounts().then(console.log); + * > ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'] + * ``` + */ + requestAccounts(): Promise; + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The chain ID of the current connected node as described in the [EIP-695](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md). + * + * ```ts + * web3.eth.getChainId().then(console.log); + * > 61n + * + * web3.eth.getChainId({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 61 + * ``` + */ + getChainId(returnFormat?: ReturnFormat): Promise; + /** + * @returns The current client version. + * + * ```ts + * web3.eth.getNodeInfo().then(console.log); + * > "Mist/v0.9.3/darwin/go1.4.1" + * ``` + */ + getNodeInfo(): Promise; + /** + * @param address The Address of the account or contract. + * @param storageKeys Array of storage-keys which should be proofed and included. See {@link web3.getStorageAt}. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The account and storage-values of the specified account including the Merkle-proof as described in [EIP-1186](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md). + * + * ```ts + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * "latest" + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0n, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0n, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0n, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0n, + * "proof": [] + * } + * ] + * } + * + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0, + * "proof": [] + * } + * ] + * } + * ``` + */ + getProof(address: Address, storageKeys: Bytes[], blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise<{ + readonly balance: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly codeHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly nonce: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly storageHash: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly accountProof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + readonly storageProof: { + readonly key: import("web3-types").ByteTypes[ReturnFormat["bytes"]]; + readonly value: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly proof: import("web3-types").ByteTypes[ReturnFormat["bytes"]][]; + }[]; + }>; + /** + * @param blockCount Number of blocks in the requested range. Between `1` and `1024` blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. + * @param newestBlock Highest number block of the requested range. + * @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `['0', '25', '50', '75', '100']` or `['0', '0.5', '1', '1.5', '3', '80']` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available. + * The range between `headBlock - 4` and `headBlock` is guaranteed to be available while retrieving data from the `pending` block and older history are optional to support. + * For pre-EIP-1559 blocks the `gasPrice`s are returned as `rewards` and zeroes are returned for the `baseFeePerGas`. + * + * ```ts + * web3.eth.getFeeHistory(4, 'pending', [0, 25, 75, 100]).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621n, + * 21417903463n, + * 19989260230n, + * 17770954829n, + * 18850641304n + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343n, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * + * web3.eth.getFeeHistory(4, BlockTags.LATEST, [0, 25, 75, 100], { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621, + * 21417903463, + * 19989260230, + * 17770954829, + * 18850641304 + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * ``` + */ + getFeeHistory(blockCount: Numbers, newestBlock: BlockNumberOrTag | undefined, rewardPercentiles: Numbers[], returnFormat?: ReturnFormat): Promise<{ + readonly oldestBlock: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly baseFeePerGas: import("web3-types").NumberTypes[ReturnFormat["number"]]; + readonly reward: import("web3-types").NumberTypes[ReturnFormat["number"]][][]; + readonly gasUsedRatio: import("web3-types").NumberTypes[ReturnFormat["number"]][]; + }>; + /** + * This method generates an access list for a transaction. + * + * @param transaction - A transaction object where all properties are optional except `from`, however it's recommended to include the `to` property. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the createAccessList should be formatted. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * @example + * ```ts + * web3.eth.createAccessList({ + * from: '0xDe95305a63302C3aa4d3A9B42654659AeA72b694', + * data: '0x9a67c8b100000000000000000000000000000000000000000000000000000000000004d0', + * gasPrice: '0x3b9aca00', + * gas: '0x3d0900', + * to: '0x940b25304947ae863568B3804434EC77E2160b87' + * }) + * .then(console.log); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + createAccessList(transaction: TransactionForAccessList, blockNumber?: BlockNumberOrTag, returnFormat?: ReturnFormat): Promise<{ + readonly accessList?: { + readonly address?: string | undefined; + readonly storageKeys?: string[] | undefined; + }[] | undefined; + readonly gasUsed?: import("web3-types").NumberTypes[ReturnFormat["number"]] | undefined; + }>; + /** + * This method sends EIP-712 typed data to the RPC provider to be signed. + * + * @param address The address that corresponds with the private key used to sign the typed data. + * @param typedData The EIP-712 typed data object. + * @param useLegacy A boolean flag determining whether the RPC call uses the legacy method `eth_signTypedData` or the newer method `eth_signTypedData_v4` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the signed typed data should be formatted. + * @returns The signed typed data. + */ + signTypedData(address: Address, typedData: Eip712TypedData, useLegacy?: boolean, returnFormat?: ReturnFormat): Promise; + /** + * Lets you subscribe to specific events in the blockchain. + * + * @param name - The subscription you want to subscribe to. + * @param args - Optional additional parameters, depending on the subscription type. + * @returns A subscription object of type {@link RegisteredSubscription}. The object contains: + * - subscription.id: The subscription id, used to identify and unsubscribing the subscription. + * - subscription.subscribe(): Can be used to re-subscribe with the same parameters. + * - subscription.unsubscribe(): Unsubscribes the subscription and returns TRUE in the callback if successful. + * - subscription.args: The subscription arguments, used when re-subscribing. + * + * + * You can use the subscription object to listen on: + * + * - on("data") - Fires on each incoming log with the log object as argument. + * - on("changed") - Fires on each log which was removed from the blockchain. The log will have the additional property "removed: true". + * - on("error") - Fires when an error in the subscription occurs. + * - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id. + * + * @example **Subscribe to Smart Contract events** + * ```ts + * // Subscribe to `logs` + * const logSubscription = web3.eth.subscribe('logs', { + * address: '0x1234567890123456789012345678901234567890', + * topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234'] + * }); + * logSubscription.on('data', (data: any) => console.log(data)); + * logSubscription.on('error', (error: any) => console.log(error)); + * + * ``` + * + * @example **Subscribe to new block headers** + * ```ts + * // Subscribe to `newBlockHeaders` + * const newBlocksSubscription = await web3.eth.subscribe('newBlockHeaders'); + * + * newBlocksSubscription.on('data', async blockhead => { + * console.log('New block header: ', blockhead); + * + * // You do not need the next line, if you like to keep notified for every new block + * await newBlocksSubscription.unsubscribe(); + * console.log('Unsubscribed from new block headers.'); + * }); + * newBlocksSubscription.on('error', error => + * console.log('Error when subscribing to New block header: ', error), + * ); + * ``` + */ + subscribe(name: T, args?: ConstructorParameters[0], returnFormat?: ReturnType): Promise>; + private static shouldClearSubscription; + /** + * Resets subscriptions. + * + * @param notClearSyncing If `true` it keeps the `syncing` subscription. + * @returns A promise to an array of subscription ids that were cleared. + * + * ```ts + * web3.eth.clearSubscriptions().then(console.log); + * > [...] An array of subscription ids that were cleared + * ``` + */ + clearSubscriptions(notClearSyncing?: boolean): Promise | undefined; +} +//# sourceMappingURL=web3_eth.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/web3_eth.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_eth.d.ts.map new file mode 100644 index 0000000..10edaad --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_eth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eth.d.ts","sourceRoot":"","sources":["../../src/web3_eth.ts"],"names":[],"mappings":"AAoBA,OAAO,EACN,kBAAkB,EAClB,OAAO,EACP,KAAK,EACL,MAAM,EACN,gBAAgB,EAChB,eAAe,EACf,OAAO,EACP,gBAAgB,EAEhB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,GAAG,OAAO,qBAAqB,EACxF,UAAU,EAAE,OAAO,EACnB,WAAW,8BAAsC,EACjD,iBAAiB,EAAE,OAAO,EAAE,EAC5B,YAAY,GAAE,YAAoD;;;;;;IAWnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACU,gBAAgB,CAAC,YAAY,SAAS,UAAU,GAAG,OAAO,qBAAqB,EAC3F,WAAW,EAAE,wBAAwB,EACrC,WAAW,GAAE,gBAAoC,EACjD,YAAY,GAAE,YAAoD;;;;;;;IAKnE;;;;;;;;OAQG;IACU,aAAa,CAAC,YAAY,SAAS,UAAU,GAAG,OAAO,qBAAqB,EACxF,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,eAAe,EAC1B,SAAS,UAAQ,EACjB,YAAY,GAAE,YAAoD;IAKnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+CG;IACU,SAAS,CACrB,CAAC,SAAS,MAAM,sBAAsB,EACtC,UAAU,SAAS,UAAU,GAAG,UAAU,EAE1C,IAAI,EAAE,CAAC,EACP,IAAI,CAAC,EAAE,qBAAqB,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAC1D,YAAY,GAAE,UAAgD,GAC5D,OAAO,CAAC,YAAY,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;IAwBnD,OAAO,CAAC,MAAM,CAAC,uBAAuB;IAItC;;;;;;;;;;OAUG;IACI,kBAAkB,CAAC,eAAe,UAAQ,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,SAAS;CAMjF"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/web3_subscriptions.d.ts b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_subscriptions.d.ts new file mode 100644 index 0000000..34d9eb7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_subscriptions.d.ts @@ -0,0 +1,118 @@ +import { SyncOutput, Address, BlockNumberOrTag, HexString, Topic, BlockHeaderOutput, LogsOutput } from 'web3-types'; +import { Web3Subscription } from 'web3-core'; +/** + * ## subscribe('logs') + * Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, web3.js will retrieve logs beginning from this point, backfilling the response as necessary. + * + * You can subscribe to logs matching a given filter object, which can take the following parameters: + * - `fromBlock`: (optional, default: 'latest') Integer block number, or `'latest'` for the last mined block or `'pending'`, `'earliest'` for not yet mined transactions. + * - `address`: (optional) Contract address or a list of addresses from which logs should originate. + * - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with `or` options. + * + */ +export declare class LogsSubscription extends Web3Subscription<{ + data: LogsOutput; +}, { + readonly fromBlock?: BlockNumberOrTag; + readonly address?: Address | Address[]; + readonly topics?: Topic[]; +}> { + protected _buildSubscriptionParams(): (string | { + readonly fromBlock?: BlockNumberOrTag | undefined; + readonly address?: string | string[] | undefined; + readonly topics?: string[] | undefined; + })[]; + protected formatSubscriptionResult(data: LogsOutput): { + readonly id?: string | undefined; + readonly removed: boolean; + readonly logIndex?: string | number | bigint | undefined; + readonly transactionIndex?: string | number | bigint | undefined; + readonly transactionHash?: string | undefined; + readonly blockHash?: string | undefined; + readonly blockNumber?: string | number | bigint | undefined; + readonly address: string; + readonly topics: string[]; + readonly data: string; + }; +} +/** + * ## subscribe('pendingTransactions') + * Subscribes to incoming pending transactions. + * + * You can subscribe to pending transactions by calling web3.eth.subscribe('pendingTransactions'). + * @example + * ```ts + * (await web3.eth.subscribe('pendingTransactions')).on('data', console.log); + * ``` + */ +export declare class NewPendingTransactionsSubscription extends Web3Subscription<{ + data: HexString; +}> { + protected _buildSubscriptionParams(): string[]; + protected formatSubscriptionResult(data: string): string; +} +/** + * ## subscribe('newHeads') ( same as subscribe('newBlockHeaders')) + * + * Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain. + * + * The structure of a returned block header is {@link BlockHeaderOutput}: + * @example + * ```ts + * (await web3.eth.subscribe('newHeads')).on( // 'newBlockHeaders' would work as well + * 'data', + * console.log + * ); + * >{ + * parentHash: '0x9e746a1d906b299def98c75b06f714d62dacadd567c7515d76eeaa8c8074c738', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0xe0f04b04861ecfa95e82a9310d6a7ef7aef8d7417f5209c182582bfb98a8e307', + * transactionsRoot: '0x31ab4ea571a9e10d3a19aaed07d190595b1dfa34e03960c04293fec565dea536', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 2n, + * number: 21n, + * gasLimit: 11738125n, + * gasUsed: 830006n, + * timestamp: 1678797237n, + * extraData: '0xd883010b02846765746888676f312e32302e31856c696e757800000000000000e0a6e93cf40e2e71a72e493272210c3f43738ccc7e7d7b14ffd51833797d896c09117e8dc4fbcbc969bd21b42e5af3e276a911524038c001b2109b63b8e0352601', + * nonce: 0n + * } + * ``` + */ +export declare class NewHeadsSubscription extends Web3Subscription<{ + data: BlockHeaderOutput; +}> { + protected _buildSubscriptionParams(): string[]; + protected formatSubscriptionResult(data: BlockHeaderOutput): BlockHeaderOutput; +} +/** + * ## subscribe('syncing') + * + * Subscribe to syncing events. This will return `true` when the node is syncing and when it’s finished syncing will return `false`, for the `changed` event. + * @example + * ```ts + * (await web3.eth.subscribe('syncing')).on('changed', console.log); + * > `true` // when syncing + * + * (await web3.eth.subscribe('syncing')).on('data', console.log); + * > { + * startingBlock: 0, + * currentBlock: 0, + * highestBlock: 0, + * pulledStates: 0, + * knownStates: 0 + * } + * ``` + */ +export declare class SyncingSubscription extends Web3Subscription<{ + data: SyncOutput; + changed: boolean; +}> { + protected _buildSubscriptionParams(): string[]; + _processSubscriptionResult(data: { + syncing: boolean; + status: SyncOutput; + } | boolean): void; +} +//# sourceMappingURL=web3_subscriptions.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/lib/types/web3_subscriptions.d.ts.map b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_subscriptions.d.ts.map new file mode 100644 index 0000000..cbde089 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/lib/types/web3_subscriptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_subscriptions.d.ts","sourceRoot":"","sources":["../../src/web3_subscriptions.ts"],"names":[],"mappings":"AAmBA,OAAO,EACN,UAAU,EACV,OAAO,EACP,gBAAgB,EAChB,SAAS,EACT,KAAK,EACL,iBAAiB,EACjB,UAAU,EACV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAG7C;;;;;;;;;GASG;AACH,qBAAa,gBAAiB,SAAQ,gBAAgB,CACrD;IACC,IAAI,EAAE,UAAU,CAAC;CACjB,EACD;IACC,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;IACtC,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,EAAE,CAAC;IACvC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CAC1B,CACD;IACA,SAAS,CAAC,wBAAwB;;;;;IAIlC,SAAS,CAAC,wBAAwB,CAAC,IAAI,EAAE,UAAU;;;;;;;;;;;;CAGnD;AAED;;;;;;;;;GASG;AACH,qBAAa,kCAAmC,SAAQ,gBAAgB,CAAC;IACxE,IAAI,EAAE,SAAS,CAAC;CAChB,CAAC;IAED,SAAS,CAAC,wBAAwB;IAIlC,SAAS,CAAC,wBAAwB,CAAC,IAAI,EAAE,MAAM;CAG/C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,oBAAqB,SAAQ,gBAAgB,CAAC;IAC1D,IAAI,EAAE,iBAAiB,CAAC;CACxB,CAAC;IAED,SAAS,CAAC,wBAAwB;IAIlC,SAAS,CAAC,wBAAwB,CAAC,IAAI,EAAE,iBAAiB,GAAG,iBAAiB;CAG9E;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,mBAAoB,SAAQ,gBAAgB,CAAC;IACzD,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,OAAO,CAAC;CACjB,CAAC;IAED,SAAS,CAAC,wBAAwB;IAI3B,0BAA0B,CAChC,IAAI,EACD;QACA,OAAO,EAAE,OAAO,CAAC;QACjB,MAAM,EAAE,UAAU,CAAC;KAClB,GACD,OAAO;CAgBX"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-eth/package.json b/test/merkletreejs/node_modules/web3-eth/package.json new file mode 100644 index 0000000..990bf86 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/package.json @@ -0,0 +1,78 @@ +{ + "name": "web3-eth", + "version": "4.3.1", + "description": "Web3 module to interact with the Ethereum blockchain and smart contracts.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:e2e:mainnet": "jest --config=./test/e2e/jest.config.js --forceExit", + "test:e2e:sepolia": "jest --config=./test/e2e/jest.config.js --forceExit", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --runInBand --forceExit", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --runInBand --forceExit --coverage=true --coverage-reporters=text", + "test:e2e:electron": "npx cypress run --headless --browser electron", + "test:e2e:chrome": "npx cypress run --headless --browser chrome", + "test:e2e:firefox": "npx cypress run --headless --browser firefox" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4", + "web3-providers-http": "^4.1.0" + }, + "dependencies": { + "setimmediate": "^1.0.5", + "web3-core": "^4.3.0", + "web3-errors": "^1.1.3", + "web3-eth-abi": "^4.1.4", + "web3-eth-accounts": "^4.1.0", + "web3-net": "^4.0.7", + "web3-providers-ws": "^4.0.7", + "web3-rpc-methods": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "web3-validator": "^2.0.3" + }, + "gitHead": "41824d669db6aae87d7917122a28d5f057f5aa74" +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/constants.ts b/test/merkletreejs/node_modules/web3-eth/src/constants.ts new file mode 100644 index 0000000..13a4857 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/constants.ts @@ -0,0 +1,27 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { AbiEventFragment, FMT_BYTES, FMT_NUMBER } from 'web3-types'; + +export const ALL_EVENTS = 'ALLEVENTS'; +export const ALL_EVENTS_ABI = { + name: ALL_EVENTS, + signature: '', + type: 'event', + inputs: [], +} as AbiEventFragment & { signature: string }; + +export const NUMBER_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.NUMBER } as const; diff --git a/test/merkletreejs/node_modules/web3-eth/src/index.ts b/test/merkletreejs/node_modules/web3-eth/src/index.ts new file mode 100644 index 0000000..d1f1d32 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/index.ts @@ -0,0 +1,68 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The `web3-eth` package allows you to interact with an Ethereum blockchain and Ethereum smart contracts. + * + * To use this package standalone and use its methods use: + * ```ts + * import { Web3Context } from 'web3-core'; + * import { BlockTags } from 'web3-types'; + * import { DEFAULT_RETURN_FORMAT } from 'web3-types'; + * import { getBalance} from 'web3-eth'; + * + * getBalance( + * new Web3Context('http://127.0.0.1:8545'), + * '0x407d73d8a49eeb85d32cf465507dd71d507100c1', + * BlockTags.LATEST, + * DEFAULT_RETURN_FORMAT + * ).then(console.log); + * > 1000000000000n + * ``` + * + * To use this package within the `web3` object use: + * ```ts + * import Web3 from 'web3'; + * + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * web3.eth.getBalance('0x407d73d8a49eeb85d32cf465507dd71d507100c1').then(console.log); + * > 1000000000000n + *``` + * + * With `web3-eth` you can also subscribe (if supported by provider) to events in the Ethereum Blockchain, using the `subscribe` function. See more at the {@link Web3Eth.subscribe} function. + */ +/** + * + */ +import 'setimmediate'; + +import { Web3Eth } from './web3_eth.js'; + +export * from './web3_eth.js'; +export * from './utils/decoding.js'; +export * from './schemas.js'; +export * from './constants.js'; +export * from './types.js'; +export * from './validation.js'; +export * from './rpc_method_wrappers.js'; +export * from './utils/format_transaction.js'; +export * from './utils/prepare_transaction_for_signing.js'; +export * from './web3_subscriptions.js'; +export { detectTransactionType } from './utils/detect_transaction_type.js'; +export { transactionBuilder } from './utils/transaction_builder.js'; + +export default Web3Eth; diff --git a/test/merkletreejs/node_modules/web3-eth/src/rpc_method_wrappers.ts b/test/merkletreejs/node_modules/web3-eth/src/rpc_method_wrappers.ts new file mode 100644 index 0000000..9a36f2d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/rpc_method_wrappers.ts @@ -0,0 +1,980 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// Disabling because returnTypes must be last param to match 1.x params +/* eslint-disable default-param-last */ +import { + ETH_DATA_FORMAT, + FormatType, + DataFormat, + DEFAULT_RETURN_FORMAT, + EthExecutionAPI, + SignedTransactionInfoAPI, + Web3BaseWalletAccount, + Address, + BlockTag, + BlockNumberOrTag, + Bytes, + Filter, + HexString, + Numbers, + HexStringBytes, + AccountObject, + Block, + FeeHistory, + Log, + TransactionReceipt, + Transaction, + TransactionCall, + Web3EthExecutionAPI, + TransactionWithFromLocalWalletIndex, + TransactionWithToLocalWalletIndex, + TransactionWithFromAndToLocalWalletIndex, + TransactionForAccessList, + AccessListResult, + Eip712TypedData, +} from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { format, hexToBytes, bytesToUint8Array, numberToHex } from 'web3-utils'; +import { TransactionFactory } from 'web3-eth-accounts'; +import { isBlockTag, isBytes, isNullish, isString } from 'web3-validator'; +import { SignatureError } from 'web3-errors'; +import { ethRpcMethods } from 'web3-rpc-methods'; + +import { decodeSignedTransaction } from './utils/decode_signed_transaction.js'; +import { + accountSchema, + blockSchema, + feeHistorySchema, + logSchema, + transactionReceiptSchema, + accessListResultSchema, + SignatureObjectSchema, +} from './schemas.js'; +import { + SendSignedTransactionEvents, + SendSignedTransactionOptions, + SendTransactionEvents, + SendTransactionOptions, +} from './types.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionFromOrToAttr } from './utils/transaction_builder.js'; +import { formatTransaction } from './utils/format_transaction.js'; +// eslint-disable-next-line import/no-cycle +import { trySendTransaction } from './utils/try_send_transaction.js'; +// eslint-disable-next-line import/no-cycle +import { waitForTransactionReceipt } from './utils/wait_for_transaction_receipt.js'; +import { NUMBER_DATA_FORMAT } from './constants.js'; +// eslint-disable-next-line import/no-cycle +import { SendTxHelper } from './utils/send_tx_helper.js'; + +/** + * View additional documentations here: {@link Web3Eth.getProtocolVersion} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const getProtocolVersion = async (web3Context: Web3Context) => + ethRpcMethods.getProtocolVersion(web3Context.requestManager); + +// TODO Add returnFormat parameter +/** + * View additional documentations here: {@link Web3Eth.isSyncing} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const isSyncing = async (web3Context: Web3Context) => + ethRpcMethods.getSyncing(web3Context.requestManager); + +// TODO consider adding returnFormat parameter (to format address as bytes) +/** + * View additional documentations here: {@link Web3Eth.getCoinbase} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const getCoinbase = async (web3Context: Web3Context) => + ethRpcMethods.getCoinbase(web3Context.requestManager); + +/** + * View additional documentations here: {@link Web3Eth.isMining} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export const isMining = async (web3Context: Web3Context) => + ethRpcMethods.getMining(web3Context.requestManager); + +/** + * View additional documentations here: {@link Web3Eth.getHashRate} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getHashRate( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.getHashRate(web3Context.requestManager); + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getGasPrice} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getGasPrice( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.getGasPrice(web3Context.requestManager); + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getBlockNumber} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getBlockNumber( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.getBlockNumber(web3Context.requestManager); + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getBalance} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getBalance( + web3Context: Web3Context, + address: Address, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + const response = await ethRpcMethods.getBalance( + web3Context.requestManager, + address, + blockNumberFormatted, + ); + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getStorageAt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getStorageAt( + web3Context: Web3Context, + address: Address, + storageSlot: Numbers, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const storageSlotFormatted = format({ format: 'uint' }, storageSlot, ETH_DATA_FORMAT); + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + const response = await ethRpcMethods.getStorageAt( + web3Context.requestManager, + address, + storageSlotFormatted, + blockNumberFormatted, + ); + return format({ format: 'bytes' }, response as Bytes, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getCode} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getCode( + web3Context: Web3Context, + address: Address, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + const response = await ethRpcMethods.getCode( + web3Context.requestManager, + address, + blockNumberFormatted, + ); + return format({ format: 'bytes' }, response as Bytes, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getBlock( + web3Context: Web3Context, + block: Bytes | BlockNumberOrTag = web3Context.defaultBlock, + hydrated = false, + returnFormat: ReturnFormat, +) { + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = await ethRpcMethods.getBlockByHash( + web3Context.requestManager, + blockHashFormatted as HexString, + hydrated, + ); + } else { + const blockNumberFormatted = isBlockTag(block as string) + ? (block as BlockTag) + : format({ format: 'uint' }, block as Numbers, ETH_DATA_FORMAT); + response = await ethRpcMethods.getBlockByNumber( + web3Context.requestManager, + blockNumberFormatted, + hydrated, + ); + } + return format(blockSchema, response as unknown as Block, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getBlockTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getBlockTransactionCount( + web3Context: Web3Context, + block: Bytes | BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = await ethRpcMethods.getBlockTransactionCountByHash( + web3Context.requestManager, + blockHashFormatted as HexString, + ); + } else { + const blockNumberFormatted = isBlockTag(block as string) + ? (block as BlockTag) + : format({ format: 'uint' }, block as Numbers, ETH_DATA_FORMAT); + response = await ethRpcMethods.getBlockTransactionCountByNumber( + web3Context.requestManager, + blockNumberFormatted, + ); + } + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getBlockUncleCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getBlockUncleCount( + web3Context: Web3Context, + block: Bytes | BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = await ethRpcMethods.getUncleCountByBlockHash( + web3Context.requestManager, + blockHashFormatted as HexString, + ); + } else { + const blockNumberFormatted = isBlockTag(block as string) + ? (block as BlockTag) + : format({ format: 'uint' }, block as Numbers, ETH_DATA_FORMAT); + response = await ethRpcMethods.getUncleCountByBlockNumber( + web3Context.requestManager, + blockNumberFormatted, + ); + } + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getUncle} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getUncle( + web3Context: Web3Context, + block: Bytes | BlockNumberOrTag = web3Context.defaultBlock, + uncleIndex: Numbers, + returnFormat: ReturnFormat, +) { + const uncleIndexFormatted = format({ format: 'uint' }, uncleIndex, ETH_DATA_FORMAT); + + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = await ethRpcMethods.getUncleByBlockHashAndIndex( + web3Context.requestManager, + blockHashFormatted as HexString, + uncleIndexFormatted, + ); + } else { + const blockNumberFormatted = isBlockTag(block as string) + ? (block as BlockTag) + : format({ format: 'uint' }, block as Numbers, ETH_DATA_FORMAT); + response = await ethRpcMethods.getUncleByBlockNumberAndIndex( + web3Context.requestManager, + blockNumberFormatted, + uncleIndexFormatted, + ); + } + + return format(blockSchema, response as unknown as Block, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.getTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getTransaction( + web3Context: Web3Context, + transactionHash: Bytes, + returnFormat: ReturnFormat, +) { + const transactionHashFormatted = format( + { format: 'bytes32' }, + transactionHash, + DEFAULT_RETURN_FORMAT, + ); + const response = await ethRpcMethods.getTransactionByHash( + web3Context.requestManager, + transactionHashFormatted, + ); + + return isNullish(response) + ? response + : formatTransaction(response, returnFormat, { fillInputAndData: true }); +} + +/** + * View additional documentations here: {@link Web3Eth.getPendingTransactions} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getPendingTransactions( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.getPendingTransactions(web3Context.requestManager); + + return response.map(transaction => + formatTransaction(transaction as unknown as Transaction, returnFormat, { + fillInputAndData: true, + }), + ); +} + +/** + * View additional documentations here: {@link Web3Eth.getTransactionFromBlock} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getTransactionFromBlock( + web3Context: Web3Context, + block: Bytes | BlockNumberOrTag = web3Context.defaultBlock, + transactionIndex: Numbers, + returnFormat: ReturnFormat, +) { + const transactionIndexFormatted = format({ format: 'uint' }, transactionIndex, ETH_DATA_FORMAT); + + let response; + if (isBytes(block)) { + const blockHashFormatted = format({ format: 'bytes32' }, block, ETH_DATA_FORMAT); + response = await ethRpcMethods.getTransactionByBlockHashAndIndex( + web3Context.requestManager, + blockHashFormatted as HexString, + transactionIndexFormatted, + ); + } else { + const blockNumberFormatted = isBlockTag(block as string) + ? (block as BlockTag) + : format({ format: 'uint' }, block as Numbers, ETH_DATA_FORMAT); + response = await ethRpcMethods.getTransactionByBlockNumberAndIndex( + web3Context.requestManager, + blockNumberFormatted, + transactionIndexFormatted, + ); + } + + return isNullish(response) + ? response + : formatTransaction(response, returnFormat, { fillInputAndData: true }); +} + +/** + * View additional documentations here: {@link Web3Eth.getTransactionReceipt} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getTransactionReceipt( + web3Context: Web3Context, + transactionHash: Bytes, + returnFormat: ReturnFormat, +) { + const transactionHashFormatted = format( + { format: 'bytes32' }, + transactionHash, + DEFAULT_RETURN_FORMAT, + ); + const response = await ethRpcMethods.getTransactionReceipt( + web3Context.requestManager, + transactionHashFormatted, + ); + + return isNullish(response) + ? response + : (format( + transactionReceiptSchema, + response as unknown as TransactionReceipt, + returnFormat, + ) as TransactionReceipt); +} + +/** + * View additional documentations here: {@link Web3Eth.getTransactionCount} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getTransactionCount( + web3Context: Web3Context, + address: Address, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + const response = await ethRpcMethods.getTransactionCount( + web3Context.requestManager, + address, + blockNumberFormatted, + ); + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.sendTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function sendTransaction< + ReturnFormat extends DataFormat, + ResolveType = FormatType, +>( + web3Context: Web3Context, + transaction: + | Transaction + | TransactionWithFromLocalWalletIndex + | TransactionWithToLocalWalletIndex + | TransactionWithFromAndToLocalWalletIndex, + returnFormat: ReturnFormat, + options: SendTransactionOptions = { checkRevertBeforeSending: true }, +): Web3PromiEvent> { + const promiEvent = new Web3PromiEvent>( + (resolve, reject) => { + setImmediate(() => { + (async () => { + const sendTxHelper = new SendTxHelper({ + web3Context, + promiEvent, + options, + returnFormat, + }); + + let transactionFormatted: + | Transaction + | TransactionWithFromLocalWalletIndex + | TransactionWithToLocalWalletIndex + | TransactionWithFromAndToLocalWalletIndex = formatTransaction( + { + ...transaction, + from: getTransactionFromOrToAttr('from', web3Context, transaction), + to: getTransactionFromOrToAttr('to', web3Context, transaction), + }, + ETH_DATA_FORMAT, + ); + + try { + transactionFormatted = await sendTxHelper.populateGasPrice({ + transaction, + transactionFormatted, + }); + + await sendTxHelper.checkRevertBeforeSending( + transactionFormatted as TransactionCall, + ); + + sendTxHelper.emitSending(transactionFormatted); + + let wallet: Web3BaseWalletAccount | undefined; + + if (web3Context.wallet && !isNullish(transactionFormatted.from)) { + wallet = web3Context.wallet.get( + (transactionFormatted as Transaction).from as string, + ); + } + + const transactionHash: HexString = await sendTxHelper.signAndSend({ + wallet, + tx: transactionFormatted, + }); + + const transactionHashFormatted = format( + { format: 'bytes32' }, + transactionHash as Bytes, + returnFormat, + ); + sendTxHelper.emitSent(transactionFormatted); + sendTxHelper.emitTransactionHash( + transactionHashFormatted as string & Uint8Array, + ); + + const transactionReceipt = await waitForTransactionReceipt( + web3Context, + transactionHash, + returnFormat, + ); + + const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents( + format(transactionReceiptSchema, transactionReceipt, returnFormat), + ); + + sendTxHelper.emitReceipt(transactionReceiptFormatted); + + resolve( + await sendTxHelper.handleResolve({ + receipt: transactionReceiptFormatted, + tx: transactionFormatted as TransactionCall, + }), + ); + + sendTxHelper.emitConfirmation({ + receipt: transactionReceiptFormatted, + transactionHash, + }); + } catch (error) { + reject( + await sendTxHelper.handleError({ + error, + tx: transactionFormatted as TransactionCall, + }), + ); + } + })() as unknown; + }); + }, + ); + + return promiEvent; +} + +/** + * View additional documentations here: {@link Web3Eth.sendSignedTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export function sendSignedTransaction< + ReturnFormat extends DataFormat, + ResolveType = FormatType, +>( + web3Context: Web3Context, + signedTransaction: Bytes, + returnFormat: ReturnFormat, + options: SendSignedTransactionOptions = { checkRevertBeforeSending: true }, +): Web3PromiEvent> { + // TODO - Promise returned in function argument where a void return was expected + // eslint-disable-next-line @typescript-eslint/no-misused-promises + const promiEvent = new Web3PromiEvent>( + (resolve, reject) => { + setImmediate(() => { + (async () => { + const sendTxHelper = new SendTxHelper({ + web3Context, + promiEvent, + options, + returnFormat, + }); + // Formatting signedTransaction to be send to RPC endpoint + const signedTransactionFormattedHex = format( + { format: 'bytes' }, + signedTransaction, + ETH_DATA_FORMAT, + ); + const unSerializedTransaction = TransactionFactory.fromSerializedData( + bytesToUint8Array(hexToBytes(signedTransactionFormattedHex)), + ); + const unSerializedTransactionWithFrom = { + ...unSerializedTransaction.toJSON(), + // Some providers will default `from` to address(0) causing the error + // reported from `eth_call` to not be the reason the user's tx failed + // e.g. `eth_call` will return an Out of Gas error for a failed + // smart contract execution contract, because the sender, address(0), + // has no balance to pay for the gas of the transaction execution + from: unSerializedTransaction.getSenderAddress().toString(), + }; + + try { + const { v , r , s, + ...txWithoutSigParams} = unSerializedTransactionWithFrom; + + await sendTxHelper.checkRevertBeforeSending( + txWithoutSigParams as TransactionCall, + ); + + sendTxHelper.emitSending(signedTransactionFormattedHex); + + const transactionHash = await trySendTransaction( + web3Context, + async (): Promise => + ethRpcMethods.sendRawTransaction( + web3Context.requestManager, + signedTransactionFormattedHex, + ), + ); + + sendTxHelper.emitSent(signedTransactionFormattedHex); + + const transactionHashFormatted = format( + { format: 'bytes32' }, + transactionHash as Bytes, + returnFormat, + ); + + sendTxHelper.emitTransactionHash( + transactionHashFormatted as string & Uint8Array, + ); + + const transactionReceipt = await waitForTransactionReceipt( + web3Context, + transactionHash, + returnFormat, + ); + + const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents( + format(transactionReceiptSchema, transactionReceipt, returnFormat), + ); + + sendTxHelper.emitReceipt(transactionReceiptFormatted); + + resolve( + await sendTxHelper.handleResolve({ + receipt: transactionReceiptFormatted, + tx: unSerializedTransactionWithFrom as TransactionCall, + }), + ); + + sendTxHelper.emitConfirmation({ + receipt: transactionReceiptFormatted, + transactionHash, + }); + } catch (error) { + reject( + await sendTxHelper.handleError({ + error, + tx: unSerializedTransactionWithFrom as TransactionCall, + }), + ); + } + })() as unknown; + }); + }, + ); + + return promiEvent; +} + +/** + * View additional documentations here: {@link Web3Eth.sign} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function sign( + web3Context: Web3Context, + message: Bytes, + addressOrIndex: Address | number, + returnFormat: ReturnFormat, +) { + const messageFormatted = format({ format: 'bytes' }, message, DEFAULT_RETURN_FORMAT); + if (web3Context.wallet?.get(addressOrIndex)) { + const wallet = web3Context.wallet.get(addressOrIndex) as Web3BaseWalletAccount; + const signed = wallet.sign(messageFormatted); + return format(SignatureObjectSchema, signed, returnFormat); + } + + if (typeof addressOrIndex === 'number') { + throw new SignatureError( + message, + 'RPC method "eth_sign" does not support index signatures', + ); + } + + const response = await ethRpcMethods.sign( + web3Context.requestManager, + addressOrIndex, + messageFormatted, + ); + + return format({ format: 'bytes' }, response as Bytes, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.signTransaction} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function signTransaction( + web3Context: Web3Context, + transaction: Transaction, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.signTransaction( + web3Context.requestManager, + formatTransaction(transaction, ETH_DATA_FORMAT), + ); + // Some clients only return the encoded signed transaction (e.g. Ganache) + // while clients such as Geth return the desired SignedTransactionInfoAPI object + return isString(response as HexStringBytes) + ? decodeSignedTransaction(response as HexStringBytes, returnFormat, { + fillInputAndData: true, + }) + : { + raw: format( + { format: 'bytes' }, + (response as SignedTransactionInfoAPI).raw, + returnFormat, + ), + tx: formatTransaction((response as SignedTransactionInfoAPI).tx, returnFormat, { + fillInputAndData: true, + }), + }; +} + +// TODO Decide what to do with transaction.to +// https://github.com/ChainSafe/web3.js/pull/4525#issuecomment-982330076 +/** + * View additional documentations here: {@link Web3Eth.call} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function call( + web3Context: Web3Context, + transaction: TransactionCall, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + + const response = await ethRpcMethods.call( + web3Context.requestManager, + formatTransaction(transaction, ETH_DATA_FORMAT), + blockNumberFormatted, + ); + + return format({ format: 'bytes' }, response as Bytes, returnFormat); +} + +// TODO - Investigate whether response is padded as 1.x docs suggest +/** + * View additional documentations here: {@link Web3Eth.estimateGas} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function estimateGas( + web3Context: Web3Context, + transaction: Transaction, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const transactionFormatted = formatTransaction(transaction, ETH_DATA_FORMAT); + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + + const response = await ethRpcMethods.estimateGas( + web3Context.requestManager, + transactionFormatted, + blockNumberFormatted, + ); + + return format({ format: 'uint' }, response as Numbers, returnFormat); +} + +// TODO - Add input formatting to filter +/** + * View additional documentations here: {@link Web3Eth.getPastLogs} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getLogs( + web3Context: Web3Context, + filter: Filter, + returnFormat: ReturnFormat, +) { + // format type bigint or number toBlock and fromBlock to hexstring. + let { toBlock, fromBlock } = filter; + if (!isNullish(toBlock)) { + if (typeof toBlock === 'number' || typeof toBlock === 'bigint') { + toBlock = numberToHex(toBlock); + } + } + if (!isNullish(fromBlock)) { + if (typeof fromBlock === 'number' || typeof fromBlock === 'bigint') { + fromBlock = numberToHex(fromBlock); + } + } + + const formattedFilter = { ...filter, fromBlock, toBlock }; + + const response = await ethRpcMethods.getLogs(web3Context.requestManager, formattedFilter); + + const result = response.map(res => { + if (typeof res === 'string') { + return res; + } + + return format(logSchema, res as unknown as Log, returnFormat); + }); + + return result; +} + +/** + * View additional documentations here: {@link Web3Eth.getChainId} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getChainId( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.getChainId(web3Context.requestManager); + + return format( + { format: 'uint' }, + // Response is number in hex formatted string + response as unknown as number, + returnFormat, + ); +} + +/** + * View additional documentations here: {@link Web3Eth.getProof} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getProof( + web3Context: Web3Context, + address: Address, + storageKeys: Bytes[], + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const storageKeysFormatted = storageKeys.map(storageKey => + format({ format: 'bytes' }, storageKey, ETH_DATA_FORMAT), + ); + + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + + const response = await ethRpcMethods.getProof( + web3Context.requestManager, + address, + storageKeysFormatted, + blockNumberFormatted, + ); + + return format(accountSchema, response as unknown as AccountObject, returnFormat); +} + +// TODO Throwing an error with Geth, but not Infura +// TODO gasUsedRatio and reward not formatting +/** + * View additional documentations here: {@link Web3Eth.getFeeHistory} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function getFeeHistory( + web3Context: Web3Context, + blockCount: Numbers, + newestBlock: BlockNumberOrTag = web3Context.defaultBlock, + rewardPercentiles: Numbers[], + returnFormat: ReturnFormat, +) { + const blockCountFormatted = format({ format: 'uint' }, blockCount, ETH_DATA_FORMAT); + + const newestBlockFormatted = isBlockTag(newestBlock as string) + ? (newestBlock as BlockTag) + : format({ format: 'uint' }, newestBlock as Numbers, ETH_DATA_FORMAT); + + const rewardPercentilesFormatted = format( + { + type: 'array', + items: { + format: 'uint', + }, + }, + rewardPercentiles, + NUMBER_DATA_FORMAT, + ); + + const response = await ethRpcMethods.getFeeHistory( + web3Context.requestManager, + blockCountFormatted, + newestBlockFormatted, + rewardPercentilesFormatted, + ); + + return format(feeHistorySchema, response as unknown as FeeHistory, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.createAccessList} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function createAccessList( + web3Context: Web3Context, + transaction: TransactionForAccessList, + blockNumber: BlockNumberOrTag = web3Context.defaultBlock, + returnFormat: ReturnFormat, +) { + const blockNumberFormatted = isBlockTag(blockNumber as string) + ? (blockNumber as BlockTag) + : format({ format: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); + + const response = (await ethRpcMethods.createAccessList( + web3Context.requestManager, + formatTransaction(transaction, ETH_DATA_FORMAT), + blockNumberFormatted, + )) as unknown as AccessListResult; + + return format(accessListResultSchema, response, returnFormat); +} + +/** + * View additional documentations here: {@link Web3Eth.signTypedData} + * @param web3Context ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + */ +export async function signTypedData( + web3Context: Web3Context, + address: Address, + typedData: Eip712TypedData, + useLegacy: boolean, + returnFormat: ReturnFormat, +) { + const response = await ethRpcMethods.signTypedData( + web3Context.requestManager, + address, + typedData, + useLegacy, + ); + + return format({ format: 'bytes' }, response, returnFormat); +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/schemas.ts b/test/merkletreejs/node_modules/web3-eth/src/schemas.ts new file mode 100644 index 0000000..89e2345 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/schemas.ts @@ -0,0 +1,641 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export const accessListItemSchema = { + type: 'object', + properties: { + address: { + format: 'address', + }, + storageKeys: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; + +export const accessListSchema = { + type: 'array', + items: { + ...accessListItemSchema, + }, +}; + +export const accessListResultSchema = { + type: 'object', + properties: { + accessList: { + ...accessListSchema, + }, + gasUsed: { + type: 'string', + }, + }, +}; + +export const chainSchema = { + type: 'string', + enum: ['goerli', 'kovan', 'mainnet', 'rinkeby', 'ropsten', 'sepolia'], +}; + +export const hardforkSchema = { + type: 'string', + enum: [ + 'arrowGlacier', + 'berlin', + 'byzantium', + 'chainstart', + 'constantinople', + 'dao', + 'homestead', + 'istanbul', + 'london', + 'merge', + 'muirGlacier', + 'petersburg', + 'shanghai', + 'spuriousDragon', + 'tangerineWhistle', + ], +}; + +export const customChainSchema = { + type: 'object', + properties: { + name: { + format: 'string', + }, + networkId: { + format: 'uint', + }, + chainId: { + format: 'uint', + }, + }, +}; + +export const transactionSchema = { + type: 'object', + properties: { + from: { + format: 'address', + }, + to: { + oneOf: [{ format: 'address' }, { type: 'null' }], + }, + value: { + format: 'uint', + }, + gas: { + format: 'uint', + }, + gasPrice: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + type: { + format: 'uint', + }, + maxFeePerGas: { + format: 'uint', + }, + maxPriorityFeePerGas: { + format: 'uint', + }, + accessList: { + ...accessListSchema, + }, + data: { + format: 'bytes', + }, + input: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + chain: { ...chainSchema }, + hardfork: { ...hardforkSchema }, + chainId: { + format: 'uint', + }, + networkId: { + format: 'uint', + }, + common: { + type: 'object', + properties: { + customChain: { ...customChainSchema }, + baseChain: { + ...chainSchema, + }, + hardfork: { + ...hardforkSchema, + }, + }, + }, + gasLimit: { + format: 'uint', + }, + v: { + format: 'uint', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + }, +}; + +export const transactionInfoSchema = { + type: 'object', + properties: { + ...transactionSchema.properties, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + hash: { + format: 'bytes32', + }, + transactionIndex: { + format: 'uint', + }, + from: { + format: 'address', + }, + to: { + oneOf: [{ format: 'address' }, { type: 'null' }], + }, + value: { + format: 'uint', + }, + gas: { + format: 'uint', + }, + gasPrice: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + type: { + format: 'uint', + }, + maxFeePerGas: { + format: 'uint', + }, + maxPriorityFeePerGas: { + format: 'uint', + }, + accessList: { + ...accessListSchema, + }, + data: { + format: 'bytes', + }, + input: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + v: { + format: 'uint', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + }, +}; + +export const blockSchema = { + type: 'object', + properties: { + parentHash: { + format: 'bytes32', + }, + sha3Uncles: { + format: 'bytes32', + }, + miner: { + format: 'bytes', + }, + stateRoot: { + format: 'bytes32', + }, + transactionsRoot: { + format: 'bytes32', + }, + receiptsRoot: { + format: 'bytes32', + }, + logsBloom: { + format: 'bytes256', + }, + difficulty: { + format: 'uint', + }, + number: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + timestamp: { + format: 'uint', + }, + extraData: { + format: 'bytes', + }, + mixHash: { + format: 'bytes32', + }, + nonce: { + format: 'uint', + }, + totalDifficulty: { + format: 'uint', + }, + baseFeePerGas: { + format: 'uint', + }, + size: { + format: 'uint', + }, + transactions: { + oneOf: [ + { + type: 'array', + items: { + ...transactionInfoSchema, + }, + }, + { + type: 'array', + items: { + format: 'bytes32', + }, + }, + ], + }, + uncles: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + hash: { + format: 'bytes32', + }, + }, +}; + +export const withdrawalsSchema = { + type: 'object', + properties: { + index: { + format: 'uint', + }, + validatorIndex: { + format: 'uint', + }, + address: { + format: 'address', + }, + amount: { + format: 'uint', + }, + }, +}; + +export const blockHeaderSchema = { + type: 'object', + properties: { + author: { + format: 'bytes32', + }, + hash: { + format: 'bytes32', + }, + parentHash: { + format: 'bytes32', + }, + receiptsRoot: { + format: 'bytes32', + }, + miner: { + format: 'bytes', + }, + stateRoot: { + format: 'bytes32', + }, + transactionsRoot: { + format: 'bytes32', + }, + withdrawalsRoot: { + format: 'bytes32', + }, + logsBloom: { + format: 'bytes256', + }, + difficulty: { + format: 'uint', + }, + totalDifficulty: { + format: 'uint', + }, + number: { + format: 'uint', + }, + gasLimit: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + timestamp: { + format: 'uint', + }, + extraData: { + format: 'bytes', + }, + nonce: { + format: 'uint', + }, + sha3Uncles: { + format: 'bytes32', + }, + size: { + format: 'uint', + }, + baseFeePerGas: { + format: 'uint', + }, + excessDataGas: { + format: 'uint', + }, + mixHash: { + format: 'bytes32', + }, + transactions: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + uncles: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + withdrawals: { + type: 'array', + items: { + ...withdrawalsSchema, + }, + }, + }, +}; + +export const logSchema = { + type: 'object', + properties: { + removed: { + format: 'bool', + }, + logIndex: { + format: 'uint', + }, + transactionIndex: { + format: 'uint', + }, + transactionHash: { + format: 'bytes32', + }, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + address: { + format: 'address', + }, + data: { + format: 'bytes', + }, + topics: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; +export const syncSchema = { + type: 'object', + properties: { + startingBlock: { + format: 'string', + }, + currentBlock: { + format: 'string', + }, + highestBlock: { + format: 'string', + }, + knownStates: { + format: 'string', + }, + pulledStates: { + format: 'string', + }, + }, +}; + +export const transactionReceiptSchema = { + type: 'object', + properties: { + transactionHash: { + format: 'bytes32', + }, + transactionIndex: { + format: 'uint', + }, + blockHash: { + format: 'bytes32', + }, + blockNumber: { + format: 'uint', + }, + from: { + format: 'address', + }, + to: { + format: 'address', + }, + cumulativeGasUsed: { + format: 'uint', + }, + gasUsed: { + format: 'uint', + }, + effectiveGasPrice: { + format: 'uint', + }, + contractAddress: { + format: 'address', + }, + logs: { + type: 'array', + items: { + ...logSchema, + }, + }, + logsBloom: { + format: 'bytes', + }, + root: { + format: 'bytes', + }, + status: { + format: 'uint', + }, + type: { + format: 'uint', + }, + }, +}; + +export const SignatureObjectSchema = { + type: 'object', + properties: { + messageHash: { + format: 'bytes', + }, + r: { + format: 'bytes32', + }, + s: { + format: 'bytes32', + }, + v: { + format: 'bytes', + }, + message: { + format: 'bytes', + }, + signature: { + format: 'bytes', + }, + }, +}; +export const feeHistorySchema = { + type: 'object', + properties: { + oldestBlock: { + format: 'uint', + }, + baseFeePerGas: { + type: 'array', + items: { + format: 'uint', + }, + }, + reward: { + type: 'array', + items: { + type: 'array', + items: { + format: 'uint', + }, + }, + }, + gasUsedRatio: { + type: 'array', + items: { + type: 'number', + }, + }, + }, +}; + +export const storageProofSchema = { + type: 'object', + properties: { + key: { + format: 'bytes32', + }, + value: { + format: 'uint', + }, + proof: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + }, +}; + +export const accountSchema = { + type: 'object', + properties: { + balance: { + format: 'uint', + }, + codeHash: { + format: 'bytes32', + }, + nonce: { + format: 'uint', + }, + storageHash: { + format: 'bytes32', + }, + accountProof: { + type: 'array', + items: { + format: 'bytes32', + }, + }, + storageProof: { + type: 'array', + items: { + ...storageProofSchema, + }, + }, + }, +}; diff --git a/test/merkletreejs/node_modules/web3-eth/src/types.ts b/test/merkletreejs/node_modules/web3-eth/src/types.ts new file mode 100644 index 0000000..ae97084 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/types.ts @@ -0,0 +1,88 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + ContractExecutionError, + TransactionRevertedWithoutReasonError, + TransactionRevertInstructionError, + TransactionRevertWithCustomError, + InvalidResponseError, +} from 'web3-errors'; +import { + FormatType, + ETH_DATA_FORMAT, + DataFormat, + Bytes, + ContractAbi, + HexString, + Numbers, + Transaction, + TransactionReceipt, +} from 'web3-types'; + +export type InternalTransaction = FormatType; + +export type SendTransactionEventsBase = { + sending: FormatType; + sent: FormatType; + transactionHash: FormatType; + receipt: FormatType; + confirmation: { + confirmations: FormatType; + receipt: FormatType; + latestBlockHash: FormatType; + }; + error: + | TransactionRevertedWithoutReasonError> + | TransactionRevertInstructionError> + | TransactionRevertWithCustomError> + | InvalidResponseError + | ContractExecutionError; +}; + +export type SendTransactionEvents = SendTransactionEventsBase< + ReturnFormat, + Transaction +>; +export type SendSignedTransactionEvents = + SendTransactionEventsBase; + +export interface SendTransactionOptions { + ignoreGasPricing?: boolean; + transactionResolver?: (receipt: TransactionReceipt) => ResolveType; + contractAbi?: ContractAbi; + checkRevertBeforeSending?: boolean; + ignoreFillingGasLimit?: boolean; +} + +export interface SendSignedTransactionOptions { + transactionResolver?: (receipt: TransactionReceipt) => ResolveType; + contractAbi?: ContractAbi; + checkRevertBeforeSending?: boolean; +} + +export interface RevertReason { + reason: string; + signature?: HexString; + data?: HexString; +} + +export interface RevertReasonWithCustomError extends RevertReason { + customErrorName: string; + customErrorDecodedSignature: string; + customErrorArguments: Record; +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/decode_signed_transaction.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/decode_signed_transaction.ts new file mode 100644 index 0000000..943ea18 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/decode_signed_transaction.ts @@ -0,0 +1,54 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { + DataFormat, + HexStringBytes, + SignedTransactionInfoAPI, + TransactionSignedAPI, +} from 'web3-types'; +import { bytesToHex, format, hexToBytes, keccak256 } from 'web3-utils'; +import { TransactionFactory } from 'web3-eth-accounts'; +import { detectRawTransactionType } from './detect_transaction_type.js'; +import { formatTransaction } from './format_transaction.js'; + +/** + * Decodes an [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded transaction. + * + * @param encodedSignedTransaction The RLP encoded transaction. + * @param returnFormat ({@link DataFormat} Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the RLP encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + */ +export function decodeSignedTransaction( + encodedSignedTransaction: HexStringBytes, + returnFormat: ReturnFormat, + options: { fillInputAndData?: boolean } = { fillInputAndData: false }, +): SignedTransactionInfoAPI { + return { + raw: format({ format: 'bytes' }, encodedSignedTransaction, returnFormat), + tx: formatTransaction( + { + ...TransactionFactory.fromSerializedData( + hexToBytes(encodedSignedTransaction), + ).toJSON(), + hash: bytesToHex(keccak256(hexToBytes(encodedSignedTransaction))), + type: detectRawTransactionType(hexToBytes(encodedSignedTransaction)), + } as TransactionSignedAPI, + returnFormat, + { fillInputAndData: options.fillInputAndData }, + ), + }; +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/decoding.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/decoding.ts new file mode 100644 index 0000000..f4b61c0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/decoding.ts @@ -0,0 +1,95 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { format } from 'web3-utils'; + +import { + AbiEventFragment, + LogsInput, + DataFormat, + DEFAULT_RETURN_FORMAT, + EventLog, + ContractAbiWithSignature, +} from 'web3-types'; + +import { decodeLog } from 'web3-eth-abi'; + +import { logSchema } from '../schemas.js'; +import { ALL_EVENTS } from '../constants.js'; + +export const decodeEventABI = ( + event: AbiEventFragment & { signature: string }, + data: LogsInput, + jsonInterface: ContractAbiWithSignature, + returnFormat: DataFormat = DEFAULT_RETURN_FORMAT, +): EventLog => { + let modifiedEvent = { ...event }; + + const result = format(logSchema, data, returnFormat); + + // if allEvents get the right event + if ([ALL_EVENTS, 'allEvents'].includes(modifiedEvent.name)) { + const matchedEvent = jsonInterface.find(j => j.signature === data.topics[0]); + if (matchedEvent) { + modifiedEvent = matchedEvent as AbiEventFragment & { signature: string }; + } else { + modifiedEvent = { anonymous: true } as unknown as AbiEventFragment & { + signature: string; + }; + } + } + + // create empty inputs if none are present (e.g. anonymous events on allEvents) + modifiedEvent.inputs = modifiedEvent.inputs ?? event.inputs ?? []; + + // Handle case where an event signature shadows the current ABI with non-identical + // arg indexing. If # of topics doesn't match, event is anon. + if (!modifiedEvent.anonymous) { + let indexedInputs = 0; + (modifiedEvent.inputs ?? []).forEach(input => { + if (input.indexed) { + indexedInputs += 1; + } + }); + + if (indexedInputs > 0 && data?.topics && data?.topics.length !== indexedInputs + 1) { + // checks if event is anonymous + modifiedEvent = { + ...modifiedEvent, + anonymous: true, + inputs: [], + }; + } + } + + const argTopics = modifiedEvent.anonymous ? data.topics : (data.topics ?? []).slice(1); + + return { + ...result, + returnValues: decodeLog([...(modifiedEvent.inputs ?? [])], data.data, argTopics), + event: modifiedEvent.name, + signature: + modifiedEvent.anonymous || !data.topics || data.topics.length === 0 || !data.topics[0] + ? undefined + : data.topics[0], + + raw: { + data: data.data, + topics: data.topics, + }, + }; +}; diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/detect_transaction_type.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/detect_transaction_type.ts new file mode 100644 index 0000000..ec5539b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/detect_transaction_type.ts @@ -0,0 +1,146 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { format, toHex } from 'web3-utils'; +import { TransactionTypeParser, Web3Context } from 'web3-core'; +import { EthExecutionAPI, HardforksOrdered, Transaction, ETH_DATA_FORMAT } from 'web3-types'; +import { Web3ValidatorError, isNullish, validator } from 'web3-validator'; +import { InvalidPropertiesForTransactionTypeError } from 'web3-errors'; + +import { InternalTransaction } from '../types.js'; + +// undefined is treated as null for JSON schema validator +const transactionType0x0Schema = { + type: 'object', + properties: { + accessList: { + type: 'null', + }, + maxFeePerGas: { + type: 'null', + }, + maxPriorityFeePerGas: { + type: 'null', + }, + }, +}; +const transactionType0x1Schema = { + type: 'object', + properties: { + maxFeePerGas: { + type: 'null', + }, + maxPriorityFeePerGas: { + type: 'null', + }, + }, +}; +const transactionType0x2Schema = { + type: 'object', + properties: { + gasPrice: { + type: 'null', + }, + }, +}; + +const validateTxTypeAndHandleErrors = ( + txSchema: object, + tx: Transaction, + txType: '0x0' | '0x1' | '0x2', +) => { + try { + validator.validateJSONSchema(txSchema, tx); + } catch (error) { + if (error instanceof Web3ValidatorError) + // Erroneously reported error + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + throw new InvalidPropertiesForTransactionTypeError(error.errors, txType); + + throw error; + } +}; + +export const defaultTransactionTypeParser: TransactionTypeParser = ( + transaction +) => { + const tx = transaction as unknown as Transaction; + if (!isNullish(tx.type)) { + let txSchema; + switch (tx.type) { + case '0x0': + txSchema = transactionType0x0Schema; + break; + case '0x1': + txSchema = transactionType0x1Schema; + break; + case '0x2': + txSchema = transactionType0x2Schema; + break; + + default: + return format({ format: 'uint' }, tx.type, ETH_DATA_FORMAT); + } + + validateTxTypeAndHandleErrors(txSchema, tx, tx.type); + + return format({ format: 'uint' }, tx.type, ETH_DATA_FORMAT); + } + + if (!isNullish(tx.maxFeePerGas) || !isNullish(tx.maxPriorityFeePerGas)) { + validateTxTypeAndHandleErrors(transactionType0x2Schema, tx, '0x2'); + return '0x2'; + } + + if (!isNullish(tx.accessList)) { + validateTxTypeAndHandleErrors(transactionType0x1Schema, tx, '0x1'); + return '0x1'; + } + + const givenHardfork = tx.hardfork ?? tx.common?.hardfork; + + if (!isNullish(givenHardfork)) { + const hardforkIndex = Object.keys(HardforksOrdered).indexOf(givenHardfork); + + // givenHardfork is London or later, so EIP-2718 is supported + if (hardforkIndex >= Object.keys(HardforksOrdered).indexOf('london')) + return !isNullish(tx.gasPrice) ? '0x0' : '0x2'; + + // givenHardfork is Berlin, tx.accessList is undefined, assume type is 0x0 + if (hardforkIndex === Object.keys(HardforksOrdered).indexOf('berlin')) return '0x0'; + } + + // gasprice is defined + if (!isNullish(tx.gasPrice)) { + validateTxTypeAndHandleErrors(transactionType0x0Schema, tx, '0x0'); + return '0x0'; + } + + // no transaction type can be inferred from properties, use default transaction type + return undefined; +}; + +export const detectTransactionType = ( + transaction: InternalTransaction, + web3Context?: Web3Context, +) => + (web3Context?.transactionTypeParser ?? defaultTransactionTypeParser)( + transaction as unknown as Record + ); + +export const detectRawTransactionType = (transaction: Uint8Array) => + transaction[0] > 0x7f ? '0x0' : toHex(transaction[0]); diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/format_transaction.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/format_transaction.ts new file mode 100644 index 0000000..5333254 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/format_transaction.ts @@ -0,0 +1,76 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Transaction, DataFormat, DEFAULT_RETURN_FORMAT, FormatType } from 'web3-types'; +import { isNullish, ValidationSchemaInput } from 'web3-validator'; +import { mergeDeep, format, bytesToHex, toHex } from 'web3-utils'; +import { TransactionDataAndInputError } from 'web3-errors'; + +import { transactionInfoSchema, transactionSchema } from '../schemas.js'; + +export function formatTransaction< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + TransactionType extends Transaction = Transaction, +>( + transaction: TransactionType, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + options: { + transactionSchema?: ValidationSchemaInput | typeof transactionSchema; + fillInputAndData?: boolean; + } = { + transactionSchema: transactionInfoSchema, + fillInputAndData: false, + }, +): FormatType { + let formattedTransaction = mergeDeep({}, transaction as Record) as Transaction; + if (!isNullish(transaction?.common)) { + formattedTransaction.common = { ...transaction.common }; + if (!isNullish(transaction.common?.customChain)) + formattedTransaction.common.customChain = { ...transaction.common.customChain }; + } + formattedTransaction = format( + options.transactionSchema ?? transactionInfoSchema, + formattedTransaction, + returnFormat, + ); + if ( + !isNullish(formattedTransaction.data) && + !isNullish(formattedTransaction.input) && + // Converting toHex is accounting for data and input being Uint8Arrays + // since comparing Uint8Array is not as straightforward as comparing strings + toHex(formattedTransaction.data) !== toHex(formattedTransaction.input) + ) + throw new TransactionDataAndInputError({ + data: bytesToHex(formattedTransaction.data), + input: bytesToHex(formattedTransaction.input), + }); + + if (options.fillInputAndData) { + if (!isNullish(formattedTransaction.data)) { + formattedTransaction.input = formattedTransaction.data; + } else if (!isNullish(formattedTransaction.input)) { + formattedTransaction.data = formattedTransaction.input; + } + } + + if (!isNullish(formattedTransaction.gasLimit)) { + formattedTransaction.gas = formattedTransaction.gasLimit; + delete formattedTransaction.gasLimit; + } + + return formattedTransaction as FormatType; +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/get_revert_reason.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/get_revert_reason.ts new file mode 100644 index 0000000..4b4b7d5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/get_revert_reason.ts @@ -0,0 +1,94 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Context } from 'web3-core'; +import { ContractExecutionError, Eip838ExecutionError, InvalidResponseError } from 'web3-errors'; +import { decodeContractErrorData, isAbiErrorFragment } from 'web3-eth-abi'; +import { + AbiErrorFragment, + ContractAbi, + DataFormat, + DEFAULT_RETURN_FORMAT, + EthExecutionAPI, + TransactionCall, +} from 'web3-types'; + +// eslint-disable-next-line import/no-cycle +import { call } from '../rpc_method_wrappers.js'; +import { RevertReason, RevertReasonWithCustomError } from '../types.js'; + +export const parseTransactionError = (error: unknown, contractAbi?: ContractAbi) => { + if ( + error instanceof ContractExecutionError && + error.innerError instanceof Eip838ExecutionError + ) { + if (contractAbi !== undefined) { + const errorsAbi = contractAbi.filter(abi => + isAbiErrorFragment(abi), + ) as unknown as AbiErrorFragment[]; + decodeContractErrorData(errorsAbi, error.innerError); + + return { + reason: error.innerError.message, + signature: error.innerError.data?.slice(0, 10), + data: error.innerError.data?.substring(10), + customErrorName: error.innerError.errorName, + customErrorDecodedSignature: error.innerError.errorSignature, + customErrorArguments: error.innerError.errorArgs, + } as RevertReasonWithCustomError; + } + + return { + reason: error.innerError.message, + signature: error.innerError.data?.slice(0, 10), + data: error.innerError.data?.substring(10), + } as RevertReason; + } + + if ( + error instanceof InvalidResponseError && + !Array.isArray(error.innerError) && + error.innerError !== undefined + ) { + return error.innerError.message; + } + + throw error; +}; + +/** + * Returns the revert reason generated by the EVM if the transaction were to be executed. + * + * @param web3Context - ({@link Web3Context}) Web3 configuration object that contains things such as the provider, request manager, wallet, etc. + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @returns `undefined` if no revert reason was given, a revert reason object, a revert reason string, or an `unknown` error + */ +export async function getRevertReason< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, +>( + web3Context: Web3Context, + transaction: TransactionCall, + contractAbi?: ContractAbi, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, +): Promise { + try { + await call(web3Context, transaction, web3Context.defaultBlock, returnFormat); + return undefined; + } catch (error) { + return parseTransactionError(error, contractAbi); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/get_transaction_error.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/get_transaction_error.ts new file mode 100644 index 0000000..4cb0f52 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/get_transaction_error.ts @@ -0,0 +1,93 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Context } from 'web3-core'; +import { + TransactionRevertedWithoutReasonError, + TransactionRevertInstructionError, + TransactionRevertWithCustomError, +} from 'web3-errors'; +import { + DataFormat, + FormatType, + ContractAbi, + TransactionCall, + TransactionReceipt, +} from 'web3-types'; +import { RevertReason, RevertReasonWithCustomError } from '../types.js'; +// eslint-disable-next-line import/no-cycle +import { getRevertReason, parseTransactionError } from './get_revert_reason.js'; + +export async function getTransactionError( + web3Context: Web3Context, + transactionFormatted?: TransactionCall, + transactionReceiptFormatted?: FormatType, + receivedError?: unknown, + contractAbi?: ContractAbi, + knownReason?: string | RevertReason | RevertReasonWithCustomError, +) { + let _reason: string | RevertReason | RevertReasonWithCustomError | undefined = knownReason; + + if (_reason === undefined) { + if (receivedError !== undefined) { + _reason = parseTransactionError(receivedError); + } else if (web3Context.handleRevert && transactionFormatted !== undefined) { + _reason = await getRevertReason(web3Context, transactionFormatted, contractAbi); + } + } + + let error: + | TransactionRevertedWithoutReasonError> + | TransactionRevertInstructionError> + | TransactionRevertWithCustomError>; + if (_reason === undefined) { + error = new TransactionRevertedWithoutReasonError< + FormatType + >(transactionReceiptFormatted); + } else if (typeof _reason === 'string') { + error = new TransactionRevertInstructionError>( + _reason, + undefined, + transactionReceiptFormatted, + ); + } else if ( + (_reason as RevertReasonWithCustomError).customErrorName !== undefined && + (_reason as RevertReasonWithCustomError).customErrorDecodedSignature !== undefined && + (_reason as RevertReasonWithCustomError).customErrorArguments !== undefined + ) { + const reasonWithCustomError: RevertReasonWithCustomError = + _reason as RevertReasonWithCustomError; + error = new TransactionRevertWithCustomError>( + reasonWithCustomError.reason, + reasonWithCustomError.customErrorName, + reasonWithCustomError.customErrorDecodedSignature, + reasonWithCustomError.customErrorArguments, + reasonWithCustomError.signature, + transactionReceiptFormatted, + reasonWithCustomError.data, + ); + } else { + error = new TransactionRevertInstructionError>( + _reason.reason, + _reason.signature, + transactionReceiptFormatted, + _reason.data, + ); + } + + return error; +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/get_transaction_gas_pricing.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/get_transaction_gas_pricing.ts new file mode 100644 index 0000000..e5bbcde --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/get_transaction_gas_pricing.ts @@ -0,0 +1,114 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Context } from 'web3-core'; +import { + EthExecutionAPI, + Numbers, + Transaction, + DataFormat, + FormatType, + ETH_DATA_FORMAT, +} from 'web3-types'; +import { isNullish } from 'web3-validator'; +import { Eip1559NotSupportedError, UnsupportedTransactionTypeError } from 'web3-errors'; +import { format } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { getBlock, getGasPrice } from '../rpc_method_wrappers.js'; +import { InternalTransaction } from '../types.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionType } from './transaction_builder.js'; + +async function getEip1559GasPricing( + transaction: FormatType, + web3Context: Web3Context, + returnFormat: ReturnFormat, +): Promise> { + const block = await getBlock(web3Context, web3Context.defaultBlock, false, returnFormat); + + if (isNullish(block.baseFeePerGas)) throw new Eip1559NotSupportedError(); + + if (!isNullish(transaction.gasPrice)) { + const convertedTransactionGasPrice = format( + { format: 'uint' }, + transaction.gasPrice as Numbers, + returnFormat, + ); + + return { + maxPriorityFeePerGas: convertedTransactionGasPrice, + maxFeePerGas: convertedTransactionGasPrice, + }; + } + return { + maxPriorityFeePerGas: format( + { format: 'uint' }, + transaction.maxPriorityFeePerGas ?? web3Context.defaultMaxPriorityFeePerGas, + returnFormat, + ), + maxFeePerGas: format( + { format: 'uint' }, + (transaction.maxFeePerGas ?? + BigInt(block.baseFeePerGas) * BigInt(2) + + BigInt( + transaction.maxPriorityFeePerGas ?? web3Context.defaultMaxPriorityFeePerGas, + )) as Numbers, + returnFormat, + ), + }; +} + +export async function getTransactionGasPricing( + transaction: InternalTransaction, + web3Context: Web3Context, + returnFormat: ReturnFormat, +): Promise< + | FormatType< + { gasPrice?: Numbers; maxPriorityFeePerGas?: Numbers; maxFeePerGas?: Numbers }, + ReturnFormat + > + | undefined +> { + const transactionType = getTransactionType(transaction, web3Context); + if (!isNullish(transactionType)) { + if (transactionType.startsWith('-')) + throw new UnsupportedTransactionTypeError(transactionType); + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2718.md#transactions + if (Number(transactionType) < 0 || Number(transactionType) > 127) + throw new UnsupportedTransactionTypeError(transactionType); + + if ( + isNullish(transaction.gasPrice) && + (transactionType === '0x0' || transactionType === '0x1') + ) + return { + gasPrice: await getGasPrice(web3Context, returnFormat), + maxPriorityFeePerGas: undefined, + maxFeePerGas: undefined, + }; + + if (transactionType === '0x2') { + return { + gasPrice: undefined, + ...(await getEip1559GasPricing(transaction, web3Context, returnFormat)), + }; + } + } + + return undefined; +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/index.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/index.ts new file mode 100644 index 0000000..1251c4a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/index.ts @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './detect_transaction_type.js'; +export * from './format_transaction.js'; +export * from './prepare_transaction_for_signing.js'; +export * from './transaction_builder.js'; diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/prepare_transaction_for_signing.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/prepare_transaction_for_signing.ts new file mode 100644 index 0000000..42072d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/prepare_transaction_for_signing.ts @@ -0,0 +1,149 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + EthExecutionAPI, + HexString, + PopulatedUnsignedEip1559Transaction, + PopulatedUnsignedEip2930Transaction, + PopulatedUnsignedTransaction, + Transaction, + ValidChains, + FormatType, + ETH_DATA_FORMAT, +} from 'web3-types'; +import { Web3Context } from 'web3-core'; +import { toNumber } from 'web3-utils'; +import { TransactionFactory, TxOptions, Common } from 'web3-eth-accounts'; +import { isNullish } from 'web3-validator'; +import { validateTransactionForSigning } from '../validation.js'; +import { formatTransaction } from './format_transaction.js'; +import { transactionBuilder } from './transaction_builder.js'; + +const getEthereumjsTxDataFromTransaction = ( + transaction: FormatType, +) => ({ + nonce: transaction.nonce, + gasPrice: transaction.gasPrice, + gasLimit: transaction.gasLimit ?? transaction.gas, + to: transaction.to, + value: transaction.value, + data: transaction.data ?? transaction.input, + type: transaction.type, + chainId: transaction.chainId, + accessList: ( + transaction as FormatType + ).accessList, + maxPriorityFeePerGas: ( + transaction as FormatType + ).maxPriorityFeePerGas, + maxFeePerGas: ( + transaction as FormatType + ).maxFeePerGas, +}); + +const getEthereumjsTransactionOptions = ( + transaction: FormatType, + web3Context: Web3Context, +) => { + const hasTransactionSigningOptions = + (!isNullish(transaction.chain) && !isNullish(transaction.hardfork)) || + !isNullish(transaction.common); + + let common; + if (!hasTransactionSigningOptions) { + // if defaultcommon is specified, use that. + if (web3Context.defaultCommon) { + common = web3Context.defaultCommon; + + if (isNullish(common.hardfork)) + common.hardfork = transaction.hardfork ?? web3Context.defaultHardfork; + if (isNullish(common.baseChain)) + common.baseChain = web3Context.defaultChain as ValidChains; + } else { + common = Common.custom( + { + name: 'custom-network', + chainId: toNumber(transaction.chainId) as number, + networkId: !isNullish(transaction.networkId) + ? (toNumber(transaction.networkId) as number) + : undefined, + defaultHardfork: transaction.hardfork ?? web3Context.defaultHardfork, + }, + { + baseChain: web3Context.defaultChain, + }, + ); + } + } else { + const name = + transaction?.common?.customChain?.name ?? transaction.chain ?? 'custom-network'; + const chainId = toNumber( + transaction?.common?.customChain?.chainId ?? transaction?.chainId, + ) as number; + const networkId = toNumber( + transaction?.common?.customChain?.networkId ?? transaction?.networkId, + ) as number; + const defaultHardfork = + transaction?.common?.hardfork ?? transaction?.hardfork ?? web3Context.defaultHardfork; + const baseChain = + transaction.common?.baseChain ?? transaction.chain ?? web3Context.defaultChain; + + if (chainId && networkId && name) { + common = Common.custom( + { + name, + chainId, + networkId, + defaultHardfork, + }, + { + baseChain, + }, + ); + } + } + return { common } as TxOptions; +}; + +export const prepareTransactionForSigning = async ( + transaction: Transaction, + web3Context: Web3Context, + privateKey?: HexString | Uint8Array, + fillGasPrice = false, + fillGasLimit = true, +) => { + const populatedTransaction = (await transactionBuilder({ + transaction, + web3Context, + privateKey, + fillGasPrice, + fillGasLimit, + })) as unknown as PopulatedUnsignedTransaction; + const formattedTransaction = formatTransaction( + populatedTransaction, + ETH_DATA_FORMAT, + ) as unknown as FormatType; + validateTransactionForSigning( + formattedTransaction as unknown as FormatType, + ); + + return TransactionFactory.fromTxData( + getEthereumjsTxDataFromTransaction(formattedTransaction), + getEthereumjsTransactionOptions(formattedTransaction, web3Context), + ); +}; diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/reject_if_block_timeout.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/reject_if_block_timeout.ts new file mode 100644 index 0000000..2019ce3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/reject_if_block_timeout.ts @@ -0,0 +1,177 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { EthExecutionAPI, Bytes, Web3BaseProvider, BlockHeaderOutput } from 'web3-types'; +import { Web3Context } from 'web3-core'; +import { rejectIfConditionAtInterval } from 'web3-utils'; + +import { TransactionBlockTimeoutError } from 'web3-errors'; +import { NUMBER_DATA_FORMAT } from '../constants.js'; +// eslint-disable-next-line import/no-cycle +import { getBlockNumber } from '../rpc_method_wrappers.js'; +import { NewHeadsSubscription } from '../web3_subscriptions.js'; + +export interface ResourceCleaner { + clean: () => void; +} + +function resolveByPolling( + web3Context: Web3Context, + starterBlockNumber: number, + transactionHash?: Bytes, +): [Promise, ResourceCleaner] { + const pollingInterval = web3Context.transactionPollingInterval; + const [intervalId, promiseToError] = + rejectIfConditionAtInterval(async () => { + let lastBlockNumber; + try { + lastBlockNumber = await getBlockNumber(web3Context, NUMBER_DATA_FORMAT); + } catch (error) { + console.warn('An error happen while trying to get the block number', error); + return undefined; + } + const numberOfBlocks = lastBlockNumber - starterBlockNumber; + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + return new TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + }); + } + return undefined; + }, pollingInterval); + + const clean = () => { + clearInterval(intervalId); + }; + + return [promiseToError, { clean }]; +} + +async function resolveBySubscription( + web3Context: Web3Context, + starterBlockNumber: number, + transactionHash?: Bytes, +): Promise<[Promise, ResourceCleaner]> { + // The following variable will stay true except if the data arrived, + // or if watching started after an error had occurred. + let needToWatchLater = true; + + let subscription: NewHeadsSubscription; + let resourceCleaner: ResourceCleaner; + // internal helper function + function revertToPolling( + reject: (value: Error | PromiseLike) => void, + previousError?: Error, + ) { + if (previousError) { + console.warn('error happened at subscription. So revert to polling...', previousError); + } + resourceCleaner.clean(); + + needToWatchLater = false; + const [promiseToError, newResourceCleaner] = resolveByPolling( + web3Context, + starterBlockNumber, + transactionHash, + ); + resourceCleaner.clean = newResourceCleaner.clean; + promiseToError.catch(error => reject(error as Error)); + } + try { + subscription = (await web3Context.subscriptionManager?.subscribe( + 'newHeads', + )) as unknown as NewHeadsSubscription; + resourceCleaner = { + clean: () => { + // Remove the subscription, if it was not removed somewhere + // else by calling, for example, subscriptionManager.clear() + if (subscription.id) { + web3Context.subscriptionManager + ?.removeSubscription(subscription) + .then(() => { + // Subscription ended successfully + }) + .catch(() => { + // An error happened while ending subscription. But no need to take any action. + }); + } + }, + }; + } catch (error) { + return resolveByPolling(web3Context, starterBlockNumber, transactionHash); + } + const promiseToError: Promise = new Promise((_, reject) => { + try { + subscription.on('data', (lastBlockHeader: BlockHeaderOutput) => { + needToWatchLater = false; + if (!lastBlockHeader?.number) { + return; + } + const numberOfBlocks = Number( + BigInt(lastBlockHeader.number) - BigInt(starterBlockNumber), + ); + + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + // Transaction Block Timeout is known to be reached by subscribing to new heads + reject( + new TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + }), + ); + } + }); + subscription.on('error', error => { + revertToPolling(reject, error); + }); + } catch (error) { + revertToPolling(reject, error as Error); + } + + // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds] + setTimeout(() => { + if (needToWatchLater) { + revertToPolling(reject); + } + }, web3Context.blockHeaderTimeout * 1000); + }); + + return [promiseToError, resourceCleaner]; +} + +/* TODO: After merge, there will be constant block mining time (exactly 12 second each block, except slot missed that currently happens in <1% of slots. ) so we can optimize following function +for POS NWs, we can skip checking getBlockNumber(); after interval and calculate only based on time that certain num of blocked are mined after that for internal double check, can do one getBlockNumber() call and timeout. +*/ +export async function rejectIfBlockTimeout( + web3Context: Web3Context, + transactionHash?: Bytes, +): Promise<[Promise, ResourceCleaner]> { + const { provider } = web3Context.requestManager; + let callingRes: [Promise, ResourceCleaner]; + const starterBlockNumber = await getBlockNumber(web3Context, NUMBER_DATA_FORMAT); + // TODO: once https://github.com/web3/web3.js/issues/5521 is implemented, remove checking for `enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout` + if ( + (provider as Web3BaseProvider).supportsSubscriptions?.() && + web3Context.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout + ) { + callingRes = await resolveBySubscription(web3Context, starterBlockNumber, transactionHash); + } else { + callingRes = resolveByPolling(web3Context, starterBlockNumber, transactionHash); + } + return callingRes; +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/send_tx_helper.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/send_tx_helper.ts new file mode 100644 index 0000000..3cc7674 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/send_tx_helper.ts @@ -0,0 +1,299 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { + ETH_DATA_FORMAT, + FormatType, + DataFormat, + EthExecutionAPI, + TransactionWithSenderAPI, + Web3BaseWalletAccount, + HexString, + TransactionReceipt, + Transaction, + TransactionCall, + TransactionWithFromLocalWalletIndex, + TransactionWithToLocalWalletIndex, + TransactionWithFromAndToLocalWalletIndex, + LogsInput, + TransactionHash, + ContractAbiWithSignature, +} from 'web3-types'; +import { Web3Context, Web3EventEmitter, Web3PromiEvent } from 'web3-core'; +import { isNullish } from 'web3-validator'; +import { + ContractExecutionError, + InvalidResponseError, + TransactionRevertedWithoutReasonError, + TransactionRevertInstructionError, + TransactionRevertWithCustomError, +} from 'web3-errors'; +import { ethRpcMethods } from 'web3-rpc-methods'; + +import { + SendSignedTransactionEvents, + SendTransactionEvents, + SendTransactionOptions, +} from '../types.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionGasPricing } from './get_transaction_gas_pricing.js'; +// eslint-disable-next-line import/no-cycle +import { trySendTransaction } from './try_send_transaction.js'; +// eslint-disable-next-line import/no-cycle +import { watchTransactionForConfirmations } from './watch_transaction_for_confirmations.js'; +import { ALL_EVENTS_ABI } from '../constants.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionError } from './get_transaction_error.js'; +// eslint-disable-next-line import/no-cycle +import { getRevertReason } from './get_revert_reason.js'; +import { decodeEventABI } from './decoding.js'; + +export class SendTxHelper< + ReturnFormat extends DataFormat, + ResolveType = FormatType, + TxType = + | Transaction + | TransactionWithFromLocalWalletIndex + | TransactionWithToLocalWalletIndex + | TransactionWithFromAndToLocalWalletIndex, +> { + private readonly web3Context: Web3Context; + private readonly promiEvent: Web3PromiEvent< + ResolveType, + SendSignedTransactionEvents | SendTransactionEvents + >; + private readonly options: SendTransactionOptions = { + checkRevertBeforeSending: true, + }; + private readonly returnFormat: ReturnFormat; + public constructor({ + options, + web3Context, + promiEvent, + returnFormat, + }: { + web3Context: Web3Context; + options: SendTransactionOptions; + promiEvent: Web3PromiEvent< + ResolveType, + SendSignedTransactionEvents | SendTransactionEvents + >; + returnFormat: ReturnFormat; + }) { + this.options = options; + this.web3Context = web3Context; + this.promiEvent = promiEvent; + this.returnFormat = returnFormat; + } + + public getReceiptWithEvents(data: TransactionReceipt): ResolveType { + const result = { ...(data ?? {}) }; + if (this.options?.contractAbi && result.logs && result.logs.length > 0) { + result.events = {}; + for (const log of result.logs) { + const event = decodeEventABI( + ALL_EVENTS_ABI, + log as LogsInput, + this.options?.contractAbi as ContractAbiWithSignature, + this.returnFormat, + ); + if (event.event) { + result.events[event.event] = event; + } + } + } + + return result as unknown as ResolveType; + } + + public async checkRevertBeforeSending(tx: TransactionCall) { + if (this.options.checkRevertBeforeSending !== false) { + const reason = await getRevertReason(this.web3Context, tx, this.options.contractAbi); + if (reason !== undefined) { + throw await getTransactionError( + this.web3Context, + tx, + undefined, + undefined, + this.options.contractAbi, + reason, + ); + } + } + } + + public emitSending(tx: TxType | HexString) { + if (this.promiEvent.listenerCount('sending') > 0) { + this.promiEvent.emit('sending', tx); + } + } + + public async populateGasPrice({ + transactionFormatted, + transaction, + }: { + transactionFormatted: TxType; + transaction: TxType; + }): Promise { + let result = transactionFormatted; + if ( + !this.options?.ignoreGasPricing && + isNullish((transactionFormatted as Transaction).gasPrice) && + (isNullish((transaction as Transaction).maxPriorityFeePerGas) || + isNullish((transaction as Transaction).maxFeePerGas)) + ) { + result = { + ...transactionFormatted, + // TODO gasPrice, maxPriorityFeePerGas, maxFeePerGas + // should not be included if undefined, but currently are + ...(await getTransactionGasPricing( + transactionFormatted, + this.web3Context, + ETH_DATA_FORMAT, + )), + }; + } + + return result; + } + + public async signAndSend({ + wallet, + tx, + }: { + wallet: Web3BaseWalletAccount | undefined; + tx: TxType; + }) { + if (wallet) { + const signedTransaction = await wallet.signTransaction(tx); + + return trySendTransaction( + this.web3Context, + async (): Promise => + ethRpcMethods.sendRawTransaction( + this.web3Context.requestManager, + signedTransaction.rawTransaction, + ), + signedTransaction.transactionHash, + ); + } + return trySendTransaction( + this.web3Context, + async (): Promise => + ethRpcMethods.sendTransaction( + this.web3Context.requestManager, + tx as Partial, + ), + ); + } + + public emitSent(tx: TxType | HexString) { + if (this.promiEvent.listenerCount('sent') > 0) { + this.promiEvent.emit('sent', tx); + } + } + public emitTransactionHash(hash: string & Uint8Array) { + if (this.promiEvent.listenerCount('transactionHash') > 0) { + this.promiEvent.emit('transactionHash', hash); + } + } + + public emitReceipt(receipt: ResolveType) { + if (this.promiEvent.listenerCount('receipt') > 0) { + ( + this.promiEvent as Web3EventEmitter< + SendTransactionEvents | SendSignedTransactionEvents + > + ).emit( + 'receipt', + // @ts-expect-error unknown type fix + receipt, + ); + } + } + + public async handleError({ error, tx }: { error: unknown; tx: TransactionCall }) { + let _error = error; + + if (_error instanceof ContractExecutionError && this.web3Context.handleRevert) { + _error = await getTransactionError( + this.web3Context, + tx, + undefined, + undefined, + this.options?.contractAbi, + ); + } + + if ( + (_error instanceof InvalidResponseError || + _error instanceof ContractExecutionError || + _error instanceof TransactionRevertWithCustomError || + _error instanceof TransactionRevertedWithoutReasonError || + _error instanceof TransactionRevertInstructionError) && + this.promiEvent.listenerCount('error') > 0 + ) { + this.promiEvent.emit('error', _error); + } + + return _error; + } + + public emitConfirmation({ + receipt, + transactionHash, + }: { + receipt: ResolveType; + transactionHash: TransactionHash; + }) { + if (this.promiEvent.listenerCount('confirmation') > 0) { + watchTransactionForConfirmations< + ReturnFormat, + SendSignedTransactionEvents | SendTransactionEvents, + ResolveType + >( + this.web3Context, + this.promiEvent, + receipt as unknown as TransactionReceipt, + transactionHash, + this.returnFormat, + ); + } + } + + public async handleResolve({ receipt, tx }: { receipt: ResolveType; tx: TransactionCall }) { + if (this.options?.transactionResolver) { + return this.options?.transactionResolver(receipt as unknown as TransactionReceipt); + } + if ((receipt as unknown as TransactionReceipt).status === BigInt(0)) { + const error = await getTransactionError( + this.web3Context, + tx, + // @ts-expect-error unknown type fix + receipt, + undefined, + this.options?.contractAbi, + ); + if (this.promiEvent.listenerCount('error') > 0) { + this.promiEvent.emit('error', error); + } + + throw error; + } else { + return receipt; + } + } +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/transaction_builder.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/transaction_builder.ts new file mode 100644 index 0000000..13edd25 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/transaction_builder.ts @@ -0,0 +1,265 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + EthExecutionAPI, + Address, + HexString, + ValidChains, + Hardfork, + Transaction, + TransactionWithFromLocalWalletIndex, + TransactionWithToLocalWalletIndex, + TransactionWithFromAndToLocalWalletIndex, + Common, + Web3NetAPI, + Numbers, + DataFormat, + DEFAULT_RETURN_FORMAT, + FormatType, + ETH_DATA_FORMAT, +} from 'web3-types'; +import { Web3Context } from 'web3-core'; +import { privateKeyToAddress } from 'web3-eth-accounts'; +import { getId } from 'web3-net'; +import { isNullish, isNumber, isHexStrict, isAddress } from 'web3-validator'; +import { + InvalidTransactionWithSender, + InvalidTransactionWithReceiver, + LocalWalletNotAvailableError, + TransactionDataAndInputError, + UnableToPopulateNonceError, +} from 'web3-errors'; +import { bytesToHex, format } from 'web3-utils'; +import { NUMBER_DATA_FORMAT } from '../constants.js'; +// eslint-disable-next-line import/no-cycle +import { getChainId, getTransactionCount, estimateGas } from '../rpc_method_wrappers.js'; +import { detectTransactionType } from './detect_transaction_type.js'; +import { transactionSchema } from '../schemas.js'; +import { InternalTransaction } from '../types.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionGasPricing } from './get_transaction_gas_pricing.js'; + +export const getTransactionFromOrToAttr = ( + attr: 'from' | 'to', + web3Context: Web3Context, + transaction?: + | Transaction + | TransactionWithFromLocalWalletIndex + | TransactionWithToLocalWalletIndex + | TransactionWithFromAndToLocalWalletIndex, + privateKey?: HexString | Uint8Array, +): Address | undefined => { + if (transaction !== undefined && attr in transaction && transaction[attr] !== undefined) { + if (typeof transaction[attr] === 'string' && isAddress(transaction[attr] as string)) { + return transaction[attr] as Address; + } + if (!isHexStrict(transaction[attr] as string) && isNumber(transaction[attr] as Numbers)) { + if (web3Context.wallet) { + const account = web3Context.wallet.get( + format({ format: 'uint' }, transaction[attr] as Numbers, NUMBER_DATA_FORMAT), + ); + + if (!isNullish(account)) { + return account.address; + } + + throw new LocalWalletNotAvailableError(); + } + throw new LocalWalletNotAvailableError(); + } else { + throw attr === 'from' + ? new InvalidTransactionWithSender(transaction.from) + : // eslint-disable-next-line @typescript-eslint/no-unsafe-call + new InvalidTransactionWithReceiver(transaction.to); + } + } + if (attr === 'from') { + if (!isNullish(privateKey)) return privateKeyToAddress(privateKey); + if (!isNullish(web3Context.defaultAccount)) return web3Context.defaultAccount; + } + + return undefined; +}; + +export const getTransactionNonce = async ( + web3Context: Web3Context, + address?: Address, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, +) => { + if (isNullish(address)) { + // TODO if (web3.eth.accounts.wallet) use address from local wallet + throw new UnableToPopulateNonceError(); + } + + return getTransactionCount(web3Context, address, web3Context.defaultBlock, returnFormat); +}; + +export const getTransactionType = ( + transaction: FormatType, + web3Context: Web3Context, +) => { + const inferredType = detectTransactionType(transaction, web3Context); + if (!isNullish(inferredType)) return inferredType; + if (!isNullish(web3Context.defaultTransactionType)) + return format({ format: 'uint' }, web3Context.defaultTransactionType, ETH_DATA_FORMAT); + + return undefined; +}; + +// Keep in mind that the order the properties of populateTransaction get populated matters +// as some of the properties are dependent on others +export async function defaultTransactionBuilder(options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; + fillGasLimit?: boolean; +}): Promise { + let populatedTransaction = format( + transactionSchema, + options.transaction, + DEFAULT_RETURN_FORMAT, + ) as InternalTransaction; + + if (isNullish(populatedTransaction.from)) { + populatedTransaction.from = getTransactionFromOrToAttr( + 'from', + options.web3Context, + undefined, + options.privateKey, + ); + } + + // TODO: Debug why need to typecase getTransactionNonce + if (isNullish(populatedTransaction.nonce)) { + populatedTransaction.nonce = await getTransactionNonce( + options.web3Context, + populatedTransaction.from, + ETH_DATA_FORMAT, + ); + } + + if (isNullish(populatedTransaction.value)) { + populatedTransaction.value = '0x0'; + } + + if (!isNullish(populatedTransaction.data)) { + if ( + !isNullish(populatedTransaction.input) && + populatedTransaction.data !== populatedTransaction.input + ) + throw new TransactionDataAndInputError({ + data: bytesToHex(populatedTransaction.data), + input: bytesToHex(populatedTransaction.input), + }); + + if (!populatedTransaction.data.startsWith('0x')) + populatedTransaction.data = `0x${populatedTransaction.data}`; + } else if (!isNullish(populatedTransaction.input)) { + if (!populatedTransaction.input.startsWith('0x')) + populatedTransaction.input = `0x${populatedTransaction.input}`; + } else { + populatedTransaction.input = '0x'; + } + + if (isNullish(populatedTransaction.common)) { + if (options.web3Context.defaultCommon) { + const common = options.web3Context.defaultCommon as unknown as Common; + const chainId = common.customChain.chainId as string; + const networkId = common.customChain.networkId as string; + const name = common.customChain.name as string; + populatedTransaction.common = { + ...common, + customChain: { chainId, networkId, name }, + }; + } + + if (isNullish(populatedTransaction.chain)) { + populatedTransaction.chain = options.web3Context.defaultChain as ValidChains; + } + if (isNullish(populatedTransaction.hardfork)) { + populatedTransaction.hardfork = options.web3Context.defaultHardfork as Hardfork; + } + } + + if ( + isNullish(populatedTransaction.chainId) && + isNullish(populatedTransaction.common?.customChain.chainId) + ) { + populatedTransaction.chainId = await getChainId(options.web3Context, ETH_DATA_FORMAT); + } + + if (isNullish(populatedTransaction.networkId)) { + populatedTransaction.networkId = + (options.web3Context.defaultNetworkId as string) ?? + (await getId(options.web3Context, ETH_DATA_FORMAT)); + } + + if (isNullish(populatedTransaction.gasLimit) && !isNullish(populatedTransaction.gas)) { + populatedTransaction.gasLimit = populatedTransaction.gas; + } + + populatedTransaction.type = getTransactionType(populatedTransaction, options.web3Context); + if ( + isNullish(populatedTransaction.accessList) && + (populatedTransaction.type === '0x1' || populatedTransaction.type === '0x2') + ) { + populatedTransaction.accessList = []; + } + if (options.fillGasPrice) + populatedTransaction = { + ...populatedTransaction, + ...(await getTransactionGasPricing( + populatedTransaction, + options.web3Context, + ETH_DATA_FORMAT, + )), + }; + if ( + isNullish(populatedTransaction.gas) && + isNullish(populatedTransaction.gasLimit) && + options.fillGasLimit + ) { + const fillGasLimit = await estimateGas( + options.web3Context, + populatedTransaction, + 'latest', + ETH_DATA_FORMAT, + ); + populatedTransaction = { + ...populatedTransaction, + gas: format({ format: 'uint' }, fillGasLimit as Numbers, ETH_DATA_FORMAT), + }; + } + return populatedTransaction as ReturnType; +} + +export const transactionBuilder = async ( + options: { + transaction: Transaction; + web3Context: Web3Context; + privateKey?: HexString | Uint8Array; + fillGasPrice?: boolean; + fillGasLimit?: boolean; + }, + // eslint-disable-next-line @typescript-eslint/require-await +) => + (options.web3Context.transactionBuilder ?? defaultTransactionBuilder)({ + ...options, + transaction: options.transaction, + }) as unknown as ReturnType; diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/try_send_transaction.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/try_send_transaction.ts new file mode 100644 index 0000000..b3a677c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/try_send_transaction.ts @@ -0,0 +1,61 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3Context } from 'web3-core'; +import { EthExecutionAPI, Bytes } from 'web3-types'; +import { AsyncFunction, rejectIfTimeout } from 'web3-utils'; +import { TransactionSendTimeoutError } from 'web3-errors'; + +// eslint-disable-next-line import/no-cycle +import { rejectIfBlockTimeout } from './reject_if_block_timeout.js'; + +/** + * An internal function to send a transaction or throws if sending did not finish during the timeout during the blocks-timeout. + * @param web3Context - the context to read the configurations from + * @param sendTransactionFunc - the function that will send the transaction (could be sendTransaction or sendRawTransaction) + * @param transactionHash - to be used inside the exception message if there will be any exceptions. + * @returns the Promise returned by the `sendTransactionFunc`. + */ +export async function trySendTransaction( + web3Context: Web3Context, + sendTransactionFunc: AsyncFunction, + transactionHash?: Bytes, +): Promise { + const [timeoutId, rejectOnTimeout] = rejectIfTimeout( + web3Context.transactionSendTimeout, + new TransactionSendTimeoutError({ + numberOfSeconds: web3Context.transactionSendTimeout / 1000, + transactionHash, + }), + ); + + const [rejectOnBlockTimeout, blockTimeoutResourceCleaner] = await rejectIfBlockTimeout( + web3Context, + transactionHash, + ); + + try { + // If an error happened here, do not catch it, just clear the resources before raising it to the caller function. + return await Promise.race([ + sendTransactionFunc(), // this is the function that will send the transaction + rejectOnTimeout, // this will throw an error on Transaction Send Timeout + rejectOnBlockTimeout, // this will throw an error on Transaction Block Timeout + ]); + } finally { + clearTimeout(timeoutId); + blockTimeoutResourceCleaner.clean(); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/wait_for_transaction_receipt.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/wait_for_transaction_receipt.ts new file mode 100644 index 0000000..d335683 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/wait_for_transaction_receipt.ts @@ -0,0 +1,74 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Context } from 'web3-core'; +import { TransactionPollingTimeoutError } from 'web3-errors'; +import { EthExecutionAPI, Bytes, TransactionReceipt, DataFormat } from 'web3-types'; + +// eslint-disable-next-line import/no-cycle +import { pollTillDefinedAndReturnIntervalId, rejectIfTimeout } from 'web3-utils'; +// eslint-disable-next-line import/no-cycle +import { rejectIfBlockTimeout } from './reject_if_block_timeout.js'; +// eslint-disable-next-line import/no-cycle +import { getTransactionReceipt } from '../rpc_method_wrappers.js'; + +export async function waitForTransactionReceipt( + web3Context: Web3Context, + transactionHash: Bytes, + returnFormat: ReturnFormat, +): Promise { + + const pollingInterval = + web3Context.transactionReceiptPollingInterval ?? web3Context.transactionPollingInterval; + + const [awaitableTransactionReceipt, IntervalId] = pollTillDefinedAndReturnIntervalId(async () => { + try { + return getTransactionReceipt(web3Context, transactionHash, returnFormat); + } catch (error) { + console.warn('An error happen while trying to get the transaction receipt', error); + return undefined; + } + }, pollingInterval); + + const [timeoutId, rejectOnTimeout] = rejectIfTimeout( + web3Context.transactionPollingTimeout, + new TransactionPollingTimeoutError({ + numberOfSeconds: web3Context.transactionPollingTimeout / 1000, + transactionHash, + }), + ); + + const [rejectOnBlockTimeout, blockTimeoutResourceCleaner] = await rejectIfBlockTimeout( + web3Context, + transactionHash, + ); + + try { + // If an error happened here, do not catch it, just clear the resources before raising it to the caller function. + return await Promise.race([ + awaitableTransactionReceipt, + rejectOnTimeout, // this will throw an error on Transaction Polling Timeout + rejectOnBlockTimeout, // this will throw an error on Transaction Block Timeout + ]); + } finally { + if(timeoutId) + clearTimeout(timeoutId); + if(IntervalId) + clearInterval(IntervalId); + blockTimeoutResourceCleaner.clean(); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_by_pooling.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_by_pooling.ts new file mode 100644 index 0000000..6be3c57 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_by_pooling.ts @@ -0,0 +1,80 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Bytes, EthExecutionAPI, TransactionReceipt } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { format, numberToHex } from 'web3-utils'; +import { ethRpcMethods } from 'web3-rpc-methods'; + +import { DataFormat } from 'web3-types'; +import { SendSignedTransactionEvents, SendTransactionEvents } from '../types.js'; +import { transactionReceiptSchema } from '../schemas.js'; + +export type Web3PromiEventEventTypeBase = + | SendTransactionEvents + | SendSignedTransactionEvents; + +export type WaitProps = { + web3Context: Web3Context; + transactionReceipt: TransactionReceipt; + transactionPromiEvent: Web3PromiEvent>; + returnFormat: ReturnFormat; +}; + +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider does not support subscription. + * And it is also used by `watchTransactionBySubscription`, as a fallback, if the subscription failed for any reason. + */ +export const watchTransactionByPolling = < + ReturnFormat extends DataFormat, + ResolveType = TransactionReceipt, +>({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, +}: WaitProps) => { + // Having a transactionReceipt means that the transaction has already been included + // in at least one block, so we start with 1 + let confirmations = 1; + const intervalId = setInterval(() => { + (async () => { + if (confirmations >= web3Context.transactionConfirmationBlocks) + clearInterval(intervalId); + + const nextBlock = await ethRpcMethods.getBlockByNumber( + web3Context.requestManager, + numberToHex(BigInt(transactionReceipt.blockNumber) + BigInt(confirmations)), + false, + ); + + if (nextBlock?.hash) { + confirmations += 1; + + transactionPromiEvent.emit('confirmation', { + confirmations: format({ format: 'uint' }, confirmations, returnFormat), + receipt: format(transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: format( + { format: 'bytes32' }, + nextBlock.hash as Bytes, + returnFormat, + ), + }); + } + })() as unknown; + }, web3Context.transactionReceiptPollingInterval ?? web3Context.transactionPollingInterval); +}; diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_by_subscription.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_by_subscription.ts new file mode 100644 index 0000000..8cdaa8f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_by_subscription.ts @@ -0,0 +1,114 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Bytes, Numbers, BlockHeaderOutput, TransactionReceipt } from 'web3-types'; +import { format } from 'web3-utils'; + +import { DataFormat } from 'web3-types'; +import { NewHeadsSubscription } from '../web3_subscriptions.js'; +import { transactionReceiptSchema } from '../schemas.js'; +import { WaitProps, watchTransactionByPolling } from './watch_transaction_by_pooling.js'; + +/** + * This function watches a Transaction by subscribing to new heads. + * It is used by `watchTransactionForConfirmations`, in case the provider supports subscription. + */ +export const watchTransactionBySubscription = < + ReturnFormat extends DataFormat, + ResolveType = TransactionReceipt, +>({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, +}: WaitProps) => { + // The following variable will stay true except if the data arrived, + // or if watching started after an error had occurred. + let needToWatchLater = true; + let lastCaughtBlockHash: string; + setImmediate(() => { + web3Context.subscriptionManager + ?.subscribe('newHeads') + .then((subscription: NewHeadsSubscription) => { + subscription.on('data', async (newBlockHeader: BlockHeaderOutput) => { + needToWatchLater = false; + if ( + !newBlockHeader?.number || + // For some cases, the on-data event is fired couple times for the same block! + // This needs investigation but seems to be because of multiple `subscription.on('data'...)` even this should not cause that. + lastCaughtBlockHash === newBlockHeader?.parentHash + ) { + return; + } + lastCaughtBlockHash = newBlockHeader?.parentHash as string; + + const confirmations = + BigInt(newBlockHeader.number) - + BigInt(transactionReceipt.blockNumber) + + BigInt(1); + + transactionPromiEvent.emit('confirmation', { + confirmations: format( + { format: 'uint' }, + confirmations as Numbers, + returnFormat, + ), + receipt: format(transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: format( + { format: 'bytes32' }, + newBlockHeader.parentHash as Bytes, + returnFormat, + ), + }); + if (confirmations >= web3Context.transactionConfirmationBlocks) { + await web3Context.subscriptionManager?.removeSubscription(subscription); + } + }); + subscription.on('error', async () => { + await web3Context.subscriptionManager?.removeSubscription(subscription); + + needToWatchLater = false; + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + }); + }) + .catch(() => { + needToWatchLater = false; + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + }); + }); + + // Fallback to polling if tx receipt didn't arrived in "blockHeaderTimeout" [10 seconds] + setTimeout(() => { + if (needToWatchLater) { + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } + }, web3Context.blockHeaderTimeout * 1000); +}; diff --git a/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_for_confirmations.ts b/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_for_confirmations.ts new file mode 100644 index 0000000..e6826fe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/utils/watch_transaction_for_confirmations.ts @@ -0,0 +1,79 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Bytes, EthExecutionAPI, Web3BaseProvider, TransactionReceipt } from 'web3-types'; +import { Web3Context, Web3PromiEvent } from 'web3-core'; +import { format } from 'web3-utils'; +import { isNullish } from 'web3-validator'; + +import { + TransactionMissingReceiptOrBlockHashError, + TransactionReceiptMissingBlockNumberError, +} from 'web3-errors'; +import { DataFormat } from 'web3-types'; +import { transactionReceiptSchema } from '../schemas.js'; +import { + watchTransactionByPolling, + Web3PromiEventEventTypeBase, +} from './watch_transaction_by_pooling.js'; +import { watchTransactionBySubscription } from './watch_transaction_by_subscription.js'; + +export function watchTransactionForConfirmations< + ReturnFormat extends DataFormat, + Web3PromiEventEventType extends Web3PromiEventEventTypeBase, + ResolveType = TransactionReceipt, +>( + web3Context: Web3Context, + transactionPromiEvent: Web3PromiEvent, + transactionReceipt: TransactionReceipt, + transactionHash: Bytes, + returnFormat: ReturnFormat, +) { + if (isNullish(transactionReceipt) || isNullish(transactionReceipt.blockHash)) + throw new TransactionMissingReceiptOrBlockHashError({ + receipt: transactionReceipt, + blockHash: format({ format: 'bytes32' }, transactionReceipt?.blockHash, returnFormat), + transactionHash: format({ format: 'bytes32' }, transactionHash, returnFormat), + }); + + if (!transactionReceipt.blockNumber) + throw new TransactionReceiptMissingBlockNumberError({ receipt: transactionReceipt }); + + // As we have the receipt, it's the first confirmation that tx is accepted. + transactionPromiEvent.emit('confirmation', { + confirmations: format({ format: 'uint' }, 1, returnFormat), + receipt: format(transactionReceiptSchema, transactionReceipt, returnFormat), + latestBlockHash: format({ format: 'bytes32' }, transactionReceipt.blockHash, returnFormat), + }); + + // so a subscription for newBlockHeaders can be made instead of polling + const provider: Web3BaseProvider = web3Context.requestManager.provider as Web3BaseProvider; + if (provider && 'supportsSubscriptions' in provider && provider.supportsSubscriptions()) { + watchTransactionBySubscription({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } else { + watchTransactionByPolling({ + web3Context, + transactionReceipt, + transactionPromiEvent, + returnFormat, + }); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/validation.ts b/test/merkletreejs/node_modules/web3-eth/src/validation.ts new file mode 100644 index 0000000..a818cc6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/validation.ts @@ -0,0 +1,312 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + AccessList, + AccessListEntry, + BaseTransactionAPI, + Transaction1559UnsignedAPI, + Transaction2930UnsignedAPI, + TransactionCall, + TransactionLegacyUnsignedAPI, + Transaction, + TransactionWithSenderAPI, + ETH_DATA_FORMAT, +} from 'web3-types'; +import { isAddress, isHexStrict, isHexString32Bytes, isNullish, isUInt } from 'web3-validator'; +import { + ChainMismatchError, + HardforkMismatchError, + ChainIdMismatchError, + CommonOrChainAndHardforkError, + Eip1559GasPriceError, + InvalidGasOrGasPrice, + InvalidMaxPriorityFeePerGasOrMaxFeePerGas, + InvalidNonceOrChainIdError, + InvalidTransactionCall, + InvalidTransactionObjectError, + InvalidTransactionWithSender, + MissingChainOrHardforkError, + MissingCustomChainError, + MissingCustomChainIdError, + MissingGasError, + TransactionGasMismatchError, + UnsupportedFeeMarketError, +} from 'web3-errors'; +import { formatTransaction } from './utils/format_transaction.js'; +import { InternalTransaction } from './types.js'; + +export function isBaseTransaction(value: BaseTransactionAPI): boolean { + if (!isNullish(value.to) && !isAddress(value.to)) return false; + if (!isHexStrict(value.type) && !isNullish(value.type) && value.type.length !== 2) return false; + if (!isHexStrict(value.nonce)) return false; + if (!isHexStrict(value.gas)) return false; + if (!isHexStrict(value.value)) return false; + if (!isHexStrict(value.input)) return false; + if (value.chainId && !isHexStrict(value.chainId)) return false; + + return true; +} + +export function isAccessListEntry(value: AccessListEntry): boolean { + if (!isNullish(value.address) && !isAddress(value.address)) return false; + if ( + !isNullish(value.storageKeys) && + !value.storageKeys.every(storageKey => isHexString32Bytes(storageKey)) + ) + return false; + + return true; +} + +export function isAccessList(value: AccessList): boolean { + if ( + !Array.isArray(value) || + !value.every(accessListEntry => isAccessListEntry(accessListEntry)) + ) + return false; + + return true; +} + +export function isTransaction1559Unsigned(value: Transaction1559UnsignedAPI): boolean { + if (!isBaseTransaction(value)) return false; + if (!isHexStrict(value.maxFeePerGas)) return false; + if (!isHexStrict(value.maxPriorityFeePerGas)) return false; + if (!isAccessList(value.accessList)) return false; + + return true; +} + +export function isTransaction2930Unsigned(value: Transaction2930UnsignedAPI): boolean { + if (!isBaseTransaction(value)) return false; + if (!isHexStrict(value.gasPrice)) return false; + if (!isAccessList(value.accessList)) return false; + + return true; +} + +export function isTransactionLegacyUnsigned(value: TransactionLegacyUnsignedAPI): boolean { + if (!isBaseTransaction(value)) return false; + if (!isHexStrict(value.gasPrice)) return false; + + return true; +} + +export function isTransactionWithSender(value: TransactionWithSenderAPI): boolean { + if (!isAddress(value.from)) return false; + if (!isBaseTransaction(value)) return false; + if ( + !isTransaction1559Unsigned(value as Transaction1559UnsignedAPI) && + !isTransaction2930Unsigned(value as Transaction2930UnsignedAPI) && + !isTransactionLegacyUnsigned(value as TransactionLegacyUnsignedAPI) + ) + return false; + + return true; +} + +export function validateTransactionWithSender(value: TransactionWithSenderAPI) { + if (!isTransactionWithSender(value)) throw new InvalidTransactionWithSender(value); +} + +export function isTransactionCall(value: TransactionCall): boolean { + if (!isNullish(value.from) && !isAddress(value.from)) return false; + if (!isAddress(value.to)) return false; + if (!isNullish(value.gas) && !isHexStrict(value.gas)) return false; + if (!isNullish(value.gasPrice) && !isHexStrict(value.gasPrice)) return false; + if (!isNullish(value.value) && !isHexStrict(value.value)) return false; + if (!isNullish(value.data) && !isHexStrict(value.data)) return false; + if (!isNullish(value.input) && !isHexStrict(value.input)) return false; + if (!isNullish(value.type)) return false; + if (isTransaction1559Unsigned(value as Transaction1559UnsignedAPI)) return false; + if (isTransaction2930Unsigned(value as Transaction2930UnsignedAPI)) return false; + + return true; +} + +export function validateTransactionCall(value: TransactionCall) { + if (!isTransactionCall(value)) throw new InvalidTransactionCall(value); +} + +export const validateCustomChainInfo = (transaction: InternalTransaction) => { + if (!isNullish(transaction.common)) { + if (isNullish(transaction.common.customChain)) throw new MissingCustomChainError(); + if (isNullish(transaction.common.customChain.chainId)) + throw new MissingCustomChainIdError(); + if ( + !isNullish(transaction.chainId) && + transaction.chainId !== transaction.common.customChain.chainId + ) + throw new ChainIdMismatchError({ + txChainId: transaction.chainId, + customChainId: transaction.common.customChain.chainId, + }); + } +}; +export const validateChainInfo = (transaction: InternalTransaction) => { + if ( + !isNullish(transaction.common) && + !isNullish(transaction.chain) && + !isNullish(transaction.hardfork) + ) { + throw new CommonOrChainAndHardforkError(); + } + if ( + (!isNullish(transaction.chain) && isNullish(transaction.hardfork)) || + (!isNullish(transaction.hardfork) && isNullish(transaction.chain)) + ) + throw new MissingChainOrHardforkError({ + chain: transaction.chain, + hardfork: transaction.hardfork, + }); +}; +export const validateBaseChain = (transaction: InternalTransaction) => { + if (!isNullish(transaction.common)) + if (!isNullish(transaction.common.baseChain)) + if ( + !isNullish(transaction.chain) && + transaction.chain !== transaction.common.baseChain + ) { + throw new ChainMismatchError({ + txChain: transaction.chain, + baseChain: transaction.common.baseChain, + }); + } +}; +export const validateHardfork = (transaction: InternalTransaction) => { + if (!isNullish(transaction.common)) + if (!isNullish(transaction.common.hardfork)) + if ( + !isNullish(transaction.hardfork) && + transaction.hardfork !== transaction.common.hardfork + ) { + throw new HardforkMismatchError({ + txHardfork: transaction.hardfork, + commonHardfork: transaction.common.hardfork, + }); + } +}; + +export const validateLegacyGas = (transaction: InternalTransaction) => { + if ( + // This check is verifying gas and gasPrice aren't less than 0. + isNullish(transaction.gas) || + !isUInt(transaction.gas) || + isNullish(transaction.gasPrice) || + !isUInt(transaction.gasPrice) + ) + throw new InvalidGasOrGasPrice({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + }); + if (!isNullish(transaction.maxFeePerGas) || !isNullish(transaction.maxPriorityFeePerGas)) + throw new UnsupportedFeeMarketError({ + maxFeePerGas: transaction.maxFeePerGas, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + }); +}; + +export const validateFeeMarketGas = (transaction: InternalTransaction) => { + // These errors come from 1.x, so they must be checked before + // InvalidMaxPriorityFeePerGasOrMaxFeePerGas to throw the same error + // for the same code executing in 1.x + if (!isNullish(transaction.gasPrice) && transaction.type === '0x2') + throw new Eip1559GasPriceError(transaction.gasPrice); + if (transaction.type === '0x0' || transaction.type === '0x1') + throw new UnsupportedFeeMarketError({ + maxFeePerGas: transaction.maxFeePerGas, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + }); + + if ( + isNullish(transaction.maxFeePerGas) || + !isUInt(transaction.maxFeePerGas) || + isNullish(transaction.maxPriorityFeePerGas) || + !isUInt(transaction.maxPriorityFeePerGas) + ) + throw new InvalidMaxPriorityFeePerGasOrMaxFeePerGas({ + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); +}; + +/** + * This method checks if all required gas properties are present for either + * legacy gas (type 0x0 and 0x1) OR fee market transactions (0x2) + */ +export const validateGas = (transaction: InternalTransaction) => { + const gasPresent = !isNullish(transaction.gas) || !isNullish(transaction.gasLimit); + const legacyGasPresent = gasPresent && !isNullish(transaction.gasPrice); + const feeMarketGasPresent = + gasPresent && + !isNullish(transaction.maxPriorityFeePerGas) && + !isNullish(transaction.maxFeePerGas); + + if (!legacyGasPresent && !feeMarketGasPresent) + throw new MissingGasError({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); + + if (legacyGasPresent && feeMarketGasPresent) + throw new TransactionGasMismatchError({ + gas: transaction.gas, + gasPrice: transaction.gasPrice, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas, + maxFeePerGas: transaction.maxFeePerGas, + }); + + (legacyGasPresent ? validateLegacyGas : validateFeeMarketGas)(transaction); + (!isNullish(transaction.type) && transaction.type > '0x1' + ? validateFeeMarketGas + : validateLegacyGas)(transaction); +}; + +export const validateTransactionForSigning = ( + transaction: InternalTransaction, + overrideMethod?: (transaction: InternalTransaction) => void, +) => { + if (!isNullish(overrideMethod)) { + overrideMethod(transaction); + return; + } + + if (typeof transaction !== 'object' || isNullish(transaction)) + throw new InvalidTransactionObjectError(transaction); + + validateCustomChainInfo(transaction); + validateChainInfo(transaction); + validateBaseChain(transaction); + validateHardfork(transaction); + + const formattedTransaction = formatTransaction(transaction as Transaction, ETH_DATA_FORMAT); + validateGas(formattedTransaction); + + if ( + isNullish(formattedTransaction.nonce) || + isNullish(formattedTransaction.chainId) || + formattedTransaction.nonce.startsWith('-') || + formattedTransaction.chainId.startsWith('-') + ) + throw new InvalidNonceOrChainIdError({ + nonce: transaction.nonce, + chainId: transaction.chainId, + }); +}; diff --git a/test/merkletreejs/node_modules/web3-eth/src/web3_eth.ts b/test/merkletreejs/node_modules/web3-eth/src/web3_eth.ts new file mode 100644 index 0000000..c4b3b6a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/web3_eth.ts @@ -0,0 +1,1656 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +// Disabling because returnTypes must be last param to match 1.x params +/* eslint-disable default-param-last */ + +import { + SupportedProviders, + Address, + Bytes, + Filter, + HexString32Bytes, + HexString8Bytes, + Numbers, + BlockNumberOrTag, + LogsOutput, + Transaction, + TransactionCall, + Web3EthExecutionAPI, + TransactionWithFromLocalWalletIndex, + TransactionWithToLocalWalletIndex, + TransactionWithFromAndToLocalWalletIndex, + TransactionForAccessList, + DataFormat, + DEFAULT_RETURN_FORMAT, + Eip712TypedData, +} from 'web3-types'; +import { isSupportedProvider, Web3Context, Web3ContextInitOptions } from 'web3-core'; +import { TransactionNotFound } from 'web3-errors'; +import { toChecksumAddress, isNullish } from 'web3-utils'; +import { ethRpcMethods } from 'web3-rpc-methods'; + +import * as rpcMethodsWrappers from './rpc_method_wrappers.js'; +import { SendTransactionOptions } from './types.js'; +import { + LogsSubscription, + NewPendingTransactionsSubscription, + NewHeadsSubscription, + SyncingSubscription, +} from './web3_subscriptions.js'; + +export type RegisteredSubscription = { + logs: typeof LogsSubscription; + newPendingTransactions: typeof NewPendingTransactionsSubscription; + pendingTransactions: typeof NewPendingTransactionsSubscription; + newHeads: typeof NewHeadsSubscription; + newBlockHeaders: typeof NewHeadsSubscription; + syncing: typeof SyncingSubscription; +}; + +export const registeredSubscriptions = { + logs: LogsSubscription, + newPendingTransactions: NewPendingTransactionsSubscription, + newHeads: NewHeadsSubscription, + syncing: SyncingSubscription, + pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x + newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x +}; + +export class Web3Eth extends Web3Context { + public constructor( + providerOrContext?: SupportedProviders | Web3ContextInitOptions | string, + ) { + if ( + typeof providerOrContext === 'string' || + isSupportedProvider(providerOrContext as SupportedProviders) + ) { + super({ + provider: providerOrContext as SupportedProviders, + registeredSubscriptions, + }); + + return; + } + + if ((providerOrContext as Web3ContextInitOptions).registeredSubscriptions) { + super(providerOrContext as Web3ContextInitOptions); + return; + } + + super({ + ...(providerOrContext as Web3ContextInitOptions), + registeredSubscriptions, + }); + } + + /** + * @returns Returns the ethereum protocol version of the node. + * + * ```ts + * web3.eth.getProtocolVersion().then(console.log); + * > "63" + * ``` + */ + public async getProtocolVersion() { + return ethRpcMethods.getProtocolVersion(this.requestManager); + } + + // TODO Add returnFormat parameter + /** + * Checks if the node is currently syncing. + * + * @returns Either a {@link SyncingStatusAPI}, or `false`. + * + * ```ts + * web3.eth.isSyncing().then(console.log); + * > { + * startingBlock: 100, + * currentBlock: 312, + * highestBlock: 512, + * knownStates: 234566, + * pulledStates: 123455 + * } + * ``` + */ + public async isSyncing() { + return ethRpcMethods.getSyncing(this.requestManager); + } + + // TODO consider adding returnFormat parameter (to format address as bytes) + /** + * @returns Returns the coinbase address to which mining rewards will go. + * + * ```ts + * web3.eth.getCoinbase().then(console.log); + * > "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" + * ``` + */ + public async getCoinbase() { + return ethRpcMethods.getCoinbase(this.requestManager); + } + + /** + * Checks whether the node is mining or not. + * + * @returns `true` if the node is mining, otherwise `false`. + * + * ```ts + * web3.eth.isMining().then(console.log); + * > true + * ``` + */ + public async isMining() { + return ethRpcMethods.getMining(this.requestManager); + } + + /** + * @deprecated Will be removed in the future, please use {@link Web3Eth.getHashRate} method instead. + * + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashrate().then(console.log); + * > 493736n + * + * web3.eth.getHashrate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + public async getHashrate( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return this.getHashRate(returnFormat); + } + + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of hashes per second that the node is mining with. + * + * ```ts + * web3.eth.getHashRate().then(console.log); + * > 493736n + * + * web3.eth.getHashRate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x788a8" + * ``` + */ + public async getHashRate( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getHashRate(this, returnFormat); + } + + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The gas price determined by the last few blocks median gas price. + * + * ```ts + * web3.eth.getGasPrice().then(console.log); + * > 20000000000n + * + * web3.eth.getGasPrice({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0x4a817c800" + * ``` + */ + public async getGasPrice( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getGasPrice(this, returnFormat); + } + + /** + * @returns A list of accounts the node controls (addresses are checksummed). + * + * ```ts + * web3.eth.getAccounts().then(console.log); + * > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"] + * ``` + */ + public async getAccounts() { + const hexAddresses = (await ethRpcMethods.getAccounts(this.requestManager)) ?? []; + return hexAddresses.map(address => toChecksumAddress(address)); + } + + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current block number. + * + * ```ts + * web3.eth.getBlockNumber().then(console.log); + * > 2744n + * + * web3.eth.getBlockNumber({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); + * > "0xab8" + * ``` + */ + public async getBlockNumber( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getBlockNumber(this, returnFormat); + } + + /** + * Get the balance of an address at a given block. + * + * @param address The address to get the balance of. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the balance query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The current balance for the given address in `wei`. + * + * ```ts + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1000000000000n + * + * web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > "0xe8d4a51000" + * ``` + */ + public async getBalance( + address: Address, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getBalance(this, address, blockNumber, returnFormat); + } + + /** + * Get the storage at a specific position of an address. + * + * @param address The address to get the storage from. + * @param storageSlot The index position of the storage. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the storage query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The value in storage at the given position. + * + * ```ts + * web3.eth.getStorageAt("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", 0).then(console.log); + * > "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234" + * + * web3.eth.getStorageAt( + * "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", + * 0, + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(31) [ + * 3, 52, 86, 115, 33, 35, 255, 255, + * 35, 66, 52, 45, 209, 35, 66, 67, + * 67, 36, 35, 66, 52, 253, 35, 79, + * 210, 63, 212, 242, 61, 66, 52 + * ] + * ``` + */ + public async getStorageAt( + address: Address, + storageSlot: Numbers, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getStorageAt( + this, + address, + storageSlot, + blockNumber, + returnFormat, + ); + } + + /** + * Get the code at a specific address. + * + * @param address The address to get the code from. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the code query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The [data](https://ethereum.org/en/developers/docs/transactions/#the-data-field) at the provided `address`. + * + * ```ts + * web3.eth.getCode("0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234").then(console.log); + * > "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056" + * + * web3.eth.getCode( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } + * ).then(console.log); + * > Uint8Array(50) [ + * 96, 1, 96, 0, 128, 53, 129, 26, 129, 129, 129, + * 20, 96, 18, 87, 131, 1, 0, 91, 96, 27, 96, + * 1, 53, 96, 37, 86, 91, 128, 96, 0, 82, 96, + * 32, 96, 0, 242, 91, 96, 0, 96, 7, 130, 2, + * 144, 80, 145, 144, 80, 86 + * ] + * ``` + */ + public async getCode( + address: Address, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getCode(this, address, blockNumber, returnFormat); + } + + /** + * Retrieves a {@link Block} matching the provided block number, block hash or block tag. + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param hydrated If specified `true`, the returned block will contain all transactions as objects. If `false` it will only contain transaction hashes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted (does not format transaction objects or hashes). + * @returns A {@link Block} object matching the provided block number or block hash. + * + * ```ts + * web3.eth.getBlock(0).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getBlock( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * false, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + public async getBlock( + block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, + hydrated = false, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getBlock(this, block, hydrated, returnFormat); + } + + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions in the provided block. + * + * ```ts + * web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + public async getBlockTransactionCount< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + >( + block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getBlockTransactionCount(this, block, returnFormat); + } + + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of [uncles](https://ethereum.org/en/glossary/#ommer) in the provided block. + * + * ```ts + * web3.eth.getBlockUncleCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getBlockUncleCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + public async getBlockUncleCount( + block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getBlockUncleCount(this, block, returnFormat); + } + + /** + * + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param uncleIndex The index position of the uncle. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A blocks [uncle](https://ethereum.org/en/glossary/#ommer) by a given uncle index position. + * + * ```ts + * web3.eth.getUncle(0, 1).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1n, + * number: 0n, + * gasLimit: 30000000n, + * gasUsed: 0n, + * timestamp: 1658281638n, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0n, + * totalDifficulty: 1n, + * baseFeePerGas: 1000000000n, + * size: 514n, + * transactions: [], + * uncles: [] + * } + * + * web3.eth.getUncle( + * "0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d", + * 1, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * hash: '0x7dbfdc6a7a67a670cb9b0c3f81ca60c007762f1e4e598cb027a470678ff26d0d', + * parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0x5ed9882897d363c4632a6e67fba6203df61bd994813dcf048da59be442a9c6c4', + * transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 1, + * number: 0, + * gasLimit: 30000000, + * gasUsed: 0, + * timestamp: 1658281638, + * extraData: '0x', + * mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * nonce: 0, + * totalDifficulty: 1, + * baseFeePerGas: 1000000000, + * size: 514, + * transactions: [], + * uncles: [] + * } + * ``` + */ + public async getUncle( + block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, + uncleIndex: Numbers, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getUncle(this, block, uncleIndex, returnFormat); + } + + /** + * @param transactionHash The hash of the desired transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransaction('0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc').then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransaction( + * web3.utils.hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + public async getTransaction( + transactionHash: Bytes, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + const response = await rpcMethodsWrappers.getTransaction( + this, + transactionHash, + returnFormat, + ); + + if (!response) throw new TransactionNotFound(); + + return response; + } + + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns A list of pending transactions. + * + * ```ts + * web3.eth.getPendingTransactions().then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0n, + * nonce: 1n, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2710n, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * + * * web3.eth.getPendingTransactions({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > [ + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * }, + * { + * hash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * type: 0, + * nonce: 1, + * blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000', + * blockNumber: null, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2710, + * r: '0x55ac19fade21db035a1b7ea0a8d49e265e05dbb926e75f273f836ad67ce5c96a', + * s: '0x6550036a7c3fd426d5c3d35d96a7075cd673957620b7889846a980d2d017ec08' + * } + * ] + * ``` + */ + public async getPendingTransactions< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + >(returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) { + return rpcMethodsWrappers.getPendingTransactions(this, returnFormat); + } + + /** + * @param block The {@link BlockNumberOrTag} (defaults to {@link Web3Eth.defaultBlock}) or block hash of the desired block. + * @param transactionIndex The index position of the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired transaction object. + * + * ```ts + * web3.eth.getTransactionFromBlock('0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', 0).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0n, + * nonce: 0n, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1n, + * transactionIndex: 0n, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1n, + * gas: 90000n, + * gasPrice: 2000000000n, + * input: '0x', + * v: 2709n, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * + * web3.eth.getTransactionFromBlock( + * hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), + * 0, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * { + * hash: '0x73aea70e969941f23f9d24103e91aa1f55c7964eb13daf1c9360c308a72686dc', + * type: 0, + * nonce: 0, + * blockHash: '0x43202bd16b6bd54bea1b310736bd78bdbe93a64ad940f7586739d9eb25ad8d00', + * blockNumber: 1, + * transactionIndex: 0, + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * value: 1, + * gas: 90000, + * gasPrice: 2000000000, + * input: '0x', + * v: 2709, + * r: '0x8b336c290f6d7b2af3ccb2c02203a8356cc7d5b150ab19cce549d55636a3a78c', + * s: '0x5a83c6f816befc5cd4b0c997a347224a8aa002e5799c4b082a3ec726d0e9531d' + * } + * ``` + */ + public async getTransactionFromBlock< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + >( + block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, + transactionIndex: Numbers, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getTransactionFromBlock( + this, + block, + transactionIndex, + returnFormat, + ); + } + + /** + * @param transactionHash Hash of the transaction to retrieve the receipt for. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The desired {@link TransactionReceipt} object. + * + * ```ts + * web3.eth.getTransactionReceipt("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f").then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * + * web3.eth.getTransactionReceipt( + * "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0, + * blockNumber: 2, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000, + * gasUsed: 21000, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1, + * effectiveGasPrice: 2000000000, + * type: 0n + * } + * ``` + */ + public async getTransactionReceipt< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + >(transactionHash: Bytes, returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) { + const response = await rpcMethodsWrappers.getTransactionReceipt( + this, + transactionHash, + returnFormat, + ); + + if (!response) throw new TransactionNotFound(); + + return response; + } + + /** + * @param address The address to get the number of transactions for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) Specifies what block to use as the current state for the query. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The number of transactions sent from the provided address. + * + * ```ts + * web3.eth.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); + * > 1n + * + * web3.eth.getTransactionCount( + * "0x407d73d8a49eeb85d32cf465507dd71d507100c1", + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > 1 + * ``` + */ + public async getTransactionCount< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + >( + address: Address, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getTransactionCount(this, address, blockNumber, returnFormat); + } + + /** + * @param transaction The {@link Transaction}, {@link TransactionWithFromLocalWalletIndex}, {@link TransactionWithToLocalWalletIndex} or {@link TransactionWithFromAndToLocalWalletIndex} to send. __Note:__ In the `to` and `from` fields when hex strings are used, it is assumed they are addresses, for any other form (number, string number, etc.) it is assumed they are wallet indexes. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @param options A configuration object used to change the behavior of the `sendTransaction` method. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const transaction = { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1' + * } + * + * const transactionHash = await web3.eth.sendTransaction(transaction); + * console.log(transactionHash); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * + * web3.eth.sendTransaction(transaction).catch(console.log); + * > + * + * // Example using options.ignoreGasPricing = true + * web3.eth.sendTransaction(transaction, undefined, { ignoreGasPricing: true }).then(console.log); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendTransaction(transaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `sent` + * ```ts + * web3.eth.sendTransaction(transaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > { + * from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + * to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + * value: '0x1', + * gasPrice: '0x77359400', + * maxPriorityFeePerGas: undefined, + * maxFeePerGas: undefined + * } + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendTransaction(transaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f + * ``` + * - `receipt` + * ```ts + * web3.eth.sendTransaction(transaction).on('receipt', receipt => console.log(receipt)); + * > { + * transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + * transactionIndex: 0n, + * blockNumber: 2n, + * blockHash: '0xeb1565a08b23429552dafa92e32409f42eb43944f7611963c63ce40e7243941a', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendTransaction(transaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * transactionHash: '0xb4a3a35ae0f3e77ef0ff7be42010d948d011b21a4e341072ee18717b67e99ab8', + * transactionIndex: 0n, + * blockNumber: 5n, + * blockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548', + * from: '0x6e599da0bff7a6598ac1224e4985430bf16458a4', + * to: '0x6f1df96865d09d21e8f3f9a7fba3b17a11c7c53c', + * cumulativeGasUsed: 21000n, + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * effectiveGasPrice: 2000000000n, + * type: 0n + * }, + * latestBlockHash: '0xb57fbe6f145cefd86a305a9a024a4351d15d4d39607d7af53d69a319bc3b5548' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendTransaction(transaction).on('error', error => console.log); + * > + * ``` + */ + public sendTransaction( + transaction: + | Transaction + | TransactionWithFromLocalWalletIndex + | TransactionWithToLocalWalletIndex + | TransactionWithFromAndToLocalWalletIndex, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + options?: SendTransactionOptions, + ) { + return rpcMethodsWrappers.sendTransaction(this, transaction, returnFormat, options); + } + + /** + * @param transaction Signed transaction in one of the valid {@link Bytes} format. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns If `await`ed or `.then`d (i.e. the promise resolves), the transaction hash is returned. + * ```ts + * const signedTransaction = "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * + * const transactionHash = await web3.eth.sendSignedTransaction(signedTransaction); + * console.log(transactionHash); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).then(console.log); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * + * web3.eth.sendSignedTransaction(signedTransaction).catch(console.log); + * > + * ``` + * + * + * Otherwise, a {@link Web3PromiEvent} is returned which has several events than can be listened to using the `.on` syntax, such as: + * - `sending` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sending', transactionToBeSent => console.log(transactionToBeSent)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `sent` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('sent', sentTransaction => console.log(sentTransaction)); + * > "0xf86580843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a95a03a42d53ca5b71f845e1cd4c65359b05446a85d16881372d3bfaab8980935cb04a0711497bc8dd3b541152e2fed14fe650a647f1f0edab0d386ad9506f0e642410f" + * ``` + * - `transactionHash` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('transactionHash', transactionHash => console.log(transactionHash)); + * > 0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700 + * ``` + * - `receipt` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('receipt', receipt => console.log(receipt)); + * > { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * } + * ``` + * - `confirmation` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('confirmation', confirmation => console.log(confirmation)); + * > { + * confirmations: 1n, + * receipt: { + * blockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081', + * blockNumber: 1n, + * cumulativeGasUsed: 21000n, + * effectiveGasPrice: 1000000001n, + * from: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * gasUsed: 21000n, + * logs: [], + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * status: 1n, + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * transactionHash: '0xed8c241ea44d57f4605dc22c63500de46254d6c7844fd65fa438b128c80cf700', + * transactionIndex: 0n, + * type: 0n + * }, + * latestBlockHash: '0xff2b1687995d81066361bc6affe4455746120a7d4bb75fc938211a2692a50081' + * } + * ``` + * - `error` + * ```ts + * web3.eth.sendSignedTransaction(signedTransaction).on('error', error => console.log(error)); + * > + * ``` + */ + public sendSignedTransaction( + transaction: Bytes, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + options?: SendTransactionOptions, + ) { + return rpcMethodsWrappers.sendSignedTransaction(this, transaction, returnFormat, options); + } + + /** + * @param message Data to sign in one of the valid {@link Bytes} format. + * @param address Address to sign data with, can be an address or the index of a local wallet. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns The signed `message`. + * + * ```ts + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + * + * // Using an unlocked account managed by connected RPC client + * web3.eth.sign("0x48656c6c6f20776f726c64", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.UINT8ARRAY }).then(console.log); + * > Uint8Array(65) [ + * 48, 117, 94, 214, 83, 150, 250, 207, 134, 197, 62, + * 98, 23, 197, 43, 77, 174, 190, 114, 170, 73, 65, + * 216, 150, 53, 64, 157, 228, 201, 199, 249, 70, 109, + * 78, 154, 174, 199, 151, 127, 5, 233, 35, 136, 155, + * 51, 192, 208, 221, 39, 215, 34, 107, 110, 111, 86, + * 206, 115, 116, 101, 197, 207, 208, 75, 228, 0 + * ] + * ``` + * + * // Using an indexed account managed by local Web3 wallet + * web3.eth.sign("0x48656c6c6f20776f726c64", 0).then(console.log); + * > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400" + */ + public async sign( + message: Bytes, + address: Address, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.sign(this, message, address, returnFormat); + } + + /** + * @param transaction The transaction object to sign. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) Specifies how the return data should be formatted. + * @returns {@link SignedTransactionInfoAPI}, an object containing the [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded signed transaction (accessed via the `raw` property) and the signed transaction object (accessed via the `tx` property). + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * gas: '21000', + * gasPrice: await web3Eth.getGasPrice(), + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.signTransaction(transaction).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0n, + * nonce: 1n, + * gasPrice: 1000000001n, + * gas: 21000n, + * value: 1n, + * v: 2710n, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * + * web3.eth.signTransaction(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * raw: '0xf86501843b9aca0182520894e899f0130fd099c0b896b2ce4e5e15a25b23139a0180820a96a0adb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679a027d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * tx: { + * type: 0, + * nonce: 1, + * gasPrice: 1000000001, + * gas: 21000, + * value: 1, + * v: 2710, + * r: '0xadb3468dbb4dce89fe1785ea9182e85fb56b399b378f82b93af7a8a12a4f9679', + * s: '0x27d37d736e9bcf00121f78b2d10e4404fa5c45856d62b746574345f5cd278097', + * to: '0xe899f0130fd099c0b896b2ce4e5e15a25b23139a', + * data: '0x' + * } + * } + * ``` + */ + public async signTransaction( + transaction: Transaction, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.signTransaction(this, transaction, returnFormat); + } + + // TODO Decide what to do with transaction.to + // https://github.com/ChainSafe/web3.js/pull/4525#issuecomment-982330076 + /** + * Executes a message call within the EVM without creating a transaction. + * It does not publish anything to the blockchain and does not consume any gas. + * + * @param transaction - A transaction object where all properties are optional except `to`, however it's recommended to include the `from` property or it may default to `0x0000000000000000000000000000000000000000` depending on your node or provider. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The returned data of the call, e.g. a smart contract function's return value. + */ + public async call( + transaction: TransactionCall, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.call(this, transaction, blockNumber, returnFormat); + } + + /** + * Simulates the transaction within the EVM to estimate the amount of gas to be used by the transaction. + * The transaction will not be added to the blockchain, and actual gas usage can vary when interacting + * with a contract as a result of updating the contract's state. + * + * @param transaction The {@link Transaction} object to estimate the gas for. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The used gas for the simulated transaction execution. + * + * ```ts + * const transaction = { + * from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', + * value: '0x1', + * nonce: '0x1', + * type: '0x0' + * } + * + * web3.eth.estimateGas(transaction).then(console.log); + * > 21000n + * + * web3.eth.estimateGas(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 21000 + * ``` + */ + public async estimateGas( + transaction: Transaction, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.estimateGas(this, transaction, blockNumber, returnFormat); + } + + /** + * Gets past logs, matching the provided `filter`. + * + * @param filter A {@link Filter} object containing the properties for the desired logs. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns {@link FilterResultsAPI}, an array of {@link Log} objects. + * + * ```ts + * web3.eth.getPastLogs({ + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0n, + * transactionIndex: 0n, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234n, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * + * web3.eth.getPastLogs( + * { + * address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", + * topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"] + * }, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > [{ + * data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'] + * logIndex: 0, + * transactionIndex: 0, + * transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', + * blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', + * blockNumber: 1234, + * address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' + * }, + * {...}] + * ``` + */ + public async getPastLogs( + filter: Filter, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getLogs(this, filter, returnFormat); + } + + /** + * Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ('target'). + * + * @returns The mining work as an array of strings with the following structure: + * + * String 32 Bytes - at index 0: current block header pow-hash + * String 32 Bytes - at index 1: the seed hash used for the DAG. + * String 32 Bytes - at index 2: the boundary condition ('target'), 2^256 / difficulty. + * + * ```ts + * web3.eth.getWork().then(console.log); + * > [ + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0x5EED00000000000000000000000000005EED0000000000000000000000000000", + * "0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000" + * ] + * ``` + */ + public async getWork() { + return ethRpcMethods.getWork(this.requestManager); + } + + /** + * Used for submitting a proof-of-work solution. + * + * @param nonce The nonce found (8 bytes). + * @param hash The header’s pow-hash (32 bytes). + * @param digest The mix digest (32 bytes). + * @returns Returns `true` if the provided solution is valid, otherwise `false`. + * + * ```ts + * web3.eth.submitWork([ + * "0x0000000000000001", + * "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + * "0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000" + * ]).then(console.log); + * > true + * ``` + */ + public async submitWork( + nonce: HexString8Bytes, + hash: HexString32Bytes, + digest: HexString32Bytes, + ) { + return ethRpcMethods.submitWork(this.requestManager, nonce, hash, digest); + } + + // TODO - Format addresses + /** + * This method will request/enable the accounts from the current environment and for supporting [EIP 1102](https://eips.ethereum.org/EIPS/eip-1102) + * This method will only work if you’re using the injected provider from a application like Metamask, Status or TrustWallet. + * It doesn’t work if you’re connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvider and IpcProvider). + * For more information about the behavior of this method please read [EIP-1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md): Opt-in account exposure. + * + * @returns An array of enabled accounts. + * + * ```ts + * web3.eth.requestAccounts().then(console.log); + * > ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'] + * ``` + */ + public async requestAccounts() { + return ethRpcMethods.requestAccounts(this.requestManager); + } + + /** + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The chain ID of the current connected node as described in the [EIP-695](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md). + * + * ```ts + * web3.eth.getChainId().then(console.log); + * > 61n + * + * web3.eth.getChainId({ number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > 61 + * ``` + */ + public async getChainId( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getChainId(this, returnFormat); + } + + /** + * @returns The current client version. + * + * ```ts + * web3.eth.getNodeInfo().then(console.log); + * > "Mist/v0.9.3/darwin/go1.4.1" + * ``` + */ + public async getNodeInfo() { + return ethRpcMethods.getNodeInfo(this.requestManager); + } + + /** + * @param address The Address of the account or contract. + * @param storageKeys Array of storage-keys which should be proofed and included. See {@link web3.getStorageAt}. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the gas estimation. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns The account and storage-values of the specified account including the Merkle-proof as described in [EIP-1186](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md). + * + * ```ts + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * "latest" + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0n, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0n, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0n, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0n, + * "proof": [] + * } + * ] + * } + * + * web3.eth.getProof( + * "0x1234567890123456789012345678901234567890", + * ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], + * undefined, + * { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } + * ).then(console.log); + * > { + * "address": "0x1234567890123456789012345678901234567890", + * "accountProof": [ + * "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", + * "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80", + * "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080", + * "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080" + * ], + * "balance": 0, + * "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + * "nonce": 0, + * "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + * "storageProof": [ + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000000", + * "value": 0, + * "proof": [] + * }, + * { + * "key": "0x0000000000000000000000000000000000000000000000000000000000000001", + * "value": 0, + * "proof": [] + * } + * ] + * } + * ``` + */ + public async getProof( + address: Address, + storageKeys: Bytes[], + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getProof(this, address, storageKeys, blockNumber, returnFormat); + } + + // TODO Throwing an error with Geth, but not Infura + // TODO gasUsedRatio and reward not formatting + /** + * @param blockCount Number of blocks in the requested range. Between `1` and `1024` blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. + * @param newestBlock Highest number block of the requested range. + * @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `['0', '25', '50', '75', '100']` or `['0', '0.5', '1', '1.5', '3', '80']` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted. + * @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available. + * The range between `headBlock - 4` and `headBlock` is guaranteed to be available while retrieving data from the `pending` block and older history are optional to support. + * For pre-EIP-1559 blocks the `gasPrice`s are returned as `rewards` and zeroes are returned for the `baseFeePerGas`. + * + * ```ts + * web3.eth.getFeeHistory(4, 'pending', [0, 25, 75, 100]).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621n, + * 21417903463n, + * 19989260230n, + * 17770954829n, + * 18850641304n + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343n, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * + * web3.eth.getFeeHistory(4, BlockTags.LATEST, [0, 25, 75, 100], { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); + * > { + * baseFeePerGas: [ + * 22983878621, + * 21417903463, + * 19989260230, + * 17770954829, + * 18850641304 + * ], + * gasUsedRatio: [ + * 0.22746546666666667, + * 0.2331871, + * 0.05610054885262125, + * 0.7430227268212117 + * ], + * oldestBlock: 15216343, + * reward: [ + * [ '0x3b9aca00', '0x53724e00', '0x77359400', '0x1d92c03423' ], + * [ '0x3b9aca00', '0x3b9aca00', '0x3b9aca00', '0xee6b2800' ], + * [ '0x3b9aca00', '0x4f86a721', '0x77d9743a', '0x9502f900' ], + * [ '0xcc8ff9e', '0x53724e00', '0x77359400', '0x1ec9771bb3' ] + * ] + * } + * ``` + */ + public async getFeeHistory( + blockCount: Numbers, + newestBlock: BlockNumberOrTag = this.defaultBlock, + rewardPercentiles: Numbers[], + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getFeeHistory( + this, + blockCount, + newestBlock, + rewardPercentiles, + returnFormat, + ); + } + + /** + * This method generates an access list for a transaction. + * + * @param transaction - A transaction object where all properties are optional except `from`, however it's recommended to include the `to` property. + * @param blockNumber ({@link BlockNumberOrTag} defaults to {@link Web3Eth.defaultBlock}) - Specifies what block to use as the current state of the blockchain while processing the transaction. + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the createAccessList should be formatted. + * @returns The returned data of the createAccessList, e.g. The generated access list for transaction. + * @example + * ```ts + * web3.eth.createAccessList({ + * from: '0xDe95305a63302C3aa4d3A9B42654659AeA72b694', + * data: '0x9a67c8b100000000000000000000000000000000000000000000000000000000000004d0', + * gasPrice: '0x3b9aca00', + * gas: '0x3d0900', + * to: '0x940b25304947ae863568B3804434EC77E2160b87' + * }) + * .then(console.log); + * + * > { + * "accessList": [ + * { + * "address": "0x15859bdf5aff2080a9968f6a410361e9598df62f", + * "storageKeys": [ + * "0x0000000000000000000000000000000000000000000000000000000000000000" + * ] + * } + * ], + * "gasUsed": "0x7671" + * } + * ``` + */ + public async createAccessList( + transaction: TransactionForAccessList, + blockNumber: BlockNumberOrTag = this.defaultBlock, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.createAccessList(this, transaction, blockNumber, returnFormat); + } + + /** + * This method sends EIP-712 typed data to the RPC provider to be signed. + * + * @param address The address that corresponds with the private key used to sign the typed data. + * @param typedData The EIP-712 typed data object. + * @param useLegacy A boolean flag determining whether the RPC call uses the legacy method `eth_signTypedData` or the newer method `eth_signTypedData_v4` + * @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the signed typed data should be formatted. + * @returns The signed typed data. + */ + public async signTypedData( + address: Address, + typedData: Eip712TypedData, + useLegacy = false, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.signTypedData(this, address, typedData, useLegacy, returnFormat); + } + + /** + * Lets you subscribe to specific events in the blockchain. + * + * @param name - The subscription you want to subscribe to. + * @param args - Optional additional parameters, depending on the subscription type. + * @returns A subscription object of type {@link RegisteredSubscription}. The object contains: + * - subscription.id: The subscription id, used to identify and unsubscribing the subscription. + * - subscription.subscribe(): Can be used to re-subscribe with the same parameters. + * - subscription.unsubscribe(): Unsubscribes the subscription and returns TRUE in the callback if successful. + * - subscription.args: The subscription arguments, used when re-subscribing. + * + * + * You can use the subscription object to listen on: + * + * - on("data") - Fires on each incoming log with the log object as argument. + * - on("changed") - Fires on each log which was removed from the blockchain. The log will have the additional property "removed: true". + * - on("error") - Fires when an error in the subscription occurs. + * - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id. + * + * @example **Subscribe to Smart Contract events** + * ```ts + * // Subscribe to `logs` + * const logSubscription = web3.eth.subscribe('logs', { + * address: '0x1234567890123456789012345678901234567890', + * topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234'] + * }); + * logSubscription.on('data', (data: any) => console.log(data)); + * logSubscription.on('error', (error: any) => console.log(error)); + * + * ``` + * + * @example **Subscribe to new block headers** + * ```ts + * // Subscribe to `newBlockHeaders` + * const newBlocksSubscription = await web3.eth.subscribe('newBlockHeaders'); + * + * newBlocksSubscription.on('data', async blockhead => { + * console.log('New block header: ', blockhead); + * + * // You do not need the next line, if you like to keep notified for every new block + * await newBlocksSubscription.unsubscribe(); + * console.log('Unsubscribed from new block headers.'); + * }); + * newBlocksSubscription.on('error', error => + * console.log('Error when subscribing to New block header: ', error), + * ); + * ``` + */ + public async subscribe< + T extends keyof RegisteredSubscription, + ReturnType extends DataFormat = DataFormat, + >( + name: T, + args?: ConstructorParameters[0], + returnFormat: ReturnType = DEFAULT_RETURN_FORMAT as ReturnType, + ): Promise> { + const subscription = await this.subscriptionManager?.subscribe(name, args, returnFormat); + if ( + subscription instanceof LogsSubscription && + name === 'logs' && + typeof args === 'object' && + !isNullish(args.fromBlock) && + Number.isFinite(Number(args.fromBlock)) + ) { + setImmediate(() => { + this.getPastLogs(args) + .then(logs => { + for (const log of logs) { + subscription._processSubscriptionResult(log as LogsOutput); + } + }) + .catch(e => { + subscription._processSubscriptionError(e as Error); + }); + }); + } + return subscription; + } + + private static shouldClearSubscription({ sub }: { sub: unknown }): boolean { + return !(sub instanceof SyncingSubscription); + } + + /** + * Resets subscriptions. + * + * @param notClearSyncing If `true` it keeps the `syncing` subscription. + * @returns A promise to an array of subscription ids that were cleared. + * + * ```ts + * web3.eth.clearSubscriptions().then(console.log); + * > [...] An array of subscription ids that were cleared + * ``` + */ + public clearSubscriptions(notClearSyncing = false): Promise | undefined { + return this.subscriptionManager?.unsubscribe( + // eslint-disable-next-line + notClearSyncing ? Web3Eth.shouldClearSubscription : undefined, + ); + } +} diff --git a/test/merkletreejs/node_modules/web3-eth/src/web3_subscriptions.ts b/test/merkletreejs/node_modules/web3-eth/src/web3_subscriptions.ts new file mode 100644 index 0000000..5838aa9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-eth/src/web3_subscriptions.ts @@ -0,0 +1,176 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable-next-line max-classes-per-file */ +import { format } from 'web3-utils'; + +import { + SyncOutput, + Address, + BlockNumberOrTag, + HexString, + Topic, + BlockHeaderOutput, + LogsOutput, +} from 'web3-types'; +import { Web3Subscription } from 'web3-core'; +import { blockHeaderSchema, logSchema, syncSchema } from './schemas.js'; + +/** + * ## subscribe('logs') + * Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, web3.js will retrieve logs beginning from this point, backfilling the response as necessary. + * + * You can subscribe to logs matching a given filter object, which can take the following parameters: + * - `fromBlock`: (optional, default: 'latest') Integer block number, or `'latest'` for the last mined block or `'pending'`, `'earliest'` for not yet mined transactions. + * - `address`: (optional) Contract address or a list of addresses from which logs should originate. + * - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with `or` options. + * + */ +export class LogsSubscription extends Web3Subscription< + { + data: LogsOutput; + }, + { + readonly fromBlock?: BlockNumberOrTag; + readonly address?: Address | Address[]; + readonly topics?: Topic[]; + } +> { + protected _buildSubscriptionParams() { + return ['logs', this.args]; + } + + protected formatSubscriptionResult(data: LogsOutput) { + return format(logSchema, data, super.returnFormat); + } +} + +/** + * ## subscribe('pendingTransactions') + * Subscribes to incoming pending transactions. + * + * You can subscribe to pending transactions by calling web3.eth.subscribe('pendingTransactions'). + * @example + * ```ts + * (await web3.eth.subscribe('pendingTransactions')).on('data', console.log); + * ``` + */ +export class NewPendingTransactionsSubscription extends Web3Subscription<{ + data: HexString; +}> { + // eslint-disable-next-line + protected _buildSubscriptionParams() { + return ['newPendingTransactions']; + } + + protected formatSubscriptionResult(data: string) { + return format({ format: 'string' }, data, super.returnFormat); + } +} + +/** + * ## subscribe('newHeads') ( same as subscribe('newBlockHeaders')) + * + * Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain. + * + * The structure of a returned block header is {@link BlockHeaderOutput}: + * @example + * ```ts + * (await web3.eth.subscribe('newHeads')).on( // 'newBlockHeaders' would work as well + * 'data', + * console.log + * ); + * >{ + * parentHash: '0x9e746a1d906b299def98c75b06f714d62dacadd567c7515d76eeaa8c8074c738', + * sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + * miner: '0x0000000000000000000000000000000000000000', + * stateRoot: '0xe0f04b04861ecfa95e82a9310d6a7ef7aef8d7417f5209c182582bfb98a8e307', + * transactionsRoot: '0x31ab4ea571a9e10d3a19aaed07d190595b1dfa34e03960c04293fec565dea536', + * logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + * difficulty: 2n, + * number: 21n, + * gasLimit: 11738125n, + * gasUsed: 830006n, + * timestamp: 1678797237n, + * extraData: '0xd883010b02846765746888676f312e32302e31856c696e757800000000000000e0a6e93cf40e2e71a72e493272210c3f43738ccc7e7d7b14ffd51833797d896c09117e8dc4fbcbc969bd21b42e5af3e276a911524038c001b2109b63b8e0352601', + * nonce: 0n + * } + * ``` + */ +export class NewHeadsSubscription extends Web3Subscription<{ + data: BlockHeaderOutput; +}> { + // eslint-disable-next-line + protected _buildSubscriptionParams() { + return ['newHeads']; + } + + protected formatSubscriptionResult(data: BlockHeaderOutput): BlockHeaderOutput { + return format(blockHeaderSchema, data, super.returnFormat); + } +} + +/** + * ## subscribe('syncing') + * + * Subscribe to syncing events. This will return `true` when the node is syncing and when it’s finished syncing will return `false`, for the `changed` event. + * @example + * ```ts + * (await web3.eth.subscribe('syncing')).on('changed', console.log); + * > `true` // when syncing + * + * (await web3.eth.subscribe('syncing')).on('data', console.log); + * > { + * startingBlock: 0, + * currentBlock: 0, + * highestBlock: 0, + * pulledStates: 0, + * knownStates: 0 + * } + * ``` + */ +export class SyncingSubscription extends Web3Subscription<{ + data: SyncOutput; + changed: boolean; +}> { + // eslint-disable-next-line + protected _buildSubscriptionParams() { + return ['syncing']; + } + + public _processSubscriptionResult( + data: + | { + syncing: boolean; + status: SyncOutput; + } + | boolean, + ) { + if (typeof data === 'boolean') { + this.emit('changed', data); + } else { + const mappedData: SyncOutput = Object.fromEntries( + Object.entries(data.status).map(([key, value]) => [ + key.charAt(0).toLowerCase() + key.substring(1), + value, + ]), + ) as SyncOutput; + + this.emit('changed', data.syncing); + this.emit('data', format(syncSchema, mappedData, super.returnFormat)); + } + } +} diff --git a/test/merkletreejs/node_modules/web3-net/LICENSE b/test/merkletreejs/node_modules/web3-net/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-net/README.md b/test/merkletreejs/node_modules/web3-net/README.md new file mode 100644 index 0000000..6e19cf6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Net + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-net` package allows to interact with an Ethereum node’s network properties. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-net) or using [Yarn](https://yarnpkg.com/package/web3-net) + +### Using NPM + +```bash +npm install web3-net +``` + +### Using Yarn + +```bash +yarn add web3-net +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-net +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-net%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-net +[downloads-image]: https://img.shields.io/npm/dm/web3-net?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.d.ts new file mode 100644 index 0000000..4feb6f8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.d.ts @@ -0,0 +1,33 @@ +/** + * The web3-net package allows you to interact with an Ethereum node’s network properties. + * + * ```ts + * import Net from 'web3-net'; + * + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // or using the web3 umbrella package + * import Web3 from 'web3'; + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * // -> web3.eth.net + * + * // get the ID of the network + * await web3.eth.net.getId(); + * > 5777n + * + * // get the peer count + * await web3.eth.net.getPeerCount(); + * > 0n + * + * // Check if the node is listening for peers + * await web3.eth.net.isListening(); + * > true + * ``` + */ +/** + * + */ +import { Net } from './net.js'; +export * from './net.js'; +export * from './rpc_method_wrappers.js'; +export default Net; diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.js new file mode 100644 index 0000000..d03327d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.js @@ -0,0 +1,66 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * The web3-net package allows you to interact with an Ethereum node’s network properties. + * + * ```ts + * import Net from 'web3-net'; + * + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // or using the web3 umbrella package + * import Web3 from 'web3'; + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * // -> web3.eth.net + * + * // get the ID of the network + * await web3.eth.net.getId(); + * > 5777n + * + * // get the peer count + * await web3.eth.net.getPeerCount(); + * > 0n + * + * // Check if the node is listening for peers + * await web3.eth.net.isListening(); + * > true + * ``` + */ +/** + * + */ +const net_js_1 = require("./net.js"); +__exportStar(require("./net.js"), exports); +__exportStar(require("./rpc_method_wrappers.js"), exports); +exports.default = net_js_1.Net; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.js.map new file mode 100644 index 0000000..8845f08 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;GAEG;AACH,qCAA+B;AAE/B,2CAAyB;AACzB,2DAAyC;AAEzC,kBAAe,YAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.d.ts b/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.d.ts new file mode 100644 index 0000000..1c60d38 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.d.ts @@ -0,0 +1,42 @@ +import { Web3Context } from 'web3-core'; +import { DataFormat, DEFAULT_RETURN_FORMAT, Web3NetAPI } from 'web3-types'; +export declare class Net extends Web3Context { + /** + * Gets the current network ID + * + * @param returnFormat - Return format + * @returns A Promise of the network ID. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getId(); + * > 1 + * ``` + */ + getId(returnFormat?: ReturnFormat): Promise; + /** + * Get the number of peers connected to. + * + * @param returnFormat - Return format + * @returns A promise of the number of the peers connected to. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getPeerCount(); + * > 0 + * ``` + */ + getPeerCount(returnFormat?: ReturnFormat): Promise; + /** + * Check if the node is listening for peers + * + * @returns A promise of a boolean if the node is listening to peers + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.isListening(); + * > true + * ``` + */ + isListening(): Promise; +} diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.js b/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.js new file mode 100644 index 0000000..0a29e68 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.js @@ -0,0 +1,108 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Net = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_core_1 = require("web3-core"); +const web3_types_1 = require("web3-types"); +const rpcMethodsWrappers = __importStar(require("./rpc_method_wrappers.js")); +class Net extends web3_core_1.Web3Context { + /** + * Gets the current network ID + * + * @param returnFormat - Return format + * @returns A Promise of the network ID. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getId(); + * > 1 + * ``` + */ + getId(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getId(this, returnFormat); + }); + } + /** + * Get the number of peers connected to. + * + * @param returnFormat - Return format + * @returns A promise of the number of the peers connected to. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getPeerCount(); + * > 0 + * ``` + */ + getPeerCount(returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getPeerCount(this, returnFormat); + }); + } + /** + * Check if the node is listening for peers + * + * @returns A promise of a boolean if the node is listening to peers + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.isListening(); + * > true + * ``` + */ + isListening() { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.isListening(this); + }); + } +} +exports.Net = Net; +//# sourceMappingURL=net.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.js.map b/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.js.map new file mode 100644 index 0000000..144ef51 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/net.js.map @@ -0,0 +1 @@ +{"version":3,"file":"net.js","sourceRoot":"","sources":["../../src/net.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,yCAAwC;AACxC,2CAA2E;AAE3E,6EAA+D;AAE/D,MAAa,GAAI,SAAQ,uBAAuB;IAC/C;;;;;;;;;;;OAWG;IACU,KAAK,CACjB,eAA6B,kCAAqC;;YAElE,OAAO,kBAAkB,CAAC,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QACrD,CAAC;KAAA;IAED;;;;;;;;;;;OAWG;IACU,YAAY,CACxB,eAA6B,kCAAqC;;YAElE,OAAO,kBAAkB,CAAC,YAAY,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC5D,CAAC;KAAA;IAED;;;;;;;;;;OAUG;IACU,WAAW;;YACvB,OAAO,kBAAkB,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC7C,CAAC;KAAA;CACD;AAnDD,kBAmDC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-net/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.d.ts b/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.d.ts new file mode 100644 index 0000000..b9fc103 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.d.ts @@ -0,0 +1,5 @@ +import { Web3Context } from 'web3-core'; +import { DataFormat, Web3NetAPI } from 'web3-types'; +export declare function getId(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +export declare function getPeerCount(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +export declare const isListening: (web3Context: Web3Context) => Promise; diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.js b/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.js new file mode 100644 index 0000000..939847a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.js @@ -0,0 +1,48 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isListening = exports.getPeerCount = exports.getId = void 0; +const web3_utils_1 = require("web3-utils"); +const web3_rpc_methods_1 = require("web3-rpc-methods"); +function getId(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.netRpcMethods.getId(web3Context.requestManager); + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getId = getId; +function getPeerCount(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield web3_rpc_methods_1.netRpcMethods.getPeerCount(web3Context.requestManager); + // Data returned is number in hex format + return (0, web3_utils_1.format)({ format: 'uint' }, response, returnFormat); + }); +} +exports.getPeerCount = getPeerCount; +const isListening = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return web3_rpc_methods_1.netRpcMethods.isListening(web3Context.requestManager); }); +exports.isListening = isListening; +//# sourceMappingURL=rpc_method_wrappers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.js.map b/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.js.map new file mode 100644 index 0000000..8db8e99 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/commonjs/rpc_method_wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.js","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAAoC;AAGpC,uDAAiD;AAEjD,SAAsB,KAAK,CAC1B,WAAoC,EACpC,YAA0B;;QAE1B,MAAM,QAAQ,GAAG,MAAM,gCAAa,CAAC,KAAK,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAEvE,OAAO,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,QAA6B,EAAE,YAAY,CAAC,CAAC;IAChF,CAAC;CAAA;AAPD,sBAOC;AAED,SAAsB,YAAY,CACjC,WAAoC,EACpC,YAA0B;;QAE1B,MAAM,QAAQ,GAAG,MAAM,gCAAa,CAAC,YAAY,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAE9E,wCAAwC;QACxC,OAAO,IAAA,mBAAM,EAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,QAA6B,EAAE,YAAY,CAAC,CAAC;IAChF,CAAC;CAAA;AARD,oCAQC;AAEM,MAAM,WAAW,GAAG,CAAO,WAAoC,EAAE,EAAE,kDACzE,OAAA,gCAAa,CAAC,WAAW,CAAC,WAAW,CAAC,cAAc,CAAC,CAAA,GAAA,CAAC;AAD1C,QAAA,WAAW,eAC+B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/index.js b/test/merkletreejs/node_modules/web3-net/lib/esm/index.js new file mode 100644 index 0000000..76923ee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/index.js @@ -0,0 +1,50 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * The web3-net package allows you to interact with an Ethereum node’s network properties. + * + * ```ts + * import Net from 'web3-net'; + * + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // or using the web3 umbrella package + * import Web3 from 'web3'; + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * // -> web3.eth.net + * + * // get the ID of the network + * await web3.eth.net.getId(); + * > 5777n + * + * // get the peer count + * await web3.eth.net.getPeerCount(); + * > 0n + * + * // Check if the node is listening for peers + * await web3.eth.net.isListening(); + * > true + * ``` + */ +/** + * + */ +import { Net } from './net.js'; +export * from './net.js'; +export * from './rpc_method_wrappers.js'; +export default Net; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-net/lib/esm/index.js.map new file mode 100644 index 0000000..1991f9f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;GAEG;AACH,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAE/B,cAAc,UAAU,CAAC;AACzB,cAAc,0BAA0B,CAAC;AAEzC,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/net.js b/test/merkletreejs/node_modules/web3-net/lib/esm/net.js new file mode 100644 index 0000000..f829110 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/net.js @@ -0,0 +1,81 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3Context } from 'web3-core'; +import { DEFAULT_RETURN_FORMAT } from 'web3-types'; +import * as rpcMethodsWrappers from './rpc_method_wrappers.js'; +export class Net extends Web3Context { + /** + * Gets the current network ID + * + * @param returnFormat - Return format + * @returns A Promise of the network ID. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getId(); + * > 1 + * ``` + */ + getId(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getId(this, returnFormat); + }); + } + /** + * Get the number of peers connected to. + * + * @param returnFormat - Return format + * @returns A promise of the number of the peers connected to. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getPeerCount(); + * > 0 + * ``` + */ + getPeerCount(returnFormat = DEFAULT_RETURN_FORMAT) { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.getPeerCount(this, returnFormat); + }); + } + /** + * Check if the node is listening for peers + * + * @returns A promise of a boolean if the node is listening to peers + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.isListening(); + * > true + * ``` + */ + isListening() { + return __awaiter(this, void 0, void 0, function* () { + return rpcMethodsWrappers.isListening(this); + }); + } +} +//# sourceMappingURL=net.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/net.js.map b/test/merkletreejs/node_modules/web3-net/lib/esm/net.js.map new file mode 100644 index 0000000..aba74e0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/net.js.map @@ -0,0 +1 @@ +{"version":3,"file":"net.js","sourceRoot":"","sources":["../../src/net.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAc,qBAAqB,EAAc,MAAM,YAAY,CAAC;AAE3E,OAAO,KAAK,kBAAkB,MAAM,0BAA0B,CAAC;AAE/D,MAAM,OAAO,GAAI,SAAQ,WAAuB;IAC/C;;;;;;;;;;;OAWG;IACU,KAAK,CACjB,eAA6B,qBAAqC;;YAElE,OAAO,kBAAkB,CAAC,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QACrD,CAAC;KAAA;IAED;;;;;;;;;;;OAWG;IACU,YAAY,CACxB,eAA6B,qBAAqC;;YAElE,OAAO,kBAAkB,CAAC,YAAY,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC5D,CAAC;KAAA;IAED;;;;;;;;;;OAUG;IACU,WAAW;;YACvB,OAAO,kBAAkB,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC7C,CAAC;KAAA;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/package.json b/test/merkletreejs/node_modules/web3-net/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/rpc_method_wrappers.js b/test/merkletreejs/node_modules/web3-net/lib/esm/rpc_method_wrappers.js new file mode 100644 index 0000000..7935326 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/rpc_method_wrappers.js @@ -0,0 +1,42 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { format } from 'web3-utils'; +import { netRpcMethods } from 'web3-rpc-methods'; +export function getId(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield netRpcMethods.getId(web3Context.requestManager); + return format({ format: 'uint' }, response, returnFormat); + }); +} +export function getPeerCount(web3Context, returnFormat) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield netRpcMethods.getPeerCount(web3Context.requestManager); + // Data returned is number in hex format + return format({ format: 'uint' }, response, returnFormat); + }); +} +export const isListening = (web3Context) => __awaiter(void 0, void 0, void 0, function* () { return netRpcMethods.isListening(web3Context.requestManager); }); +//# sourceMappingURL=rpc_method_wrappers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/esm/rpc_method_wrappers.js.map b/test/merkletreejs/node_modules/web3-net/lib/esm/rpc_method_wrappers.js.map new file mode 100644 index 0000000..d076598 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/esm/rpc_method_wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.js","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAGpC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,UAAgB,KAAK,CAC1B,WAAoC,EACpC,YAA0B;;QAE1B,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAEvE,OAAO,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,QAA6B,EAAE,YAAY,CAAC,CAAC;IAChF,CAAC;CAAA;AAED,MAAM,UAAgB,YAAY,CACjC,WAAoC,EACpC,YAA0B;;QAE1B,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC,YAAY,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAE9E,wCAAwC;QACxC,OAAO,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,QAA6B,EAAE,YAAY,CAAC,CAAC;IAChF,CAAC;CAAA;AAED,MAAM,CAAC,MAAM,WAAW,GAAG,CAAO,WAAoC,EAAE,EAAE,kDACzE,OAAA,aAAa,CAAC,WAAW,CAAC,WAAW,CAAC,cAAc,CAAC,CAAA,GAAA,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-net/lib/types/index.d.ts new file mode 100644 index 0000000..1487fe5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/types/index.d.ts @@ -0,0 +1,34 @@ +/** + * The web3-net package allows you to interact with an Ethereum node’s network properties. + * + * ```ts + * import Net from 'web3-net'; + * + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // or using the web3 umbrella package + * import Web3 from 'web3'; + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * // -> web3.eth.net + * + * // get the ID of the network + * await web3.eth.net.getId(); + * > 5777n + * + * // get the peer count + * await web3.eth.net.getPeerCount(); + * > 0n + * + * // Check if the node is listening for peers + * await web3.eth.net.isListening(); + * > true + * ``` + */ +/** + * + */ +import { Net } from './net.js'; +export * from './net.js'; +export * from './rpc_method_wrappers.js'; +export default Net; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-net/lib/types/index.d.ts.map new file mode 100644 index 0000000..e35026e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;GAEG;AACH,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAE/B,cAAc,UAAU,CAAC;AACzB,cAAc,0BAA0B,CAAC;AAEzC,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/types/net.d.ts b/test/merkletreejs/node_modules/web3-net/lib/types/net.d.ts new file mode 100644 index 0000000..37fd8e6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/types/net.d.ts @@ -0,0 +1,43 @@ +import { Web3Context } from 'web3-core'; +import { DataFormat, DEFAULT_RETURN_FORMAT, Web3NetAPI } from 'web3-types'; +export declare class Net extends Web3Context { + /** + * Gets the current network ID + * + * @param returnFormat - Return format + * @returns A Promise of the network ID. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getId(); + * > 1 + * ``` + */ + getId(returnFormat?: ReturnFormat): Promise; + /** + * Get the number of peers connected to. + * + * @param returnFormat - Return format + * @returns A promise of the number of the peers connected to. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getPeerCount(); + * > 0 + * ``` + */ + getPeerCount(returnFormat?: ReturnFormat): Promise; + /** + * Check if the node is listening for peers + * + * @returns A promise of a boolean if the node is listening to peers + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.isListening(); + * > true + * ``` + */ + isListening(): Promise; +} +//# sourceMappingURL=net.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/types/net.d.ts.map b/test/merkletreejs/node_modules/web3-net/lib/types/net.d.ts.map new file mode 100644 index 0000000..251cd78 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/types/net.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"net.d.ts","sourceRoot":"","sources":["../../src/net.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAI3E,qBAAa,GAAI,SAAQ,WAAW,CAAC,UAAU,CAAC;IAC/C;;;;;;;;;;;OAWG;IACU,KAAK,CAAC,YAAY,SAAS,UAAU,GAAG,OAAO,qBAAqB,EAChF,YAAY,GAAE,YAAoD;IAKnE;;;;;;;;;;;OAWG;IACU,YAAY,CAAC,YAAY,SAAS,UAAU,GAAG,OAAO,qBAAqB,EACvF,YAAY,GAAE,YAAoD;IAKnE;;;;;;;;;;OAUG;IACU,WAAW;CAGxB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/types/rpc_method_wrappers.d.ts b/test/merkletreejs/node_modules/web3-net/lib/types/rpc_method_wrappers.d.ts new file mode 100644 index 0000000..cfcd81f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/types/rpc_method_wrappers.d.ts @@ -0,0 +1,6 @@ +import { Web3Context } from 'web3-core'; +import { DataFormat, Web3NetAPI } from 'web3-types'; +export declare function getId(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +export declare function getPeerCount(web3Context: Web3Context, returnFormat: ReturnFormat): Promise; +export declare const isListening: (web3Context: Web3Context) => Promise; +//# sourceMappingURL=rpc_method_wrappers.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/lib/types/rpc_method_wrappers.d.ts.map b/test/merkletreejs/node_modules/web3-net/lib/types/rpc_method_wrappers.d.ts.map new file mode 100644 index 0000000..4c17736 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/lib/types/rpc_method_wrappers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc_method_wrappers.d.ts","sourceRoot":"","sources":["../../src/rpc_method_wrappers.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAGpD,wBAAsB,KAAK,CAAC,YAAY,SAAS,UAAU,EAC1D,WAAW,EAAE,WAAW,CAAC,UAAU,CAAC,EACpC,YAAY,EAAE,YAAY,qEAK1B;AAED,wBAAsB,YAAY,CAAC,YAAY,SAAS,UAAU,EACjE,WAAW,EAAE,WAAW,CAAC,UAAU,CAAC,EACpC,YAAY,EAAE,YAAY,qEAM1B;AAED,eAAO,MAAM,WAAW,gBAAuB,YAAY,UAAU,CAAC,qBAChB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-net/package.json b/test/merkletreejs/node_modules/web3-net/package.json new file mode 100644 index 0000000..4c85aa3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/package.json @@ -0,0 +1,65 @@ +{ + "name": "web3-net", + "version": "4.0.7", + "description": "Web3 module to interact with the Ethereum nodes networking properties.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "web3-core": "^4.3.0", + "web3-rpc-methods": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-net/src/index.ts b/test/merkletreejs/node_modules/web3-net/src/index.ts new file mode 100644 index 0000000..d2ba11d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/src/index.ts @@ -0,0 +1,53 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * The web3-net package allows you to interact with an Ethereum node’s network properties. + * + * ```ts + * import Net from 'web3-net'; + * + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * // or using the web3 umbrella package + * import Web3 from 'web3'; + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * // -> web3.eth.net + * + * // get the ID of the network + * await web3.eth.net.getId(); + * > 5777n + * + * // get the peer count + * await web3.eth.net.getPeerCount(); + * > 0n + * + * // Check if the node is listening for peers + * await web3.eth.net.isListening(); + * > true + * ``` + */ + +/** + * + */ +import { Net } from './net.js'; + +export * from './net.js'; +export * from './rpc_method_wrappers.js'; + +export default Net; diff --git a/test/merkletreejs/node_modules/web3-net/src/net.ts b/test/merkletreejs/node_modules/web3-net/src/net.ts new file mode 100644 index 0000000..b03dcb2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/src/net.ts @@ -0,0 +1,73 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3Context } from 'web3-core'; +import { DataFormat, DEFAULT_RETURN_FORMAT, Web3NetAPI } from 'web3-types'; + +import * as rpcMethodsWrappers from './rpc_method_wrappers.js'; + +export class Net extends Web3Context { + /** + * Gets the current network ID + * + * @param returnFormat - Return format + * @returns A Promise of the network ID. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getId(); + * > 1 + * ``` + */ + public async getId( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getId(this, returnFormat); + } + + /** + * Get the number of peers connected to. + * + * @param returnFormat - Return format + * @returns A promise of the number of the peers connected to. + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.getPeerCount(); + * > 0 + * ``` + */ + public async getPeerCount( + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + ) { + return rpcMethodsWrappers.getPeerCount(this, returnFormat); + } + + /** + * Check if the node is listening for peers + * + * @returns A promise of a boolean if the node is listening to peers + * @example + * ```ts + * const net = new Net(Net.givenProvider || 'ws://some.local-or-remote.node:8546'); + * await net.isListening(); + * > true + * ``` + */ + public async isListening() { + return rpcMethodsWrappers.isListening(this); + } +} diff --git a/test/merkletreejs/node_modules/web3-net/src/rpc_method_wrappers.ts b/test/merkletreejs/node_modules/web3-net/src/rpc_method_wrappers.ts new file mode 100644 index 0000000..f923615 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-net/src/rpc_method_wrappers.ts @@ -0,0 +1,43 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { format } from 'web3-utils'; +import { Web3Context } from 'web3-core'; +import { DataFormat, Web3NetAPI } from 'web3-types'; +import { netRpcMethods } from 'web3-rpc-methods'; + +export async function getId( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await netRpcMethods.getId(web3Context.requestManager); + + return format({ format: 'uint' }, response as unknown as number, returnFormat); +} + +export async function getPeerCount( + web3Context: Web3Context, + returnFormat: ReturnFormat, +) { + const response = await netRpcMethods.getPeerCount(web3Context.requestManager); + + // Data returned is number in hex format + return format({ format: 'uint' }, response as unknown as number, returnFormat); +} + +export const isListening = async (web3Context: Web3Context) => + netRpcMethods.isListening(web3Context.requestManager); diff --git a/test/merkletreejs/node_modules/web3-providers-http/LICENSE b/test/merkletreejs/node_modules/web3-providers-http/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-providers-http/README.md b/test/merkletreejs/node_modules/web3-providers-http/README.md new file mode 100644 index 0000000..12c52dd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Http Provider + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-providers-http` contains the Web3.js provider for the HTTP protocol. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-providers-http) or using [Yarn](https://yarnpkg.com/package/web3-providers-http) + +### Using NPM + +```bash +npm install web3-providers-http +``` + +### Using Yarn + +```bash +yarn add web3-providers-http +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new/choose) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-providers-http +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-providers-http%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-providers-http +[downloads-image]: https://img.shields.io/npm/dm/web3-providers-http?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.d.ts new file mode 100644 index 0000000..713c449 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.d.ts @@ -0,0 +1,21 @@ +import { EthExecutionAPI, JsonRpcResponseWithResult, Web3APIMethod, Web3APIPayload, Web3APIReturnType, Web3APISpec, Web3BaseProvider, Web3ProviderStatus } from 'web3-types'; +import { HttpProviderOptions } from './types.js'; +export { HttpProviderOptions } from './types.js'; +export default class HttpProvider extends Web3BaseProvider { + private readonly clientUrl; + private readonly httpProviderOptions; + constructor(clientUrl: string, httpProviderOptions?: HttpProviderOptions); + private static validateClientUrl; + getStatus(): Web3ProviderStatus; + supportsSubscriptions(): boolean; + request, ResultType = Web3APIReturnType>(payload: Web3APIPayload, requestOptions?: RequestInit): Promise>; + on(): void; + removeListener(): void; + once(): void; + removeAllListeners(): void; + connect(): void; + disconnect(): void; + reset(): void; + reconnect(): void; +} +export { HttpProvider }; diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.js new file mode 100644 index 0000000..d935ac9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.js @@ -0,0 +1,100 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpProvider = void 0; +const cross_fetch_1 = __importDefault(require("cross-fetch")); +const web3_types_1 = require("web3-types"); +const web3_errors_1 = require("web3-errors"); +class HttpProvider extends web3_types_1.Web3BaseProvider { + constructor(clientUrl, httpProviderOptions) { + super(); + if (!HttpProvider.validateClientUrl(clientUrl)) + throw new web3_errors_1.InvalidClientError(clientUrl); + this.clientUrl = clientUrl; + this.httpProviderOptions = httpProviderOptions; + } + static validateClientUrl(clientUrl) { + return typeof clientUrl === 'string' ? /^http(s)?:\/\//i.test(clientUrl) : false; + } + /* eslint-disable class-methods-use-this */ + getStatus() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + supportsSubscriptions() { + return false; + } + request(payload, requestOptions) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const providerOptionsCombined = Object.assign(Object.assign({}, (_a = this.httpProviderOptions) === null || _a === void 0 ? void 0 : _a.providerOptions), requestOptions); + const response = yield (0, cross_fetch_1.default)(this.clientUrl, Object.assign(Object.assign({}, providerOptionsCombined), { method: 'POST', headers: Object.assign(Object.assign({}, providerOptionsCombined.headers), { 'Content-Type': 'application/json' }), body: JSON.stringify(payload) })); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + if (!response.ok) + throw new web3_errors_1.ResponseError(yield response.json()); + return (yield response.json()); + }); + } + /* eslint-disable class-methods-use-this */ + on() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + removeListener() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + once() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + removeAllListeners() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + connect() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + disconnect() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + reset() { + throw new web3_errors_1.MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + reconnect() { + throw new web3_errors_1.MethodNotImplementedError(); + } +} +exports.default = HttpProvider; +exports.HttpProvider = HttpProvider; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.js.map new file mode 100644 index 0000000..662cb65 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;AAEF,8DAAgC;AAChC,2CASoB;AACpB,6CAA2F;AAK3F,MAAqB,YAEnB,SAAQ,6BAAqB;IAI9B,YAAmB,SAAiB,EAAE,mBAAyC;QAC9E,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,CAAC,iBAAiB,CAAC,SAAS,CAAC;YAAE,MAAM,IAAI,gCAAkB,CAAC,SAAS,CAAC,CAAC;QACxF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IAChD,CAAC;IAEO,MAAM,CAAC,iBAAiB,CAAC,SAAiB;QACjD,OAAO,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAClF,CAAC;IAED,2CAA2C;IACpC,SAAS;QACf,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,qBAAqB;QAC3B,OAAO,KAAK,CAAC;IACd,CAAC;IAEY,OAAO,CAInB,OAAoC,EACpC,cAA4B;;;YAE5B,MAAM,uBAAuB,mCACzB,MAAA,IAAI,CAAC,mBAAmB,0CAAE,eAAe,GACzC,cAAc,CACjB,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,IAAA,qBAAK,EAAC,IAAI,CAAC,SAAS,kCACvC,uBAAuB,KAC1B,MAAM,EAAE,MAAM,EACd,OAAO,kCACH,uBAAuB,CAAC,OAAO,KAClC,cAAc,EAAE,kBAAkB,KAEnC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAC5B,CAAC;YAEH,iEAAiE;YACjE,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,MAAM,IAAI,2BAAa,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;YAEjE,OAAO,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAA0C,CAAC;;KACxE;IAED,2CAA2C;IACpC,EAAE;QACR,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,cAAc;QACpB,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,IAAI;QACV,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,kBAAkB;QACxB,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,OAAO;QACb,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,UAAU;QAChB,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,KAAK;QACX,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,SAAS;QACf,MAAM,IAAI,uCAAyB,EAAE,CAAC;IACvC,CAAC;CACD;AA7FD,+BA6FC;AAEQ,oCAAY"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.d.ts new file mode 100644 index 0000000..c8b9930 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.d.ts @@ -0,0 +1,3 @@ +export interface HttpProviderOptions { + providerOptions: RequestInit; +} diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/esm/index.js b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/index.js new file mode 100644 index 0000000..5503d3b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/index.js @@ -0,0 +1,93 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import fetch from 'cross-fetch'; +import { Web3BaseProvider, } from 'web3-types'; +import { InvalidClientError, MethodNotImplementedError, ResponseError } from 'web3-errors'; +export default class HttpProvider extends Web3BaseProvider { + constructor(clientUrl, httpProviderOptions) { + super(); + if (!HttpProvider.validateClientUrl(clientUrl)) + throw new InvalidClientError(clientUrl); + this.clientUrl = clientUrl; + this.httpProviderOptions = httpProviderOptions; + } + static validateClientUrl(clientUrl) { + return typeof clientUrl === 'string' ? /^http(s)?:\/\//i.test(clientUrl) : false; + } + /* eslint-disable class-methods-use-this */ + getStatus() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + supportsSubscriptions() { + return false; + } + request(payload, requestOptions) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const providerOptionsCombined = Object.assign(Object.assign({}, (_a = this.httpProviderOptions) === null || _a === void 0 ? void 0 : _a.providerOptions), requestOptions); + const response = yield fetch(this.clientUrl, Object.assign(Object.assign({}, providerOptionsCombined), { method: 'POST', headers: Object.assign(Object.assign({}, providerOptionsCombined.headers), { 'Content-Type': 'application/json' }), body: JSON.stringify(payload) })); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + if (!response.ok) + throw new ResponseError(yield response.json()); + return (yield response.json()); + }); + } + /* eslint-disable class-methods-use-this */ + on() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + removeListener() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + once() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + removeAllListeners() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + connect() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + disconnect() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + reset() { + throw new MethodNotImplementedError(); + } + /* eslint-disable class-methods-use-this */ + reconnect() { + throw new MethodNotImplementedError(); + } +} +export { HttpProvider }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/index.js.map new file mode 100644 index 0000000..0c9d7c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,KAAK,MAAM,aAAa,CAAC;AAChC,OAAO,EAON,gBAAgB,GAEhB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAK3F,MAAM,CAAC,OAAO,OAAO,YAEnB,SAAQ,gBAAqB;IAI9B,YAAmB,SAAiB,EAAE,mBAAyC;QAC9E,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,CAAC,iBAAiB,CAAC,SAAS,CAAC;YAAE,MAAM,IAAI,kBAAkB,CAAC,SAAS,CAAC,CAAC;QACxF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IAChD,CAAC;IAEO,MAAM,CAAC,iBAAiB,CAAC,SAAiB;QACjD,OAAO,OAAO,SAAS,KAAK,QAAQ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,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,KAAK;QACX,MAAM,IAAI,yBAAyB,EAAE,CAAC;IACvC,CAAC;IAED,2CAA2C;IACpC,SAAS;QACf,MAAM,IAAI,yBAAyB,EAAE,CAAC;IACvC,CAAC;CACD;AAED,OAAO,EAAE,YAAY,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/esm/package.json b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/esm/types.js b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-providers-http/lib/types/index.d.ts new file mode 100644 index 0000000..0e2dd33 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/types/index.d.ts @@ -0,0 +1,22 @@ +import { EthExecutionAPI, JsonRpcResponseWithResult, Web3APIMethod, Web3APIPayload, Web3APIReturnType, Web3APISpec, Web3BaseProvider, Web3ProviderStatus } from 'web3-types'; +import { HttpProviderOptions } from './types.js'; +export { HttpProviderOptions } from './types.js'; +export default class HttpProvider extends Web3BaseProvider { + private readonly clientUrl; + private readonly httpProviderOptions; + constructor(clientUrl: string, httpProviderOptions?: HttpProviderOptions); + private static validateClientUrl; + getStatus(): Web3ProviderStatus; + supportsSubscriptions(): boolean; + request, ResultType = Web3APIReturnType>(payload: Web3APIPayload, requestOptions?: RequestInit): Promise>; + on(): void; + removeListener(): void; + once(): void; + removeAllListeners(): void; + connect(): void; + disconnect(): void; + reset(): void; + reconnect(): void; +} +export { HttpProvider }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-providers-http/lib/types/index.d.ts.map new file mode 100644 index 0000000..4cb7c07 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAkBA,OAAO,EACN,eAAe,EACf,yBAAyB,EACzB,aAAa,EACb,cAAc,EACd,iBAAiB,EACjB,WAAW,EACX,gBAAgB,EAChB,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,CAAC,OAAO,OAAO,YAAY,CAChC,GAAG,SAAS,WAAW,GAAG,eAAe,CACxC,SAAQ,gBAAgB,CAAC,GAAG,CAAC;IAC9B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAkC;gBAEnD,SAAS,EAAE,MAAM,EAAE,mBAAmB,CAAC,EAAE,mBAAmB;IAO/E,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAKzB,SAAS,IAAI,kBAAkB;IAK/B,qBAAqB;IAIf,OAAO,CACnB,MAAM,SAAS,aAAa,CAAC,GAAG,CAAC,EACjC,UAAU,GAAG,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,EAE3C,OAAO,EAAE,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,EACpC,cAAc,CAAC,EAAE,WAAW,GAC1B,OAAO,CAAC,yBAAyB,CAAC,UAAU,CAAC,CAAC;IAsB1C,EAAE;IAKF,cAAc;IAKd,IAAI;IAKJ,kBAAkB;IAKlB,OAAO;IAKP,UAAU;IAKV,KAAK;IAKL,SAAS;CAGhB;AAED,OAAO,EAAE,YAAY,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-providers-http/lib/types/types.d.ts new file mode 100644 index 0000000..8638d16 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/types/types.d.ts @@ -0,0 +1,4 @@ +export interface HttpProviderOptions { + providerOptions: RequestInit; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-providers-http/lib/types/types.d.ts.map new file mode 100644 index 0000000..7372e89 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,MAAM,WAAW,mBAAmB;IACnC,eAAe,EAAE,WAAW,CAAC;CAC7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-http/package.json b/test/merkletreejs/node_modules/web3-providers-http/package.json new file mode 100644 index 0000000..8178e0c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/package.json @@ -0,0 +1,69 @@ +{ + "name": "web3-providers-http", + "version": "4.1.0", + "description": "HTTP provider for Web3 4.x.x", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js", + "test:e2e:electron": "npx cypress run --headless --browser electron", + "test:e2e:chrome": "npx cypress run --headless --browser chrome", + "test:e2e:firefox": "npx cypress run --headless --browser firefox" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "jest-fetch-mock": "^3.0.3", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "cross-fetch": "^4.0.0", + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-providers-http/src/index.ts b/test/merkletreejs/node_modules/web3-providers-http/src/index.ts new file mode 100644 index 0000000..64dadd9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/src/index.ts @@ -0,0 +1,129 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import fetch from 'cross-fetch'; +import { + EthExecutionAPI, + JsonRpcResponseWithResult, + Web3APIMethod, + Web3APIPayload, + Web3APIReturnType, + Web3APISpec, + Web3BaseProvider, + Web3ProviderStatus, +} from 'web3-types'; +import { InvalidClientError, MethodNotImplementedError, ResponseError } from 'web3-errors'; +import { HttpProviderOptions } from './types.js'; + +export { HttpProviderOptions } from './types.js'; + +export default class HttpProvider< + API extends Web3APISpec = EthExecutionAPI, +> extends Web3BaseProvider { + private readonly clientUrl: string; + private readonly httpProviderOptions: HttpProviderOptions | undefined; + + public constructor(clientUrl: string, httpProviderOptions?: HttpProviderOptions) { + super(); + if (!HttpProvider.validateClientUrl(clientUrl)) throw new InvalidClientError(clientUrl); + this.clientUrl = clientUrl; + this.httpProviderOptions = httpProviderOptions; + } + + private static validateClientUrl(clientUrl: string): boolean { + return typeof clientUrl === 'string' ? /^http(s)?:\/\//i.test(clientUrl) : false; + } + + /* eslint-disable class-methods-use-this */ + public getStatus(): Web3ProviderStatus { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public supportsSubscriptions() { + return false; + } + + public async request< + Method extends Web3APIMethod, + ResultType = Web3APIReturnType, + >( + payload: Web3APIPayload, + requestOptions?: RequestInit, + ): Promise> { + const providerOptionsCombined = { + ...this.httpProviderOptions?.providerOptions, + ...requestOptions, + }; + const response = await fetch(this.clientUrl, { + ...providerOptionsCombined, + method: 'POST', + headers: { + ...providerOptionsCombined.headers, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(payload), + }); + + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + if (!response.ok) throw new ResponseError(await response.json()); + + return (await response.json()) as JsonRpcResponseWithResult; + } + + /* eslint-disable class-methods-use-this */ + public on() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public removeListener() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public once() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public removeAllListeners() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public connect() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public disconnect() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public reset() { + throw new MethodNotImplementedError(); + } + + /* eslint-disable class-methods-use-this */ + public reconnect() { + throw new MethodNotImplementedError(); + } +} + +export { HttpProvider }; diff --git a/test/merkletreejs/node_modules/web3-providers-http/src/types.ts b/test/merkletreejs/node_modules/web3-providers-http/src/types.ts new file mode 100644 index 0000000..e6d109c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-http/src/types.ts @@ -0,0 +1,20 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export interface HttpProviderOptions { + providerOptions: RequestInit; +} diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/LICENSE b/test/merkletreejs/node_modules/web3-providers-ipc/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/README.md b/test/merkletreejs/node_modules/web3-providers-ipc/README.md new file mode 100644 index 0000000..39913cd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - IPC Provider + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-providers-ipc` contains the Web3.js provider for Inter Process Communication (IPC). + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-providers-ipc) or using [Yarn](https://yarnpkg.com/package/web3-providers-ipc) + +### Using NPM + +```bash +npm install web3-providers-ipc +``` + +### Using Yarn + +```bash +yarn add web3-providers-ipc +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-probiders-ipc +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-providers-ipc%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-providers-ipc +[downloads-image]: https://img.shields.io/npm/dm/web3-providers-ipc?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.d.ts new file mode 100644 index 0000000..d82f961 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.d.ts @@ -0,0 +1,57 @@ +/// +import { Socket, SocketConstructorOpts } from 'net'; +import { ReconnectOptions, SocketProvider } from 'web3-utils'; +import { EthExecutionAPI, Web3APIMethod, Web3APIPayload, Web3APISpec, Web3ProviderStatus } from 'web3-types'; +/** + * The IPC Provider could be used in node.js dapps when running a local node. And it provide the most secure connection. + * + * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * { + * writable: false, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class IpcProvider extends SocketProvider { + protected readonly _socketOptions?: SocketConstructorOpts; + protected _socketConnection?: Socket; + /** + * This is a class used for IPC connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the IPC socket. + * @param socketOptions - The options for the IPC socket connection. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath: string, socketOptions?: SocketConstructorOpts, reconnectOptions?: Partial); + getStatus(): Web3ProviderStatus; + protected _openSocketConnection(): void; + protected _closeSocketConnection(code: number, data?: string): void; + protected _sendToSocket>(payload: Web3APIPayload): void; + protected _parseResponses(e: Uint8Array | string): import("web3-types").JsonRpcResponse[]; + protected _addSocketListeners(): void; + protected _removeSocketListeners(): void; + protected _onCloseEvent(event: CloseEvent): void; + protected _onClose(event: CloseEvent): void; +} +export { IpcProvider }; diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.js new file mode 100644 index 0000000..5e12a32 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.js @@ -0,0 +1,136 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IpcProvider = void 0; +const net_1 = require("net"); +const web3_errors_1 = require("web3-errors"); +const web3_utils_1 = require("web3-utils"); +const fs_1 = require("fs"); +/** + * The IPC Provider could be used in node.js dapps when running a local node. And it provide the most secure connection. + * + * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * { + * writable: false, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +class IpcProvider extends web3_utils_1.SocketProvider { + /** + * This is a class used for IPC connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the IPC socket. + * @param socketOptions - The options for the IPC socket connection. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + // this constructor is to specify the type for `socketOptions` for a better intellisense. + // eslint-disable-next-line no-useless-constructor + constructor(socketPath, socketOptions, reconnectOptions) { + super(socketPath, socketOptions, reconnectOptions); + } + getStatus() { + var _a; + if ((_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.connecting) { + return 'connecting'; + } + return this._connectionStatus; + } + _openSocketConnection() { + if (!(0, fs_1.existsSync)(this._socketPath)) { + throw new web3_errors_1.InvalidClientError(this._socketPath); + } + if (!this._socketConnection || this.getStatus() === 'disconnected') { + this._socketConnection = new net_1.Socket(this._socketOptions); + } + this._socketConnection.connect({ path: this._socketPath }); + } + _closeSocketConnection(code, data) { + var _a; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.end(() => { + this._onDisconnect(code, data); + }); + } + _sendToSocket(payload) { + var _a; + if (this.getStatus() === 'disconnected') { + throw new web3_errors_1.ConnectionNotOpenError(); + } + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.write(JSON.stringify(payload)); + } + _parseResponses(e) { + return this.chunkResponseParser.parseResponse(typeof e === 'string' ? e : (0, web3_utils_1.toUtf8)(e)); + } + _addSocketListeners() { + var _a, _b, _c, _d, _e; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.on('data', this._onMessageHandler); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.on('connect', this._onOpenHandler); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.on('close', this._onClose.bind(this)); + (_d = this._socketConnection) === null || _d === void 0 ? void 0 : _d.on('end', this._onCloseHandler); + (_e = this._socketConnection) === null || _e === void 0 ? void 0 : _e.on('error', this._onErrorHandler); + } + _removeSocketListeners() { + var _a, _b, _c, _d; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeAllListeners('connect'); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.removeAllListeners('end'); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.removeAllListeners('close'); + (_d = this._socketConnection) === null || _d === void 0 ? void 0 : _d.removeAllListeners('data'); + // note: we intentionally keep the error event listener to be able to emit it in case an error happens when closing the connection + } + _onCloseEvent(event) { + var _a; + if (!event && this._reconnectOptions.autoReconnect) { + this._connectionStatus = 'disconnected'; + this._reconnect(); + return; + } + this._clearQueues(event); + this._removeSocketListeners(); + this._onDisconnect(event === null || event === void 0 ? void 0 : event.code, event === null || event === void 0 ? void 0 : event.reason); + // disconnect was successful and can safely remove error listener + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeAllListeners('error'); + } + _onClose(event) { + this._clearQueues(event); + this._removeSocketListeners(); + } +} +exports.default = IpcProvider; +exports.IpcProvider = IpcProvider; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.js.map new file mode 100644 index 0000000..dc6695b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6BAAoD;AACpD,6CAAyE;AACzE,2CAAsE;AAQtE,2BAAgC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAqB,WAAuD,SAAQ,2BAKnF;IAKA;;;;;OAKG;IACH,yFAAyF;IACzF,kDAAkD;IAClD,YACC,UAAkB,EAClB,aAAqC,EACrC,gBAA4C;QAE5C,KAAK,CAAC,UAAU,EAAE,aAAa,EAAE,gBAAgB,CAAC,CAAC;IACpD,CAAC;IAEM,SAAS;;QACf,IAAI,MAAA,IAAI,CAAC,iBAAiB,0CAAE,UAAU,EAAE;YACvC,OAAO,YAAY,CAAC;SACpB;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAC/B,CAAC;IAES,qBAAqB;QAC9B,IAAI,CAAC,IAAA,eAAU,EAAC,IAAI,CAAC,WAAW,CAAC,EAAE;YAClC,MAAM,IAAI,gCAAkB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;SAC/C;QACD,IAAI,CAAC,IAAI,CAAC,iBAAiB,IAAI,IAAI,CAAC,SAAS,EAAE,KAAK,cAAc,EAAE;YACnE,IAAI,CAAC,iBAAiB,GAAG,IAAI,YAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;SACzD;QAED,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;IAC5D,CAAC;IAES,sBAAsB,CAAC,IAAY,EAAE,IAAa;;QAC3D,MAAA,IAAI,CAAC,iBAAiB,0CAAE,GAAG,CAAC,GAAG,EAAE;YAChC,IAAI,CAAC,aA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AAiB,0CAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;QACpD,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,MAAM,CAAC,CAAC;QACnD,kIAAkI;IACnI,CAAC;IAES,aAAa,CAAC,KAAiB;;QACxC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,iBAAiB,CAAC,aAAa,EAAE;YACnD,IAAI,CAAC,iBAAiB,GAAG,cAAc,CAAC;YACxC,IAAI,CAAC,UAAU,EAAE,CAAC;YAClB,OAAO;SACP;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACzB,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC9B,IAAI,CAAC,aAAa,CAAC,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,CAAC,CAAC;QAC/C,iEAAiE;QACjE,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC;IAES,QAAQ,CAAC,KAAiB;QACnC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACzB,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAC/B,CAAC;CACD;AAjGD,8BAiGC;AAEQ,kCAAW"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/index.js b/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/index.js new file mode 100644 index 0000000..274957b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/index.js @@ -0,0 +1,132 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Socket } from 'net'; +import { ConnectionNotOpenError, InvalidClientError } from 'web3-errors'; +import { SocketProvider, toUtf8 } from 'web3-utils'; +import { existsSync } from 'fs'; +/** + * The IPC Provider could be used in node.js dapps when running a local node. And it provide the most secure connection. + * + * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * { + * writable: false, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class IpcProvider extends SocketProvider { + /** + * This is a class used for IPC connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the IPC socket. + * @param socketOptions - The options for the IPC socket connection. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + // this constructor is to specify the type for `socketOptions` for a better intellisense. + // eslint-disable-next-line no-useless-constructor + constructor(socketPath, socketOptions, reconnectOptions) { + super(socketPath, socketOptions, reconnectOptions); + } + getStatus() { + var _a; + if ((_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.connecting) { + return 'connecting'; + } + return this._connectionStatus; + } + _openSocketConnection() { + if (!existsSync(this._socketPath)) { + throw new InvalidClientError(this._socketPath); + } + if (!this._socketConnection || this.getStatus() === 'disconnected') { + this._socketConnection = new Socket(this._socketOptions); + } + this._socketConnection.connect({ path: this._socketPath }); + } + _closeSocketConnection(code, data) { + var _a; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.end(() => { + this._onDisconnect(code, data); + }); + } + _sendToSocket(payload) { + var _a; + if (this.getStatus() === 'disconnected') { + throw new ConnectionNotOpenError(); + } + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.write(JSON.stringify(payload)); + } + _parseResponses(e) { + return this.chunkResponseParser.parseResponse(typeof e === 'string' ? e : toUtf8(e)); + } + _addSocketListeners() { + var _a, _b, _c, _d, _e; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.on('data', this._onMessageHandler); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.on('connect', this._onOpenHandler); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.on('close', this._onClose.bind(this)); + (_d = this._socketConnection) === null || _d === void 0 ? void 0 : _d.on('end', this._onCloseHandler); + (_e = this._socketConnection) === null || _e === void 0 ? void 0 : _e.on('error', this._onErrorHandler); + } + _removeSocketListeners() { + var _a, _b, _c, _d; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeAllListeners('connect'); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.removeAllListeners('end'); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.removeAllListeners('close'); + (_d = this._socketConnection) === null || _d === void 0 ? void 0 : _d.removeAllListeners('data'); + // note: we intentionally keep the error event listener to be able to emit it in case an error happens when closing the connection + } + _onCloseEvent(event) { + var _a; + if (!event && this._reconnectOptions.autoReconnect) { + this._connectionStatus = 'disconnected'; + this._reconnect(); + return; + } + this._clearQueues(event); + this._removeSocketListeners(); + this._onDisconnect(event === null || event === void 0 ? void 0 : event.code, event === null || event === void 0 ? void 0 : event.reason); + // disconnect was successful and can safely remove error listener + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeAllListeners('error'); + } + _onClose(event) { + this._clearQueues(event); + this._removeSocketListeners(); + } +} +export { IpcProvider }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/index.js.map new file mode 100644 index 0000000..6542598 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,MAAM,EAAyB,MAAM,KAAK,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAoB,cAAc,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAQtE,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,CAAC,OAAO,OAAO,WAAuD,SAAQ,cAKnF;IAKA;;;;;OAKG;IACH,yFAAyF;IACzF,kDAAkD;IAClD,YACC,UAAkB,EAClB,aAAqC,EACrC,gBAA4C;QAE5C,KAAK,CAAC,UAAU,EAAE,aAAa,EAAE,gBAAgB,CAAC,CAAC;IACpD,CAAC;IAEM,SAAS;;QACf,IAAI,MAAA,IAAI,CAAC,iBAAiB,0CAAE,UAAU,EAAE;YACvC,OAAO,YAAY,CAAC;SACpB;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAC/B,CAAC;IAES,qBAAqB;QAC9B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE;YAClC,MAAM,IAAI,kBAAkB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;SAC/C;QACD,IAAI,CAAC,IAAI,CAAC,iBAAiB,IAAI,IAAI,CAAC,SAAS,EAAE,KAAK,cAAc,EAAE;YACnE,IAAI,CAAC,iBAAiB,GAAG,IAAI,MAAM,CAAC,IAAI,CA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,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;IAC3D,CAAC;IAES,sBAAsB;;QAC/B,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,SAAS,CAAC,CAAC;QACtD,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAClD,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;QACpD,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,MAAM,CAAC,CAAC;QACnD,kIAAkI;IACnI,CAAC;IAES,aAAa,CAAC,KAAiB;;QACxC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,iBAAiB,CAAC,aAAa,EAAE;YACnD,IAAI,CAAC,iBAAiB,GAAG,cAAc,CAAC;YACxC,IAAI,CAAC,UAAU,EAAE,CAAC;YAClB,OAAO;SACP;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACzB,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC9B,IAAI,CAAC,aAAa,CAAC,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,CAAC,CAAC;QAC/C,iEAAiE;QACjE,MAAA,IAAI,CAAC,iBAAiB,0CAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC;IAES,QAAQ,CAAC,KAAiB;QACnC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACzB,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAC/B,CAAC;CACD;AAED,OAAO,EAAE,WAAW,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/package.json b/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-providers-ipc/lib/types/index.d.ts new file mode 100644 index 0000000..91ca1ed --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/types/index.d.ts @@ -0,0 +1,58 @@ +/// +import { Socket, SocketConstructorOpts } from 'net'; +import { ReconnectOptions, SocketProvider } from 'web3-utils'; +import { EthExecutionAPI, Web3APIMethod, Web3APIPayload, Web3APISpec, Web3ProviderStatus } from 'web3-types'; +/** + * The IPC Provider could be used in node.js dapps when running a local node. And it provide the most secure connection. + * + * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * { + * writable: false, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class IpcProvider extends SocketProvider { + protected readonly _socketOptions?: SocketConstructorOpts; + protected _socketConnection?: Socket; + /** + * This is a class used for IPC connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the IPC socket. + * @param socketOptions - The options for the IPC socket connection. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath: string, socketOptions?: SocketConstructorOpts, reconnectOptions?: Partial); + getStatus(): Web3ProviderStatus; + protected _openSocketConnection(): void; + protected _closeSocketConnection(code: number, data?: string): void; + protected _sendToSocket>(payload: Web3APIPayload): void; + protected _parseResponses(e: Uint8Array | string): import("web3-types").JsonRpcResponse[]; + protected _addSocketListeners(): void; + protected _removeSocketListeners(): void; + protected _onCloseEvent(event: CloseEvent): void; + protected _onClose(event: CloseEvent): void; +} +export { IpcProvider }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-providers-ipc/lib/types/index.d.ts.map new file mode 100644 index 0000000..88b00e6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAiBA,OAAO,EAAE,MAAM,EAAE,qBAAqB,EAAE,MAAM,KAAK,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAU,MAAM,YAAY,CAAC;AACtE,OAAO,EACN,eAAe,EACf,aAAa,EACb,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAGpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,CAAC,OAAO,OAAO,WAAW,CAAC,GAAG,SAAS,WAAW,GAAG,eAAe,CAAE,SAAQ,cAAc,CACjG,UAAU,GAAG,MAAM,EACnB,UAAU,EACV,KAAK,EACL,GAAG,CACH;IACA,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,qBAAqB,CAAC;IAE1D,SAAS,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAErC;;;;;OAKG;gBAIF,UAAU,EAAE,MAAM,EAClB,aAAa,CAAC,EAAE,qBAAqB,EACrC,gBAAgB,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC;IAKtC,SAAS,IAAI,kBAAkB;IAOtC,SAAS,CAAC,qBAAqB;IAW/B,SAAS,CAAC,sBAAsB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM;IAM5D,SAAS,CAAC,aAAa,CAAC,MAAM,SAAS,aAAa,CAAC,GAAG,CAAC,EACxD,OAAO,EAAE,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,GAClC,IAAI;IAOP,SAAS,CAAC,eAAe,CAAC,CAAC,EAAE,UAAU,GAAG,MAAM;IAIhD,SAAS,CAAC,mBAAmB,IAAI,IAAI;IAQrC,SAAS,CAAC,sBAAsB,IAAI,IAAI;IAQxC,SAAS,CAAC,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;IAchD,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;CAI3C;AAED,OAAO,EAAE,WAAW,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/package.json b/test/merkletreejs/node_modules/web3-providers-ipc/package.json new file mode 100644 index 0000000..ec02ea7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/package.json @@ -0,0 +1,64 @@ +{ + "name": "web3-providers-ipc", + "version": "4.0.7", + "description": "IPC provider for Web3 4.x.x", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-providers-ipc/src/index.ts b/test/merkletreejs/node_modules/web3-providers-ipc/src/index.ts new file mode 100644 index 0000000..641d36e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ipc/src/index.ts @@ -0,0 +1,161 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Socket, SocketConstructorOpts } from 'net'; +import { ConnectionNotOpenError, InvalidClientError } from 'web3-errors'; +import { ReconnectOptions, SocketProvider, toUtf8 } from 'web3-utils'; +import { + EthExecutionAPI, + Web3APIMethod, + Web3APIPayload, + Web3APISpec, + Web3ProviderStatus, +} from 'web3-types'; +import { existsSync } from 'fs'; + +/** + * The IPC Provider could be used in node.js dapps when running a local node. And it provide the most secure connection. + * + * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * { + * writable: false, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new IpcProvider( + * `path.ipc`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class IpcProvider extends SocketProvider< + Uint8Array | string, + CloseEvent, + Error, + API +> { + protected readonly _socketOptions?: SocketConstructorOpts; + + protected _socketConnection?: Socket; + + /** + * This is a class used for IPC connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the IPC socket. + * @param socketOptions - The options for the IPC socket connection. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + // this constructor is to specify the type for `socketOptions` for a better intellisense. + // eslint-disable-next-line no-useless-constructor + public constructor( + socketPath: string, + socketOptions?: SocketConstructorOpts, + reconnectOptions?: Partial, + ) { + super(socketPath, socketOptions, reconnectOptions); + } + + public getStatus(): Web3ProviderStatus { + if (this._socketConnection?.connecting) { + return 'connecting'; + } + return this._connectionStatus; + } + + protected _openSocketConnection() { + if (!existsSync(this._socketPath)) { + throw new InvalidClientError(this._socketPath); + } + if (!this._socketConnection || this.getStatus() === 'disconnected') { + this._socketConnection = new Socket(this._socketOptions); + } + + this._socketConnection.connect({ path: this._socketPath }); + } + + protected _closeSocketConnection(code: number, data?: string) { + this._socketConnection?.end(() => { + this._onDisconnect(code, data); + }); + } + + protected _sendToSocket>( + payload: Web3APIPayload, + ): void { + if (this.getStatus() === 'disconnected') { + throw new ConnectionNotOpenError(); + } + this._socketConnection?.write(JSON.stringify(payload)); + } + + protected _parseResponses(e: Uint8Array | string) { + return this.chunkResponseParser.parseResponse(typeof e === 'string' ? e : toUtf8(e)); + } + + protected _addSocketListeners(): void { + this._socketConnection?.on('data', this._onMessageHandler); + this._socketConnection?.on('connect', this._onOpenHandler); + this._socketConnection?.on('close', this._onClose.bind(this)); + this._socketConnection?.on('end', this._onCloseHandler); + this._socketConnection?.on('error', this._onErrorHandler); + } + + protected _removeSocketListeners(): void { + this._socketConnection?.removeAllListeners('connect'); + this._socketConnection?.removeAllListeners('end'); + this._socketConnection?.removeAllListeners('close'); + this._socketConnection?.removeAllListeners('data'); + // note: we intentionally keep the error event listener to be able to emit it in case an error happens when closing the connection + } + + protected _onCloseEvent(event: CloseEvent): void { + if (!event && this._reconnectOptions.autoReconnect) { + this._connectionStatus = 'disconnected'; + this._reconnect(); + return; + } + + this._clearQueues(event); + this._removeSocketListeners(); + this._onDisconnect(event?.code, event?.reason); + // disconnect was successful and can safely remove error listener + this._socketConnection?.removeAllListeners('error'); + } + + protected _onClose(event: CloseEvent): void { + this._clearQueues(event); + this._removeSocketListeners(); + } +} + +export { IpcProvider }; diff --git a/test/merkletreejs/node_modules/web3-providers-ws/LICENSE b/test/merkletreejs/node_modules/web3-providers-ws/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-providers-ws/README.md b/test/merkletreejs/node_modules/web3-providers-ws/README.md new file mode 100644 index 0000000..942839b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3.js - Websocket Provider + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-providers-ws` contains the Web3.js provider for the Websocket protocol. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-providers-ws) or using [Yarn](https://yarnpkg.com/package/web3-providers-ws) + +### Using NPM + +```bash +npm install web3-providers-ws +``` + +### Using Yarn + +```bash +yarn add web3-providers-ws +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-providers-ws +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-providers-ws%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-providers-ws +[downloads-image]: https://img.shields.io/npm/dm/web3-providers-ws?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.d.ts new file mode 100644 index 0000000..cbc6381 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.d.ts @@ -0,0 +1,64 @@ +/// +/// +import { ClientRequestArgs } from 'http'; +import WebSocket, { ClientOptions, CloseEvent } from 'isomorphic-ws'; +import { EthExecutionAPI, Web3APIMethod, Web3APIPayload, Web3APISpec, Web3ProviderStatus } from 'web3-types'; +import { ReconnectOptions, SocketProvider } from 'web3-utils'; +export { ClientRequestArgs } from 'http'; +export { ClientOptions } from 'isomorphic-ws'; +/** + * Use WebSocketProvider to connect to a Node using a WebSocket connection, i.e. over the `ws` or `wss` protocol. + * + * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * { + * headers: { + * // to provide the API key if the Node requires the key to be inside the `headers` for example: + * 'x-api-key': '', + * }, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class WebSocketProvider extends SocketProvider { + protected readonly _socketOptions?: ClientOptions | ClientRequestArgs; + protected _socketConnection?: WebSocket; + protected _validateProviderPath(providerUrl: string): boolean; + /** + * This is a class used for Web Socket connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the Web Socket. + * @param socketOptions - The options for the Web Socket client. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath: string, socketOptions?: ClientOptions | ClientRequestArgs, reconnectOptions?: Partial); + getStatus(): Web3ProviderStatus; + protected _openSocketConnection(): void; + protected _closeSocketConnection(code?: number, data?: string): void; + protected _sendToSocket>(payload: Web3APIPayload): void; + protected _parseResponses(event: WebSocket.MessageEvent): import("web3-types").JsonRpcResponse[]; + protected _addSocketListeners(): void; + protected _removeSocketListeners(): void; + protected _onCloseEvent(event: CloseEvent): void; +} +export { WebSocketProvider }; diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.js new file mode 100644 index 0000000..bc7e5a6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.js @@ -0,0 +1,142 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketProvider = void 0; +const isomorphic_ws_1 = __importDefault(require("isomorphic-ws")); +const web3_utils_1 = require("web3-utils"); +const web3_errors_1 = require("web3-errors"); +/** + * Use WebSocketProvider to connect to a Node using a WebSocket connection, i.e. over the `ws` or `wss` protocol. + * + * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * { + * headers: { + * // to provide the API key if the Node requires the key to be inside the `headers` for example: + * 'x-api-key': '', + * }, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +class WebSocketProvider extends web3_utils_1.SocketProvider { + /** + * This is a class used for Web Socket connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the Web Socket. + * @param socketOptions - The options for the Web Socket client. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + // this constructor is to specify the type for `socketOptions` for a better intellisense. + // eslint-disable-next-line no-useless-constructor + constructor(socketPath, socketOptions, reconnectOptions) { + super(socketPath, socketOptions, reconnectOptions); + } + // eslint-disable-next-line class-methods-use-this + _validateProviderPath(providerUrl) { + return typeof providerUrl === 'string' ? /^ws(s)?:\/\//i.test(providerUrl) : false; + } + getStatus() { + if (this._socketConnection && !(0, web3_utils_1.isNullish)(this._socketConnection)) { + switch (this._socketConnection.readyState) { + case this._socketConnection.CONNECTING: { + return 'connecting'; + } + case this._socketConnection.OPEN: { + return 'connected'; + } + default: { + return 'disconnected'; + } + } + } + return 'disconnected'; + } + _openSocketConnection() { + this._socketConnection = new isomorphic_ws_1.default(this._socketPath, undefined, this._socketOptions && Object.keys(this._socketOptions).length === 0 + ? undefined + : this._socketOptions); + } + _closeSocketConnection(code, data) { + var _a; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.close(code, data); + } + _sendToSocket(payload) { + var _a; + if (this.getStatus() === 'disconnected') { + throw new web3_errors_1.ConnectionNotOpenError(); + } + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(payload)); + } + _parseResponses(event) { + return this.chunkResponseParser.parseResponse(event.data); + } + _addSocketListeners() { + var _a, _b, _c, _d; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.addEventListener('open', this._onOpenHandler); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.addEventListener('message', this._onMessageHandler); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.addEventListener('close', e => this._onCloseHandler(e)); + (_d = this._socketConnection) === null || _d === void 0 ? void 0 : _d.addEventListener('error', this._onErrorHandler); + } + _removeSocketListeners() { + var _a, _b, _c; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeEventListener('message', this._onMessageHandler); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.removeEventListener('open', this._onOpenHandler); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.removeEventListener('close', this._onCloseHandler); + // note: we intentionally keep the error event listener to be able to emit it in case an error happens when closing the connection + } + _onCloseEvent(event) { + var _a; + if (this._reconnectOptions.autoReconnect && + (![1000, 1001].includes(event.code) || !event.wasClean)) { + this._reconnect(); + return; + } + this._clearQueues(event); + this._removeSocketListeners(); + this._onDisconnect(event.code, event.reason); + // disconnect was successful and can safely remove error listener + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeEventListener('error', this._onErrorHandler); + } +} +exports.default = WebSocketProvider; +exports.WebSocketProvider = WebSocketProvider; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.js.map new file mode 100644 index 0000000..7e286c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;AAGF,kEAAqE;AAQrE,2CAAyE;AACzE,6CAAqD;AAMrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAqB,iBAEnB,SAAQ,2BAAuF;IAUhG;;;;;OAKG;IACH,yFAAyF;IACzF,kDAAkD;IAClD,YACC,UAAkB,EAClB,aAAiD,EACjD,gBAA4C;QAE5C,KAAK,CAAC,UAAU,EAAE,aAAa,EAAE,gBAAgB,CAAC,CAAC;IACpD,CAAC;IAnBD,kDAAkD;IACxC,qBAAqB,CAAC,WAAmB;QAClD,OAAO,OAAO,WAAW,KAAK,QAAQ,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,KA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QACjE,MAAA,IAAI,CAAC,iBAAiB,0CAAE,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;IAC5E,CAAC;CACD;AApGD,oCAoGC;AAEQ,8CAAiB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/index.js b/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/index.js new file mode 100644 index 0000000..a8ac987 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/index.js @@ -0,0 +1,135 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import WebSocket from 'isomorphic-ws'; +import { isNullish, SocketProvider } from 'web3-utils'; +import { ConnectionNotOpenError } from 'web3-errors'; +/** + * Use WebSocketProvider to connect to a Node using a WebSocket connection, i.e. over the `ws` or `wss` protocol. + * + * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * { + * headers: { + * // to provide the API key if the Node requires the key to be inside the `headers` for example: + * 'x-api-key': '', + * }, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class WebSocketProvider extends SocketProvider { + /** + * This is a class used for Web Socket connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the Web Socket. + * @param socketOptions - The options for the Web Socket client. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + // this constructor is to specify the type for `socketOptions` for a better intellisense. + // eslint-disable-next-line no-useless-constructor + constructor(socketPath, socketOptions, reconnectOptions) { + super(socketPath, socketOptions, reconnectOptions); + } + // eslint-disable-next-line class-methods-use-this + _validateProviderPath(providerUrl) { + return typeof providerUrl === 'string' ? /^ws(s)?:\/\//i.test(providerUrl) : false; + } + getStatus() { + if (this._socketConnection && !isNullish(this._socketConnection)) { + switch (this._socketConnection.readyState) { + case this._socketConnection.CONNECTING: { + return 'connecting'; + } + case this._socketConnection.OPEN: { + return 'connected'; + } + default: { + return 'disconnected'; + } + } + } + return 'disconnected'; + } + _openSocketConnection() { + this._socketConnection = new WebSocket(this._socketPath, undefined, this._socketOptions && Object.keys(this._socketOptions).length === 0 + ? undefined + : this._socketOptions); + } + _closeSocketConnection(code, data) { + var _a; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.close(code, data); + } + _sendToSocket(payload) { + var _a; + if (this.getStatus() === 'disconnected') { + throw new ConnectionNotOpenError(); + } + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(payload)); + } + _parseResponses(event) { + return this.chunkResponseParser.parseResponse(event.data); + } + _addSocketListeners() { + var _a, _b, _c, _d; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.addEventListener('open', this._onOpenHandler); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.addEventListener('message', this._onMessageHandler); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.addEventListener('close', e => this._onCloseHandler(e)); + (_d = this._socketConnection) === null || _d === void 0 ? void 0 : _d.addEventListener('error', this._onErrorHandler); + } + _removeSocketListeners() { + var _a, _b, _c; + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeEventListener('message', this._onMessageHandler); + (_b = this._socketConnection) === null || _b === void 0 ? void 0 : _b.removeEventListener('open', this._onOpenHandler); + (_c = this._socketConnection) === null || _c === void 0 ? void 0 : _c.removeEventListener('close', this._onCloseHandler); + // note: we intentionally keep the error event listener to be able to emit it in case an error happens when closing the connection + } + _onCloseEvent(event) { + var _a; + if (this._reconnectOptions.autoReconnect && + (![1000, 1001].includes(event.code) || !event.wasClean)) { + this._reconnect(); + return; + } + this._clearQueues(event); + this._removeSocketListeners(); + this._onDisconnect(event.code, event.reason); + // disconnect was successful and can safely remove error listener + (_a = this._socketConnection) === null || _a === void 0 ? void 0 : _a.removeEventListener('error', this._onErrorHandler); + } +} +export { WebSocketProvider }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/index.js.map new file mode 100644 index 0000000..a4082f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,SAAwC,MAAM,eAAe,CAAC;AAQrE,OAAO,EAAE,SAAS,EAAoB,cAAc,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAMrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,CAAC,OAAO,OAAO,iBAEnB,SAAQ,cAAuF;IAUhG;;;;;OAKG;IACH,yFAAyF;IACzF,kDAAkD;IAClD,YACC,UAAkB,EAClB,aAAiD,EACjD,gBAA4C;QAE5C,KAAK,CAA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C;YAClB,OAAO;SACP;QACD,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACzB,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC9B,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,iEAAiE;QACjE,MAAA,IAAI,CAAC,iBAAiB,0CAAE,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;IAC5E,CAAC;CACD;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/package.json b/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-providers-ws/lib/types/index.d.ts new file mode 100644 index 0000000..aebb8d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/types/index.d.ts @@ -0,0 +1,65 @@ +/// +/// +import { ClientRequestArgs } from 'http'; +import WebSocket, { ClientOptions, CloseEvent } from 'isomorphic-ws'; +import { EthExecutionAPI, Web3APIMethod, Web3APIPayload, Web3APISpec, Web3ProviderStatus } from 'web3-types'; +import { ReconnectOptions, SocketProvider } from 'web3-utils'; +export { ClientRequestArgs } from 'http'; +export { ClientOptions } from 'isomorphic-ws'; +/** + * Use WebSocketProvider to connect to a Node using a WebSocket connection, i.e. over the `ws` or `wss` protocol. + * + * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * { + * headers: { + * // to provide the API key if the Node requires the key to be inside the `headers` for example: + * 'x-api-key': '', + * }, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class WebSocketProvider extends SocketProvider { + protected readonly _socketOptions?: ClientOptions | ClientRequestArgs; + protected _socketConnection?: WebSocket; + protected _validateProviderPath(providerUrl: string): boolean; + /** + * This is a class used for Web Socket connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the Web Socket. + * @param socketOptions - The options for the Web Socket client. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath: string, socketOptions?: ClientOptions | ClientRequestArgs, reconnectOptions?: Partial); + getStatus(): Web3ProviderStatus; + protected _openSocketConnection(): void; + protected _closeSocketConnection(code?: number, data?: string): void; + protected _sendToSocket>(payload: Web3APIPayload): void; + protected _parseResponses(event: WebSocket.MessageEvent): import("web3-types").JsonRpcResponse[]; + protected _addSocketListeners(): void; + protected _removeSocketListeners(): void; + protected _onCloseEvent(event: CloseEvent): void; +} +export { WebSocketProvider }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ws/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-providers-ws/lib/types/index.d.ts.map new file mode 100644 index 0000000..4cabfba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAiBA,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACzC,OAAO,SAAS,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EACN,eAAe,EACf,aAAa,EACb,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,MAAM,YAA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AAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-providers-ws/package.json b/test/merkletreejs/node_modules/web3-providers-ws/package.json new file mode 100644 index 0000000..c852eac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/package.json @@ -0,0 +1,72 @@ +{ + "name": "web3-providers-ws", + "version": "4.0.7", + "description": "Websocket provider for Web3 4.x.x", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js" + }, + "devDependencies": { + "@types/express": "^4.17.13", + "@types/jest": "^28.1.6", + "@types/morgan": "^1.9.3", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "express": "^4.18.1", + "ganache": "^7.7.6", + "http-proxy-middleware": "^2.0.6", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "@types/ws": "8.5.3", + "isomorphic-ws": "^5.0.0", + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "web3-utils": "^4.0.7", + "ws": "^8.8.1" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-providers-ws/src/index.ts b/test/merkletreejs/node_modules/web3-providers-ws/src/index.ts new file mode 100644 index 0000000..4591e2b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-providers-ws/src/index.ts @@ -0,0 +1,171 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ClientRequestArgs } from 'http'; +import WebSocket, { ClientOptions, CloseEvent } from 'isomorphic-ws'; +import { + EthExecutionAPI, + Web3APIMethod, + Web3APIPayload, + Web3APISpec, + Web3ProviderStatus, +} from 'web3-types'; +import { isNullish, ReconnectOptions, SocketProvider } from 'web3-utils'; +import { ConnectionNotOpenError } from 'web3-errors'; + +export { ClientRequestArgs } from 'http'; + +export { ClientOptions } from 'isomorphic-ws'; + +/** + * Use WebSocketProvider to connect to a Node using a WebSocket connection, i.e. over the `ws` or `wss` protocol. + * + * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * { + * headers: { + * // to provide the API key if the Node requires the key to be inside the `headers` for example: + * 'x-api-key': '', + * }, + * }, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + * + * The second and the third parameters are both optional. And you can for example, the second parameter could be an empty object or undefined. + * * @example + * ```ts + * const provider = new WebSocketProvider( + * `ws://localhost:8545`, + * {}, + * { + * delay: 500, + * autoReconnect: true, + * maxAttempts: 10, + * }, + * ); + * ``` + */ +export default class WebSocketProvider< + API extends Web3APISpec = EthExecutionAPI, +> extends SocketProvider { + protected readonly _socketOptions?: ClientOptions | ClientRequestArgs; + + protected _socketConnection?: WebSocket; + + // eslint-disable-next-line class-methods-use-this + protected _validateProviderPath(providerUrl: string): boolean { + return typeof providerUrl === 'string' ? /^ws(s)?:\/\//i.test(providerUrl) : false; + } + + /** + * This is a class used for Web Socket connections. It extends the abstract class SocketProvider {@link SocketProvider} that extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the Web Socket. + * @param socketOptions - The options for the Web Socket client. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + // this constructor is to specify the type for `socketOptions` for a better intellisense. + // eslint-disable-next-line no-useless-constructor + public constructor( + socketPath: string, + socketOptions?: ClientOptions | ClientRequestArgs, + reconnectOptions?: Partial, + ) { + super(socketPath, socketOptions, reconnectOptions); + } + + public getStatus(): Web3ProviderStatus { + if (this._socketConnection && !isNullish(this._socketConnection)) { + switch (this._socketConnection.readyState) { + case this._socketConnection.CONNECTING: { + return 'connecting'; + } + case this._socketConnection.OPEN: { + return 'connected'; + } + default: { + return 'disconnected'; + } + } + } + return 'disconnected'; + } + + protected _openSocketConnection() { + this._socketConnection = new WebSocket( + this._socketPath, + undefined, + this._socketOptions && Object.keys(this._socketOptions).length === 0 + ? undefined + : this._socketOptions, + ); + } + + protected _closeSocketConnection(code?: number, data?: string) { + this._socketConnection?.close(code, data); + } + + protected _sendToSocket>( + payload: Web3APIPayload, + ): void { + if (this.getStatus() === 'disconnected') { + throw new ConnectionNotOpenError(); + } + this._socketConnection?.send(JSON.stringify(payload)); + } + + protected _parseResponses(event: WebSocket.MessageEvent) { + return this.chunkResponseParser.parseResponse(event.data as string); + } + + protected _addSocketListeners(): void { + this._socketConnection?.addEventListener('open', this._onOpenHandler); + this._socketConnection?.addEventListener('message', this._onMessageHandler); + this._socketConnection?.addEventListener('close', e => this._onCloseHandler(e)); + this._socketConnection?.addEventListener('error', this._onErrorHandler); + } + + protected _removeSocketListeners(): void { + this._socketConnection?.removeEventListener('message', this._onMessageHandler); + this._socketConnection?.removeEventListener('open', this._onOpenHandler); + this._socketConnection?.removeEventListener('close', this._onCloseHandler); + // note: we intentionally keep the error event listener to be able to emit it in case an error happens when closing the connection + } + + protected _onCloseEvent(event: CloseEvent): void { + if ( + this._reconnectOptions.autoReconnect && + (![1000, 1001].includes(event.code) || !event.wasClean) + ) { + this._reconnect(); + return; + } + this._clearQueues(event); + this._removeSocketListeners(); + this._onDisconnect(event.code, event.reason); + // disconnect was successful and can safely remove error listener + this._socketConnection?.removeEventListener('error', this._onErrorHandler); + } +} + +export { WebSocketProvider }; diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/LICENSE b/test/merkletreejs/node_modules/web3-rpc-methods/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/README.md b/test/merkletreejs/node_modules/web3-rpc-methods/README.md new file mode 100644 index 0000000..2b46d10 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# Web3 RPC Methods + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-rpc-methods` contains RPC methods for various ETH related protocols. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-rpc-methods) or using [Yarn](https://yarnpkg.com/package/web3-rpc-methods) + +### Using NPM + +```bash +npm install web3-rpc-methods +``` + +### Using Yarn + +```bash +yarn add web3-rpc-methods +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-rpc-methods +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-rpc-methods%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-rpc-methods +[downloads-image]: https://img.shields.io/npm/dm/web3-rpc-methods?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.js new file mode 100644 index 0000000..ead7c81 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.js @@ -0,0 +1,18 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.js.map new file mode 100644 index 0000000..9edfec4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.d.ts new file mode 100644 index 0000000..bde55f6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.d.ts @@ -0,0 +1,54 @@ +import { Web3RequestManager } from 'web3-core'; +import { Address, BlockNumberOrTag, Filter, HexString32Bytes, HexString8Bytes, HexStringBytes, TransactionCallAPI, TransactionWithSenderAPI, Uint, Uint256, Web3EthExecutionAPI, Eip712TypedData } from 'web3-types'; +export declare function getProtocolVersion(requestManager: Web3RequestManager): Promise; +export declare function getSyncing(requestManager: Web3RequestManager): Promise; +export declare function getCoinbase(requestManager: Web3RequestManager): Promise; +export declare function getMining(requestManager: Web3RequestManager): Promise; +export declare function getHashRate(requestManager: Web3RequestManager): Promise; +export declare function getGasPrice(requestManager: Web3RequestManager): Promise; +export declare function getAccounts(requestManager: Web3RequestManager): Promise; +export declare function getBlockNumber(requestManager: Web3RequestManager): Promise; +export declare function getBalance(requestManager: Web3RequestManager, address: Address, blockNumber: BlockNumberOrTag): Promise; +export declare function getStorageAt(requestManager: Web3RequestManager, address: Address, storageSlot: Uint256, blockNumber: BlockNumberOrTag): Promise; +export declare function getTransactionCount(requestManager: Web3RequestManager, address: Address, blockNumber: BlockNumberOrTag): Promise; +export declare function getBlockTransactionCountByHash(requestManager: Web3RequestManager, blockHash: HexString32Bytes): Promise; +export declare function getBlockTransactionCountByNumber(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag): Promise; +export declare function getUncleCountByBlockHash(requestManager: Web3RequestManager, blockHash: HexString32Bytes): Promise; +export declare function getUncleCountByBlockNumber(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag): Promise; +export declare function getCode(requestManager: Web3RequestManager, address: Address, blockNumber: BlockNumberOrTag): Promise; +export declare function sign(requestManager: Web3RequestManager, address: Address, message: HexStringBytes): Promise; +export declare function signTransaction(requestManager: Web3RequestManager, transaction: TransactionWithSenderAPI | Partial): Promise; +export declare function sendTransaction(requestManager: Web3RequestManager, transaction: TransactionWithSenderAPI | Partial): Promise; +export declare function sendRawTransaction(requestManager: Web3RequestManager, transaction: HexStringBytes): Promise; +export declare function call(requestManager: Web3RequestManager, transaction: TransactionCallAPI, blockNumber: BlockNumberOrTag): Promise; +export declare function estimateGas(requestManager: Web3RequestManager, transaction: Partial, blockNumber: BlockNumberOrTag): Promise; +export declare function getBlockByHash(requestManager: Web3RequestManager, blockHash: HexString32Bytes, hydrated: boolean): Promise; +export declare function getBlockByNumber(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag, hydrated: boolean): Promise; +export declare function getTransactionByHash(requestManager: Web3RequestManager, transactionHash: HexString32Bytes): Promise; +export declare function getTransactionByBlockHashAndIndex(requestManager: Web3RequestManager, blockHash: HexString32Bytes, transactionIndex: Uint): Promise; +export declare function getTransactionByBlockNumberAndIndex(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag, transactionIndex: Uint): Promise; +export declare function getTransactionReceipt(requestManager: Web3RequestManager, transactionHash: HexString32Bytes): Promise; +export declare function getUncleByBlockHashAndIndex(requestManager: Web3RequestManager, blockHash: HexString32Bytes, uncleIndex: Uint): Promise; +export declare function getUncleByBlockNumberAndIndex(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag, uncleIndex: Uint): Promise; +export declare function getCompilers(requestManager: Web3RequestManager): Promise; +export declare function compileSolidity(requestManager: Web3RequestManager, code: string): Promise; +export declare function compileLLL(requestManager: Web3RequestManager, code: string): Promise; +export declare function compileSerpent(requestManager: Web3RequestManager, code: string): Promise; +export declare function newFilter(requestManager: Web3RequestManager, filter: Filter): Promise; +export declare function newBlockFilter(requestManager: Web3RequestManager): Promise; +export declare function newPendingTransactionFilter(requestManager: Web3RequestManager): Promise; +export declare function uninstallFilter(requestManager: Web3RequestManager, filterIdentifier: Uint): Promise; +export declare function getFilterChanges(requestManager: Web3RequestManager, filterIdentifier: Uint): Promise; +export declare function getFilterLogs(requestManager: Web3RequestManager, filterIdentifier: Uint): Promise; +export declare function getLogs(requestManager: Web3RequestManager, filter: Filter): Promise; +export declare function getWork(requestManager: Web3RequestManager): Promise<[string, string, string]>; +export declare function submitWork(requestManager: Web3RequestManager, nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes): Promise; +export declare function submitHashrate(requestManager: Web3RequestManager, hashRate: HexString32Bytes, id: HexString32Bytes): Promise; +export declare function getFeeHistory(requestManager: Web3RequestManager, blockCount: Uint, newestBlock: BlockNumberOrTag, rewardPercentiles: number[]): Promise; +export declare function getPendingTransactions(requestManager: Web3RequestManager): Promise; +export declare function requestAccounts(requestManager: Web3RequestManager): Promise; +export declare function getChainId(requestManager: Web3RequestManager): Promise; +export declare function getProof(requestManager: Web3RequestManager, address: Address, storageKeys: HexString32Bytes[], blockNumber: BlockNumberOrTag): Promise; +export declare function getNodeInfo(requestManager: Web3RequestManager): Promise; +export declare function createAccessList(requestManager: Web3RequestManager, transaction: TransactionWithSenderAPI | Partial, blockNumber: BlockNumberOrTag): Promise; +export declare function signTypedData(requestManager: Web3RequestManager, address: Address, typedData: Eip712TypedData, useLegacy?: boolean): Promise; diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.js new file mode 100644 index 0000000..3a1bc8f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.js @@ -0,0 +1,532 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getNodeInfo = exports.getProof = exports.getChainId = exports.requestAccounts = exports.getPendingTransactions = exports.getFeeHistory = exports.submitHashrate = exports.submitWork = exports.getWork = exports.getLogs = exports.getFilterLogs = exports.getFilterChanges = exports.uninstallFilter = exports.newPendingTransactionFilter = exports.newBlockFilter = exports.newFilter = exports.compileSerpent = exports.compileLLL = exports.compileSolidity = exports.getCompilers = exports.getUncleByBlockNumberAndIndex = exports.getUncleByBlockHashAndIndex = exports.getTransactionReceipt = exports.getTransactionByBlockNumberAndIndex = exports.getTransactionByBlockHashAndIndex = exports.getTransactionByHash = exports.getBlockByNumber = exports.getBlockByHash = exports.estimateGas = exports.call = exports.sendRawTransaction = exports.sendTransaction = exports.signTransaction = exports.sign = exports.getCode = exports.getUncleCountByBlockNumber = exports.getUncleCountByBlockHash = exports.getBlockTransactionCountByNumber = exports.getBlockTransactionCountByHash = exports.getTransactionCount = exports.getStorageAt = exports.getBalance = exports.getBlockNumber = exports.getAccounts = exports.getGasPrice = exports.getHashRate = exports.getMining = exports.getCoinbase = exports.getSyncing = exports.getProtocolVersion = void 0; +exports.signTypedData = exports.createAccessList = void 0; +const web3_validator_1 = require("web3-validator"); +function getProtocolVersion(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_protocolVersion', + params: [], + }); + }); +} +exports.getProtocolVersion = getProtocolVersion; +function getSyncing(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_syncing', + params: [], + }); + }); +} +exports.getSyncing = getSyncing; +function getCoinbase(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_coinbase', + params: [], + }); + }); +} +exports.getCoinbase = getCoinbase; +function getMining(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_mining', + params: [], + }); + }); +} +exports.getMining = getMining; +function getHashRate(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_hashrate', + params: [], + }); + }); +} +exports.getHashRate = getHashRate; +function getGasPrice(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_gasPrice', + params: [], + }); + }); +} +exports.getGasPrice = getGasPrice; +function getAccounts(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_accounts', + params: [], + }); + }); +} +exports.getAccounts = getAccounts; +function getBlockNumber(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_blockNumber', + params: [], + }); + }); +} +exports.getBlockNumber = getBlockNumber; +function getBalance(requestManager, address, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + return requestManager.send({ + method: 'eth_getBalance', + params: [address, blockNumber], + }); + }); +} +exports.getBalance = getBalance; +function getStorageAt(requestManager, address, storageSlot, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'hex', 'blockNumberOrTag'], [address, storageSlot, blockNumber]); + return requestManager.send({ + method: 'eth_getStorageAt', + params: [address, storageSlot, blockNumber], + }); + }); +} +exports.getStorageAt = getStorageAt; +function getTransactionCount(requestManager, address, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + return requestManager.send({ + method: 'eth_getTransactionCount', + params: [address, blockNumber], + }); + }); +} +exports.getTransactionCount = getTransactionCount; +function getBlockTransactionCountByHash(requestManager, blockHash) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32'], [blockHash]); + return requestManager.send({ + method: 'eth_getBlockTransactionCountByHash', + params: [blockHash], + }); + }); +} +exports.getBlockTransactionCountByHash = getBlockTransactionCountByHash; +function getBlockTransactionCountByNumber(requestManager, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_getBlockTransactionCountByNumber', + params: [blockNumber], + }); + }); +} +exports.getBlockTransactionCountByNumber = getBlockTransactionCountByNumber; +function getUncleCountByBlockHash(requestManager, blockHash) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32'], [blockHash]); + return requestManager.send({ + method: 'eth_getUncleCountByBlockHash', + params: [blockHash], + }); + }); +} +exports.getUncleCountByBlockHash = getUncleCountByBlockHash; +function getUncleCountByBlockNumber(requestManager, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_getUncleCountByBlockNumber', + params: [blockNumber], + }); + }); +} +exports.getUncleCountByBlockNumber = getUncleCountByBlockNumber; +function getCode(requestManager, address, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + return requestManager.send({ + method: 'eth_getCode', + params: [address, blockNumber], + }); + }); +} +exports.getCode = getCode; +function sign(requestManager, address, message) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'hex'], [address, message]); + return requestManager.send({ + method: 'eth_sign', + params: [address, message], + }); + }); +} +exports.sign = sign; +// TODO - Validation should be: +// isTransactionWithSender(transaction) +// ? validateTransactionWithSender(transaction) +// : validateTransactionWithSender(transaction, true) with true being a isPartial flag +function signTransaction(requestManager, transaction) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_signTransaction', + params: [transaction], + }); + }); +} +exports.signTransaction = signTransaction; +// TODO - Validation should be: +// isTransactionWithSender(transaction) +// ? validateTransactionWithSender(transaction) +// : validateTransactionWithSender(transaction, true) with true being a isPartial flag +function sendTransaction(requestManager, transaction) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_sendTransaction', + params: [transaction], + }); + }); +} +exports.sendTransaction = sendTransaction; +function sendRawTransaction(requestManager, transaction) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['hex'], [transaction]); + return requestManager.send({ + method: 'eth_sendRawTransaction', + params: [transaction], + }); + }); +} +exports.sendRawTransaction = sendRawTransaction; +// TODO - validate transaction +function call(requestManager, transaction, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + // validateTransactionCall(transaction); + web3_validator_1.validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_call', + params: [transaction, blockNumber], + }); + }); +} +exports.call = call; +// TODO Not sure how to best validate Partial +function estimateGas(requestManager, transaction, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_estimateGas', + params: [transaction, blockNumber], + }); + }); +} +exports.estimateGas = estimateGas; +function getBlockByHash(requestManager, blockHash, hydrated) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32', 'bool'], [blockHash, hydrated]); + return requestManager.send({ + method: 'eth_getBlockByHash', + params: [blockHash, hydrated], + }); + }); +} +exports.getBlockByHash = getBlockByHash; +function getBlockByNumber(requestManager, blockNumber, hydrated) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag', 'bool'], [blockNumber, hydrated]); + return requestManager.send({ + method: 'eth_getBlockByNumber', + params: [blockNumber, hydrated], + }); + }); +} +exports.getBlockByNumber = getBlockByNumber; +function getTransactionByHash(requestManager, transactionHash) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32'], [transactionHash]); + return requestManager.send({ + method: 'eth_getTransactionByHash', + params: [transactionHash], + }); + }); +} +exports.getTransactionByHash = getTransactionByHash; +function getTransactionByBlockHashAndIndex(requestManager, blockHash, transactionIndex) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32', 'hex'], [blockHash, transactionIndex]); + return requestManager.send({ + method: 'eth_getTransactionByBlockHashAndIndex', + params: [blockHash, transactionIndex], + }); + }); +} +exports.getTransactionByBlockHashAndIndex = getTransactionByBlockHashAndIndex; +function getTransactionByBlockNumberAndIndex(requestManager, blockNumber, transactionIndex) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag', 'hex'], [blockNumber, transactionIndex]); + return requestManager.send({ + method: 'eth_getTransactionByBlockNumberAndIndex', + params: [blockNumber, transactionIndex], + }); + }); +} +exports.getTransactionByBlockNumberAndIndex = getTransactionByBlockNumberAndIndex; +function getTransactionReceipt(requestManager, transactionHash) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32'], [transactionHash]); + return requestManager.send({ + method: 'eth_getTransactionReceipt', + params: [transactionHash], + }); + }); +} +exports.getTransactionReceipt = getTransactionReceipt; +function getUncleByBlockHashAndIndex(requestManager, blockHash, uncleIndex) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32', 'hex'], [blockHash, uncleIndex]); + return requestManager.send({ + method: 'eth_getUncleByBlockHashAndIndex', + params: [blockHash, uncleIndex], + }); + }); +} +exports.getUncleByBlockHashAndIndex = getUncleByBlockHashAndIndex; +function getUncleByBlockNumberAndIndex(requestManager, blockNumber, uncleIndex) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag', 'hex'], [blockNumber, uncleIndex]); + return requestManager.send({ + method: 'eth_getUncleByBlockNumberAndIndex', + params: [blockNumber, uncleIndex], + }); + }); +} +exports.getUncleByBlockNumberAndIndex = getUncleByBlockNumberAndIndex; +function getCompilers(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_getCompilers', + params: [], + }); + }); +} +exports.getCompilers = getCompilers; +function compileSolidity(requestManager, code) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string'], [code]); + return requestManager.send({ + method: 'eth_compileSolidity', + params: [code], + }); + }); +} +exports.compileSolidity = compileSolidity; +function compileLLL(requestManager, code) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string'], [code]); + return requestManager.send({ + method: 'eth_compileLLL', + params: [code], + }); + }); +} +exports.compileLLL = compileLLL; +function compileSerpent(requestManager, code) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['string'], [code]); + return requestManager.send({ + method: 'eth_compileSerpent', + params: [code], + }); + }); +} +exports.compileSerpent = compileSerpent; +function newFilter(requestManager, filter) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['filter'], [filter]); + return requestManager.send({ + method: 'eth_newFilter', + params: [filter], + }); + }); +} +exports.newFilter = newFilter; +function newBlockFilter(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_newBlockFilter', + params: [], + }); + }); +} +exports.newBlockFilter = newBlockFilter; +function newPendingTransactionFilter(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_newPendingTransactionFilter', + params: [], + }); + }); +} +exports.newPendingTransactionFilter = newPendingTransactionFilter; +function uninstallFilter(requestManager, filterIdentifier) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['hex'], [filterIdentifier]); + return requestManager.send({ + method: 'eth_uninstallFilter', + params: [filterIdentifier], + }); + }); +} +exports.uninstallFilter = uninstallFilter; +function getFilterChanges(requestManager, filterIdentifier) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['hex'], [filterIdentifier]); + return requestManager.send({ + method: 'eth_getFilterChanges', + params: [filterIdentifier], + }); + }); +} +exports.getFilterChanges = getFilterChanges; +function getFilterLogs(requestManager, filterIdentifier) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['hex'], [filterIdentifier]); + return requestManager.send({ + method: 'eth_getFilterLogs', + params: [filterIdentifier], + }); + }); +} +exports.getFilterLogs = getFilterLogs; +function getLogs(requestManager, filter) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['filter'], [filter]); + return requestManager.send({ + method: 'eth_getLogs', + params: [filter], + }); + }); +} +exports.getLogs = getLogs; +function getWork(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_getWork', + params: [], + }); + }); +} +exports.getWork = getWork; +function submitWork(requestManager, nonce, hash, digest) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes8', 'bytes32', 'bytes32'], [nonce, hash, digest]); + return requestManager.send({ + method: 'eth_submitWork', + params: [nonce, hash, digest], + }); + }); +} +exports.submitWork = submitWork; +function submitHashrate(requestManager, hashRate, id) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['bytes32', 'bytes32'], [hashRate, id]); + return requestManager.send({ + method: 'eth_submitHashrate', + params: [hashRate, id], + }); + }); +} +exports.submitHashrate = submitHashrate; +function getFeeHistory(requestManager, blockCount, newestBlock, rewardPercentiles) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['hex', 'blockNumberOrTag'], [blockCount, newestBlock]); + for (const rewardPercentile of rewardPercentiles) { + web3_validator_1.validator.validate(['number'], [rewardPercentile]); + } + return requestManager.send({ + method: 'eth_feeHistory', + params: [blockCount, newestBlock, rewardPercentiles], + }); + }); +} +exports.getFeeHistory = getFeeHistory; +function getPendingTransactions(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_pendingTransactions', + params: [], + }); + }); +} +exports.getPendingTransactions = getPendingTransactions; +function requestAccounts(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_requestAccounts', + params: [], + }); + }); +} +exports.requestAccounts = requestAccounts; +function getChainId(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_chainId', + params: [], + }); + }); +} +exports.getChainId = getChainId; +function getProof(requestManager, address, storageKeys, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['address', 'bytes32[]', 'blockNumberOrTag'], [address, storageKeys, blockNumber]); + return requestManager.send({ + method: 'eth_getProof', + params: [address, storageKeys, blockNumber], + }); + }); +} +exports.getProof = getProof; +function getNodeInfo(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'web3_clientVersion', + params: [], + }); + }); +} +exports.getNodeInfo = getNodeInfo; +function createAccessList(requestManager, transaction, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + web3_validator_1.validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_createAccessList', + params: [transaction, blockNumber], + }); + }); +} +exports.createAccessList = createAccessList; +function signTypedData(requestManager, address, typedData, useLegacy = false) { + return __awaiter(this, void 0, void 0, function* () { + // TODO Add validation for typedData + web3_validator_1.validator.validate(['address'], [address]); + return requestManager.send({ + method: `eth_signTypedData${useLegacy ? '' : '_v4'}`, + params: [address, typedData], + }); + }); +} +exports.signTypedData = signTypedData; +//# sourceMappingURL=eth_rpc_methods.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.js.map new file mode 100644 index 0000000..20e4284 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/eth_rpc_methods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_rpc_methods.js","sourceRoot":"","sources":["../../src/eth_rpc_methods.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA+BA,mDAA2C;AAE3C,SAAsB,kBAAkB,CAAC,cAAkC;;QAC1E,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,qBAAqB;YAC7B,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,gDAKC;AAED,SAAsB,UAAU,CAAC,cAAkC;;QAClE,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,aAAa;YACrB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,gCAKC;AAED,SAAsB,WAAW,CAAC,cAAkC;;QACnE,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,cAAc;YACtB,MAAM,EAAE,EAAE;SACV,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SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;QAE3C,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,oBAAoB,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE;YACpD,MAAM,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC;SAC5B,CAAC,CAAC;IACJ,CAAC;CAAA;AAbD,sCAaC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.d.ts new file mode 100644 index 0000000..9232bbb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.d.ts @@ -0,0 +1,4 @@ +import * as ethRpcMethods from './eth_rpc_methods.js'; +import * as netRpcMethods from './net_rpc_methods.js'; +import * as personalRpcMethods from './personal_rpc_methods.js'; +export { ethRpcMethods, netRpcMethods, personalRpcMethods }; diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.js new file mode 100644 index 0000000..8e430fe --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.js @@ -0,0 +1,49 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.personalRpcMethods = exports.netRpcMethods = exports.ethRpcMethods = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const ethRpcMethods = __importStar(require("./eth_rpc_methods.js")); +exports.ethRpcMethods = ethRpcMethods; +const netRpcMethods = __importStar(require("./net_rpc_methods.js")); +exports.netRpcMethods = netRpcMethods; +const personalRpcMethods = __importStar(require("./personal_rpc_methods.js")); +exports.personalRpcMethods = personalRpcMethods; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.js.map new file mode 100644 index 0000000..3a9126a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,oEAAsD;AAI7C,sCAAa;AAHtB,oEAAsD;AAG9B,sCAAa;AAFrC,8EAAgE;AAEzB,gDAAkB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.d.ts new file mode 100644 index 0000000..3506f3f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.d.ts @@ -0,0 +1,5 @@ +import { Web3RequestManager } from 'web3-core'; +import { Web3NetAPI } from 'web3-types'; +export declare function getId(requestManager: Web3RequestManager): Promise; +export declare function getPeerCount(requestManager: Web3RequestManager): Promise; +export declare function isListening(requestManager: Web3RequestManager): Promise; diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.js new file mode 100644 index 0000000..ce36479 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.js @@ -0,0 +1,40 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isListening = exports.getPeerCount = exports.getId = void 0; +function getId(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'net_version', + params: [], + }); + }); +} +exports.getId = getId; +function getPeerCount(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'net_peerCount', + params: [], + }); + }); +} +exports.getPeerCount = getPeerCount; +function isListening(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'net_listening', + params: [], + }); + }); +} +exports.isListening = isListening; +//# sourceMappingURL=net_rpc_methods.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.js.map new file mode 100644 index 0000000..e83fbe6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/net_rpc_methods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"net_rpc_methods.js","sourceRoot":"","sources":["../../src/net_rpc_methods.ts"],"names":[],"mappings":";;;;;;;;;;;;AAmBA,SAAsB,KAAK,CAAC,cAA8C;;QACzE,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,aAAa;YACrB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,sBAKC;AAED,SAAsB,YAAY,CAAC,cAA8C;;QAChF,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,eAAe;YACvB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oCAKC;AAED,SAAsB,WAAW,CAAC,cAA8C;;QAC/E,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,eAAe;YACvB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,kCAKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.d.ts new file mode 100644 index 0000000..b5c1d03 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.d.ts @@ -0,0 +1,11 @@ +import { Web3RequestManager } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; +export declare const getAccounts: (requestManager: Web3RequestManager) => Promise; +export declare const newAccount: (requestManager: Web3RequestManager, password: string) => Promise; +export declare const unlockAccount: (requestManager: Web3RequestManager, address: Address, password: string, unlockDuration: number) => Promise; +export declare const lockAccount: (requestManager: Web3RequestManager, address: Address) => Promise; +export declare const importRawKey: (requestManager: Web3RequestManager, keyData: HexString, passphrase: string) => Promise; +export declare const sendTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const signTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const sign: (requestManager: Web3RequestManager, data: HexString, address: Address, passphrase: string) => Promise; +export declare const ecRecover: (requestManager: Web3RequestManager, signedData: HexString, signature: string) => Promise; diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.js new file mode 100644 index 0000000..dc6c0e1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.js @@ -0,0 +1,76 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ecRecover = exports.sign = exports.signTransaction = exports.sendTransaction = exports.importRawKey = exports.lockAccount = exports.unlockAccount = exports.newAccount = exports.getAccounts = void 0; +const getAccounts = (requestManager) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_listAccounts', + params: [], + }); +}); +exports.getAccounts = getAccounts; +const newAccount = (requestManager, password) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_newAccount', + params: [password], + }); +}); +exports.newAccount = newAccount; +const unlockAccount = (requestManager, address, password, unlockDuration) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_unlockAccount', + params: [address, password, unlockDuration], + }); +}); +exports.unlockAccount = unlockAccount; +const lockAccount = (requestManager, address) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_lockAccount', + params: [address], + }); +}); +exports.lockAccount = lockAccount; +const importRawKey = (requestManager, keyData, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_importRawKey', + params: [keyData, passphrase], + }); +}); +exports.importRawKey = importRawKey; +const sendTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_sendTransaction', + params: [tx, passphrase], + }); +}); +exports.sendTransaction = sendTransaction; +const signTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_signTransaction', + params: [tx, passphrase], + }); +}); +exports.signTransaction = signTransaction; +const sign = (requestManager, data, address, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_sign', + params: [data, address, passphrase], + }); +}); +exports.sign = sign; +const ecRecover = (requestManager, signedData, signature) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_ecRecover', + params: [signedData, signature], + }); +}); +exports.ecRecover = ecRecover; +//# sourceMappingURL=personal_rpc_methods.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.js.map new file mode 100644 index 0000000..576888c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/commonjs/personal_rpc_methods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"personal_rpc_methods.js","sourceRoot":"","sources":["../../src/personal_rpc_methods.ts"],"names":[],"mappings":";;;;;;;;;;;;AAmBO,MAAM,WAAW,GAAG,CAAO,cAAkD,EAAE,EAAE;IACvF,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,uBAAuB;QAC/B,MAAM,EAAE,EAAE;KACV,CAAC,CAAA;EAAA,CAAC;AAJS,QAAA,WAAW,eAIpB;AAEG,MAAM,UAAU,GAAG,CACzB,cAAkD,EAClD,QAAgB,EACf,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,qBAAqB;QAC7B,MAAM,EAAE,CAAC,QAAQ,CAAC;KAClB,CAAC,CAAA;EAAA,CAAC;AAPS,QAAA,UAAU,cAOnB;AAEG,MAAM,aAAa,GAAG,CAC5B,cAAkD,EAClD,OAAgB,EAChB,QAAgB,EAChB,cAAsB,EACrB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,wBAAwB;QAChC,MAAM,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,cAAc,CAAC;KAC3C,CAAC,CAAA;EAAA,CAAC;AATS,QAAA,aAAa,iBAStB;AAEG,MAAM,WAAW,GAAG,CAC1B,cAAkD,EAClD,OAAgB,EACf,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,sBAAsB;QAC9B,MAAM,EAAE,CAAC,OAAO,CAAC;KACjB,CAAC,CAAA;EAAA,CAAC;AAPS,QAAA,WAAW,eAOpB;AAEG,MAAM,YAAY,GAAG,CAC3B,cAAkD,EAClD,OAAkB,EAClB,UAAkB,EACjB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,uBAAuB;QAC/B,MAAM,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC;KAC7B,CAAC,CAAA;EAAA,CAAC;AARS,QAAA,YAAY,gBAQrB;AAEG,MAAM,eAAe,GAAG,CAC9B,cAAkD,EAClD,EAAe,EACf,UAAkB,EACjB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,0BAA0B;QAClC,MAAM,EAAE,CAAC,EAAE,EAAE,UAAU,CAAC;KACxB,CAAC,CAAA;EAAA,CAAC;AARS,QAAA,eAAe,mBAQxB;AAEG,MAAM,eAAe,GAAG,CAC9B,cAAkD,EAClD,EAAe,EACf,UAAkB,EACjB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,0BAA0B;QAClC,MAAM,EAAE,CAAC,EAAE,EAAE,UAAU,CAAC;KACxB,CAAC,CAAA;EAAA,CAAC;AARS,QAAA,eAAe,mBAQxB;AAEG,MAAM,IAAI,GAAG,CACnB,cAAkD,EAClD,IAAe,EACf,OAAgB,EAChB,UAAkB,EACjB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,eAAe;QACvB,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC;KACnC,CAAC,CAAA;EAAA,CAAC;AATS,QAAA,IAAI,QASb;AAEG,MAAM,SAAS,GAAG,CACxB,cAAkD,EAClD,UAAqB,EACrB,SAAiB,EAChB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,oBAAoB;QAC5B,MAAM,EAAE,CAAC,UAAU,EAAE,SAAS,CAAC;KAC/B,CAAC,CAAA;EAAA,CAAC;AARS,QAAA,SAAS,aAQlB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/errors.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/errors.js new file mode 100644 index 0000000..ead7c81 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/errors.js @@ -0,0 +1,18 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/errors.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/errors.js.map new file mode 100644 index 0000000..9edfec4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/eth_rpc_methods.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/eth_rpc_methods.js new file mode 100644 index 0000000..1615f1a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/eth_rpc_methods.js @@ -0,0 +1,476 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { validator } from 'web3-validator'; +export function getProtocolVersion(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_protocolVersion', + params: [], + }); + }); +} +export function getSyncing(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_syncing', + params: [], + }); + }); +} +export function getCoinbase(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_coinbase', + params: [], + }); + }); +} +export function getMining(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_mining', + params: [], + }); + }); +} +export function getHashRate(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_hashrate', + params: [], + }); + }); +} +export function getGasPrice(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_gasPrice', + params: [], + }); + }); +} +export function getAccounts(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_accounts', + params: [], + }); + }); +} +export function getBlockNumber(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_blockNumber', + params: [], + }); + }); +} +export function getBalance(requestManager, address, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + return requestManager.send({ + method: 'eth_getBalance', + params: [address, blockNumber], + }); + }); +} +export function getStorageAt(requestManager, address, storageSlot, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['address', 'hex', 'blockNumberOrTag'], [address, storageSlot, blockNumber]); + return requestManager.send({ + method: 'eth_getStorageAt', + params: [address, storageSlot, blockNumber], + }); + }); +} +export function getTransactionCount(requestManager, address, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + return requestManager.send({ + method: 'eth_getTransactionCount', + params: [address, blockNumber], + }); + }); +} +export function getBlockTransactionCountByHash(requestManager, blockHash) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32'], [blockHash]); + return requestManager.send({ + method: 'eth_getBlockTransactionCountByHash', + params: [blockHash], + }); + }); +} +export function getBlockTransactionCountByNumber(requestManager, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_getBlockTransactionCountByNumber', + params: [blockNumber], + }); + }); +} +export function getUncleCountByBlockHash(requestManager, blockHash) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32'], [blockHash]); + return requestManager.send({ + method: 'eth_getUncleCountByBlockHash', + params: [blockHash], + }); + }); +} +export function getUncleCountByBlockNumber(requestManager, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_getUncleCountByBlockNumber', + params: [blockNumber], + }); + }); +} +export function getCode(requestManager, address, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + return requestManager.send({ + method: 'eth_getCode', + params: [address, blockNumber], + }); + }); +} +export function sign(requestManager, address, message) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['address', 'hex'], [address, message]); + return requestManager.send({ + method: 'eth_sign', + params: [address, message], + }); + }); +} +// TODO - Validation should be: +// isTransactionWithSender(transaction) +// ? validateTransactionWithSender(transaction) +// : validateTransactionWithSender(transaction, true) with true being a isPartial flag +export function signTransaction(requestManager, transaction) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_signTransaction', + params: [transaction], + }); + }); +} +// TODO - Validation should be: +// isTransactionWithSender(transaction) +// ? validateTransactionWithSender(transaction) +// : validateTransactionWithSender(transaction, true) with true being a isPartial flag +export function sendTransaction(requestManager, transaction) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_sendTransaction', + params: [transaction], + }); + }); +} +export function sendRawTransaction(requestManager, transaction) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['hex'], [transaction]); + return requestManager.send({ + method: 'eth_sendRawTransaction', + params: [transaction], + }); + }); +} +// TODO - validate transaction +export function call(requestManager, transaction, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + // validateTransactionCall(transaction); + validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_call', + params: [transaction, blockNumber], + }); + }); +} +// TODO Not sure how to best validate Partial +export function estimateGas(requestManager, transaction, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_estimateGas', + params: [transaction, blockNumber], + }); + }); +} +export function getBlockByHash(requestManager, blockHash, hydrated) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32', 'bool'], [blockHash, hydrated]); + return requestManager.send({ + method: 'eth_getBlockByHash', + params: [blockHash, hydrated], + }); + }); +} +export function getBlockByNumber(requestManager, blockNumber, hydrated) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag', 'bool'], [blockNumber, hydrated]); + return requestManager.send({ + method: 'eth_getBlockByNumber', + params: [blockNumber, hydrated], + }); + }); +} +export function getTransactionByHash(requestManager, transactionHash) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32'], [transactionHash]); + return requestManager.send({ + method: 'eth_getTransactionByHash', + params: [transactionHash], + }); + }); +} +export function getTransactionByBlockHashAndIndex(requestManager, blockHash, transactionIndex) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32', 'hex'], [blockHash, transactionIndex]); + return requestManager.send({ + method: 'eth_getTransactionByBlockHashAndIndex', + params: [blockHash, transactionIndex], + }); + }); +} +export function getTransactionByBlockNumberAndIndex(requestManager, blockNumber, transactionIndex) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag', 'hex'], [blockNumber, transactionIndex]); + return requestManager.send({ + method: 'eth_getTransactionByBlockNumberAndIndex', + params: [blockNumber, transactionIndex], + }); + }); +} +export function getTransactionReceipt(requestManager, transactionHash) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32'], [transactionHash]); + return requestManager.send({ + method: 'eth_getTransactionReceipt', + params: [transactionHash], + }); + }); +} +export function getUncleByBlockHashAndIndex(requestManager, blockHash, uncleIndex) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32', 'hex'], [blockHash, uncleIndex]); + return requestManager.send({ + method: 'eth_getUncleByBlockHashAndIndex', + params: [blockHash, uncleIndex], + }); + }); +} +export function getUncleByBlockNumberAndIndex(requestManager, blockNumber, uncleIndex) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag', 'hex'], [blockNumber, uncleIndex]); + return requestManager.send({ + method: 'eth_getUncleByBlockNumberAndIndex', + params: [blockNumber, uncleIndex], + }); + }); +} +export function getCompilers(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_getCompilers', + params: [], + }); + }); +} +export function compileSolidity(requestManager, code) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['string'], [code]); + return requestManager.send({ + method: 'eth_compileSolidity', + params: [code], + }); + }); +} +export function compileLLL(requestManager, code) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['string'], [code]); + return requestManager.send({ + method: 'eth_compileLLL', + params: [code], + }); + }); +} +export function compileSerpent(requestManager, code) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['string'], [code]); + return requestManager.send({ + method: 'eth_compileSerpent', + params: [code], + }); + }); +} +export function newFilter(requestManager, filter) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['filter'], [filter]); + return requestManager.send({ + method: 'eth_newFilter', + params: [filter], + }); + }); +} +export function newBlockFilter(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_newBlockFilter', + params: [], + }); + }); +} +export function newPendingTransactionFilter(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_newPendingTransactionFilter', + params: [], + }); + }); +} +export function uninstallFilter(requestManager, filterIdentifier) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['hex'], [filterIdentifier]); + return requestManager.send({ + method: 'eth_uninstallFilter', + params: [filterIdentifier], + }); + }); +} +export function getFilterChanges(requestManager, filterIdentifier) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['hex'], [filterIdentifier]); + return requestManager.send({ + method: 'eth_getFilterChanges', + params: [filterIdentifier], + }); + }); +} +export function getFilterLogs(requestManager, filterIdentifier) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['hex'], [filterIdentifier]); + return requestManager.send({ + method: 'eth_getFilterLogs', + params: [filterIdentifier], + }); + }); +} +export function getLogs(requestManager, filter) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['filter'], [filter]); + return requestManager.send({ + method: 'eth_getLogs', + params: [filter], + }); + }); +} +export function getWork(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_getWork', + params: [], + }); + }); +} +export function submitWork(requestManager, nonce, hash, digest) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes8', 'bytes32', 'bytes32'], [nonce, hash, digest]); + return requestManager.send({ + method: 'eth_submitWork', + params: [nonce, hash, digest], + }); + }); +} +export function submitHashrate(requestManager, hashRate, id) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['bytes32', 'bytes32'], [hashRate, id]); + return requestManager.send({ + method: 'eth_submitHashrate', + params: [hashRate, id], + }); + }); +} +export function getFeeHistory(requestManager, blockCount, newestBlock, rewardPercentiles) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['hex', 'blockNumberOrTag'], [blockCount, newestBlock]); + for (const rewardPercentile of rewardPercentiles) { + validator.validate(['number'], [rewardPercentile]); + } + return requestManager.send({ + method: 'eth_feeHistory', + params: [blockCount, newestBlock, rewardPercentiles], + }); + }); +} +export function getPendingTransactions(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_pendingTransactions', + params: [], + }); + }); +} +export function requestAccounts(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_requestAccounts', + params: [], + }); + }); +} +export function getChainId(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'eth_chainId', + params: [], + }); + }); +} +export function getProof(requestManager, address, storageKeys, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['address', 'bytes32[]', 'blockNumberOrTag'], [address, storageKeys, blockNumber]); + return requestManager.send({ + method: 'eth_getProof', + params: [address, storageKeys, blockNumber], + }); + }); +} +export function getNodeInfo(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'web3_clientVersion', + params: [], + }); + }); +} +export function createAccessList(requestManager, transaction, blockNumber) { + return __awaiter(this, void 0, void 0, function* () { + validator.validate(['blockNumberOrTag'], [blockNumber]); + return requestManager.send({ + method: 'eth_createAccessList', + params: [transaction, blockNumber], + }); + }); +} +export function signTypedData(requestManager, address, typedData, useLegacy = false) { + return __awaiter(this, void 0, void 0, function* () { + // TODO Add validation for typedData + validator.validate(['address'], [address]); + return requestManager.send({ + method: `eth_signTypedData${useLegacy ? '' : '_v4'}`, + params: [address, typedData], + }); + }); +} +//# sourceMappingURL=eth_rpc_methods.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/eth_rpc_methods.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/eth_rpc_methods.js.map new file mode 100644 index 0000000..8e3306e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/eth_rpc_methods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_rpc_methods.js","sourceRoot":"","sources":["../../src/eth_rpc_methods.ts"],"names":[],"mappings":";;;;;;;;;AA+BA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,MAAM,UAAgB,kBAAkB,CAAC,cAAkC;;QAC1E,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,qBAAqB;YAC7B,MAAM,EAAE,EAA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OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,oBAAoB,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE;YACpD,MAAM,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC;SAC5B,CAAC,CAAC;IACJ,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/index.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/index.js new file mode 100644 index 0000000..9bd4aca --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/index.js @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import * as ethRpcMethods from './eth_rpc_methods.js'; +import * as netRpcMethods from './net_rpc_methods.js'; +import * as personalRpcMethods from './personal_rpc_methods.js'; +export { ethRpcMethods, netRpcMethods, personalRpcMethods }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/index.js.map new file mode 100644 index 0000000..ad10fc3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,KAAK,aAAa,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,aAAa,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,kBAAkB,MAAM,2BAA2B,CAAC;AAEhE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,kBAAkB,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/net_rpc_methods.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/net_rpc_methods.js new file mode 100644 index 0000000..8b184c2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/net_rpc_methods.js @@ -0,0 +1,34 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +export function getId(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'net_version', + params: [], + }); + }); +} +export function getPeerCount(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'net_peerCount', + params: [], + }); + }); +} +export function isListening(requestManager) { + return __awaiter(this, void 0, void 0, function* () { + return requestManager.send({ + method: 'net_listening', + params: [], + }); + }); +} +//# sourceMappingURL=net_rpc_methods.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/net_rpc_methods.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/net_rpc_methods.js.map new file mode 100644 index 0000000..6335f5b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/net_rpc_methods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"net_rpc_methods.js","sourceRoot":"","sources":["../../src/net_rpc_methods.ts"],"names":[],"mappings":";;;;;;;;;AAmBA,MAAM,UAAgB,KAAK,CAAC,cAA8C;;QACzE,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,aAAa;YACrB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AAED,MAAM,UAAgB,YAAY,CAAC,cAA8C;;QAChF,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,eAAe;YACvB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA;AAED,MAAM,UAAgB,WAAW,CAAC,cAA8C;;QAC/E,OAAO,cAAc,CAAC,IAAI,CAAC;YAC1B,MAAM,EAAE,eAAe;YACvB,MAAM,EAAE,EAAE;SACV,CAAC,CAAC;IACJ,CAAC;CAAA"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/package.json b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/personal_rpc_methods.js b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/personal_rpc_methods.js new file mode 100644 index 0000000..ef095a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/personal_rpc_methods.js @@ -0,0 +1,64 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +export const getAccounts = (requestManager) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_listAccounts', + params: [], + }); +}); +export const newAccount = (requestManager, password) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_newAccount', + params: [password], + }); +}); +export const unlockAccount = (requestManager, address, password, unlockDuration) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_unlockAccount', + params: [address, password, unlockDuration], + }); +}); +export const lockAccount = (requestManager, address) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_lockAccount', + params: [address], + }); +}); +export const importRawKey = (requestManager, keyData, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_importRawKey', + params: [keyData, passphrase], + }); +}); +export const sendTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_sendTransaction', + params: [tx, passphrase], + }); +}); +export const signTransaction = (requestManager, tx, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_signTransaction', + params: [tx, passphrase], + }); +}); +export const sign = (requestManager, data, address, passphrase) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_sign', + params: [data, address, passphrase], + }); +}); +export const ecRecover = (requestManager, signedData, signature) => __awaiter(void 0, void 0, void 0, function* () { + return requestManager.send({ + method: 'personal_ecRecover', + params: [signedData, signature], + }); +}); +//# sourceMappingURL=personal_rpc_methods.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/personal_rpc_methods.js.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/personal_rpc_methods.js.map new file mode 100644 index 0000000..e416044 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/esm/personal_rpc_methods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"personal_rpc_methods.js","sourceRoot":"","sources":["../../src/personal_rpc_methods.ts"],"names":[],"mappings":";;;;;;;;;AAmBA,MAAM,CAAC,MAAM,WAAW,GAA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U,CAAC;KACxB,CAAC,CAAA;EAAA,CAAC;AAEJ,MAAM,CAAC,MAAM,eAAe,GAAG,CAC9B,cAAkD,EAClD,EAAe,EACf,UAAkB,EACjB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,0BAA0B;QAClC,MAAM,EAAE,CAAC,EAAE,EAAE,UAAU,CAAC;KACxB,CAAC,CAAA;EAAA,CAAC;AAEJ,MAAM,CAAC,MAAM,IAAI,GAAG,CACnB,cAAkD,EAClD,IAAe,EACf,OAAgB,EAChB,UAAkB,EACjB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,eAAe;QACvB,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC;KACnC,CAAC,CAAA;EAAA,CAAC;AAEJ,MAAM,CAAC,MAAM,SAAS,GAAG,CACxB,cAAkD,EAClD,UAAqB,EACrB,SAAiB,EAChB,EAAE;IACH,OAAA,cAAc,CAAC,IAAI,CAAC;QACnB,MAAM,EAAE,oBAAoB;QAC5B,MAAM,EAAE,CAAC,UAAU,EAAE,SAAS,CAAC;KAC/B,CAAC,CAAA;EAAA,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/errors.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/errors.d.ts new file mode 100644 index 0000000..30f6c5d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/errors.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/errors.d.ts.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/errors.d.ts.map new file mode 100644 index 0000000..0457a1d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/eth_rpc_methods.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/eth_rpc_methods.d.ts new file mode 100644 index 0000000..e3bf3e5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/eth_rpc_methods.d.ts @@ -0,0 +1,55 @@ +import { Web3RequestManager } from 'web3-core'; +import { Address, BlockNumberOrTag, Filter, HexString32Bytes, HexString8Bytes, HexStringBytes, TransactionCallAPI, TransactionWithSenderAPI, Uint, Uint256, Web3EthExecutionAPI, Eip712TypedData } from 'web3-types'; +export declare function getProtocolVersion(requestManager: Web3RequestManager): Promise; +export declare function getSyncing(requestManager: Web3RequestManager): Promise; +export declare function getCoinbase(requestManager: Web3RequestManager): Promise; +export declare function getMining(requestManager: Web3RequestManager): Promise; +export declare function getHashRate(requestManager: Web3RequestManager): Promise; +export declare function getGasPrice(requestManager: Web3RequestManager): Promise; +export declare function getAccounts(requestManager: Web3RequestManager): Promise; +export declare function getBlockNumber(requestManager: Web3RequestManager): Promise; +export declare function getBalance(requestManager: Web3RequestManager, address: Address, blockNumber: BlockNumberOrTag): Promise; +export declare function getStorageAt(requestManager: Web3RequestManager, address: Address, storageSlot: Uint256, blockNumber: BlockNumberOrTag): Promise; +export declare function getTransactionCount(requestManager: Web3RequestManager, address: Address, blockNumber: BlockNumberOrTag): Promise; +export declare function getBlockTransactionCountByHash(requestManager: Web3RequestManager, blockHash: HexString32Bytes): Promise; +export declare function getBlockTransactionCountByNumber(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag): Promise; +export declare function getUncleCountByBlockHash(requestManager: Web3RequestManager, blockHash: HexString32Bytes): Promise; +export declare function getUncleCountByBlockNumber(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag): Promise; +export declare function getCode(requestManager: Web3RequestManager, address: Address, blockNumber: BlockNumberOrTag): Promise; +export declare function sign(requestManager: Web3RequestManager, address: Address, message: HexStringBytes): Promise; +export declare function signTransaction(requestManager: Web3RequestManager, transaction: TransactionWithSenderAPI | Partial): Promise; +export declare function sendTransaction(requestManager: Web3RequestManager, transaction: TransactionWithSenderAPI | Partial): Promise; +export declare function sendRawTransaction(requestManager: Web3RequestManager, transaction: HexStringBytes): Promise; +export declare function call(requestManager: Web3RequestManager, transaction: TransactionCallAPI, blockNumber: BlockNumberOrTag): Promise; +export declare function estimateGas(requestManager: Web3RequestManager, transaction: Partial, blockNumber: BlockNumberOrTag): Promise; +export declare function getBlockByHash(requestManager: Web3RequestManager, blockHash: HexString32Bytes, hydrated: boolean): Promise; +export declare function getBlockByNumber(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag, hydrated: boolean): Promise; +export declare function getTransactionByHash(requestManager: Web3RequestManager, transactionHash: HexString32Bytes): Promise; +export declare function getTransactionByBlockHashAndIndex(requestManager: Web3RequestManager, blockHash: HexString32Bytes, transactionIndex: Uint): Promise; +export declare function getTransactionByBlockNumberAndIndex(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag, transactionIndex: Uint): Promise; +export declare function getTransactionReceipt(requestManager: Web3RequestManager, transactionHash: HexString32Bytes): Promise; +export declare function getUncleByBlockHashAndIndex(requestManager: Web3RequestManager, blockHash: HexString32Bytes, uncleIndex: Uint): Promise; +export declare function getUncleByBlockNumberAndIndex(requestManager: Web3RequestManager, blockNumber: BlockNumberOrTag, uncleIndex: Uint): Promise; +export declare function getCompilers(requestManager: Web3RequestManager): Promise; +export declare function compileSolidity(requestManager: Web3RequestManager, code: string): Promise; +export declare function compileLLL(requestManager: Web3RequestManager, code: string): Promise; +export declare function compileSerpent(requestManager: Web3RequestManager, code: string): Promise; +export declare function newFilter(requestManager: Web3RequestManager, filter: Filter): Promise; +export declare function newBlockFilter(requestManager: Web3RequestManager): Promise; +export declare function newPendingTransactionFilter(requestManager: Web3RequestManager): Promise; +export declare function uninstallFilter(requestManager: Web3RequestManager, filterIdentifier: Uint): Promise; +export declare function getFilterChanges(requestManager: Web3RequestManager, filterIdentifier: Uint): Promise; +export declare function getFilterLogs(requestManager: Web3RequestManager, filterIdentifier: Uint): Promise; +export declare function getLogs(requestManager: Web3RequestManager, filter: Filter): Promise; +export declare function getWork(requestManager: Web3RequestManager): Promise<[string, string, string]>; +export declare function submitWork(requestManager: Web3RequestManager, nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes): Promise; +export declare function submitHashrate(requestManager: Web3RequestManager, hashRate: HexString32Bytes, id: HexString32Bytes): Promise; +export declare function getFeeHistory(requestManager: Web3RequestManager, blockCount: Uint, newestBlock: BlockNumberOrTag, rewardPercentiles: number[]): Promise; +export declare function getPendingTransactions(requestManager: Web3RequestManager): Promise; +export declare function requestAccounts(requestManager: Web3RequestManager): Promise; +export declare function getChainId(requestManager: Web3RequestManager): Promise; +export declare function getProof(requestManager: Web3RequestManager, address: Address, storageKeys: HexString32Bytes[], blockNumber: BlockNumberOrTag): Promise; +export declare function getNodeInfo(requestManager: Web3RequestManager): Promise; +export declare function createAccessList(requestManager: Web3RequestManager, transaction: TransactionWithSenderAPI | Partial, blockNumber: BlockNumberOrTag): Promise; +export declare function signTypedData(requestManager: Web3RequestManager, address: Address, typedData: Eip712TypedData, useLegacy?: boolean): Promise; +//# sourceMappingURL=eth_rpc_methods.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/eth_rpc_methods.d.ts.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/eth_rpc_methods.d.ts.map new file mode 100644 index 0000000..c290666 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/eth_rpc_methods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_rpc_methods.d.ts","sourceRoot":"","sources":["../../src/eth_rpc_methods.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACN,OAAO,EACP,gBA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AkB,qCAK/D;AAED,wBAAsB,UAAU,CAC/B,cAAc,EAAE,kBAAkB,EAClC,KAAK,EAAE,eAAe,EACtB,IAAI,EAAE,gBAAgB,EACtB,MAAM,EAAE,gBAAgB,oBAQxB;AAED,wBAAsB,cAAc,CACnC,cAAc,EAAE,kBAAkB,EAClC,QAAQ,EAAE,gBAAgB,EAC1B,EAAE,EAAE,gBAAgB,oBAQpB;AAED,wBAAsB,aAAa,CAClC,cAAc,EAAE,kBAAkB,EAClC,UAAU,EAAE,IAAI,EAChB,WAAW,EAAE,gBAAgB,EAC7B,iBAAiB,EAAE,MAAM,EAAE,qDAY3B;AAED,wBAAsB,sBAAsB,CAC3C,cAAc,EAAE,kBAAkB,CAAC,mBAAmB,CAAC,mDAMvD;AAED,wBAAsB,eAAe,CAAC,cAAc,EAAE,kBAAkB,CAAC,mBAAmB,CAAC,qBAK5F;AAED,wBAAsB,UAAU,CAAC,cAAc,EAAE,kBAAkB,CAAC,mBAAmB,CAAC,mBAKvF;AAED,wBAAsB,QAAQ,CAC7B,cAAc,EAAE,kBAAkB,CAAC,mBAAmB,CAAC,EACvD,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,gBAAgB,EAAE,EAC/B,WAAW,EAAE,gBAAgB,+CAW7B;AAED,wBAAsB,WAAW,CAAC,cAAc,EAAE,kBAAkB,CAAC,mBAAmB,CAAC,mBAKxF;AAED,wBAAsB,gBAAgB,CACrC,cAAc,EAAE,kBAAkB,EAClC,WAAW,EAAE,wBAAwB,GAAG,OAAO,CAAC,wBAAwB,CAAC,EACzE,WAAW,EAAE,gBAAgB,gBAQ7B;AAED,wBAAsB,aAAa,CAClC,cAAc,EAAE,kBAAkB,EAClC,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,eAAe,EAC1B,SAAS,UAAQ,GACf,OAAO,CAAC,MAAM,CAAC,CAQjB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/index.d.ts new file mode 100644 index 0000000..f3cd046 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/index.d.ts @@ -0,0 +1,5 @@ +import * as ethRpcMethods from './eth_rpc_methods.js'; +import * as netRpcMethods from './net_rpc_methods.js'; +import * as personalRpcMethods from './personal_rpc_methods.js'; +export { ethRpcMethods, netRpcMethods, personalRpcMethods }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/index.d.ts.map new file mode 100644 index 0000000..c8bba35 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,aAAa,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,aAAa,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,kBAAkB,MAAM,2BAA2B,CAAC;AAEhE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,kBAAkB,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/net_rpc_methods.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/net_rpc_methods.d.ts new file mode 100644 index 0000000..0b9fb92 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/net_rpc_methods.d.ts @@ -0,0 +1,6 @@ +import { Web3RequestManager } from 'web3-core'; +import { Web3NetAPI } from 'web3-types'; +export declare function getId(requestManager: Web3RequestManager): Promise; +export declare function getPeerCount(requestManager: Web3RequestManager): Promise; +export declare function isListening(requestManager: Web3RequestManager): Promise; +//# sourceMappingURL=net_rpc_methods.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/net_rpc_methods.d.ts.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/net_rpc_methods.d.ts.map new file mode 100644 index 0000000..51b387c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/net_rpc_methods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"net_rpc_methods.d.ts","sourceRoot":"","sources":["../../src/net_rpc_methods.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,wBAAsB,KAAK,CAAC,cAAc,EAAE,kBAAkB,CAAC,UAAU,CAAC,mBAKzE;AAED,wBAAsB,YAAY,CAAC,cAAc,EAAE,kBAAkB,CAAC,UAAU,CAAC,mBAKhF;AAED,wBAAsB,WAAW,CAAC,cAAc,EAAE,kBAAkB,CAAC,UAAU,CAAC,oBAK/E"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/personal_rpc_methods.d.ts b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/personal_rpc_methods.d.ts new file mode 100644 index 0000000..a42f00b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/personal_rpc_methods.d.ts @@ -0,0 +1,12 @@ +import { Web3RequestManager } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; +export declare const getAccounts: (requestManager: Web3RequestManager) => Promise; +export declare const newAccount: (requestManager: Web3RequestManager, password: string) => Promise; +export declare const unlockAccount: (requestManager: Web3RequestManager, address: Address, password: string, unlockDuration: number) => Promise; +export declare const lockAccount: (requestManager: Web3RequestManager, address: Address) => Promise; +export declare const importRawKey: (requestManager: Web3RequestManager, keyData: HexString, passphrase: string) => Promise; +export declare const sendTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const signTransaction: (requestManager: Web3RequestManager, tx: Transaction, passphrase: string) => Promise; +export declare const sign: (requestManager: Web3RequestManager, data: HexString, address: Address, passphrase: string) => Promise; +export declare const ecRecover: (requestManager: Web3RequestManager, signedData: HexString, signature: string) => Promise; +//# sourceMappingURL=personal_rpc_methods.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/personal_rpc_methods.d.ts.map b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/personal_rpc_methods.d.ts.map new file mode 100644 index 0000000..b13176b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/lib/types/personal_rpc_methods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"personal_rpc_methods.d.ts","sourceRoot":"","sources":["../../src/personal_rpc_methods.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE7E,eAAO,MAAM,WAAW,mBAA0B,mBAAmB,cAAc,CAAC,sBAIjF,CAAC;AAEJ,eAAO,MAAM,UAAU,mBACN,mBAAmB,cAAc,CAAC,YACxC,MAAM,oBAKd,CAAC;AAEJ,eAAO,MAAM,aAAa,mBACT,mBAAmB,cAAc,CAAC,WACzC,OAAO,YACN,MAAM,kBACA,MAAM,qBAKpB,CAAC;AAEJ,eAAO,MAAM,WAAW,mBACP,mBAAmB,cAAc,CAAC,WACzC,OAAO,qBAKd,CAAC;AAEJ,eAAO,MAAM,YAAY,mBACR,mBAAmB,cAAc,CAAC,WACzC,SAAS,cACN,MAAM,oBAKhB,CAAC;AAEJ,eAAO,MAAM,eAAe,mBACX,mBAAmB,cAAc,CAAC,MAC9C,WAAW,cACH,MAAM,oBAKhB,CAAC;AAEJ,eAAO,MAAM,eAAe,mBACX,mBAAmB,cAAc,CAAC,MAC9C,WAAW,cACH,MAAM,oBAKhB,CAAC;AAEJ,eAAO,MAAM,IAAI,mBACA,mBAAmB,cAAc,CAAC,QAC5C,SAAS,WACN,OAAO,cACJ,MAAM,oBAKhB,CAAC;AAEJ,eAAO,MAAM,SAAS,mBACL,mBAAmB,cAAc,CAAC,cACtC,SAAS,aACV,MAAM,oBAKf,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/package.json b/test/merkletreejs/node_modules/web3-rpc-methods/package.json new file mode 100644 index 0000000..c01972d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/package.json @@ -0,0 +1,64 @@ +{ + "name": "web3-rpc-methods", + "version": "1.1.4", + "description": "Ethereum RPC methods for Web3 4.x.x", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "web3-core": "^4.3.2", + "web3-types": "^1.3.1", + "web3-validator": "^2.0.3" + }, + "gitHead": "b9b5fe0210da1a4ebf62e2b54f37a9c747bfa136" +} diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/src/errors.ts b/test/merkletreejs/node_modules/web3-rpc-methods/src/errors.ts new file mode 100644 index 0000000..303b689 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/src/errors.ts @@ -0,0 +1,16 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/src/eth_rpc_methods.ts b/test/merkletreejs/node_modules/web3-rpc-methods/src/eth_rpc_methods.ts new file mode 100644 index 0000000..59c2690 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/src/eth_rpc_methods.ts @@ -0,0 +1,593 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3RequestManager } from 'web3-core'; +import { + Address, + BlockNumberOrTag, + Filter, + HexString32Bytes, + HexString8Bytes, + HexStringBytes, + TransactionCallAPI, + TransactionWithSenderAPI, + Uint, + Uint256, + Web3EthExecutionAPI, + Eip712TypedData, +} from 'web3-types'; +import { validator } from 'web3-validator'; + +export async function getProtocolVersion(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_protocolVersion', + params: [], + }); +} + +export async function getSyncing(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_syncing', + params: [], + }); +} + +export async function getCoinbase(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_coinbase', + params: [], + }); +} + +export async function getMining(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_mining', + params: [], + }); +} + +export async function getHashRate(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_hashrate', + params: [], + }); +} + +export async function getGasPrice(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_gasPrice', + params: [], + }); +} + +export async function getAccounts(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_accounts', + params: [], + }); +} + +export async function getBlockNumber(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_blockNumber', + params: [], + }); +} + +export async function getBalance( + requestManager: Web3RequestManager, + address: Address, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + + return requestManager.send({ + method: 'eth_getBalance', + params: [address, blockNumber], + }); +} + +export async function getStorageAt( + requestManager: Web3RequestManager, + address: Address, + storageSlot: Uint256, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['address', 'hex', 'blockNumberOrTag'], [address, storageSlot, blockNumber]); + + return requestManager.send({ + method: 'eth_getStorageAt', + params: [address, storageSlot, blockNumber], + }); +} + +export async function getTransactionCount( + requestManager: Web3RequestManager, + address: Address, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + + return requestManager.send({ + method: 'eth_getTransactionCount', + params: [address, blockNumber], + }); +} + +export async function getBlockTransactionCountByHash( + requestManager: Web3RequestManager, + blockHash: HexString32Bytes, +) { + validator.validate(['bytes32'], [blockHash]); + + return requestManager.send({ + method: 'eth_getBlockTransactionCountByHash', + params: [blockHash], + }); +} + +export async function getBlockTransactionCountByNumber( + requestManager: Web3RequestManager, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['blockNumberOrTag'], [blockNumber]); + + return requestManager.send({ + method: 'eth_getBlockTransactionCountByNumber', + params: [blockNumber], + }); +} + +export async function getUncleCountByBlockHash( + requestManager: Web3RequestManager, + blockHash: HexString32Bytes, +) { + validator.validate(['bytes32'], [blockHash]); + + return requestManager.send({ + method: 'eth_getUncleCountByBlockHash', + params: [blockHash], + }); +} + +export async function getUncleCountByBlockNumber( + requestManager: Web3RequestManager, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['blockNumberOrTag'], [blockNumber]); + + return requestManager.send({ + method: 'eth_getUncleCountByBlockNumber', + params: [blockNumber], + }); +} + +export async function getCode( + requestManager: Web3RequestManager, + address: Address, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['address', 'blockNumberOrTag'], [address, blockNumber]); + + return requestManager.send({ + method: 'eth_getCode', + params: [address, blockNumber], + }); +} + +export async function sign( + requestManager: Web3RequestManager, + address: Address, + message: HexStringBytes, +) { + validator.validate(['address', 'hex'], [address, message]); + + return requestManager.send({ + method: 'eth_sign', + params: [address, message], + }); +} + +// TODO - Validation should be: +// isTransactionWithSender(transaction) +// ? validateTransactionWithSender(transaction) +// : validateTransactionWithSender(transaction, true) with true being a isPartial flag +export async function signTransaction( + requestManager: Web3RequestManager, + transaction: TransactionWithSenderAPI | Partial, +) { + return requestManager.send({ + method: 'eth_signTransaction', + params: [transaction], + }); +} + +// TODO - Validation should be: +// isTransactionWithSender(transaction) +// ? validateTransactionWithSender(transaction) +// : validateTransactionWithSender(transaction, true) with true being a isPartial flag +export async function sendTransaction( + requestManager: Web3RequestManager, + transaction: TransactionWithSenderAPI | Partial, +) { + return requestManager.send({ + method: 'eth_sendTransaction', + params: [transaction], + }); +} + +export async function sendRawTransaction( + requestManager: Web3RequestManager, + transaction: HexStringBytes, +) { + validator.validate(['hex'], [transaction]); + + return requestManager.send({ + method: 'eth_sendRawTransaction', + params: [transaction], + }); +} + +// TODO - validate transaction +export async function call( + requestManager: Web3RequestManager, + transaction: TransactionCallAPI, + blockNumber: BlockNumberOrTag, +) { + // validateTransactionCall(transaction); + validator.validate(['blockNumberOrTag'], [blockNumber]); + + return requestManager.send({ + method: 'eth_call', + params: [transaction, blockNumber], + }); +} + +// TODO Not sure how to best validate Partial +export async function estimateGas( + requestManager: Web3RequestManager, + transaction: Partial, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['blockNumberOrTag'], [blockNumber]); + + return requestManager.send({ + method: 'eth_estimateGas', + params: [transaction, blockNumber], + }); +} + +export async function getBlockByHash( + requestManager: Web3RequestManager, + blockHash: HexString32Bytes, + hydrated: boolean, +) { + validator.validate(['bytes32', 'bool'], [blockHash, hydrated]); + + return requestManager.send({ + method: 'eth_getBlockByHash', + params: [blockHash, hydrated], + }); +} + +export async function getBlockByNumber( + requestManager: Web3RequestManager, + blockNumber: BlockNumberOrTag, + hydrated: boolean, +) { + validator.validate(['blockNumberOrTag', 'bool'], [blockNumber, hydrated]); + + return requestManager.send({ + method: 'eth_getBlockByNumber', + params: [blockNumber, hydrated], + }); +} + +export async function getTransactionByHash( + requestManager: Web3RequestManager, + transactionHash: HexString32Bytes, +) { + validator.validate(['bytes32'], [transactionHash]); + + return requestManager.send({ + method: 'eth_getTransactionByHash', + params: [transactionHash], + }); +} + +export async function getTransactionByBlockHashAndIndex( + requestManager: Web3RequestManager, + blockHash: HexString32Bytes, + transactionIndex: Uint, +) { + validator.validate(['bytes32', 'hex'], [blockHash, transactionIndex]); + + return requestManager.send({ + method: 'eth_getTransactionByBlockHashAndIndex', + params: [blockHash, transactionIndex], + }); +} + +export async function getTransactionByBlockNumberAndIndex( + requestManager: Web3RequestManager, + blockNumber: BlockNumberOrTag, + transactionIndex: Uint, +) { + validator.validate(['blockNumberOrTag', 'hex'], [blockNumber, transactionIndex]); + + return requestManager.send({ + method: 'eth_getTransactionByBlockNumberAndIndex', + params: [blockNumber, transactionIndex], + }); +} + +export async function getTransactionReceipt( + requestManager: Web3RequestManager, + transactionHash: HexString32Bytes, +) { + validator.validate(['bytes32'], [transactionHash]); + + return requestManager.send({ + method: 'eth_getTransactionReceipt', + params: [transactionHash], + }); +} + +export async function getUncleByBlockHashAndIndex( + requestManager: Web3RequestManager, + blockHash: HexString32Bytes, + uncleIndex: Uint, +) { + validator.validate(['bytes32', 'hex'], [blockHash, uncleIndex]); + + return requestManager.send({ + method: 'eth_getUncleByBlockHashAndIndex', + params: [blockHash, uncleIndex], + }); +} + +export async function getUncleByBlockNumberAndIndex( + requestManager: Web3RequestManager, + blockNumber: BlockNumberOrTag, + uncleIndex: Uint, +) { + validator.validate(['blockNumberOrTag', 'hex'], [blockNumber, uncleIndex]); + + return requestManager.send({ + method: 'eth_getUncleByBlockNumberAndIndex', + params: [blockNumber, uncleIndex], + }); +} + +export async function getCompilers(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_getCompilers', + params: [], + }); +} + +export async function compileSolidity(requestManager: Web3RequestManager, code: string) { + validator.validate(['string'], [code]); + + return requestManager.send({ + method: 'eth_compileSolidity', + params: [code], + }); +} + +export async function compileLLL(requestManager: Web3RequestManager, code: string) { + validator.validate(['string'], [code]); + + return requestManager.send({ + method: 'eth_compileLLL', + params: [code], + }); +} + +export async function compileSerpent(requestManager: Web3RequestManager, code: string) { + validator.validate(['string'], [code]); + + return requestManager.send({ + method: 'eth_compileSerpent', + params: [code], + }); +} + +export async function newFilter(requestManager: Web3RequestManager, filter: Filter) { + validator.validate(['filter'], [filter]); + + return requestManager.send({ + method: 'eth_newFilter', + params: [filter], + }); +} + +export async function newBlockFilter(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_newBlockFilter', + params: [], + }); +} + +export async function newPendingTransactionFilter(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_newPendingTransactionFilter', + params: [], + }); +} + +export async function uninstallFilter(requestManager: Web3RequestManager, filterIdentifier: Uint) { + validator.validate(['hex'], [filterIdentifier]); + + return requestManager.send({ + method: 'eth_uninstallFilter', + params: [filterIdentifier], + }); +} + +export async function getFilterChanges(requestManager: Web3RequestManager, filterIdentifier: Uint) { + validator.validate(['hex'], [filterIdentifier]); + + return requestManager.send({ + method: 'eth_getFilterChanges', + params: [filterIdentifier], + }); +} + +export async function getFilterLogs(requestManager: Web3RequestManager, filterIdentifier: Uint) { + validator.validate(['hex'], [filterIdentifier]); + + return requestManager.send({ + method: 'eth_getFilterLogs', + params: [filterIdentifier], + }); +} + +export async function getLogs(requestManager: Web3RequestManager, filter: Filter) { + validator.validate(['filter'], [filter]); + + return requestManager.send({ + method: 'eth_getLogs', + params: [filter], + }); +} + +export async function getWork(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_getWork', + params: [], + }); +} + +export async function submitWork( + requestManager: Web3RequestManager, + nonce: HexString8Bytes, + hash: HexString32Bytes, + digest: HexString32Bytes, +) { + validator.validate(['bytes8', 'bytes32', 'bytes32'], [nonce, hash, digest]); + + return requestManager.send({ + method: 'eth_submitWork', + params: [nonce, hash, digest], + }); +} + +export async function submitHashrate( + requestManager: Web3RequestManager, + hashRate: HexString32Bytes, + id: HexString32Bytes, +) { + validator.validate(['bytes32', 'bytes32'], [hashRate, id]); + + return requestManager.send({ + method: 'eth_submitHashrate', + params: [hashRate, id], + }); +} + +export async function getFeeHistory( + requestManager: Web3RequestManager, + blockCount: Uint, + newestBlock: BlockNumberOrTag, + rewardPercentiles: number[], +) { + validator.validate(['hex', 'blockNumberOrTag'], [blockCount, newestBlock]); + + for (const rewardPercentile of rewardPercentiles) { + validator.validate(['number'], [rewardPercentile]); + } + + return requestManager.send({ + method: 'eth_feeHistory', + params: [blockCount, newestBlock, rewardPercentiles], + }); +} + +export async function getPendingTransactions( + requestManager: Web3RequestManager, +) { + return requestManager.send({ + method: 'eth_pendingTransactions', + params: [], + }); +} + +export async function requestAccounts(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_requestAccounts', + params: [], + }); +} + +export async function getChainId(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'eth_chainId', + params: [], + }); +} + +export async function getProof( + requestManager: Web3RequestManager, + address: Address, + storageKeys: HexString32Bytes[], + blockNumber: BlockNumberOrTag, +) { + validator.validate( + ['address', 'bytes32[]', 'blockNumberOrTag'], + [address, storageKeys, blockNumber], + ); + + return requestManager.send({ + method: 'eth_getProof', + params: [address, storageKeys, blockNumber], + }); +} + +export async function getNodeInfo(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'web3_clientVersion', + params: [], + }); +} + +export async function createAccessList( + requestManager: Web3RequestManager, + transaction: TransactionWithSenderAPI | Partial, + blockNumber: BlockNumberOrTag, +) { + validator.validate(['blockNumberOrTag'], [blockNumber]); + + return requestManager.send({ + method: 'eth_createAccessList', + params: [transaction, blockNumber], + }); +} + +export async function signTypedData( + requestManager: Web3RequestManager, + address: Address, + typedData: Eip712TypedData, + useLegacy = false, +): Promise { + // TODO Add validation for typedData + validator.validate(['address'], [address]); + + return requestManager.send({ + method: `eth_signTypedData${useLegacy ? '' : '_v4'}`, + params: [address, typedData], + }); +} diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/src/index.ts b/test/merkletreejs/node_modules/web3-rpc-methods/src/index.ts new file mode 100644 index 0000000..c2fc512 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/src/index.ts @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import * as ethRpcMethods from './eth_rpc_methods.js'; +import * as netRpcMethods from './net_rpc_methods.js'; +import * as personalRpcMethods from './personal_rpc_methods.js'; + +export { ethRpcMethods, netRpcMethods, personalRpcMethods }; diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/src/net_rpc_methods.ts b/test/merkletreejs/node_modules/web3-rpc-methods/src/net_rpc_methods.ts new file mode 100644 index 0000000..7b638cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/src/net_rpc_methods.ts @@ -0,0 +1,39 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3RequestManager } from 'web3-core'; +import { Web3NetAPI } from 'web3-types'; + +export async function getId(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'net_version', + params: [], + }); +} + +export async function getPeerCount(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'net_peerCount', + params: [], + }); +} + +export async function isListening(requestManager: Web3RequestManager) { + return requestManager.send({ + method: 'net_listening', + params: [], + }); +} diff --git a/test/merkletreejs/node_modules/web3-rpc-methods/src/personal_rpc_methods.ts b/test/merkletreejs/node_modules/web3-rpc-methods/src/personal_rpc_methods.ts new file mode 100644 index 0000000..c73e1c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-rpc-methods/src/personal_rpc_methods.ts @@ -0,0 +1,104 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3RequestManager } from 'web3-core'; +import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; + +export const getAccounts = async (requestManager: Web3RequestManager) => + requestManager.send({ + method: 'personal_listAccounts', + params: [], + }); + +export const newAccount = async ( + requestManager: Web3RequestManager, + password: string, +) => + requestManager.send({ + method: 'personal_newAccount', + params: [password], + }); + +export const unlockAccount = async ( + requestManager: Web3RequestManager, + address: Address, + password: string, + unlockDuration: number, +) => + requestManager.send({ + method: 'personal_unlockAccount', + params: [address, password, unlockDuration], + }); + +export const lockAccount = async ( + requestManager: Web3RequestManager, + address: Address, +) => + requestManager.send({ + method: 'personal_lockAccount', + params: [address], + }); + +export const importRawKey = async ( + requestManager: Web3RequestManager, + keyData: HexString, + passphrase: string, +) => + requestManager.send({ + method: 'personal_importRawKey', + params: [keyData, passphrase], + }); + +export const sendTransaction = async ( + requestManager: Web3RequestManager, + tx: Transaction, + passphrase: string, +) => + requestManager.send({ + method: 'personal_sendTransaction', + params: [tx, passphrase], + }); + +export const signTransaction = async ( + requestManager: Web3RequestManager, + tx: Transaction, + passphrase: string, +) => + requestManager.send({ + method: 'personal_signTransaction', + params: [tx, passphrase], + }); + +export const sign = async ( + requestManager: Web3RequestManager, + data: HexString, + address: Address, + passphrase: string, +) => + requestManager.send({ + method: 'personal_sign', + params: [data, address, passphrase], + }); + +export const ecRecover = async ( + requestManager: Web3RequestManager, + signedData: HexString, + signature: string, +) => + requestManager.send({ + method: 'personal_ecRecover', + params: [signedData, signature], + }); diff --git a/test/merkletreejs/node_modules/web3-types/LICENSE b/test/merkletreejs/node_modules/web3-types/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-types/README.md b/test/merkletreejs/node_modules/web3-types/README.md new file mode 100644 index 0000000..7c15e2d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/README.md @@ -0,0 +1,59 @@ +

+ web3.js +

+ +# web3-types + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-types` contains the common data structures and interfaces used in [web3.js][repo]. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-types) or using [Yarn](https://yarnpkg.com/package/web3-types) + +### Using NPM + +```bash +npm install web3-types +``` + +### Using Yarn + +```bash +yarn add web3-types +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-types +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-types%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-types +[downloads-image]: https://img.shields.io/npm/dm/web3-types?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.d.ts new file mode 100644 index 0000000..d5d0036 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.d.ts @@ -0,0 +1,155 @@ +import { Address, HexString32Bytes, Uint, HexStringBytes, HexStringSingleByte, HexString256Bytes, FeeHistoryBase, HexString8Bytes, Uint256, BlockNumberOrTag, Filter, AccessList, TransactionHash, TransactionReceiptBase, BlockBase, LogBase } from '../eth_types.js'; +import { HexString } from '../primitives_types.js'; +export interface TransactionCallAPI { + readonly from?: Address; + readonly to: Address; + readonly gas?: Uint; + readonly gasPrice?: Uint; + readonly value?: Uint; + readonly data?: HexStringBytes; + readonly type?: HexStringSingleByte; + readonly maxFeePerGas?: Uint; + readonly maxPriorityFeePerGas?: Uint; + readonly accessList?: AccessList; +} +export interface BaseTransactionAPI { + readonly to?: Address | null; + readonly type: HexStringSingleByte; + readonly nonce: Uint; + readonly gas: Uint; + readonly value: Uint; + readonly input: HexStringBytes; + readonly data?: HexStringBytes; + readonly chainId?: Uint; + readonly hash?: HexString32Bytes; +} +export interface Transaction1559UnsignedAPI extends BaseTransactionAPI { + readonly maxFeePerGas: Uint; + readonly maxPriorityFeePerGas: Uint; + readonly accessList: AccessList; + readonly gasPrice: Uint; +} +export interface Transaction1559SignedAPI extends Transaction1559UnsignedAPI { + readonly yParity: Uint; + readonly r: Uint; + readonly s: Uint; + readonly v?: never; +} +export interface Transaction2930UnsignedAPI extends BaseTransactionAPI { + readonly gasPrice: Uint; + readonly accessList: AccessList; + readonly maxFeePerGas?: never; + readonly maxPriorityFeePerGas?: never; +} +export interface Transaction2930SignedAPI extends Transaction2930UnsignedAPI { + readonly yParity: Uint; + readonly r: Uint; + readonly s: Uint; + readonly v?: never; +} +export interface TransactionLegacyUnsignedAPI extends BaseTransactionAPI { + readonly gasPrice: Uint; + readonly accessList?: never; + readonly maxFeePerGas?: never; + readonly maxPriorityFeePerGas?: never; +} +export interface TransactionLegacySignedAPI extends TransactionLegacyUnsignedAPI { + readonly v: Uint; + readonly r: Uint; + readonly s: Uint; +} +export declare type TransactionUnsignedAPI = Transaction1559UnsignedAPI | Transaction2930UnsignedAPI | TransactionLegacyUnsignedAPI; +export declare type TransactionSignedAPI = Transaction1559SignedAPI | Transaction2930SignedAPI | TransactionLegacySignedAPI; +export declare type TransactionInfoAPI = TransactionSignedAPI & { + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: Uint; + readonly from: Address; + readonly hash: HexString32Bytes; + readonly transactionIndex?: Uint; +}; +export interface SignedTransactionInfoAPI { + raw: HexStringBytes; + tx: TransactionSignedAPI; +} +export declare type TransactionWithSenderAPI = TransactionUnsignedAPI & { + from: Address; +}; +export declare type BlockAPI = BlockBase; +export declare type LogAPI = LogBase; +export declare type TransactionReceiptAPI = TransactionReceiptBase; +export declare type SyncingStatusAPI = { + startingBlock: Uint; + currentBlock: Uint; + highestBlock: Uint; +} | boolean; +export declare type FeeHistoryResultAPI = FeeHistoryBase; +export declare type FilterResultsAPI = HexString32Bytes[] | LogAPI[]; +export interface CompileResultAPI { + readonly code: HexStringBytes; + readonly info: { + readonly source: string; + readonly language: string; + readonly languageVersion: string; + readonly compilerVersion: string; + readonly abiDefinition: Record[]; + readonly userDoc: { + readonly methods: Record; + }; + readonly developerDoc: { + readonly methods: Record; + }; + }; +} +export declare type EthExecutionAPI = { + eth_getBlockByHash: (blockHash: HexString32Bytes, hydrated: boolean) => BlockAPI; + eth_getBlockByNumber: (blockNumber: BlockNumberOrTag, hydrated: boolean) => BlockAPI; + eth_getBlockTransactionCountByHash: (blockHash: HexString32Bytes) => Uint; + eth_getBlockTransactionCountByNumber: (blockNumber: BlockNumberOrTag) => Uint; + eth_getUncleCountByBlockHash: (blockHash: HexString32Bytes) => Uint; + eth_getUncleCountByBlockNumber: (blockNumber: BlockNumberOrTag) => Uint; + eth_getUncleByBlockHashAndIndex: (blockHash: HexString32Bytes, uncleIndex: Uint) => BlockAPI; + eth_getUncleByBlockNumberAndIndex: (blockNumber: BlockNumberOrTag, uncleIndex: Uint) => BlockAPI; + eth_getTransactionByHash: (transactionHash: HexString32Bytes) => TransactionInfoAPI | undefined; + eth_getTransactionByBlockHashAndIndex: (blockHash: HexString32Bytes, transactionIndex: Uint) => TransactionInfoAPI | undefined; + eth_getTransactionByBlockNumberAndIndex: (blockNumber: BlockNumberOrTag, transactionIndex: Uint) => TransactionInfoAPI | undefined; + eth_getTransactionReceipt: (transactionHash: HexString32Bytes) => TransactionReceiptAPI | undefined; + eth_protocolVersion: () => string; + eth_syncing: () => SyncingStatusAPI; + eth_coinbase: () => Address; + eth_accounts: () => Address[]; + eth_blockNumber: () => Uint; + eth_call: (transaction: TransactionCallAPI, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_estimateGas: (transaction: Partial, blockNumber: BlockNumberOrTag) => Uint; + eth_gasPrice: () => Uint; + eth_feeHistory: (blockCount: Uint, newestBlock: BlockNumberOrTag, rewardPercentiles: number[]) => FeeHistoryResultAPI; + eth_newFilter: (filter: Filter) => Uint; + eth_newBlockFilter: () => Uint; + eth_newPendingTransactionFilter: () => Uint; + eth_uninstallFilter: (filterIdentifier: Uint) => boolean; + eth_getFilterChanges: (filterIdentifier: Uint) => FilterResultsAPI; + eth_getFilterLogs: (filterIdentifier: Uint) => FilterResultsAPI; + eth_getLogs: (filter: Filter) => FilterResultsAPI; + eth_mining: () => boolean; + eth_hashrate: () => Uint; + eth_getWork: () => [HexString32Bytes, HexString32Bytes, HexString32Bytes]; + eth_submitWork: (nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes) => boolean; + eth_submitHashrate: (hashRate: HexString32Bytes, id: HexString32Bytes) => boolean; + eth_sign: (address: Address, message: HexStringBytes) => HexString256Bytes; + eth_signTransaction: (transaction: TransactionWithSenderAPI | Partial) => HexStringBytes | SignedTransactionInfoAPI; + eth_getBalance: (address: Address, blockNumber: BlockNumberOrTag) => Uint; + eth_getStorageAt: (address: Address, storageSlot: Uint256, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_getTransactionCount: (address: Address, blockNumber: BlockNumberOrTag) => Uint; + eth_getCode: (address: Address, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_sendTransaction: (transaction: TransactionWithSenderAPI | Partial) => HexString32Bytes; + eth_sendRawTransaction: (transaction: HexStringBytes) => HexString32Bytes; + eth_subscribe: (...params: ['newHeads'] | ['newPendingTransactions'] | ['syncing'] | ['logs', { + address?: HexString; + topics?: HexString[]; + }]) => HexString; + eth_unsubscribe: (subscriptionId: HexString) => HexString; + eth_clearSubscriptions: (keepSyncing?: boolean) => void; + eth_getCompilers: () => string[]; + eth_compileSolidity: (code: string) => CompileResultAPI; + eth_compileLLL: (code: string) => HexStringBytes; + eth_compileSerpent: (code: string) => HexStringBytes; +}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.js new file mode 100644 index 0000000..86d8465 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=eth_execution_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.js.map new file mode 100644 index 0000000..8343249 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_execution_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_execution_api.js","sourceRoot":"","sources":["../../../src/apis/eth_execution_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.d.ts new file mode 100644 index 0000000..0798a45 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.d.ts @@ -0,0 +1,13 @@ +import { Address, Transaction } from '../eth_types.js'; +import { HexString } from '../primitives_types.js'; +export declare type EthPersonalAPI = { + personal_listAccounts: () => Address[]; + personal_newAccount: (password: string) => Address; + personal_unlockAccount: (address: Address, password: string, unlockDuration: number) => boolean; + personal_lockAccount: (address: Address) => boolean; + personal_importRawKey: (keyData: HexString, passphrase: string) => HexString; + personal_sendTransaction: (tx: Transaction, passphrase: string) => HexString; + personal_signTransaction: (tx: Transaction, passphrase: string) => HexString; + personal_sign: (data: HexString, address: Address, passphrase: string) => HexString; + personal_ecRecover: (signedData: HexString, signature: HexString) => Address; +}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.js new file mode 100644 index 0000000..85fde63 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=eth_personal_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.js.map new file mode 100644 index 0000000..40df4a0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/eth_personal_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_personal_api.js","sourceRoot":"","sources":["../../../src/apis/eth_personal_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.d.ts new file mode 100644 index 0000000..9b62578 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.d.ts @@ -0,0 +1,11 @@ +import { EthExecutionAPI } from './eth_execution_api.js'; +import { AccountObject, Address, BlockNumberOrTag, Eip712TypedData, HexString256Bytes, HexString32Bytes, TransactionInfo, Uint } from '../eth_types.js'; +export declare type Web3EthExecutionAPI = EthExecutionAPI & { + eth_pendingTransactions: () => TransactionInfo[]; + eth_requestAccounts: () => Address[]; + eth_chainId: () => Uint; + web3_clientVersion: () => string; + eth_getProof: (address: Address, storageKeys: HexString32Bytes[], blockNumber: BlockNumberOrTag) => AccountObject; + eth_signTypedData: (address: Address, typedData: Eip712TypedData, useLegacy: true) => HexString256Bytes; + eth_signTypedData_v4: (address: Address, typedData: Eip712TypedData, useLegacy: false | undefined) => HexString256Bytes; +}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.js new file mode 100644 index 0000000..f6af48d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=web3_eth_execution_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.js.map new file mode 100644 index 0000000..9650ada --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_eth_execution_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eth_execution_api.js","sourceRoot":"","sources":["../../../src/apis/web3_eth_execution_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.d.ts new file mode 100644 index 0000000..6b9baf2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.d.ts @@ -0,0 +1,6 @@ +import { HexString } from '../primitives_types.js'; +export declare type Web3NetAPI = { + net_version: () => string; + net_peerCount: () => HexString; + net_listening: () => boolean; +}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.js new file mode 100644 index 0000000..cbaf033 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=web3_net_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.js.map new file mode 100644 index 0000000..92dd3f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/apis/web3_net_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_net_api.js","sourceRoot":"","sources":["../../../src/apis/web3_net_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.d.ts new file mode 100644 index 0000000..a354daa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.d.ts @@ -0,0 +1,36 @@ +import { Bytes, HexString, Numbers } from './primitives_types.js'; +export declare enum FMT_NUMBER { + NUMBER = "NUMBER_NUMBER", + HEX = "NUMBER_HEX", + STR = "NUMBER_STR", + BIGINT = "NUMBER_BIGINT" +} +export declare type NumberTypes = { + [FMT_NUMBER.NUMBER]: number; + [FMT_NUMBER.HEX]: HexString; + [FMT_NUMBER.STR]: string; + [FMT_NUMBER.BIGINT]: bigint; +}; +export declare enum FMT_BYTES { + HEX = "BYTES_HEX", + UINT8ARRAY = "BYTES_UINT8ARRAY" +} +export declare type ByteTypes = { + [FMT_BYTES.HEX]: HexString; + [FMT_BYTES.UINT8ARRAY]: Uint8Array; +}; +export declare type DataFormat = { + readonly number: FMT_NUMBER; + readonly bytes: FMT_BYTES; +}; +export declare const DEFAULT_RETURN_FORMAT: { + readonly number: FMT_NUMBER.BIGINT; + readonly bytes: FMT_BYTES.HEX; +}; +export declare const ETH_DATA_FORMAT: { + readonly number: FMT_NUMBER.HEX; + readonly bytes: FMT_BYTES.HEX; +}; +export declare type FormatType = number extends Extract ? NumberTypes[F['number']] | Exclude : Uint8Array extends Extract ? ByteTypes[F['bytes']] | Exclude : T extends object | undefined ? { + [P in keyof T]: FormatType; +} : T; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.js new file mode 100644 index 0000000..2399ae1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.js @@ -0,0 +1,34 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ETH_DATA_FORMAT = exports.DEFAULT_RETURN_FORMAT = exports.FMT_BYTES = exports.FMT_NUMBER = void 0; +var FMT_NUMBER; +(function (FMT_NUMBER) { + FMT_NUMBER["NUMBER"] = "NUMBER_NUMBER"; + FMT_NUMBER["HEX"] = "NUMBER_HEX"; + FMT_NUMBER["STR"] = "NUMBER_STR"; + FMT_NUMBER["BIGINT"] = "NUMBER_BIGINT"; +})(FMT_NUMBER = exports.FMT_NUMBER || (exports.FMT_NUMBER = {})); +var FMT_BYTES; +(function (FMT_BYTES) { + FMT_BYTES["HEX"] = "BYTES_HEX"; + FMT_BYTES["UINT8ARRAY"] = "BYTES_UINT8ARRAY"; +})(FMT_BYTES = exports.FMT_BYTES || (exports.FMT_BYTES = {})); +exports.DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX }; +exports.ETH_DATA_FORMAT = { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX }; +//# sourceMappingURL=data_format_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.js.map new file mode 100644 index 0000000..6158d96 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/data_format_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"data_format_types.js","sourceRoot":"","sources":["../../src/data_format_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAIF,IAAY,UAKX;AALD,WAAY,UAAU;IACrB,sCAAwB,CAAA;IACxB,gCAAkB,CAAA;IAClB,gCAAkB,CAAA;IAClB,sCAAwB,CAAA;AACzB,CAAC,EALW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAKrB;AASD,IAAY,SAGX;AAHD,WAAY,SAAS;IACpB,8BAAiB,CAAA;IACjB,4CAA+B,CAAA;AAChC,CAAC,EAHW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAGpB;AAYY,QAAA,qBAAqB,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,EAAW,CAAC;AACrF,QAAA,eAAe,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,EAAW,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.d.ts new file mode 100644 index 0000000..0bd6f41 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.d.ts @@ -0,0 +1,15 @@ +export interface Web3Error extends Error { + readonly name: string; + readonly code: number; + readonly stack?: string; +} +export declare type Web3ValidationErrorObject, S = unknown> = { + keyword: K; + instancePath: string; + schemaPath: string; + params: P; + propertyName?: string; + message?: string; + schema?: S; + data?: unknown; +}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.js new file mode 100644 index 0000000..cfcd403 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=error_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.js.map new file mode 100644 index 0000000..dddb3df --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/error_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error_types.js","sourceRoot":"","sources":["../../src/error_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.d.ts new file mode 100644 index 0000000..a2d484f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.d.ts @@ -0,0 +1,156 @@ +import { Address } from './eth_types.js'; +import { Bytes, Numbers } from './primitives_types.js'; +import { FixedSizeArray } from './utility_types.js'; +declare type _SolidityIndexRange = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 25 | 26 | 27 | 28 | 29 | 30; +export declare type ConvertToNumber = Range extends unknown ? (`${Range}` extends T ? Range : never) : never; +export declare type Components = { + name: string; + type: string; + indexed?: boolean; + components?: Components[]; +}; +export interface AbiStruct { + [key: string]: unknown; + name: string; + type: string; +} +export interface AbiCoderStruct extends AbiStruct { + [key: string]: unknown; + components?: Array; +} +export declare type AbiParameter = { + readonly name: string; + readonly type: string; + readonly baseType?: string; + readonly indexed?: boolean; + readonly components?: ReadonlyArray; + readonly arrayLength?: number; + readonly arrayChildren?: ReadonlyArray; + readonly internalType?: string; +}; +declare type FragmentTypes = 'constructor' | 'event' | 'function' | 'fallback' | 'receive'; +export declare type AbiBaseFragment = { + readonly type: string | FragmentTypes; +}; +export declare type AbiConstructorFragment = AbiBaseFragment & { + readonly type: string | 'constructor'; + readonly stateMutability: string | 'nonpayable' | 'payable'; + readonly inputs?: ReadonlyArray; +}; +export declare type AbiFunctionFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'function'; + readonly stateMutability?: string | 'nonpayable' | 'payable' | 'pure' | 'view'; + readonly inputs?: ReadonlyArray; + readonly outputs?: ReadonlyArray; + readonly constant?: boolean; + readonly payable?: boolean; +}; +export declare type AbiFallbackFragment = AbiBaseFragment & { + readonly name: never; + readonly type: string | 'fallback'; + readonly stateMutability: string | 'nonpayable' | 'payable' | 'pure' | 'view'; + readonly inputs: never; + readonly outputs: never; + readonly constant?: boolean; + readonly payable?: boolean; +}; +export declare type AbiEventFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'event'; + readonly inputs?: ReadonlyArray; + readonly anonymous?: boolean; +}; +export declare type AbiErrorFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'error'; + readonly inputs?: ReadonlyArray; +}; +export declare type AbiFragment = AbiConstructorFragment | AbiFunctionFragment | AbiEventFragment | AbiErrorFragment | AbiFallbackFragment; +export declare type ContractAbi = ReadonlyArray; +export declare type AbiInput = string | AbiParameter | { + name: string; + type: string; + components?: Components; + index?: boolean; + internalType?: string; +} | { + readonly [key: string]: unknown; +}; +export declare type JsonFunctionInterface = { + type: 'function'; + name: string; + inputs: Components[]; + outputs?: AbiInput[]; + stateMutability?: string; +}; +export declare type JsonEventInterface = { + type: 'event'; + name: string; + inputs: Components[]; + indexed: boolean; + anonymous: boolean; +}; +export declare type FilterAbis = Abi extends Filter ? Abi : never; +declare type _TypedArray = Size extends '' ? Type[] : FixedSizeArray>; +export declare type PrimitiveAddressType = Type extends `address[${infer Size}]` ? _TypedArray : Type extends 'address' ? Address : never; +export declare type PrimitiveStringType = Type extends `string${string}[${infer Size}]` ? _TypedArray : Type extends 'string' | `string${string}` ? string : never; +export declare type PrimitiveBooleanType = Type extends `bool[${infer Size}]` ? _TypedArray : Type extends 'bool' ? boolean : never; +export declare type PrimitiveIntegerType = Type extends `uint${string}[${infer Size}]` | `int${string}[${infer Size}]` ? _TypedArray : Type extends 'uint' | 'int' | `int${string}` | `uint${string}` ? Numbers : never; +export declare type PrimitiveBytesType = Type extends `bytes${string}[${infer Size}]` ? _TypedArray : Type extends 'bytes' | `bytes${string}` ? Bytes : never; +export declare type PrimitiveTupleType | undefined | unknown = []> = TypeComponents extends ReadonlyArray ? Type extends 'tuple' ? { + [Param in TypeComponents[number] as Param['name']]: MatchPrimitiveType; +} : Type extends `tuple[${infer Size}]` ? _TypedArray<{ + [Param in TypeComponents[number] as Param['name']]: MatchPrimitiveType; +}, Size> : never : never; +declare type ObjectToArray = T extends [...infer R, infer A] ? Record & ObjectToArray : T; +declare type ArrToObjectWithFunctions = Array & ObjectToArray; +export declare type MatchPrimitiveType | undefined | unknown> = PrimitiveAddressType | PrimitiveStringType | PrimitiveBooleanType | PrimitiveIntegerType | PrimitiveBytesType | PrimitiveTupleType | never; +declare type ContractMethodOutputParametersRecursiveArray | undefined> = Params extends readonly [] ? [] : Params extends readonly [infer H, ...infer R] ? H extends AbiParameter ? [ + MatchPrimitiveType, + ...ContractMethodOutputParametersRecursiveArray +] : [] : []; +declare type ContractMethodOutputParametersRecursiveRecord | undefined> = Params extends readonly [] ? [] : Params extends readonly [infer H, ...infer R] ? H extends AbiParameter ? H['name'] extends '' ? ContractMethodOutputParametersRecursiveRecord : Record> & // sets key-value pair of output param name and type +ContractMethodOutputParametersRecursiveRecord : ContractMethodOutputParametersRecursiveRecord : Params extends undefined | unknown ? [] : Params; +export declare type ContractMethodOutputParameters | undefined> = Params extends readonly [] ? void : Params extends readonly [infer H, ...infer R] ? R extends readonly [] ? H extends AbiParameter ? MatchPrimitiveType : [] : // if more than one output +ArrToObjectWithFunctions<[...ContractMethodOutputParametersRecursiveArray]> & ContractMethodOutputParametersRecursiveRecord : []; +export declare type ContractMethodInputParameters | undefined> = Params extends readonly [] ? [] : Params extends readonly [infer H, ...infer R] ? H extends AbiParameter ? [ + MatchPrimitiveType, + ...ContractMethodInputParameters +] : ContractMethodInputParameters : Params extends undefined | unknown ? [] : Params; +export declare type ContractConstructor = { + [Abi in FilterAbis as 'constructor']: { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; + }; +}['constructor']; +export declare type ContractConstructorArgs = { + [Abi in FilterAbis as 'constructor']: ContractMethodInputParameters; +}['constructor']; +export declare type ContractMethod = { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; + readonly Outputs: ContractMethodOutputParameters; +}; +export declare type ContractMethods = { + [Abi in FilterAbis as Abi['name']]: ContractMethod; +}; +export declare type ContractEvent = { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; +}; +export declare type ContractEvents = { + [Abi in FilterAbis as Abi['name']]: ContractEvent; +}; +export interface DecodedParams extends Record { + __length__: number; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.js new file mode 100644 index 0000000..c90eaeb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=eth_abi_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.js.map new file mode 100644 index 0000000..f17f3b1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_abi_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_abi_types.js","sourceRoot":"","sources":["../../src/eth_abi_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.d.ts new file mode 100644 index 0000000..7de726e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.d.ts @@ -0,0 +1,133 @@ +import { Address, Uint } from './eth_types.js'; +import { SupportedProviders } from './web3_base_provider.js'; +import { Bytes, HexString } from './primitives_types.js'; +import { EthExecutionAPI } from './apis/eth_execution_api.js'; +import { AbiFragment, ContractAbi } from './eth_abi_types.js'; +export interface ContractInitOptions { + /** + * The maximum gas provided for a transaction (gas limit). + */ + readonly gas?: Uint; + readonly gasLimit?: Uint; + /** + * The gas price in wei to use for transactions. + */ + readonly gasPrice?: Uint; + /** + * The address transactions should be made from + */ + readonly from?: Address; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly data?: Bytes; + readonly input?: Bytes; + readonly provider?: SupportedProviders | string; + /** + * If `true`, the defaults of the contract instance will be updated automatically based on the changes of the context used to instantiate the contract. + */ + readonly syncWithContext?: boolean; + readonly dataInputFill?: 'data' | 'input' | 'both'; +} +export interface NonPayableCallOptions { + nonce?: HexString; + /** + * The address which is the call (the transaction) should be made from. For calls the `from` property is optional however it is + * highly recommended to explicitly set it or it may default to address(0) depending on your node or provider. + */ + from?: Address; + /** + * The maximum gas (gas limit) provided for this call (this transaction) + */ + gas?: string; + maxPriorityFeePerGas?: HexString; + maxFeePerGas?: HexString; + /** + * The gas price in wei to use for this call `transaction`. + */ + gasPrice?: string; + type?: string | number; + data?: HexString; + input?: HexString; +} +export interface PayableCallOptions extends NonPayableCallOptions { + /** + * + */ + value?: string; +} +export declare type ContractAbiWithSignature = ReadonlyArray; +export interface ContractOptions { + /** + * The maximum gas provided for a transaction (gas limit). + */ + readonly gas?: Uint; + /** + * The gas price in wei to use for transactions. + */ + readonly gasPrice?: Uint; + /** + * The address transactions should be made from. + */ + readonly from?: Address; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly input?: Bytes; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly data?: Bytes; + /** + * The {@doclink glossary/json_interface | json interface} object derived from the [ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) of this contract. + * + * Re-setting this will regenerate the methods and events of the contract instance. + * + * ```ts + * myContract.options.jsonInterface; + * > [{ + * "type":"function", + * "name":"foo", + * "inputs": [{"name":"a","type":"uint256"}], + * "outputs": [{"name":"b","type":"address"}], + * "signature": "0x...", + * },{ + * "type":"event", + * "name":"Event", + * "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}], + * "signature": "0x...", + * }] + * + * // Set a new ABI interface + * // Note: the "signature" of every function and event's ABI is not needed to be provided when assigning. + * // It will be calculated and set automatically inside the setter. + * myContract.options.jsonInterface = [...]; + * ``` + */ + get jsonInterface(): ContractAbiWithSignature; + set jsonInterface(value: ContractAbi); + /** + * The address used for this contract instance. All transactions generated by web3.js from this contract will contain this address as the `to`. + * + * The address will be stored in lowercase. + * + * ```ts + * myContract.options.address; + * > '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae' + * + * // set a new address + * myContract.options.address = '0x1234FFDD...'; + * ``` + */ + address?: Address; + /** + * The max priority fee per gas to use for transactions. + */ + maxPriorityFeePerGas?: Uint; + /** + * The max fee per gas to use for transactions. + */ + maxFeePerGas?: Uint; +} diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.js new file mode 100644 index 0000000..942c9e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=eth_contract_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.js.map new file mode 100644 index 0000000..c5e31a3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_contract_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_contract_types.js","sourceRoot":"","sources":["../../src/eth_contract_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.d.ts new file mode 100644 index 0000000..0b6e288 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.d.ts @@ -0,0 +1,440 @@ +import { Bytes, HexString, Numbers } from './primitives_types.js'; +export declare type ValueTypes = 'address' | 'bool' | 'string' | 'int256' | 'uint256' | 'bytes' | 'bigint'; +export declare type HexString32Bytes = HexString; +export declare type HexString16Bytes = HexString; +export declare type HexString8Bytes = HexString; +export declare type HexStringSingleByte = HexString; +export declare type HexStringBytes = HexString; +export declare type HexString256Bytes = HexString; +export declare type Uint = HexString; +export declare type Uint256 = HexString; +export declare type Address = HexString; +export declare type Topic = HexString32Bytes; +export declare type TransactionHash = HexString; +export declare type Uncles = HexString32Bytes[]; +export declare enum BlockTags { + EARLIEST = "earliest", + LATEST = "latest", + PENDING = "pending", + SAFE = "safe", + FINALIZED = "finalized" +} +export declare type BlockTag = `${BlockTags}`; +export declare type BlockNumberOrTag = Numbers | BlockTag; +export interface Proof { + readonly address: HexString; + readonly nonce: string; + readonly balance: string; +} +export interface TransactionInput { + readonly [key: string]: unknown; + readonly to?: HexString; + readonly from?: HexString; + readonly data?: string; + readonly input?: string; + readonly gas: HexString; + readonly gasLimit?: string; + readonly gasPrice?: string; + readonly maxPriorityFeePerGas?: string; + readonly maxFeePerGas?: string; + readonly nonce: string; + readonly value: string; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly type?: HexString; + readonly chainId?: HexString; +} +export declare type TransactionOutput = { + readonly [key: string]: unknown; + readonly to?: HexString; + readonly from?: HexString; + readonly input: string; + readonly gas?: Numbers; + readonly gasLimit?: string; + readonly nonce: Numbers; + readonly value: Numbers; + readonly blockNumber?: Numbers; + readonly transactionIndex?: Numbers; +} & ({ + maxPriorityFeePerGas: Numbers; + maxFeePerGas: Numbers; + gasPrice?: never; +} | { + maxPriorityFeePerGas?: never; + maxFeePerGas?: never; + gasPrice: Numbers; +}); +export interface LogsInput { + readonly blockHash?: HexString; + readonly transactionHash?: HexString; + readonly logIndex?: HexString; + readonly id?: string; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly address: HexString; + readonly topics: HexString[]; + readonly data: HexString; +} +export interface LogsOutput { + readonly id?: string; + readonly removed: boolean; + readonly logIndex?: Numbers; + readonly transactionIndex?: Numbers; + readonly transactionHash?: HexString32Bytes; + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: Numbers; + readonly address: string; + readonly topics: HexString[]; + readonly data: HexString; +} +export interface BlockInput { + readonly gasLimit: HexString; + readonly gasUsed: HexString; + readonly size: HexString; + readonly timestamp: HexString; + readonly number?: HexString; + readonly difficulty?: HexString; + readonly totalDifficulty?: HexString; + readonly transactions?: TransactionInput[]; + readonly miner?: HexString; + readonly baseFeePerGas?: HexString; +} +export interface BlockOutput { + readonly gasLimit: bigint | number; + readonly gasUsed: bigint | number; + readonly size: bigint | number; + readonly timestamp: bigint | number; + readonly number?: bigint | number; + readonly difficulty?: bigint | number; + readonly totalDifficulty?: bigint | number; + readonly transactions?: TransactionOutput[]; + readonly miner?: HexString; + readonly baseFeePerGas?: bigint | number; + readonly parentHash?: HexString32Bytes; +} +export interface Withdrawals { + readonly index: Numbers; + readonly validatorIndex: Numbers; + readonly address: Address; + readonly amount: Numbers; +} +export interface BlockHeaderOutput { + readonly hash?: HexString32Bytes; + readonly parentHash?: HexString32Bytes; + readonly receiptsRoot?: HexString32Bytes; + readonly miner?: HexString; + readonly stateRoot?: HexString32Bytes; + readonly transactionsRoot?: HexString32Bytes; + readonly withdrawalsRoot?: HexString32Bytes; + readonly logsBloom?: Bytes; + readonly difficulty?: Numbers; + readonly number?: Numbers; + readonly gasLimit: Numbers; + readonly gasUsed: Numbers; + readonly timestamp: Numbers; + readonly extraData?: Bytes; + readonly nonce?: Numbers; + readonly sha3Uncles: HexString32Bytes[]; + readonly baseFeePerGas?: Numbers; + readonly author?: Address; + readonly totalDifficulty?: Numbers; + readonly size?: Numbers; + readonly excessDataGas?: Numbers; + readonly mixHash?: HexString32Bytes; + readonly transactions?: TransactionOutput[]; + readonly uncles?: Uncles; + readonly withdrawals?: Withdrawals[]; +} +export interface ReceiptInput { + readonly [x: string]: unknown; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly cumulativeGasUsed: HexString; + readonly gasUsed: HexString; + readonly logs?: LogsInput[]; + readonly contractAddress?: HexString; + readonly status?: string; + readonly effectiveGasPrice?: HexString; +} +export interface ReceiptOutput { + readonly blockNumber?: bigint | number; + readonly transactionIndex?: bigint | number; + readonly cumulativeGasUsed: bigint | number; + readonly gasUsed: bigint | number; + readonly logs?: LogsOutput[]; + readonly contractAddress?: HexString; + readonly status: boolean; + readonly effectiveGasPrice?: bigint | number; +} +export interface PostInput { + readonly ttl?: HexString; + readonly workToProve?: HexString; + readonly priority?: HexString; + readonly expiry?: HexString; + readonly sent?: HexString; + readonly workProved?: HexString; + readonly topics?: HexString[]; +} +export interface PostOutput { + readonly ttl?: bigint | number; + readonly workToProve?: bigint | number; + readonly priority?: bigint | number; + readonly expiry?: bigint | number; + readonly sent?: bigint | number; + readonly workProved?: bigint | number; + readonly topics?: string[]; +} +export interface SyncInput { + readonly startingBlock: HexString; + readonly currentBlock: HexString; + readonly highestBlock: HexString; + readonly knownStates?: HexString; + readonly pulledStates?: HexString; +} +export interface SyncOutput { + readonly startingBlock: Numbers; + readonly currentBlock: Numbers; + readonly highestBlock: Numbers; + readonly knownStates?: Numbers; + readonly pulledStates?: Numbers; +} +export declare type Receipt = Record; +declare type FilterOption = Record; +export interface Filter { + readonly fromBlock?: BlockNumberOrTag; + readonly toBlock?: BlockNumberOrTag; + readonly address?: Address | Address[]; + readonly blockHash?: Address; + readonly topics?: (null | Topic | Topic[])[]; + readonly filter?: FilterOption; +} +export interface AccessListEntry { + readonly address?: Address; + readonly storageKeys?: HexString32Bytes[]; +} +export declare type AccessList = AccessListEntry[]; +export declare type AccessListResult = { + readonly accessList?: AccessList; + readonly gasUsed?: Numbers; +}; +export declare type ValidChains = 'goerli' | 'kovan' | 'mainnet' | 'rinkeby' | 'ropsten' | 'sepolia'; +export declare enum HardforksOrdered { + chainstart = "chainstart", + frontier = "frontier", + homestead = "homestead", + dao = "dao", + tangerineWhistle = "tangerineWhistle", + spuriousDragon = "spuriousDragon", + byzantium = "byzantium", + constantinople = "constantinople", + petersburg = "petersburg", + istanbul = "istanbul", + muirGlacier = "muirGlacier", + berlin = "berlin", + london = "london", + altair = "altair", + arrowGlacier = "arrowGlacier", + grayGlacier = "grayGlacier", + bellatrix = "bellatrix", + merge = "merge", + capella = "capella", + shanghai = "shanghai" +} +export declare type Hardfork = `${HardforksOrdered}`; +export interface LogBase { + readonly removed?: boolean; + readonly logIndex?: NumberType; + readonly transactionIndex?: NumberType; + readonly transactionHash?: ByteType; + readonly blockHash?: ByteType; + readonly blockNumber?: NumberType; + readonly address?: Address; + readonly data?: ByteType; + readonly topics?: ByteType[]; + readonly id?: string; +} +export interface Log extends LogBase { + readonly id?: string; +} +export interface EventLog { + readonly event: string; + readonly id?: string; + readonly logIndex?: bigint | number | string; + readonly transactionIndex?: bigint | number | string; + readonly transactionHash?: HexString32Bytes; + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: bigint | number | string; + readonly address: string; + readonly topics: HexString[]; + readonly data: HexString; + readonly raw?: { + data: string; + topics: unknown[]; + }; + readonly returnValues: Record; + readonly signature?: HexString; +} +export interface TransactionReceiptBase { + readonly transactionHash: hashByteType; + readonly transactionIndex: numberType; + readonly blockHash: hashByteType; + readonly blockNumber: numberType; + readonly from: Address; + readonly to: Address; + readonly cumulativeGasUsed: numberType; + readonly gasUsed: numberType; + readonly effectiveGasPrice?: numberType; + readonly contractAddress?: Address; + readonly logs: logsType[]; + readonly logsBloom: logsBloomByteType; + readonly root: hashByteType; + readonly status: numberType; + readonly type?: numberType; + events?: { + [key: string]: EventLog; + }; +} +export declare type TransactionReceipt = TransactionReceiptBase; +export interface CustomChain { + name?: string; + networkId: Numbers; + chainId: Numbers; +} +export interface Common { + customChain: CustomChain; + baseChain?: ValidChains; + hardfork?: Hardfork; +} +interface TransactionBase { + value?: Numbers; + accessList?: AccessList; + common?: Common; + gas?: Numbers; + gasPrice?: Numbers; + type?: Numbers; + maxFeePerGas?: Numbers; + maxPriorityFeePerGas?: Numbers; + data?: Bytes; + input?: Bytes; + nonce?: Numbers; + chain?: ValidChains; + hardfork?: Hardfork; + chainId?: Numbers; + networkId?: Numbers; + gasLimit?: Numbers; + yParity?: Uint; + v?: Numbers; + r?: Bytes; + s?: Bytes; +} +export interface Transaction extends TransactionBase { + from?: Address; + to?: Address | null; +} +export interface TransactionForAccessList extends Transaction { + from: Address; +} +export interface TransactionCall extends Transaction { + to: Address; +} +export interface TransactionWithFromLocalWalletIndex extends Omit { + from: Numbers; +} +export interface TransactionWithToLocalWalletIndex extends Omit { + to: Numbers; +} +export interface TransactionWithFromAndToLocalWalletIndex extends Omit { + from: Numbers; + to: Numbers; +} +export interface TransactionInfo extends Transaction { + readonly blockHash?: Bytes; + readonly blockNumber?: Numbers; + readonly from: Address; + readonly hash: Bytes; + readonly transactionIndex?: Numbers; +} +export interface PopulatedUnsignedBaseTransaction { + from: Address; + to?: Address; + value: Numbers; + gas?: Numbers; + gasPrice: Numbers; + type: Numbers; + input?: Bytes; + data?: Bytes; + nonce: Numbers; + networkId: Numbers; + chain: ValidChains; + hardfork: Hardfork; + chainId: Numbers; + common: Common; + gasLimit: Numbers; +} +export interface PopulatedUnsignedEip2930Transaction extends PopulatedUnsignedBaseTransaction { + accessList: AccessList; +} +export interface PopulatedUnsignedEip1559Transaction extends PopulatedUnsignedEip2930Transaction { + gasPrice: never; + maxFeePerGas: Numbers; + maxPriorityFeePerGas: Numbers; +} +export declare type PopulatedUnsignedTransaction = PopulatedUnsignedBaseTransaction | PopulatedUnsignedEip2930Transaction | PopulatedUnsignedEip1559Transaction; +export interface BlockBase { + readonly parentHash: ByteType; + readonly sha3Uncles: ByteType; + readonly miner: HexStringType; + readonly stateRoot: ByteType; + readonly transactionsRoot: ByteType; + readonly receiptsRoot: ByteType; + readonly logsBloom?: logsBloomType; + readonly difficulty?: NumberType; + readonly number: NumberType; + readonly gasLimit: NumberType; + readonly gasUsed: NumberType; + readonly timestamp: NumberType; + readonly extraData: extraDataType; + readonly mixHash: ByteType; + readonly nonce: NumberType; + readonly totalDifficulty: NumberType; + readonly baseFeePerGas?: NumberType; + readonly size: NumberType; + readonly transactions: TransactionTypes; + readonly uncles: Uncles; + readonly hash?: ByteType; +} +export declare type Block = BlockBase; +export interface FeeHistoryBase { + readonly oldestBlock: NumberType; + readonly baseFeePerGas: NumberType; + readonly reward: NumberType[][]; + readonly gasUsedRatio: NumberType[]; +} +export declare type FeeHistory = FeeHistoryBase; +export interface StorageProof { + readonly key: Bytes; + readonly value: Numbers; + readonly proof: Bytes[]; +} +export interface AccountObject { + readonly balance: Numbers; + readonly codeHash: Bytes; + readonly nonce: Numbers; + readonly storageHash: Bytes; + readonly accountProof: Bytes[]; + readonly storageProof: StorageProof[]; +} +export interface Eip712TypeDetails { + name: string; + type: string; +} +export interface Eip712TypedData { + readonly types: { + EIP712Domain: Eip712TypeDetails[]; + [key: string]: Eip712TypeDetails[]; + }; + readonly primaryType: string; + readonly domain: Record; + readonly message: Record; +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.js new file mode 100644 index 0000000..db6eb13 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HardforksOrdered = exports.BlockTags = void 0; +var BlockTags; +(function (BlockTags) { + BlockTags["EARLIEST"] = "earliest"; + BlockTags["LATEST"] = "latest"; + BlockTags["PENDING"] = "pending"; + BlockTags["SAFE"] = "safe"; + BlockTags["FINALIZED"] = "finalized"; +})(BlockTags = exports.BlockTags || (exports.BlockTags = {})); +// This list of hardforks is expected to be in order +// keep this in mind when making changes to it +var HardforksOrdered; +(function (HardforksOrdered) { + HardforksOrdered["chainstart"] = "chainstart"; + HardforksOrdered["frontier"] = "frontier"; + HardforksOrdered["homestead"] = "homestead"; + HardforksOrdered["dao"] = "dao"; + HardforksOrdered["tangerineWhistle"] = "tangerineWhistle"; + HardforksOrdered["spuriousDragon"] = "spuriousDragon"; + HardforksOrdered["byzantium"] = "byzantium"; + HardforksOrdered["constantinople"] = "constantinople"; + HardforksOrdered["petersburg"] = "petersburg"; + HardforksOrdered["istanbul"] = "istanbul"; + HardforksOrdered["muirGlacier"] = "muirGlacier"; + HardforksOrdered["berlin"] = "berlin"; + HardforksOrdered["london"] = "london"; + HardforksOrdered["altair"] = "altair"; + HardforksOrdered["arrowGlacier"] = "arrowGlacier"; + HardforksOrdered["grayGlacier"] = "grayGlacier"; + HardforksOrdered["bellatrix"] = "bellatrix"; + HardforksOrdered["merge"] = "merge"; + HardforksOrdered["capella"] = "capella"; + HardforksOrdered["shanghai"] = "shanghai"; +})(HardforksOrdered = exports.HardforksOrdered || (exports.HardforksOrdered = {})); +//# sourceMappingURL=eth_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.js.map new file mode 100644 index 0000000..41de683 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/eth_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_types.js","sourceRoot":"","sources":["../../src/eth_types.ts"],"names":[],"mappings":";;;AA2CA,IAAY,SAMX;AAND,WAAY,SAAS;IACpB,kCAAqB,CAAA;IACrB,8BAAiB,CAAA;IACjB,gCAAmB,CAAA;IACnB,0BAAa,CAAA;IACb,oCAAuB,CAAA;AACxB,CAAC,EANW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAMpB;AA+ND,oDAAoD;AACpD,8CAA8C;AAC9C,IAAY,gBAqBX;AArBD,WAAY,gBAAgB;IAC3B,6CAAyB,CAAA;IACzB,yCAAqB,CAAA;IACrB,2CAAuB,CAAA;IACvB,+BAAW,CAAA;IACX,yDAAqC,CAAA;IACrC,qDAAiC,CAAA;IACjC,2CAAuB,CAAA;IACvB,qDAAiC,CAAA;IACjC,6CAAyB,CAAA;IACzB,yCAAqB,CAAA;IACrB,+CAA2B,CAAA;IAC3B,qCAAiB,CAAA;IACjB,qCAAiB,CAAA;IACjB,qCAAiB,CAAA;IACjB,iDAA6B,CAAA;IAC7B,+CAA2B,CAAA;IAC3B,2CAAuB,CAAA;IACvB,mCAAe,CAAA;IACf,uCAAmB,CAAA;IACnB,yCAAqB,CAAA;AACtB,CAAC,EArBW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAqB3B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.d.ts new file mode 100644 index 0000000..0db7a4c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.d.ts @@ -0,0 +1,16 @@ +export * from './error_types.js'; +export * from './apis/eth_execution_api.js'; +export * from './apis/web3_eth_execution_api.js'; +export * from './apis/web3_net_api.js'; +export * from './apis/eth_personal_api.js'; +export * from './data_format_types.js'; +export * from './eth_types.js'; +export * from './eth_abi_types.js'; +export * from './eth_contract_types.js'; +export * from './json_rpc_types.js'; +export * from './primitives_types.js'; +export * from './utility_types.js'; +export * from './web3_api_types.js'; +export * from './web3_base_provider.js'; +export * from './web3_base_wallet.js'; +export * from './web3_deferred_promise_type.js'; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.js new file mode 100644 index 0000000..cb64d7a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.js @@ -0,0 +1,49 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./error_types.js"), exports); +__exportStar(require("./apis/eth_execution_api.js"), exports); +__exportStar(require("./apis/web3_eth_execution_api.js"), exports); +__exportStar(require("./apis/web3_net_api.js"), exports); +__exportStar(require("./apis/eth_personal_api.js"), exports); +__exportStar(require("./data_format_types.js"), exports); +__exportStar(require("./eth_types.js"), exports); +__exportStar(require("./eth_abi_types.js"), exports); +__exportStar(require("./eth_contract_types.js"), exports); +__exportStar(require("./json_rpc_types.js"), exports); +__exportStar(require("./primitives_types.js"), exports); +__exportStar(require("./utility_types.js"), exports); +__exportStar(require("./web3_api_types.js"), exports); +__exportStar(require("./web3_base_provider.js"), exports); +__exportStar(require("./web3_base_wallet.js"), exports); +__exportStar(require("./web3_deferred_promise_type.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.js.map new file mode 100644 index 0000000..f9e52b8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF,mDAAiC;AACjC,8DAA4C;AAC5C,mEAAiD;AACjD,yDAAuC;AACvC,6DAA2C;AAC3C,yDAAuC;AACvC,iDAA+B;AAC/B,qDAAmC;AACnC,0DAAwC;AACxC,sDAAoC;AACpC,wDAAsC;AACtC,qDAAmC;AACnC,sDAAoC;AACpC,0DAAwC;AACxC,wDAAsC;AACtC,kEAAgD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.d.ts new file mode 100644 index 0000000..0553249 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.d.ts @@ -0,0 +1,60 @@ +export declare type JsonRpcId = string | number | undefined; +export declare type JsonRpcResult = string | number | boolean | Record; +export declare type JsonRpcIdentifier = string & ('2.0' | '1.0'); +export interface JsonRpcError { + readonly code: number; + readonly message: string; + readonly data?: T; +} +export interface JsonRpcResponseWithError { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly error: JsonRpcError; + readonly result?: never; +} +export interface JsonRpcResponseWithResult { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly error?: never; + readonly result: T; +} +export interface SubscriptionParams { + readonly subscription: string; + readonly result: T; +} +export interface JsonRpcSubscriptionResultOld { + readonly error?: never; + readonly params?: never; + readonly type: string; + readonly data: SubscriptionParams; +} +export interface JsonRpcNotification { + readonly id?: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly method: string; + readonly params: SubscriptionParams; + readonly result: never; + readonly data?: never; +} +export interface JsonRpcSubscriptionResult { + readonly id: number; + readonly jsonrpc: string; + readonly result: string; + readonly method: never; + readonly params: never; + readonly data?: never; +} +export interface JsonRpcRequest { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly method: string; + readonly params?: T; +} +export interface JsonRpcOptionalRequest extends Omit, 'id' | 'jsonrpc'> { + readonly id?: JsonRpcId; + readonly jsonrpc?: JsonRpcIdentifier; +} +export declare type JsonRpcBatchRequest = JsonRpcRequest[]; +export declare type JsonRpcPayload = JsonRpcRequest | JsonRpcBatchRequest; +export declare type JsonRpcBatchResponse = (JsonRpcResponseWithError | JsonRpcResponseWithResult)[]; +export declare type JsonRpcResponse = JsonRpcResponseWithError | JsonRpcResponseWithResult | JsonRpcBatchResponse; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.js new file mode 100644 index 0000000..bb8855d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=json_rpc_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.js.map new file mode 100644 index 0000000..9686310 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/json_rpc_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json_rpc_types.js","sourceRoot":"","sources":["../../src/json_rpc_types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-types/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.d.ts new file mode 100644 index 0000000..1860c19 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.d.ts @@ -0,0 +1,4 @@ +export declare type HexString = string; +export declare type Bytes = Uint8Array | HexString; +export declare type Numbers = number | bigint | string | HexString; +export declare const TypedArray: any; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.js new file mode 100644 index 0000000..b404080 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.js @@ -0,0 +1,22 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypedArray = void 0; +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment +exports.TypedArray = Object.getPrototypeOf(Uint8Array); +//# sourceMappingURL=primitives_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.js.map new file mode 100644 index 0000000..a887c37 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/primitives_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"primitives_types.js","sourceRoot":"","sources":["../../src/primitives_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAMF,mEAAmE;AACtD,QAAA,UAAU,GAAG,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.d.ts new file mode 100644 index 0000000..f5effcb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.d.ts @@ -0,0 +1,31 @@ +import { Numbers } from './primitives_types.js'; +export declare type Mutable = { + -readonly [P in keyof T]: T[P]; +}; +export declare type ConnectionEvent = { + code: number; + reason: string; + wasClean?: boolean; +}; +export declare type Optional = Pick, K> & Omit; +export declare type EncodingTypes = Numbers | boolean | Numbers[] | boolean[]; +export declare type TypedObject = { + type: string; + value: EncodingTypes; +}; +export declare type TypedObjectAbbreviated = { + t: string; + v: EncodingTypes; +}; +export declare type Sha3Input = TypedObject | TypedObjectAbbreviated | Numbers | boolean | object; +export declare type IndexKeysForArray = Exclude; +export declare type ArrayToIndexObject> = { + [K in IndexKeysForArray]: T[K]; +}; +declare type _Grow> = ((x: T, ...xs: A) => void) extends (...a: infer X) => void ? X : never; +export declare type GrowToSize, N extends number> = { + 0: A; + 1: GrowToSize, N>; +}[A['length'] extends N ? 0 : 1]; +export declare type FixedSizeArray = GrowToSize; +export {}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.js new file mode 100644 index 0000000..23cdbde --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=utility_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.js.map new file mode 100644 index 0000000..a80e22d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/utility_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utility_types.js","sourceRoot":"","sources":["../../src/utility_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.d.ts new file mode 100644 index 0000000..8d62030 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.d.ts @@ -0,0 +1,32 @@ +import { JsonRpcId, JsonRpcIdentifier } from './json_rpc_types.js'; +export interface ProviderMessage { + readonly type: string; + readonly data: unknown; +} +export interface EthSubscription extends ProviderMessage { + readonly type: 'eth_subscription'; + readonly data: { + readonly subscription: string; + readonly result: unknown; + }; +} +export interface ProviderRpcError extends Error { + code: number; + data?: unknown; +} +export interface ProviderConnectInfo { + readonly chainId: string; +} +export declare type Web3APISpec = Record any> | unknown; +export declare type Web3APIMethod = string & keyof Exclude; +export declare type Web3APIParams> = API extends Exclude ? Parameters : unknown; +export interface Web3APIRequest> { + method: Method | string; + params?: Web3APIParams | readonly unknown[] | object; +} +export interface Web3APIPayload> extends Web3APIRequest { + readonly jsonrpc?: JsonRpcIdentifier; + readonly id?: JsonRpcId; + readonly requestOptions?: unknown; +} +export declare type Web3APIReturnType> = API extends Record any> ? ReturnType : any; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.js new file mode 100644 index 0000000..cfeda7f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=web3_api_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.js.map new file mode 100644 index 0000000..5db4ef6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_api_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_api_types.js","sourceRoot":"","sources":["../../src/web3_api_types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.d.ts new file mode 100644 index 0000000..59d6c15 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.d.ts @@ -0,0 +1,122 @@ +/// +import { Socket } from 'net'; +import { Web3Error } from './error_types.js'; +import { EthExecutionAPI } from './apis/eth_execution_api.js'; +import { JsonRpcNotification, JsonRpcPayload, JsonRpcResponse, JsonRpcResponseWithError, JsonRpcResponseWithResult, JsonRpcResult, JsonRpcSubscriptionResult } from './json_rpc_types'; +import { Web3APISpec, Web3APIMethod, Web3APIReturnType, Web3APIPayload, ProviderConnectInfo, ProviderRpcError, ProviderMessage } from './web3_api_types'; +import { Web3EthExecutionAPI } from './apis/web3_eth_execution_api'; +import { Web3DeferredPromiseInterface } from './web3_deferred_promise_type'; +declare const symbol: unique symbol; +export interface SocketRequestItem, ResponseType> { + payload: Web3APIPayload; + deferredPromise: Web3DeferredPromiseInterface; +} +export declare type Web3ProviderStatus = 'connecting' | 'connected' | 'disconnected'; +export declare type Web3ProviderEventCallback = (error: Error | ProviderRpcError | undefined, result?: JsonRpcSubscriptionResult | JsonRpcNotification) => void; +export declare type Web3ProviderMessageEventCallback = (result?: JsonRpcSubscriptionResult | JsonRpcNotification) => void; +export declare type Web3Eip1193ProviderEventCallback = (data: T) => void; +export declare type Web3ProviderRequestCallback = (err?: Error | Web3Error | null | JsonRpcResponseWithError, response?: JsonRpcResponseWithResult) => void; +export interface LegacySendProvider { + send(payload: JsonRpcPayload

, callback: (err: Error | null, response?: JsonRpcResponse) => void): void; +} +export interface LegacySendAsyncProvider { + sendAsync(payload: JsonRpcPayload

): Promise>; +} +export interface LegacyRequestProvider { + request(payload: JsonRpcPayload

, callback: (err: Error | null, response: JsonRpcResponse) => void): void; +} +export interface SimpleProvider { + request, ResponseType = Web3APIReturnType>(args: Web3APIPayload): Promise | unknown>; +} +export interface ProviderInfo { + chainId: string; +} +export declare type ProviderChainId = string; +export declare type ProviderAccounts = string[]; +export declare type Eip1193EventName = 'connect' | 'disconnect' | 'message' | 'chainChanged' | 'accountsChanged'; +export interface EIP1193Provider extends SimpleProvider { + on(event: 'connect', listener: (info: ProviderInfo) => void): void; + on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + on(event: 'message', listener: (message: ProviderMessage) => void): void; + on(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + on(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + removeListener(event: 'connect', listener: (info: ProviderInfo) => void): void; + removeListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + removeListener(event: 'message', listener: (message: ProviderMessage) => void): void; + removeListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + removeListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; +} +export interface MetaMaskProvider extends SimpleProvider { + on(event: 'connect', listener: (info: ProviderInfo) => void): void; + on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + on(event: 'message', listener: (message: ProviderMessage) => void): void; + on(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + on(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + removeListener(event: 'connect', listener: (info: ProviderInfo) => void): void; + removeListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + removeListener(event: 'message', listener: (message: ProviderMessage) => void): void; + removeListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + removeListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + isMetaMask: boolean; +} +export declare type Eip1193Compatible = Omit, 'asEIP1193Provider'> & { + request, ResultType = Web3APIReturnType | unknown>(request: Web3APIPayload): Promise; +}; +export declare abstract class Web3BaseProvider implements LegacySendProvider, LegacySendAsyncProvider, EIP1193Provider { + static isWeb3Provider(provider: unknown): boolean; + get [symbol](): boolean; + abstract getStatus(): Web3ProviderStatus; + abstract supportsSubscriptions(): boolean; + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + * @param callback - Callback + */ + send(payload: JsonRpcPayload

, callback: (err: Error | null, response?: JsonRpcResponse) => void): void; + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + */ + sendAsync(payload: JsonRpcPayload

): Promise>; + /** + * Modify the return type of the request method to be fully compatible with EIP-1193 + * + * [deprecated] In the future major releases (\>= v5) all providers are supposed to be fully compatible with EIP-1193. + * So this method will not be needed and would not be available in the future. + * + * @returns A new instance of the provider with the request method fully compatible with EIP-1193 + * + * @example + * ```ts + * const provider = new Web3HttpProvider('http://localhost:8545'); + * const fullyCompatibleProvider = provider.asEIP1193Provider(); + * const result = await fullyCompatibleProvider.request({ method: 'eth_getBalance' }); + * console.log(result); // '0x0234c8a3397aab58' or something like that + * ``` + */ + asEIP1193Provider(): Eip1193Compatible; + abstract request, ResultType = Web3APIReturnType | unknown>(args: Web3APIPayload): Promise>; + abstract on(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + abstract on(type: 'message' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + abstract on(type: 'data' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + abstract on(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + abstract on(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract on(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'message' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + abstract removeListener(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'message' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + abstract once(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeAllListeners?(type: string): void; + abstract connect(): void; + abstract disconnect(code?: number, data?: string): void; + abstract reset(): void; +} +export declare type SupportedProviders = EIP1193Provider | Web3BaseProvider | LegacyRequestProvider | LegacySendProvider | LegacySendAsyncProvider | SimpleProvider | MetaMaskProvider; +export declare type Web3BaseProviderConstructor = new (url: string, net?: Socket) => Web3BaseProvider; +export {}; diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.js new file mode 100644 index 0000000..3911373 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.js @@ -0,0 +1,90 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3BaseProvider = void 0; +const symbol = Symbol.for('web3/base-provider'); +// Provider interface compatible with EIP-1193 +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md +class Web3BaseProvider { + static isWeb3Provider(provider) { + return (provider instanceof Web3BaseProvider || + Boolean(provider && provider[symbol])); + } + // To match an object "instanceof" does not work if + // matcher class and object is using different package versions + // to overcome this bottleneck used this approach. + // The symbol value for one string will always remain same regardless of package versions + // eslint-disable-next-line class-methods-use-this + get [symbol]() { + return true; + } + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + * @param callback - Callback + */ + send(payload, + // eslint-disable-next-line @typescript-eslint/ban-types + callback) { + this.request(payload) + .then(response => { + // eslint-disable-next-line no-null/no-null + callback(null, response); + }) + .catch((err) => { + callback(err); + }); + } + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + */ + sendAsync(payload) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(payload); + }); + } + /** + * Modify the return type of the request method to be fully compatible with EIP-1193 + * + * [deprecated] In the future major releases (\>= v5) all providers are supposed to be fully compatible with EIP-1193. + * So this method will not be needed and would not be available in the future. + * + * @returns A new instance of the provider with the request method fully compatible with EIP-1193 + * + * @example + * ```ts + * const provider = new Web3HttpProvider('http://localhost:8545'); + * const fullyCompatibleProvider = provider.asEIP1193Provider(); + * const result = await fullyCompatibleProvider.request({ method: 'eth_getBalance' }); + * console.log(result); // '0x0234c8a3397aab58' or something like that + * ``` + */ + asEIP1193Provider() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const newObj = Object.create(this); + // eslint-disable-next-line @typescript-eslint/unbound-method + const originalRequest = newObj.request; + newObj.request = function request(args) { + return __awaiter(this, void 0, void 0, function* () { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + const response = (yield originalRequest(args)); + return response.result; + }); + }; + // @ts-expect-error the property should not be available in the new object because of using Object.create(this). + // But it is available if we do not delete it. + newObj.asEIP1193Provider = undefined; // to prevent the user for calling this method again + return newObj; + } +} +exports.Web3BaseProvider = Web3BaseProvider; +//# sourceMappingURL=web3_base_provider.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.js.map new file mode 100644 index 0000000..fde1398 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_base_provider.js","sourceRoot":"","sources":["../../src/web3_base_provider.ts"],"names":[],"mappings":";;;;;;;;;;;;AA6CA,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAwHhD,8CAA8C;AAC9C,gEAAgE;AAChE,MAAsB,gBAAgB;IAG9B,MAAM,CAAC,cAAc,CAAC,QAAiB;QAC7C,OAAO,CACN,QAAQ,YAAY,gBAAgB;YACpC,OAAO,CAAC,QAAQ,IAAK,QAAkC,CAAC,MAAM,CAAC,CAAC,CAChE,CAAC;IACH,CAAC;IAED,mDAAmD;IACnD,+DAA+D;IAC/D,kDAAkD;IAClD,yFAAyF;IACzF,kDAAkD;IAClD,IAAW,CAAC,MAAM,CAAC;QAClB,OAAO,IAAI,CAAC;IACb,CAAC;IAKD;;;;OAIG;IACI,IAAI,CACV,OAA0B;IAC1B,wDAAwD;IACxD,QAA6E;QAE7E,IAAI,CAAC,OAAO,CACX,OAAkD,CAClD;aACC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAChB,2CAA2C;YAC3C,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC1B,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,GAAsB,EAAE,EAAE;YACjC,QAAQ,CAAC,GAAG,CAAC,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACU,SAAS,CAAiC,OAA0B;;YAChF,OAAO,IAAI,CAAC,OAAO,CAAC,OAAkD,CAErE,CAAC;QACH,CAAC;KAAA;IAED;;;;;;;;;;;;;;;OAeG;IACI,iBAAiB;QACvB,mEAAmE;QACnE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAA2B,CAAC;QAC7D,6DAA6D;QAC7D,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC;QACvC,MAAM,CAAC,OAAO,GAAG,SAAe,OAAO,CACtC,IAA6C;;gBAE7C,4EAA4E;gBAC5E,MAAM,QAAQ,GAAG,CAAC,MAAM,eAAe,CAAC,IAAI,CAAC,CAAuC,CAAC;gBACrF,OAAO,QAAQ,CAAC,MAAM,CAAC;YACxB,CAAC;SAAyB,CAAC;QAC3B,gHAAgH;QAChH,8CAA8C;QAC9C,MAAM,CAAC,iBAAiB,GAAG,SAAS,CAAC,CAAC,oDAAoD;QAC1F,OAAO,MAAM,CAAC;IACf,CAAC;CAmFD;AAzKD,4CAyKC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.d.ts new file mode 100644 index 0000000..5ad6ae0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.d.ts @@ -0,0 +1,81 @@ +import { Transaction } from './eth_types.js'; +import { HexString } from './primitives_types.js'; +export declare type Cipher = 'aes-128-ctr' | 'aes-128-cbc' | 'aes-256-cbc'; +export declare type CipherOptions = { + salt?: Uint8Array | string; + iv?: Uint8Array | string; + kdf?: 'scrypt' | 'pbkdf2'; + dklen?: number; + c?: number; + n?: number; + r?: number; + p?: number; +}; +export declare type ScryptParams = { + dklen: number; + n: number; + p: number; + r: number; + salt: Uint8Array | string; +}; +export declare type PBKDF2SHA256Params = { + c: number; + dklen: number; + prf: 'hmac-sha256'; + salt: Uint8Array | string; +}; +export declare type KeyStore = { + crypto: { + cipher: Cipher; + ciphertext: string; + cipherparams: { + iv: string; + }; + kdf: 'pbkdf2' | 'scrypt'; + kdfparams: ScryptParams | PBKDF2SHA256Params; + mac: HexString; + }; + id: string; + version: 3; + address: string; +}; +export interface Web3BaseWalletAccount { + [key: string]: unknown; + readonly address: string; + readonly privateKey: string; + readonly signTransaction: (tx: Transaction) => Promise<{ + readonly messageHash: HexString; + readonly r: HexString; + readonly s: HexString; + readonly v: HexString; + readonly rawTransaction: HexString; + readonly transactionHash: HexString; + }>; + readonly sign: (data: Record | string) => { + readonly messageHash: HexString; + readonly r: HexString; + readonly s: HexString; + readonly v: HexString; + readonly message?: string; + readonly signature: HexString; + }; + readonly encrypt: (password: string, options?: Record) => Promise; +} +export interface Web3AccountProvider { + privateKeyToAccount: (privateKey: string) => T; + create: () => T; + decrypt: (keystore: KeyStore | string, password: string, options?: Record) => Promise; +} +export declare abstract class Web3BaseWallet extends Array { + protected readonly _accountProvider: Web3AccountProvider; + constructor(accountProvider: Web3AccountProvider); + abstract create(numberOfAccounts: number): this; + abstract add(account: T | string): this; + abstract get(addressOrIndex: string | number): T | undefined; + abstract remove(addressOrIndex: string | number): boolean; + abstract clear(): this; + abstract encrypt(password: string, options?: Record): Promise; + abstract decrypt(encryptedWallet: KeyStore[], password: string, options?: Record): Promise; + abstract save(password: string, keyName?: string): Promise; + abstract load(password: string, keyName?: string): Promise; +} diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.js new file mode 100644 index 0000000..5919d29 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3BaseWallet = void 0; +class Web3BaseWallet extends Array { + constructor(accountProvider) { + super(); + this._accountProvider = accountProvider; + } +} +exports.Web3BaseWallet = Web3BaseWallet; +//# sourceMappingURL=web3_base_wallet.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.js.map new file mode 100644 index 0000000..b67e37a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_base_wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_base_wallet.js","sourceRoot":"","sources":["../../src/web3_base_wallet.ts"],"names":[],"mappings":";;;AA+FA,MAAsB,cAAgD,SAAQ,KAAQ;IAGrF,YAAmB,eAAuC;QACzD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;IACzC,CAAC;CAkBD;AAxBD,wCAwBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.d.ts b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.d.ts new file mode 100644 index 0000000..cfe4faa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.d.ts @@ -0,0 +1,6 @@ +export interface Web3DeferredPromiseInterface extends Promise { + state: 'pending' | 'fulfilled' | 'rejected'; + resolve(value: T | PromiseLike): void; + reject(reason?: unknown): void; + startTimer(): void; +} diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.js b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.js new file mode 100644 index 0000000..20b371a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=web3_deferred_promise_type.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.js.map b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.js.map new file mode 100644 index 0000000..d1164ec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/commonjs/web3_deferred_promise_type.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_deferred_promise_type.js","sourceRoot":"","sources":["../../src/web3_deferred_promise_type.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_execution_api.js b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_execution_api.js new file mode 100644 index 0000000..fb0e363 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_execution_api.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=eth_execution_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_execution_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_execution_api.js.map new file mode 100644 index 0000000..8343249 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_execution_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_execution_api.js","sourceRoot":"","sources":["../../../src/apis/eth_execution_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_personal_api.js b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_personal_api.js new file mode 100644 index 0000000..c9195c0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_personal_api.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=eth_personal_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_personal_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_personal_api.js.map new file mode 100644 index 0000000..40df4a0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/eth_personal_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_personal_api.js","sourceRoot":"","sources":["../../../src/apis/eth_personal_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_eth_execution_api.js b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_eth_execution_api.js new file mode 100644 index 0000000..cf9bcf4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_eth_execution_api.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=web3_eth_execution_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_eth_execution_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_eth_execution_api.js.map new file mode 100644 index 0000000..9650ada --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_eth_execution_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eth_execution_api.js","sourceRoot":"","sources":["../../../src/apis/web3_eth_execution_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_net_api.js b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_net_api.js new file mode 100644 index 0000000..ef68633 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_net_api.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=web3_net_api.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_net_api.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_net_api.js.map new file mode 100644 index 0000000..92dd3f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/apis/web3_net_api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_net_api.js","sourceRoot":"","sources":["../../../src/apis/web3_net_api.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/data_format_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/data_format_types.js new file mode 100644 index 0000000..bcc6471 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/data_format_types.js @@ -0,0 +1,31 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export var FMT_NUMBER; +(function (FMT_NUMBER) { + FMT_NUMBER["NUMBER"] = "NUMBER_NUMBER"; + FMT_NUMBER["HEX"] = "NUMBER_HEX"; + FMT_NUMBER["STR"] = "NUMBER_STR"; + FMT_NUMBER["BIGINT"] = "NUMBER_BIGINT"; +})(FMT_NUMBER || (FMT_NUMBER = {})); +export var FMT_BYTES; +(function (FMT_BYTES) { + FMT_BYTES["HEX"] = "BYTES_HEX"; + FMT_BYTES["UINT8ARRAY"] = "BYTES_UINT8ARRAY"; +})(FMT_BYTES || (FMT_BYTES = {})); +export const DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX }; +export const ETH_DATA_FORMAT = { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX }; +//# sourceMappingURL=data_format_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/data_format_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/data_format_types.js.map new file mode 100644 index 0000000..3141f17 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/data_format_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"data_format_types.js","sourceRoot":"","sources":["../../src/data_format_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAIF,MAAM,CAAN,IAAY,UAKX;AALD,WAAY,UAAU;IACrB,sCAAwB,CAAA;IACxB,gCAAkB,CAAA;IAClB,gCAAkB,CAAA;IAClB,sCAAwB,CAAA;AACzB,CAAC,EALW,UAAU,KAAV,UAAU,QAKrB;AASD,MAAM,CAAN,IAAY,SAGX;AAHD,WAAY,SAAS;IACpB,8BAAiB,CAAA;IACjB,4CAA+B,CAAA;AAChC,CAAC,EAHW,SAAS,KAAT,SAAS,QAGpB;AAYD,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,EAAW,CAAC;AAClG,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,EAAW,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/error_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/error_types.js new file mode 100644 index 0000000..a1039ea --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/error_types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=error_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/error_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/error_types.js.map new file mode 100644 index 0000000..478c804 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/error_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error_types.js","sourceRoot":"","sources":["../../src/error_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/eth_abi_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_abi_types.js new file mode 100644 index 0000000..a1e8fa5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_abi_types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=eth_abi_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/eth_abi_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_abi_types.js.map new file mode 100644 index 0000000..4874225 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_abi_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_abi_types.js","sourceRoot":"","sources":["../../src/eth_abi_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/eth_contract_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_contract_types.js new file mode 100644 index 0000000..ee3674e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_contract_types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=eth_contract_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/eth_contract_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_contract_types.js.map new file mode 100644 index 0000000..bb7f0af --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_contract_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_contract_types.js","sourceRoot":"","sources":["../../src/eth_contract_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/eth_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_types.js new file mode 100644 index 0000000..1ba8822 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_types.js @@ -0,0 +1,34 @@ +export var BlockTags; +(function (BlockTags) { + BlockTags["EARLIEST"] = "earliest"; + BlockTags["LATEST"] = "latest"; + BlockTags["PENDING"] = "pending"; + BlockTags["SAFE"] = "safe"; + BlockTags["FINALIZED"] = "finalized"; +})(BlockTags || (BlockTags = {})); +// This list of hardforks is expected to be in order +// keep this in mind when making changes to it +export var HardforksOrdered; +(function (HardforksOrdered) { + HardforksOrdered["chainstart"] = "chainstart"; + HardforksOrdered["frontier"] = "frontier"; + HardforksOrdered["homestead"] = "homestead"; + HardforksOrdered["dao"] = "dao"; + HardforksOrdered["tangerineWhistle"] = "tangerineWhistle"; + HardforksOrdered["spuriousDragon"] = "spuriousDragon"; + HardforksOrdered["byzantium"] = "byzantium"; + HardforksOrdered["constantinople"] = "constantinople"; + HardforksOrdered["petersburg"] = "petersburg"; + HardforksOrdered["istanbul"] = "istanbul"; + HardforksOrdered["muirGlacier"] = "muirGlacier"; + HardforksOrdered["berlin"] = "berlin"; + HardforksOrdered["london"] = "london"; + HardforksOrdered["altair"] = "altair"; + HardforksOrdered["arrowGlacier"] = "arrowGlacier"; + HardforksOrdered["grayGlacier"] = "grayGlacier"; + HardforksOrdered["bellatrix"] = "bellatrix"; + HardforksOrdered["merge"] = "merge"; + HardforksOrdered["capella"] = "capella"; + HardforksOrdered["shanghai"] = "shanghai"; +})(HardforksOrdered || (HardforksOrdered = {})); +//# sourceMappingURL=eth_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/eth_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_types.js.map new file mode 100644 index 0000000..fe0daa5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/eth_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_types.js","sourceRoot":"","sources":["../../src/eth_types.ts"],"names":[],"mappings":"AA2CA,MAAM,CAAN,IAAY,SAMX;AAND,WAAY,SAAS;IACpB,kCAAqB,CAAA;IACrB,8BAAiB,CAAA;IACjB,gCAAmB,CAAA;IACnB,0BAAa,CAAA;IACb,oCAAuB,CAAA;AACxB,CAAC,EANW,SAAS,KAAT,SAAS,QAMpB;AA+ND,oDAAoD;AACpD,8CAA8C;AAC9C,MAAM,CAAN,IAAY,gBAqBX;AArBD,WAAY,gBAAgB;IAC3B,6CAAyB,CAAA;IACzB,yCAAqB,CAAA;IACrB,2CAAuB,CAAA;IACvB,+BAAW,CAAA;IACX,yDAAqC,CAAA;IACrC,qDAAiC,CAAA;IACjC,2CAAuB,CAAA;IACvB,qDAAiC,CAAA;IACjC,6CAAyB,CAAA;IACzB,yCAAqB,CAAA;IACrB,+CAA2B,CAAA;IAC3B,qCAAiB,CAAA;IACjB,qCAAiB,CAAA;IACjB,qCAAiB,CAAA;IACjB,iDAA6B,CAAA;IAC7B,+CAA2B,CAAA;IAC3B,2CAAuB,CAAA;IACvB,mCAAe,CAAA;IACf,uCAAmB,CAAA;IACnB,yCAAqB,CAAA;AACtB,CAAC,EArBW,gBAAgB,KAAhB,gBAAgB,QAqB3B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/index.js b/test/merkletreejs/node_modules/web3-types/lib/esm/index.js new file mode 100644 index 0000000..f1a61d1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/index.js @@ -0,0 +1,33 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './error_types.js'; +export * from './apis/eth_execution_api.js'; +export * from './apis/web3_eth_execution_api.js'; +export * from './apis/web3_net_api.js'; +export * from './apis/eth_personal_api.js'; +export * from './data_format_types.js'; +export * from './eth_types.js'; +export * from './eth_abi_types.js'; +export * from './eth_contract_types.js'; +export * from './json_rpc_types.js'; +export * from './primitives_types.js'; +export * from './utility_types.js'; +export * from './web3_api_types.js'; +export * from './web3_base_provider.js'; +export * from './web3_base_wallet.js'; +export * from './web3_deferred_promise_type.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/index.js.map new file mode 100644 index 0000000..445c7fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,kBAAkB,CAAC;AACjC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,kCAAkC,CAAC;AACjD,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iCAAiC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/json_rpc_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/json_rpc_types.js new file mode 100644 index 0000000..c80d4da --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/json_rpc_types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=json_rpc_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/json_rpc_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/json_rpc_types.js.map new file mode 100644 index 0000000..9686310 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/json_rpc_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json_rpc_types.js","sourceRoot":"","sources":["../../src/json_rpc_types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/package.json b/test/merkletreejs/node_modules/web3-types/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/primitives_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/primitives_types.js new file mode 100644 index 0000000..c94092d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/primitives_types.js @@ -0,0 +1,19 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment +export const TypedArray = Object.getPrototypeOf(Uint8Array); +//# sourceMappingURL=primitives_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/primitives_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/primitives_types.js.map new file mode 100644 index 0000000..0ed54a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/primitives_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"primitives_types.js","sourceRoot":"","sources":["../../src/primitives_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAMF,mEAAmE;AACnE,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/utility_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/utility_types.js new file mode 100644 index 0000000..5e277a0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/utility_types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=utility_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/utility_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/utility_types.js.map new file mode 100644 index 0000000..580a1d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/utility_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utility_types.js","sourceRoot":"","sources":["../../src/utility_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_api_types.js b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_api_types.js new file mode 100644 index 0000000..12eb11f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_api_types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=web3_api_types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_api_types.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_api_types.js.map new file mode 100644 index 0000000..bd3341a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_api_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_api_types.js","sourceRoot":"","sources":["../../src/web3_api_types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_provider.js b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_provider.js new file mode 100644 index 0000000..cfb5ae6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_provider.js @@ -0,0 +1,86 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const symbol = Symbol.for('web3/base-provider'); +// Provider interface compatible with EIP-1193 +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md +export class Web3BaseProvider { + static isWeb3Provider(provider) { + return (provider instanceof Web3BaseProvider || + Boolean(provider && provider[symbol])); + } + // To match an object "instanceof" does not work if + // matcher class and object is using different package versions + // to overcome this bottleneck used this approach. + // The symbol value for one string will always remain same regardless of package versions + // eslint-disable-next-line class-methods-use-this + get [symbol]() { + return true; + } + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + * @param callback - Callback + */ + send(payload, + // eslint-disable-next-line @typescript-eslint/ban-types + callback) { + this.request(payload) + .then(response => { + // eslint-disable-next-line no-null/no-null + callback(null, response); + }) + .catch((err) => { + callback(err); + }); + } + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + */ + sendAsync(payload) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(payload); + }); + } + /** + * Modify the return type of the request method to be fully compatible with EIP-1193 + * + * [deprecated] In the future major releases (\>= v5) all providers are supposed to be fully compatible with EIP-1193. + * So this method will not be needed and would not be available in the future. + * + * @returns A new instance of the provider with the request method fully compatible with EIP-1193 + * + * @example + * ```ts + * const provider = new Web3HttpProvider('http://localhost:8545'); + * const fullyCompatibleProvider = provider.asEIP1193Provider(); + * const result = await fullyCompatibleProvider.request({ method: 'eth_getBalance' }); + * console.log(result); // '0x0234c8a3397aab58' or something like that + * ``` + */ + asEIP1193Provider() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const newObj = Object.create(this); + // eslint-disable-next-line @typescript-eslint/unbound-method + const originalRequest = newObj.request; + newObj.request = function request(args) { + return __awaiter(this, void 0, void 0, function* () { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + const response = (yield originalRequest(args)); + return response.result; + }); + }; + // @ts-expect-error the property should not be available in the new object because of using Object.create(this). + // But it is available if we do not delete it. + newObj.asEIP1193Provider = undefined; // to prevent the user for calling this method again + return newObj; + } +} +//# sourceMappingURL=web3_base_provider.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_provider.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_provider.js.map new file mode 100644 index 0000000..c6cb9c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_base_provider.js","sourceRoot":"","sources":["../../src/web3_base_provider.ts"],"names":[],"mappings":";;;;;;;;;AA6CA,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAwHhD,8CAA8C;AAC9C,gEAAgE;AAChE,MAAM,OAAgB,gBAAgB;IAG9B,MAAM,CAAC,cAAc,CAAC,QAAiB;QAC7C,OAAO,CACN,QAAQ,YAAY,gBAAgB;YACpC,OAAO,CAAC,QAAQ,IAAK,QAAkC,CAAC,MAAM,CAAC,CAAC,CAChE,CAAC;IACH,CAAC;IAED,mDAAmD;IACnD,+DAA+D;IAC/D,kDAAkD;IAClD,yFAAyF;IACzF,kDAAkD;IAClD,IAAW,CAAC,MAAM,CAAC;QAClB,OAAO,IAAI,CAAC;IACb,CAAC;IAKD;;;;OAIG;IACI,IAAI,CACV,OAA0B;IAC1B,wDAAwD;IACxD,QAA6E;QAE7E,IAAI,CAAC,OAAO,CACX,OAAkD,CAClD;aACC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAChB,2CAA2C;YAC3C,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC1B,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,GAAsB,EAAE,EAAE;YACjC,QAAQ,CAAC,GAAG,CAAC,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACU,SAAS,CAAiC,OAA0B;;YAChF,OAAO,IAAI,CAAC,OAAO,CAAC,OAAkD,CAErE,CAAC;QACH,CAAC;KAAA;IAED;;;;;;;;;;;;;;;OAeG;IACI,iBAAiB;QACvB,mEAAmE;QACnE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAA2B,CAAC;QAC7D,6DAA6D;QAC7D,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC;QACvC,MAAM,CAAC,OAAO,GAAG,SAAe,OAAO,CACtC,IAA6C;;gBAE7C,4EAA4E;gBAC5E,MAAM,QAAQ,GAAG,CAAC,MAAM,eAAe,CAAC,IAAI,CAAC,CAAuC,CAAC;gBACrF,OAAO,QAAQ,CAAC,MAAM,CAAC;YACxB,CAAC;SAAyB,CAAC;QAC3B,gHAAgH;QAChH,8CAA8C;QAC9C,MAAM,CAAC,iBAAiB,GAAG,SAAS,CAAC,CAAC,oDAAoD;QAC1F,OAAO,MAAM,CAAC;IACf,CAAC;CAmFD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_wallet.js b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_wallet.js new file mode 100644 index 0000000..6206c6b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_wallet.js @@ -0,0 +1,7 @@ +export class Web3BaseWallet extends Array { + constructor(accountProvider) { + super(); + this._accountProvider = accountProvider; + } +} +//# sourceMappingURL=web3_base_wallet.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_wallet.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_wallet.js.map new file mode 100644 index 0000000..a4a638b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_base_wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_base_wallet.js","sourceRoot":"","sources":["../../src/web3_base_wallet.ts"],"names":[],"mappings":"AA+FA,MAAM,OAAgB,cAAgD,SAAQ,KAAQ;IAGrF,YAAmB,eAAuC;QACzD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;IACzC,CAAC;CAkBD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_deferred_promise_type.js b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_deferred_promise_type.js new file mode 100644 index 0000000..de5ac1a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_deferred_promise_type.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=web3_deferred_promise_type.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/esm/web3_deferred_promise_type.js.map b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_deferred_promise_type.js.map new file mode 100644 index 0000000..bb79b56 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/esm/web3_deferred_promise_type.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_deferred_promise_type.js","sourceRoot":"","sources":["../../src/web3_deferred_promise_type.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_execution_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_execution_api.d.ts new file mode 100644 index 0000000..3bf4180 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_execution_api.d.ts @@ -0,0 +1,156 @@ +import { Address, HexString32Bytes, Uint, HexStringBytes, HexStringSingleByte, HexString256Bytes, FeeHistoryBase, HexString8Bytes, Uint256, BlockNumberOrTag, Filter, AccessList, TransactionHash, TransactionReceiptBase, BlockBase, LogBase } from '../eth_types.js'; +import { HexString } from '../primitives_types.js'; +export interface TransactionCallAPI { + readonly from?: Address; + readonly to: Address; + readonly gas?: Uint; + readonly gasPrice?: Uint; + readonly value?: Uint; + readonly data?: HexStringBytes; + readonly type?: HexStringSingleByte; + readonly maxFeePerGas?: Uint; + readonly maxPriorityFeePerGas?: Uint; + readonly accessList?: AccessList; +} +export interface BaseTransactionAPI { + readonly to?: Address | null; + readonly type: HexStringSingleByte; + readonly nonce: Uint; + readonly gas: Uint; + readonly value: Uint; + readonly input: HexStringBytes; + readonly data?: HexStringBytes; + readonly chainId?: Uint; + readonly hash?: HexString32Bytes; +} +export interface Transaction1559UnsignedAPI extends BaseTransactionAPI { + readonly maxFeePerGas: Uint; + readonly maxPriorityFeePerGas: Uint; + readonly accessList: AccessList; + readonly gasPrice: Uint; +} +export interface Transaction1559SignedAPI extends Transaction1559UnsignedAPI { + readonly yParity: Uint; + readonly r: Uint; + readonly s: Uint; + readonly v?: never; +} +export interface Transaction2930UnsignedAPI extends BaseTransactionAPI { + readonly gasPrice: Uint; + readonly accessList: AccessList; + readonly maxFeePerGas?: never; + readonly maxPriorityFeePerGas?: never; +} +export interface Transaction2930SignedAPI extends Transaction2930UnsignedAPI { + readonly yParity: Uint; + readonly r: Uint; + readonly s: Uint; + readonly v?: never; +} +export interface TransactionLegacyUnsignedAPI extends BaseTransactionAPI { + readonly gasPrice: Uint; + readonly accessList?: never; + readonly maxFeePerGas?: never; + readonly maxPriorityFeePerGas?: never; +} +export interface TransactionLegacySignedAPI extends TransactionLegacyUnsignedAPI { + readonly v: Uint; + readonly r: Uint; + readonly s: Uint; +} +export declare type TransactionUnsignedAPI = Transaction1559UnsignedAPI | Transaction2930UnsignedAPI | TransactionLegacyUnsignedAPI; +export declare type TransactionSignedAPI = Transaction1559SignedAPI | Transaction2930SignedAPI | TransactionLegacySignedAPI; +export declare type TransactionInfoAPI = TransactionSignedAPI & { + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: Uint; + readonly from: Address; + readonly hash: HexString32Bytes; + readonly transactionIndex?: Uint; +}; +export interface SignedTransactionInfoAPI { + raw: HexStringBytes; + tx: TransactionSignedAPI; +} +export declare type TransactionWithSenderAPI = TransactionUnsignedAPI & { + from: Address; +}; +export declare type BlockAPI = BlockBase; +export declare type LogAPI = LogBase; +export declare type TransactionReceiptAPI = TransactionReceiptBase; +export declare type SyncingStatusAPI = { + startingBlock: Uint; + currentBlock: Uint; + highestBlock: Uint; +} | boolean; +export declare type FeeHistoryResultAPI = FeeHistoryBase; +export declare type FilterResultsAPI = HexString32Bytes[] | LogAPI[]; +export interface CompileResultAPI { + readonly code: HexStringBytes; + readonly info: { + readonly source: string; + readonly language: string; + readonly languageVersion: string; + readonly compilerVersion: string; + readonly abiDefinition: Record[]; + readonly userDoc: { + readonly methods: Record; + }; + readonly developerDoc: { + readonly methods: Record; + }; + }; +} +export declare type EthExecutionAPI = { + eth_getBlockByHash: (blockHash: HexString32Bytes, hydrated: boolean) => BlockAPI; + eth_getBlockByNumber: (blockNumber: BlockNumberOrTag, hydrated: boolean) => BlockAPI; + eth_getBlockTransactionCountByHash: (blockHash: HexString32Bytes) => Uint; + eth_getBlockTransactionCountByNumber: (blockNumber: BlockNumberOrTag) => Uint; + eth_getUncleCountByBlockHash: (blockHash: HexString32Bytes) => Uint; + eth_getUncleCountByBlockNumber: (blockNumber: BlockNumberOrTag) => Uint; + eth_getUncleByBlockHashAndIndex: (blockHash: HexString32Bytes, uncleIndex: Uint) => BlockAPI; + eth_getUncleByBlockNumberAndIndex: (blockNumber: BlockNumberOrTag, uncleIndex: Uint) => BlockAPI; + eth_getTransactionByHash: (transactionHash: HexString32Bytes) => TransactionInfoAPI | undefined; + eth_getTransactionByBlockHashAndIndex: (blockHash: HexString32Bytes, transactionIndex: Uint) => TransactionInfoAPI | undefined; + eth_getTransactionByBlockNumberAndIndex: (blockNumber: BlockNumberOrTag, transactionIndex: Uint) => TransactionInfoAPI | undefined; + eth_getTransactionReceipt: (transactionHash: HexString32Bytes) => TransactionReceiptAPI | undefined; + eth_protocolVersion: () => string; + eth_syncing: () => SyncingStatusAPI; + eth_coinbase: () => Address; + eth_accounts: () => Address[]; + eth_blockNumber: () => Uint; + eth_call: (transaction: TransactionCallAPI, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_estimateGas: (transaction: Partial, blockNumber: BlockNumberOrTag) => Uint; + eth_gasPrice: () => Uint; + eth_feeHistory: (blockCount: Uint, newestBlock: BlockNumberOrTag, rewardPercentiles: number[]) => FeeHistoryResultAPI; + eth_newFilter: (filter: Filter) => Uint; + eth_newBlockFilter: () => Uint; + eth_newPendingTransactionFilter: () => Uint; + eth_uninstallFilter: (filterIdentifier: Uint) => boolean; + eth_getFilterChanges: (filterIdentifier: Uint) => FilterResultsAPI; + eth_getFilterLogs: (filterIdentifier: Uint) => FilterResultsAPI; + eth_getLogs: (filter: Filter) => FilterResultsAPI; + eth_mining: () => boolean; + eth_hashrate: () => Uint; + eth_getWork: () => [HexString32Bytes, HexString32Bytes, HexString32Bytes]; + eth_submitWork: (nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes) => boolean; + eth_submitHashrate: (hashRate: HexString32Bytes, id: HexString32Bytes) => boolean; + eth_sign: (address: Address, message: HexStringBytes) => HexString256Bytes; + eth_signTransaction: (transaction: TransactionWithSenderAPI | Partial) => HexStringBytes | SignedTransactionInfoAPI; + eth_getBalance: (address: Address, blockNumber: BlockNumberOrTag) => Uint; + eth_getStorageAt: (address: Address, storageSlot: Uint256, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_getTransactionCount: (address: Address, blockNumber: BlockNumberOrTag) => Uint; + eth_getCode: (address: Address, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_sendTransaction: (transaction: TransactionWithSenderAPI | Partial) => HexString32Bytes; + eth_sendRawTransaction: (transaction: HexStringBytes) => HexString32Bytes; + eth_subscribe: (...params: ['newHeads'] | ['newPendingTransactions'] | ['syncing'] | ['logs', { + address?: HexString; + topics?: HexString[]; + }]) => HexString; + eth_unsubscribe: (subscriptionId: HexString) => HexString; + eth_clearSubscriptions: (keepSyncing?: boolean) => void; + eth_getCompilers: () => string[]; + eth_compileSolidity: (code: string) => CompileResultAPI; + eth_compileLLL: (code: string) => HexStringBytes; + eth_compileSerpent: (code: string) => HexStringBytes; +}; +//# sourceMappingURL=eth_execution_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_execution_api.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_execution_api.d.ts.map new file mode 100644 index 0000000..9793455 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_execution_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_execution_api.d.ts","sourceRoot":"","sources":["../../../src/apis/eth_execution_api.ts"],"names":[],"mappings":"AAgBA,OAAO,EACN,OAAO,EACP,gBAAgB,EAChB,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,OAAO,EACP,gBAAgB,EAChB,MAAM,EACN,UAAU,EACV,eAAe,EACf,sBA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AC,UAAU,CAAC,GACZ,CAAC,wBAAwB,CAAC,GAC1B,CAAC,SAAS,CAAC,GACX,CAAC,MAAM,EAAE;QAAE,OAAO,CAAC,EAAE,SAAS,CAAC;QAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC,KACtD,SAAS,CAAC;IACf,eAAe,EAAE,CAAC,cAAc,EAAE,SAAS,KAAK,SAAS,CAAC;IAC1D,sBAAsB,EAAE,CAAC,WAAW,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IAExD,gBAAgB,EAAE,MAAM,MAAM,EAAE,CAAC;IACjC,mBAAmB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,gBAAgB,CAAC;IACxD,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,CAAC;IACjD,kBAAkB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,CAAC;CACrD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_personal_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_personal_api.d.ts new file mode 100644 index 0000000..47c3c16 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_personal_api.d.ts @@ -0,0 +1,14 @@ +import { Address, Transaction } from '../eth_types.js'; +import { HexString } from '../primitives_types.js'; +export declare type EthPersonalAPI = { + personal_listAccounts: () => Address[]; + personal_newAccount: (password: string) => Address; + personal_unlockAccount: (address: Address, password: string, unlockDuration: number) => boolean; + personal_lockAccount: (address: Address) => boolean; + personal_importRawKey: (keyData: HexString, passphrase: string) => HexString; + personal_sendTransaction: (tx: Transaction, passphrase: string) => HexString; + personal_signTransaction: (tx: Transaction, passphrase: string) => HexString; + personal_sign: (data: HexString, address: Address, passphrase: string) => HexString; + personal_ecRecover: (signedData: HexString, signature: HexString) => Address; +}; +//# sourceMappingURL=eth_personal_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_personal_api.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_personal_api.d.ts.map new file mode 100644 index 0000000..a06382e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/eth_personal_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_personal_api.d.ts","sourceRoot":"","sources":["../../../src/apis/eth_personal_api.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD,oBAAY,cAAc,GAAG;IAC5B,qBAAqB,EAAE,MAAM,OAAO,EAAE,CAAC;IACvC,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;IACnD,sBAAsB,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC;IAChG,oBAAoB,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC;IACpD,qBAAqB,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,KAAK,SAAS,CAAC;IAC7E,wBAAwB,EAAE,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,KAAK,SAAS,CAAC;IAC7E,wBAAwB,EAAE,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,KAAK,SAAS,CAAC;IAC7E,aAAa,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,KAAK,SAAS,CAAC;IACpF,kBAAkB,EAAE,CAAC,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC;CAC7E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_eth_execution_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_eth_execution_api.d.ts new file mode 100644 index 0000000..d8047fb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_eth_execution_api.d.ts @@ -0,0 +1,12 @@ +import { EthExecutionAPI } from './eth_execution_api.js'; +import { AccountObject, Address, BlockNumberOrTag, Eip712TypedData, HexString256Bytes, HexString32Bytes, TransactionInfo, Uint } from '../eth_types.js'; +export declare type Web3EthExecutionAPI = EthExecutionAPI & { + eth_pendingTransactions: () => TransactionInfo[]; + eth_requestAccounts: () => Address[]; + eth_chainId: () => Uint; + web3_clientVersion: () => string; + eth_getProof: (address: Address, storageKeys: HexString32Bytes[], blockNumber: BlockNumberOrTag) => AccountObject; + eth_signTypedData: (address: Address, typedData: Eip712TypedData, useLegacy: true) => HexString256Bytes; + eth_signTypedData_v4: (address: Address, typedData: Eip712TypedData, useLegacy: false | undefined) => HexString256Bytes; +}; +//# sourceMappingURL=web3_eth_execution_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_eth_execution_api.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_eth_execution_api.d.ts.map new file mode 100644 index 0000000..c1962f5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_eth_execution_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eth_execution_api.d.ts","sourceRoot":"","sources":["../../../src/apis/web3_eth_execution_api.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EACN,aAAa,EACb,OAAO,EACP,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,IAAI,EACJ,MAAM,iBAAiB,CAAC;AAEzB,oBAAY,mBAAmB,GAAG,eAAe,GAAG;IACnD,uBAAuB,EAAE,MAAM,eAAe,EAAE,CAAC;IAGjD,mBAAmB,EAAE,MAAM,OAAO,EAAE,CAAC;IAGrC,WAAW,EAAE,MAAM,IAAI,CAAC;IAExB,kBAAkB,EAAE,MAAM,MAAM,CAAC;IAGjC,YAAY,EAAE,CACb,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,gBAAgB,EAAE,EAC/B,WAAW,EAAE,gBAAgB,KACzB,aAAa,CAAC;IAGnB,iBAAiB,EAAE,CAClB,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,eAAe,EAC1B,SAAS,EAAE,IAAI,KACX,iBAAiB,CAAC;IAGvB,oBAAoB,EAAE,CACrB,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,eAAe,EAC1B,SAAS,EAAE,KAAK,GAAG,SAAS,KACxB,iBAAiB,CAAC;CACvB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_net_api.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_net_api.d.ts new file mode 100644 index 0000000..1883380 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_net_api.d.ts @@ -0,0 +1,7 @@ +import { HexString } from '../primitives_types.js'; +export declare type Web3NetAPI = { + net_version: () => string; + net_peerCount: () => HexString; + net_listening: () => boolean; +}; +//# sourceMappingURL=web3_net_api.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_net_api.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_net_api.d.ts.map new file mode 100644 index 0000000..4b6bd6a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/apis/web3_net_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_net_api.d.ts","sourceRoot":"","sources":["../../../src/apis/web3_net_api.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD,oBAAY,UAAU,GAAG;IACxB,WAAW,EAAE,MAAM,MAAM,CAAC;IAC1B,aAAa,EAAE,MAAM,SAAS,CAAC;IAC/B,aAAa,EAAE,MAAM,OAAO,CAAC;CAC7B,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/data_format_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/data_format_types.d.ts new file mode 100644 index 0000000..fd2529e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/data_format_types.d.ts @@ -0,0 +1,37 @@ +import { Bytes, HexString, Numbers } from './primitives_types.js'; +export declare enum FMT_NUMBER { + NUMBER = "NUMBER_NUMBER", + HEX = "NUMBER_HEX", + STR = "NUMBER_STR", + BIGINT = "NUMBER_BIGINT" +} +export declare type NumberTypes = { + [FMT_NUMBER.NUMBER]: number; + [FMT_NUMBER.HEX]: HexString; + [FMT_NUMBER.STR]: string; + [FMT_NUMBER.BIGINT]: bigint; +}; +export declare enum FMT_BYTES { + HEX = "BYTES_HEX", + UINT8ARRAY = "BYTES_UINT8ARRAY" +} +export declare type ByteTypes = { + [FMT_BYTES.HEX]: HexString; + [FMT_BYTES.UINT8ARRAY]: Uint8Array; +}; +export declare type DataFormat = { + readonly number: FMT_NUMBER; + readonly bytes: FMT_BYTES; +}; +export declare const DEFAULT_RETURN_FORMAT: { + readonly number: FMT_NUMBER.BIGINT; + readonly bytes: FMT_BYTES.HEX; +}; +export declare const ETH_DATA_FORMAT: { + readonly number: FMT_NUMBER.HEX; + readonly bytes: FMT_BYTES.HEX; +}; +export declare type FormatType = number extends Extract ? NumberTypes[F['number']] | Exclude : Uint8Array extends Extract ? ByteTypes[F['bytes']] | Exclude : T extends object | undefined ? { + [P in keyof T]: FormatType; +} : T; +//# sourceMappingURL=data_format_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/data_format_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/data_format_types.d.ts.map new file mode 100644 index 0000000..00be0fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/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CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,KAAK,CAAC,GACzC,CAAC,SAAS,MAAM,GAAG,SAAS,GAC5B;KACC,CAAC,IAAI,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;CAClC,GACD,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/error_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/error_types.d.ts new file mode 100644 index 0000000..aacb215 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/error_types.d.ts @@ -0,0 +1,16 @@ +export interface Web3Error extends Error { + readonly name: string; + readonly code: number; + readonly stack?: string; +} +export declare type Web3ValidationErrorObject, S = unknown> = { + keyword: K; + instancePath: string; + schemaPath: string; + params: P; + propertyName?: string; + message?: string; + schema?: S; + data?: unknown; +}; +//# sourceMappingURL=error_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/error_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/error_types.d.ts.map new file mode 100644 index 0000000..ad34c38 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/error_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error_types.d.ts","sourceRoot":"","sources":["../../src/error_types.ts"],"names":[],"mappings":"AAiBA,MAAM,WAAW,SAAU,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,oBAAY,yBAAyB,CACpC,CAAC,SAAS,MAAM,GAAG,MAAM,EACzB,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACvB,CAAC,GAAG,OAAO,IACR;IACH,OAAO,EAAE,CAAC,CAAC;IACX,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,CAAC,CAAC;IAEV,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,CAAC,CAAC;IACX,IAAI,CAAC,EAAE,OAAO,CAAC;CACf,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/eth_abi_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/eth_abi_types.d.ts new file mode 100644 index 0000000..e470ba1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/eth_abi_types.d.ts @@ -0,0 +1,157 @@ +import { Address } from './eth_types.js'; +import { Bytes, Numbers } from './primitives_types.js'; +import { FixedSizeArray } from './utility_types.js'; +declare type _SolidityIndexRange = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 25 | 26 | 27 | 28 | 29 | 30; +export declare type ConvertToNumber = Range extends unknown ? (`${Range}` extends T ? Range : never) : never; +export declare type Components = { + name: string; + type: string; + indexed?: boolean; + components?: Components[]; +}; +export interface AbiStruct { + [key: string]: unknown; + name: string; + type: string; +} +export interface AbiCoderStruct extends AbiStruct { + [key: string]: unknown; + components?: Array; +} +export declare type AbiParameter = { + readonly name: string; + readonly type: string; + readonly baseType?: string; + readonly indexed?: boolean; + readonly components?: ReadonlyArray; + readonly arrayLength?: number; + readonly arrayChildren?: ReadonlyArray; + readonly internalType?: string; +}; +declare type FragmentTypes = 'constructor' | 'event' | 'function' | 'fallback' | 'receive'; +export declare type AbiBaseFragment = { + readonly type: string | FragmentTypes; +}; +export declare type AbiConstructorFragment = AbiBaseFragment & { + readonly type: string | 'constructor'; + readonly stateMutability: string | 'nonpayable' | 'payable'; + readonly inputs?: ReadonlyArray; +}; +export declare type AbiFunctionFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'function'; + readonly stateMutability?: string | 'nonpayable' | 'payable' | 'pure' | 'view'; + readonly inputs?: ReadonlyArray; + readonly outputs?: ReadonlyArray; + readonly constant?: boolean; + readonly payable?: boolean; +}; +export declare type AbiFallbackFragment = AbiBaseFragment & { + readonly name: never; + readonly type: string | 'fallback'; + readonly stateMutability: string | 'nonpayable' | 'payable' | 'pure' | 'view'; + readonly inputs: never; + readonly outputs: never; + readonly constant?: boolean; + readonly payable?: boolean; +}; +export declare type AbiEventFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'event'; + readonly inputs?: ReadonlyArray; + readonly anonymous?: boolean; +}; +export declare type AbiErrorFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'error'; + readonly inputs?: ReadonlyArray; +}; +export declare type AbiFragment = AbiConstructorFragment | AbiFunctionFragment | AbiEventFragment | AbiErrorFragment | AbiFallbackFragment; +export declare type ContractAbi = ReadonlyArray; +export declare type AbiInput = string | AbiParameter | { + name: string; + type: string; + components?: Components; + index?: boolean; + internalType?: string; +} | { + readonly [key: string]: unknown; +}; +export declare type JsonFunctionInterface = { + type: 'function'; + name: string; + inputs: Components[]; + outputs?: AbiInput[]; + stateMutability?: string; +}; +export declare type JsonEventInterface = { + type: 'event'; + name: string; + inputs: Components[]; + indexed: boolean; + anonymous: boolean; +}; +export declare type FilterAbis = Abi extends Filter ? Abi : never; +declare type _TypedArray = Size extends '' ? Type[] : FixedSizeArray>; +export declare type PrimitiveAddressType = Type extends `address[${infer Size}]` ? _TypedArray : Type extends 'address' ? Address : never; +export declare type PrimitiveStringType = Type extends `string${string}[${infer Size}]` ? _TypedArray : Type extends 'string' | `string${string}` ? string : never; +export declare type PrimitiveBooleanType = Type extends `bool[${infer Size}]` ? _TypedArray : Type extends 'bool' ? boolean : never; +export declare type PrimitiveIntegerType = Type extends `uint${string}[${infer Size}]` | `int${string}[${infer Size}]` ? _TypedArray : Type extends 'uint' | 'int' | `int${string}` | `uint${string}` ? Numbers : never; +export declare type PrimitiveBytesType = Type extends `bytes${string}[${infer Size}]` ? _TypedArray : Type extends 'bytes' | `bytes${string}` ? Bytes : never; +export declare type PrimitiveTupleType | undefined | unknown = []> = TypeComponents extends ReadonlyArray ? Type extends 'tuple' ? { + [Param in TypeComponents[number] as Param['name']]: MatchPrimitiveType; +} : Type extends `tuple[${infer Size}]` ? _TypedArray<{ + [Param in TypeComponents[number] as Param['name']]: MatchPrimitiveType; +}, Size> : never : never; +declare type ObjectToArray = T extends [...infer R, infer A] ? Record & ObjectToArray : T; +declare type ArrToObjectWithFunctions = Array & ObjectToArray; +export declare type MatchPrimitiveType | undefined | unknown> = PrimitiveAddressType | PrimitiveStringType | PrimitiveBooleanType | PrimitiveIntegerType | PrimitiveBytesType | PrimitiveTupleType | never; +declare type ContractMethodOutputParametersRecursiveArray | undefined> = Params extends readonly [] ? [] : Params extends readonly [infer H, ...infer R] ? H extends AbiParameter ? [ + MatchPrimitiveType, + ...ContractMethodOutputParametersRecursiveArray +] : [] : []; +declare type ContractMethodOutputParametersRecursiveRecord | undefined> = Params extends readonly [] ? [] : Params extends readonly [infer H, ...infer R] ? H extends AbiParameter ? H['name'] extends '' ? ContractMethodOutputParametersRecursiveRecord : Record> & // sets key-value pair of output param name and type +ContractMethodOutputParametersRecursiveRecord : ContractMethodOutputParametersRecursiveRecord : Params extends undefined | unknown ? [] : Params; +export declare type ContractMethodOutputParameters | undefined> = Params extends readonly [] ? void : Params extends readonly [infer H, ...infer R] ? R extends readonly [] ? H extends AbiParameter ? MatchPrimitiveType : [] : // if more than one output +ArrToObjectWithFunctions<[...ContractMethodOutputParametersRecursiveArray]> & ContractMethodOutputParametersRecursiveRecord : []; +export declare type ContractMethodInputParameters | undefined> = Params extends readonly [] ? [] : Params extends readonly [infer H, ...infer R] ? H extends AbiParameter ? [ + MatchPrimitiveType, + ...ContractMethodInputParameters +] : ContractMethodInputParameters : Params extends undefined | unknown ? [] : Params; +export declare type ContractConstructor = { + [Abi in FilterAbis as 'constructor']: { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; + }; +}['constructor']; +export declare type ContractConstructorArgs = { + [Abi in FilterAbis as 'constructor']: ContractMethodInputParameters; +}['constructor']; +export declare type ContractMethod = { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; + readonly Outputs: ContractMethodOutputParameters; +}; +export declare type ContractMethods = { + [Abi in FilterAbis as Abi['name']]: ContractMethod; +}; +export declare type ContractEvent = { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; +}; +export declare type ContractEvents = { + [Abi in FilterAbis as Abi['name']]: ContractEvent; +}; +export interface DecodedParams extends Record { + __length__: number; +} +export {}; +//# sourceMappingURL=eth_abi_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/eth_abi_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/eth_abi_types.d.ts.map new file mode 100644 index 0000000..641062c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/eth_abi_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_abi_types.d.ts","sourceRoot":"","sources":["../../src/eth_abi_types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,aAAK,mBAAmB,GACrB,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,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AAG,CAAC;CACrC,CAAC;AAEF,MAAM,WAAW,aAAc,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC7D,UAAU,EAAE,MAAM,CAAC;CACnB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/eth_contract_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/eth_contract_types.d.ts new file mode 100644 index 0000000..d087e8d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/eth_contract_types.d.ts @@ -0,0 +1,134 @@ +import { Address, Uint } from './eth_types.js'; +import { SupportedProviders } from './web3_base_provider.js'; +import { Bytes, HexString } from './primitives_types.js'; +import { EthExecutionAPI } from './apis/eth_execution_api.js'; +import { AbiFragment, ContractAbi } from './eth_abi_types.js'; +export interface ContractInitOptions { + /** + * The maximum gas provided for a transaction (gas limit). + */ + readonly gas?: Uint; + readonly gasLimit?: Uint; + /** + * The gas price in wei to use for transactions. + */ + readonly gasPrice?: Uint; + /** + * The address transactions should be made from + */ + readonly from?: Address; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly data?: Bytes; + readonly input?: Bytes; + readonly provider?: SupportedProviders | string; + /** + * If `true`, the defaults of the contract instance will be updated automatically based on the changes of the context used to instantiate the contract. + */ + readonly syncWithContext?: boolean; + readonly dataInputFill?: 'data' | 'input' | 'both'; +} +export interface NonPayableCallOptions { + nonce?: HexString; + /** + * The address which is the call (the transaction) should be made from. For calls the `from` property is optional however it is + * highly recommended to explicitly set it or it may default to address(0) depending on your node or provider. + */ + from?: Address; + /** + * The maximum gas (gas limit) provided for this call (this transaction) + */ + gas?: string; + maxPriorityFeePerGas?: HexString; + maxFeePerGas?: HexString; + /** + * The gas price in wei to use for this call `transaction`. + */ + gasPrice?: string; + type?: string | number; + data?: HexString; + input?: HexString; +} +export interface PayableCallOptions extends NonPayableCallOptions { + /** + * + */ + value?: string; +} +export declare type ContractAbiWithSignature = ReadonlyArray; +export interface ContractOptions { + /** + * The maximum gas provided for a transaction (gas limit). + */ + readonly gas?: Uint; + /** + * The gas price in wei to use for transactions. + */ + readonly gasPrice?: Uint; + /** + * The address transactions should be made from. + */ + readonly from?: Address; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly input?: Bytes; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly data?: Bytes; + /** + * The {@doclink glossary/json_interface | json interface} object derived from the [ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) of this contract. + * + * Re-setting this will regenerate the methods and events of the contract instance. + * + * ```ts + * myContract.options.jsonInterface; + * > [{ + * "type":"function", + * "name":"foo", + * "inputs": [{"name":"a","type":"uint256"}], + * "outputs": [{"name":"b","type":"address"}], + * "signature": "0x...", + * },{ + * "type":"event", + * "name":"Event", + * "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}], + * "signature": "0x...", + * }] + * + * // Set a new ABI interface + * // Note: the "signature" of every function and event's ABI is not needed to be provided when assigning. + * // It will be calculated and set automatically inside the setter. + * myContract.options.jsonInterface = [...]; + * ``` + */ + get jsonInterface(): ContractAbiWithSignature; + set jsonInterface(value: ContractAbi); + /** + * The address used for this contract instance. All transactions generated by web3.js from this contract will contain this address as the `to`. + * + * The address will be stored in lowercase. + * + * ```ts + * myContract.options.address; + * > '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae' + * + * // set a new address + * myContract.options.address = '0x1234FFDD...'; + * ``` + */ + address?: Address; + /** + * The max priority fee per gas to use for transactions. + */ + maxPriorityFeePerGas?: Uint; + /** + * The max fee per gas to use for transactions. + */ + maxFeePerGas?: Uint; +} +//# sourceMappingURL=eth_contract_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/eth_contract_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/eth_contract_types.d.ts.map new file mode 100644 index 0000000..52575cf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/eth_contract_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_contract_types.d.ts","sourceRoot":"","sources":["../../src/eth_contract_types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAE9D,MAAM,WAAW,mBAAmB;IACnC;;OAEG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC;IACpB,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC;IACzB;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC;IACzB;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC;IAEvB,QAAQ,CAAC,QAAQ,CAAC,EAAE,kBAAkB,CAAC,eAAe,CAAC,GAAG,MAAM,CAAC;IACjE;;OAEG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAEnC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;CAInD;AAED,MAAM,WAAW,qBAAqB;IACrC,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IACf;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oBAAoB,CAAC,EAAE,SAAS,CAAC;IACjC,YAAY,CAAC,EAAE,SAAS,CAAC;IACzB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB;AAED,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAChE;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,oBAAY,wBAAwB,GAAG,aAAa,CAAC,WAAW,GAAG;IAAE,SAAS,EAAE,SAAS,CAAA;CAAE,CAAC,CAAC;AAC7F,MAAM,WAAW,eAAe;IAC/B;;OAEG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC;IACpB;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC;IACzB;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC;IACvB;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC;IACtB;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,IAAI,aAAa,IAAI,wBAAwB,CAAC;IAC9C,IAAI,aAAa,CAAC,KAAK,EAAE,WAAW,EAAE;IAEtC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;OAEG;IACH,oBAAoB,CAAC,EAAE,IAAI,CAAC;IAC5B;;OAEG;IACH,YAAY,CAAC,EAAE,IAAI,CAAC;CACpB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/eth_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/eth_types.d.ts new file mode 100644 index 0000000..abda648 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/eth_types.d.ts @@ -0,0 +1,441 @@ +import { Bytes, HexString, Numbers } from './primitives_types.js'; +export declare type ValueTypes = 'address' | 'bool' | 'string' | 'int256' | 'uint256' | 'bytes' | 'bigint'; +export declare type HexString32Bytes = HexString; +export declare type HexString16Bytes = HexString; +export declare type HexString8Bytes = HexString; +export declare type HexStringSingleByte = HexString; +export declare type HexStringBytes = HexString; +export declare type HexString256Bytes = HexString; +export declare type Uint = HexString; +export declare type Uint256 = HexString; +export declare type Address = HexString; +export declare type Topic = HexString32Bytes; +export declare type TransactionHash = HexString; +export declare type Uncles = HexString32Bytes[]; +export declare enum BlockTags { + EARLIEST = "earliest", + LATEST = "latest", + PENDING = "pending", + SAFE = "safe", + FINALIZED = "finalized" +} +export declare type BlockTag = `${BlockTags}`; +export declare type BlockNumberOrTag = Numbers | BlockTag; +export interface Proof { + readonly address: HexString; + readonly nonce: string; + readonly balance: string; +} +export interface TransactionInput { + readonly [key: string]: unknown; + readonly to?: HexString; + readonly from?: HexString; + readonly data?: string; + readonly input?: string; + readonly gas: HexString; + readonly gasLimit?: string; + readonly gasPrice?: string; + readonly maxPriorityFeePerGas?: string; + readonly maxFeePerGas?: string; + readonly nonce: string; + readonly value: string; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly type?: HexString; + readonly chainId?: HexString; +} +export declare type TransactionOutput = { + readonly [key: string]: unknown; + readonly to?: HexString; + readonly from?: HexString; + readonly input: string; + readonly gas?: Numbers; + readonly gasLimit?: string; + readonly nonce: Numbers; + readonly value: Numbers; + readonly blockNumber?: Numbers; + readonly transactionIndex?: Numbers; +} & ({ + maxPriorityFeePerGas: Numbers; + maxFeePerGas: Numbers; + gasPrice?: never; +} | { + maxPriorityFeePerGas?: never; + maxFeePerGas?: never; + gasPrice: Numbers; +}); +export interface LogsInput { + readonly blockHash?: HexString; + readonly transactionHash?: HexString; + readonly logIndex?: HexString; + readonly id?: string; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly address: HexString; + readonly topics: HexString[]; + readonly data: HexString; +} +export interface LogsOutput { + readonly id?: string; + readonly removed: boolean; + readonly logIndex?: Numbers; + readonly transactionIndex?: Numbers; + readonly transactionHash?: HexString32Bytes; + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: Numbers; + readonly address: string; + readonly topics: HexString[]; + readonly data: HexString; +} +export interface BlockInput { + readonly gasLimit: HexString; + readonly gasUsed: HexString; + readonly size: HexString; + readonly timestamp: HexString; + readonly number?: HexString; + readonly difficulty?: HexString; + readonly totalDifficulty?: HexString; + readonly transactions?: TransactionInput[]; + readonly miner?: HexString; + readonly baseFeePerGas?: HexString; +} +export interface BlockOutput { + readonly gasLimit: bigint | number; + readonly gasUsed: bigint | number; + readonly size: bigint | number; + readonly timestamp: bigint | number; + readonly number?: bigint | number; + readonly difficulty?: bigint | number; + readonly totalDifficulty?: bigint | number; + readonly transactions?: TransactionOutput[]; + readonly miner?: HexString; + readonly baseFeePerGas?: bigint | number; + readonly parentHash?: HexString32Bytes; +} +export interface Withdrawals { + readonly index: Numbers; + readonly validatorIndex: Numbers; + readonly address: Address; + readonly amount: Numbers; +} +export interface BlockHeaderOutput { + readonly hash?: HexString32Bytes; + readonly parentHash?: HexString32Bytes; + readonly receiptsRoot?: HexString32Bytes; + readonly miner?: HexString; + readonly stateRoot?: HexString32Bytes; + readonly transactionsRoot?: HexString32Bytes; + readonly withdrawalsRoot?: HexString32Bytes; + readonly logsBloom?: Bytes; + readonly difficulty?: Numbers; + readonly number?: Numbers; + readonly gasLimit: Numbers; + readonly gasUsed: Numbers; + readonly timestamp: Numbers; + readonly extraData?: Bytes; + readonly nonce?: Numbers; + readonly sha3Uncles: HexString32Bytes[]; + readonly baseFeePerGas?: Numbers; + readonly author?: Address; + readonly totalDifficulty?: Numbers; + readonly size?: Numbers; + readonly excessDataGas?: Numbers; + readonly mixHash?: HexString32Bytes; + readonly transactions?: TransactionOutput[]; + readonly uncles?: Uncles; + readonly withdrawals?: Withdrawals[]; +} +export interface ReceiptInput { + readonly [x: string]: unknown; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly cumulativeGasUsed: HexString; + readonly gasUsed: HexString; + readonly logs?: LogsInput[]; + readonly contractAddress?: HexString; + readonly status?: string; + readonly effectiveGasPrice?: HexString; +} +export interface ReceiptOutput { + readonly blockNumber?: bigint | number; + readonly transactionIndex?: bigint | number; + readonly cumulativeGasUsed: bigint | number; + readonly gasUsed: bigint | number; + readonly logs?: LogsOutput[]; + readonly contractAddress?: HexString; + readonly status: boolean; + readonly effectiveGasPrice?: bigint | number; +} +export interface PostInput { + readonly ttl?: HexString; + readonly workToProve?: HexString; + readonly priority?: HexString; + readonly expiry?: HexString; + readonly sent?: HexString; + readonly workProved?: HexString; + readonly topics?: HexString[]; +} +export interface PostOutput { + readonly ttl?: bigint | number; + readonly workToProve?: bigint | number; + readonly priority?: bigint | number; + readonly expiry?: bigint | number; + readonly sent?: bigint | number; + readonly workProved?: bigint | number; + readonly topics?: string[]; +} +export interface SyncInput { + readonly startingBlock: HexString; + readonly currentBlock: HexString; + readonly highestBlock: HexString; + readonly knownStates?: HexString; + readonly pulledStates?: HexString; +} +export interface SyncOutput { + readonly startingBlock: Numbers; + readonly currentBlock: Numbers; + readonly highestBlock: Numbers; + readonly knownStates?: Numbers; + readonly pulledStates?: Numbers; +} +export declare type Receipt = Record; +declare type FilterOption = Record; +export interface Filter { + readonly fromBlock?: BlockNumberOrTag; + readonly toBlock?: BlockNumberOrTag; + readonly address?: Address | Address[]; + readonly blockHash?: Address; + readonly topics?: (null | Topic | Topic[])[]; + readonly filter?: FilterOption; +} +export interface AccessListEntry { + readonly address?: Address; + readonly storageKeys?: HexString32Bytes[]; +} +export declare type AccessList = AccessListEntry[]; +export declare type AccessListResult = { + readonly accessList?: AccessList; + readonly gasUsed?: Numbers; +}; +export declare type ValidChains = 'goerli' | 'kovan' | 'mainnet' | 'rinkeby' | 'ropsten' | 'sepolia'; +export declare enum HardforksOrdered { + chainstart = "chainstart", + frontier = "frontier", + homestead = "homestead", + dao = "dao", + tangerineWhistle = "tangerineWhistle", + spuriousDragon = "spuriousDragon", + byzantium = "byzantium", + constantinople = "constantinople", + petersburg = "petersburg", + istanbul = "istanbul", + muirGlacier = "muirGlacier", + berlin = "berlin", + london = "london", + altair = "altair", + arrowGlacier = "arrowGlacier", + grayGlacier = "grayGlacier", + bellatrix = "bellatrix", + merge = "merge", + capella = "capella", + shanghai = "shanghai" +} +export declare type Hardfork = `${HardforksOrdered}`; +export interface LogBase { + readonly removed?: boolean; + readonly logIndex?: NumberType; + readonly transactionIndex?: NumberType; + readonly transactionHash?: ByteType; + readonly blockHash?: ByteType; + readonly blockNumber?: NumberType; + readonly address?: Address; + readonly data?: ByteType; + readonly topics?: ByteType[]; + readonly id?: string; +} +export interface Log extends LogBase { + readonly id?: string; +} +export interface EventLog { + readonly event: string; + readonly id?: string; + readonly logIndex?: bigint | number | string; + readonly transactionIndex?: bigint | number | string; + readonly transactionHash?: HexString32Bytes; + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: bigint | number | string; + readonly address: string; + readonly topics: HexString[]; + readonly data: HexString; + readonly raw?: { + data: string; + topics: unknown[]; + }; + readonly returnValues: Record; + readonly signature?: HexString; +} +export interface TransactionReceiptBase { + readonly transactionHash: hashByteType; + readonly transactionIndex: numberType; + readonly blockHash: hashByteType; + readonly blockNumber: numberType; + readonly from: Address; + readonly to: Address; + readonly cumulativeGasUsed: numberType; + readonly gasUsed: numberType; + readonly effectiveGasPrice?: numberType; + readonly contractAddress?: Address; + readonly logs: logsType[]; + readonly logsBloom: logsBloomByteType; + readonly root: hashByteType; + readonly status: numberType; + readonly type?: numberType; + events?: { + [key: string]: EventLog; + }; +} +export declare type TransactionReceipt = TransactionReceiptBase; +export interface CustomChain { + name?: string; + networkId: Numbers; + chainId: Numbers; +} +export interface Common { + customChain: CustomChain; + baseChain?: ValidChains; + hardfork?: Hardfork; +} +interface TransactionBase { + value?: Numbers; + accessList?: AccessList; + common?: Common; + gas?: Numbers; + gasPrice?: Numbers; + type?: Numbers; + maxFeePerGas?: Numbers; + maxPriorityFeePerGas?: Numbers; + data?: Bytes; + input?: Bytes; + nonce?: Numbers; + chain?: ValidChains; + hardfork?: Hardfork; + chainId?: Numbers; + networkId?: Numbers; + gasLimit?: Numbers; + yParity?: Uint; + v?: Numbers; + r?: Bytes; + s?: Bytes; +} +export interface Transaction extends TransactionBase { + from?: Address; + to?: Address | null; +} +export interface TransactionForAccessList extends Transaction { + from: Address; +} +export interface TransactionCall extends Transaction { + to: Address; +} +export interface TransactionWithFromLocalWalletIndex extends Omit { + from: Numbers; +} +export interface TransactionWithToLocalWalletIndex extends Omit { + to: Numbers; +} +export interface TransactionWithFromAndToLocalWalletIndex extends Omit { + from: Numbers; + to: Numbers; +} +export interface TransactionInfo extends Transaction { + readonly blockHash?: Bytes; + readonly blockNumber?: Numbers; + readonly from: Address; + readonly hash: Bytes; + readonly transactionIndex?: Numbers; +} +export interface PopulatedUnsignedBaseTransaction { + from: Address; + to?: Address; + value: Numbers; + gas?: Numbers; + gasPrice: Numbers; + type: Numbers; + input?: Bytes; + data?: Bytes; + nonce: Numbers; + networkId: Numbers; + chain: ValidChains; + hardfork: Hardfork; + chainId: Numbers; + common: Common; + gasLimit: Numbers; +} +export interface PopulatedUnsignedEip2930Transaction extends PopulatedUnsignedBaseTransaction { + accessList: AccessList; +} +export interface PopulatedUnsignedEip1559Transaction extends PopulatedUnsignedEip2930Transaction { + gasPrice: never; + maxFeePerGas: Numbers; + maxPriorityFeePerGas: Numbers; +} +export declare type PopulatedUnsignedTransaction = PopulatedUnsignedBaseTransaction | PopulatedUnsignedEip2930Transaction | PopulatedUnsignedEip1559Transaction; +export interface BlockBase { + readonly parentHash: ByteType; + readonly sha3Uncles: ByteType; + readonly miner: HexStringType; + readonly stateRoot: ByteType; + readonly transactionsRoot: ByteType; + readonly receiptsRoot: ByteType; + readonly logsBloom?: logsBloomType; + readonly difficulty?: NumberType; + readonly number: NumberType; + readonly gasLimit: NumberType; + readonly gasUsed: NumberType; + readonly timestamp: NumberType; + readonly extraData: extraDataType; + readonly mixHash: ByteType; + readonly nonce: NumberType; + readonly totalDifficulty: NumberType; + readonly baseFeePerGas?: NumberType; + readonly size: NumberType; + readonly transactions: TransactionTypes; + readonly uncles: Uncles; + readonly hash?: ByteType; +} +export declare type Block = BlockBase; +export interface FeeHistoryBase { + readonly oldestBlock: NumberType; + readonly baseFeePerGas: NumberType; + readonly reward: NumberType[][]; + readonly gasUsedRatio: NumberType[]; +} +export declare type FeeHistory = FeeHistoryBase; +export interface StorageProof { + readonly key: Bytes; + readonly value: Numbers; + readonly proof: Bytes[]; +} +export interface AccountObject { + readonly balance: Numbers; + readonly codeHash: Bytes; + readonly nonce: Numbers; + readonly storageHash: Bytes; + readonly accountProof: Bytes[]; + readonly storageProof: StorageProof[]; +} +export interface Eip712TypeDetails { + name: string; + type: string; +} +export interface Eip712TypedData { + readonly types: { + EIP712Domain: Eip712TypeDetails[]; + [key: string]: Eip712TypeDetails[]; + }; + readonly primaryType: string; + readonly domain: Record; + readonly message: Record; +} +export {}; +//# sourceMappingURL=eth_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/eth_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/eth_types.d.ts.map new file mode 100644 index 0000000..d015d0d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/eth_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth_types.d.ts","sourceRoot":"","sources":["../../src/eth_types.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAElE,oBAAY,UAAU,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEnG,oBAAY,gBAAgB,GAAG,SAAS,CAAC;AAEzC,oBAAY,gBAAgB,GAAG,SAAS,CAAC;AAEzC,oBAAY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,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;IACjD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/index.d.ts new file mode 100644 index 0000000..2383ba2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/index.d.ts @@ -0,0 +1,17 @@ +export * from './error_types.js'; +export * from './apis/eth_execution_api.js'; +export * from './apis/web3_eth_execution_api.js'; +export * from './apis/web3_net_api.js'; +export * from './apis/eth_personal_api.js'; +export * from './data_format_types.js'; +export * from './eth_types.js'; +export * from './eth_abi_types.js'; +export * from './eth_contract_types.js'; +export * from './json_rpc_types.js'; +export * from './primitives_types.js'; +export * from './utility_types.js'; +export * from './web3_api_types.js'; +export * from './web3_base_provider.js'; +export * from './web3_base_wallet.js'; +export * from './web3_deferred_promise_type.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/index.d.ts.map new file mode 100644 index 0000000..b705d7d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA,cAAc,kBAAkB,CAAC;AACjC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,kCAAkC,CAAC;AACjD,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iCAAiC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/json_rpc_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/json_rpc_types.d.ts new file mode 100644 index 0000000..1074c61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/json_rpc_types.d.ts @@ -0,0 +1,61 @@ +export declare type JsonRpcId = string | number | undefined; +export declare type JsonRpcResult = string | number | boolean | Record; +export declare type JsonRpcIdentifier = string & ('2.0' | '1.0'); +export interface JsonRpcError { + readonly code: number; + readonly message: string; + readonly data?: T; +} +export interface JsonRpcResponseWithError { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly error: JsonRpcError; + readonly result?: never; +} +export interface JsonRpcResponseWithResult { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly error?: never; + readonly result: T; +} +export interface SubscriptionParams { + readonly subscription: string; + readonly result: T; +} +export interface JsonRpcSubscriptionResultOld { + readonly error?: never; + readonly params?: never; + readonly type: string; + readonly data: SubscriptionParams; +} +export interface JsonRpcNotification { + readonly id?: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly method: string; + readonly params: SubscriptionParams; + readonly result: never; + readonly data?: never; +} +export interface JsonRpcSubscriptionResult { + readonly id: number; + readonly jsonrpc: string; + readonly result: string; + readonly method: never; + readonly params: never; + readonly data?: never; +} +export interface JsonRpcRequest { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly method: string; + readonly params?: T; +} +export interface JsonRpcOptionalRequest extends Omit, 'id' | 'jsonrpc'> { + readonly id?: JsonRpcId; + readonly jsonrpc?: JsonRpcIdentifier; +} +export declare type JsonRpcBatchRequest = JsonRpcRequest[]; +export declare type JsonRpcPayload = JsonRpcRequest | JsonRpcBatchRequest; +export declare type JsonRpcBatchResponse = (JsonRpcResponseWithError | JsonRpcResponseWithResult)[]; +export declare type JsonRpcResponse = JsonRpcResponseWithError | JsonRpcResponseWithResult | JsonRpcBatchResponse; +//# sourceMappingURL=json_rpc_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/json_rpc_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/json_rpc_types.d.ts.map new file mode 100644 index 0000000..46b2cd2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/json_rpc_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json_rpc_types.d.ts","sourceRoot":"","sources":["../../src/json_rpc_types.ts"],"names":[],"mappings":"AAgBA,oBAAY,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AACpD,oBAAY,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAChF,oBAAY,iBAAiB,GAAG,MAAM,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC;AAEzD,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,aAAa;IAC9C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;CAClB;AAED,MAAM,WAAW,wBAAwB,CAAC,KAAK,GAAG,aAAa;IAC9D,QAAQ,CAAC,EAAE,EAAE,SAAS,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC;IACpC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC;CACxB;AAED,MAAM,WAAW,yBAAyB,CAAC,CAAC,GAAG,a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K,CAAC;CACtB;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,GAAG,OAAO,EAAE;IAC5C,QAAQ,CAAC,EAAE,EAAE,SAAS,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;CACpB;AAED,MAAM,WAAW,sBAAsB,CAAC,SAAS,GAAG,OAAO,EAAE,CAC5D,SAAQ,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC;IACzD,QAAQ,CAAC,EAAE,CAAC,EAAE,SAAS,CAAC;IACxB,QAAQ,CAAC,OAAO,CAAC,EAAE,iBAAiB,CAAC;CACrC;AAED,oBAAY,mBAAmB,GAAG,cAAc,EAAE,CAAC;AAEnD,oBAAY,cAAc,CAAC,KAAK,GAAG,OAAO,EAAE,IAAI,cAAc,CAAC,KAAK,CAAC,GAAG,mBAAmB,CAAC;AAE5F,oBAAY,oBAAoB,CAAC,MAAM,GAAG,aAAa,EAAE,KAAK,GAAG,aAAa,IAC3E,CAAC,wBAAwB,CAAC,KAAK,CAAC,GAAG,yBAAyB,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;AAE3E,oBAAY,eAAe,CAAC,MAAM,GAAG,aAAa,EAAE,KAAK,GAAG,aAAa,IACtE,wBAAwB,CAAC,KAAK,CAAC,GAC/B,yBAAyB,CAAC,MAAM,CAAC,GACjC,oBAAoB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/primitives_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/primitives_types.d.ts new file mode 100644 index 0000000..3b4cb74 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/primitives_types.d.ts @@ -0,0 +1,5 @@ +export declare type HexString = string; +export declare type Bytes = Uint8Array | HexString; +export declare type Numbers = number | bigint | string | HexString; +export declare const TypedArray: any; +//# sourceMappingURL=primitives_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/primitives_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/primitives_types.d.ts.map new file mode 100644 index 0000000..abb72d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/primitives_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"primitives_types.d.ts","sourceRoot":"","sources":["../../src/primitives_types.ts"],"names":[],"mappings":"AAiBA,oBAAY,SAAS,GAAG,MAAM,CAAC;AAC/B,oBAAY,KAAK,GAAG,UAAU,GAAG,SAAS,CAAC;AAC3C,oBAAY,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAG3D,eAAO,MAAM,UAAU,KAAoC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/utility_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/utility_types.d.ts new file mode 100644 index 0000000..8cdca12 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/utility_types.d.ts @@ -0,0 +1,32 @@ +import { Numbers } from './primitives_types.js'; +export declare type Mutable = { + -readonly [P in keyof T]: T[P]; +}; +export declare type ConnectionEvent = { + code: number; + reason: string; + wasClean?: boolean; +}; +export declare type Optional = Pick, K> & Omit; +export declare type EncodingTypes = Numbers | boolean | Numbers[] | boolean[]; +export declare type TypedObject = { + type: string; + value: EncodingTypes; +}; +export declare type TypedObjectAbbreviated = { + t: string; + v: EncodingTypes; +}; +export declare type Sha3Input = TypedObject | TypedObjectAbbreviated | Numbers | boolean | object; +export declare type IndexKeysForArray = Exclude; +export declare type ArrayToIndexObject> = { + [K in IndexKeysForArray]: T[K]; +}; +declare type _Grow> = ((x: T, ...xs: A) => void) extends (...a: infer X) => void ? X : never; +export declare type GrowToSize, N extends number> = { + 0: A; + 1: GrowToSize, N>; +}[A['length'] extends N ? 0 : 1]; +export declare type FixedSizeArray = GrowToSize; +export {}; +//# sourceMappingURL=utility_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/utility_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/utility_types.d.ts.map new file mode 100644 index 0000000..1263b3b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/utility_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utility_types.d.ts","sourceRoot":"","sources":["../../src/utility_types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAGhD,oBAAY,OAAO,CAAC,CAAC,IAAI;IACxB,CAAC,UAAU,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAC9B,CAAC;AAEF,oBAAY,eAAe,GAAG;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,oBAAY,QAAQ,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC9E,oBAAY,aAAa,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;AAEtE,oBAAY,WAAW,GAAG;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,aAAa,CAAC;CACrB,CAAC;AAEF,oBAAY,sBAAsB,GAAG;IACpC,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,aAAa,CAAC;CACjB,CAAC;AAEF,oBAAY,SAAS,GAAG,WAAW,GAAG,sBAAsB,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;AAE1F,oBAAY,iBAAiB,CAAC,CAAC,SAAS,SAAS,OAAO,EAAE,IAAI,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AAEzF,oBAAY,kBAAkB,CAAC,CAAC,SAAS,aAAa,CAAC,OAAO,CAAC,IAAI;KACjE,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CACjC,CAAC;AAEF,aAAK,KAAK,CAAC,CAAC,EAAE,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,KAAK,IAAI,GAC3F,CAAC,GACD,KAAK,CAAC;AAET,oBAAY,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,IAAI;IACjE,CAAC,EAAE,CAAC,CAAC;IACL,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;CACjC,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;AAEjC,oBAAY,cAAc,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,IAAI,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_api_types.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/web3_api_types.d.ts new file mode 100644 index 0000000..12bbb38 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_api_types.d.ts @@ -0,0 +1,33 @@ +import { JsonRpcId, JsonRpcIdentifier } from './json_rpc_types.js'; +export interface ProviderMessage { + readonly type: string; + readonly data: unknown; +} +export interface EthSubscription extends ProviderMessage { + readonly type: 'eth_subscription'; + readonly data: { + readonly subscription: string; + readonly result: unknown; + }; +} +export interface ProviderRpcError extends Error { + code: number; + data?: unknown; +} +export interface ProviderConnectInfo { + readonly chainId: string; +} +export declare type Web3APISpec = Record any> | unknown; +export declare type Web3APIMethod = string & keyof Exclude; +export declare type Web3APIParams> = API extends Exclude ? Parameters : unknown; +export interface Web3APIRequest> { + method: Method | string; + params?: Web3APIParams | readonly unknown[] | object; +} +export interface Web3APIPayload> extends Web3APIRequest { + readonly jsonrpc?: JsonRpcIdentifier; + readonly id?: JsonRpcId; + readonly requestOptions?: unknown; +} +export declare type Web3APIReturnType> = API extends Record any> ? ReturnType : any; +//# sourceMappingURL=web3_api_types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_api_types.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/web3_api_types.d.ts.map new file mode 100644 index 0000000..68377de --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_api_types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_api_types.d.ts","sourceRoot":"","sources":["../../src/web3_api_types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAEnE,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,eAAgB,SAAQ,eAAe;IACvD,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,IAAI,EAAE;QACd,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;QAC9B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;KACzB,CAAC;CACF;AAED,MAAM,WAAW,gBAAiB,SAAQ,KAAK;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OA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AC,GAAG,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,GAAG,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_provider.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_provider.d.ts new file mode 100644 index 0000000..7d642f1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_provider.d.ts @@ -0,0 +1,123 @@ +/// +import { Socket } from 'net'; +import { Web3Error } from './error_types.js'; +import { EthExecutionAPI } from './apis/eth_execution_api.js'; +import { JsonRpcNotification, JsonRpcPayload, JsonRpcResponse, JsonRpcResponseWithError, JsonRpcResponseWithResult, JsonRpcResult, JsonRpcSubscriptionResult } from './json_rpc_types'; +import { Web3APISpec, Web3APIMethod, Web3APIReturnType, Web3APIPayload, ProviderConnectInfo, ProviderRpcError, ProviderMessage } from './web3_api_types'; +import { Web3EthExecutionAPI } from './apis/web3_eth_execution_api'; +import { Web3DeferredPromiseInterface } from './web3_deferred_promise_type'; +declare const symbol: unique symbol; +export interface SocketRequestItem, ResponseType> { + payload: Web3APIPayload; + deferredPromise: Web3DeferredPromiseInterface; +} +export declare type Web3ProviderStatus = 'connecting' | 'connected' | 'disconnected'; +export declare type Web3ProviderEventCallback = (error: Error | ProviderRpcError | undefined, result?: JsonRpcSubscriptionResult | JsonRpcNotification) => void; +export declare type Web3ProviderMessageEventCallback = (result?: JsonRpcSubscriptionResult | JsonRpcNotification) => void; +export declare type Web3Eip1193ProviderEventCallback = (data: T) => void; +export declare type Web3ProviderRequestCallback = (err?: Error | Web3Error | null | JsonRpcResponseWithError, response?: JsonRpcResponseWithResult) => void; +export interface LegacySendProvider { + send(payload: JsonRpcPayload

, callback: (err: Error | null, response?: JsonRpcResponse) => void): void; +} +export interface LegacySendAsyncProvider { + sendAsync(payload: JsonRpcPayload

): Promise>; +} +export interface LegacyRequestProvider { + request(payload: JsonRpcPayload

, callback: (err: Error | null, response: JsonRpcResponse) => void): void; +} +export interface SimpleProvider { + request, ResponseType = Web3APIReturnType>(args: Web3APIPayload): Promise | unknown>; +} +export interface ProviderInfo { + chainId: string; +} +export declare type ProviderChainId = string; +export declare type ProviderAccounts = string[]; +export declare type Eip1193EventName = 'connect' | 'disconnect' | 'message' | 'chainChanged' | 'accountsChanged'; +export interface EIP1193Provider extends SimpleProvider { + on(event: 'connect', listener: (info: ProviderInfo) => void): void; + on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + on(event: 'message', listener: (message: ProviderMessage) => void): void; + on(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + on(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + removeListener(event: 'connect', listener: (info: ProviderInfo) => void): void; + removeListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + removeListener(event: 'message', listener: (message: ProviderMessage) => void): void; + removeListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + removeListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; +} +export interface MetaMaskProvider extends SimpleProvider { + on(event: 'connect', listener: (info: ProviderInfo) => void): void; + on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + on(event: 'message', listener: (message: ProviderMessage) => void): void; + on(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + on(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + removeListener(event: 'connect', listener: (info: ProviderInfo) => void): void; + removeListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + removeListener(event: 'message', listener: (message: ProviderMessage) => void): void; + removeListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + removeListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + isMetaMask: boolean; +} +export declare type Eip1193Compatible = Omit, 'asEIP1193Provider'> & { + request, ResultType = Web3APIReturnType | unknown>(request: Web3APIPayload): Promise; +}; +export declare abstract class Web3BaseProvider implements LegacySendProvider, LegacySendAsyncProvider, EIP1193Provider { + static isWeb3Provider(provider: unknown): boolean; + get [symbol](): boolean; + abstract getStatus(): Web3ProviderStatus; + abstract supportsSubscriptions(): boolean; + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + * @param callback - Callback + */ + send(payload: JsonRpcPayload

, callback: (err: Error | null, response?: JsonRpcResponse) => void): void; + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + */ + sendAsync(payload: JsonRpcPayload

): Promise>; + /** + * Modify the return type of the request method to be fully compatible with EIP-1193 + * + * [deprecated] In the future major releases (\>= v5) all providers are supposed to be fully compatible with EIP-1193. + * So this method will not be needed and would not be available in the future. + * + * @returns A new instance of the provider with the request method fully compatible with EIP-1193 + * + * @example + * ```ts + * const provider = new Web3HttpProvider('http://localhost:8545'); + * const fullyCompatibleProvider = provider.asEIP1193Provider(); + * const result = await fullyCompatibleProvider.request({ method: 'eth_getBalance' }); + * console.log(result); // '0x0234c8a3397aab58' or something like that + * ``` + */ + asEIP1193Provider(): Eip1193Compatible; + abstract request, ResultType = Web3APIReturnType | unknown>(args: Web3APIPayload): Promise>; + abstract on(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + abstract on(type: 'message' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + abstract on(type: 'data' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + abstract on(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + abstract on(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract on(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'message' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + abstract removeListener(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeListener(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'message' | string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + abstract once(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract once(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + abstract removeAllListeners?(type: string): void; + abstract connect(): void; + abstract disconnect(code?: number, data?: string): void; + abstract reset(): void; +} +export declare type SupportedProviders = EIP1193Provider | Web3BaseProvider | LegacyRequestProvider | LegacySendProvider | LegacySendAsyncProvider | SimpleProvider | MetaMaskProvider; +export declare type Web3BaseProviderConstructor = new (url: string, net?: Socket) => Web3BaseProvider; +export {}; +//# sourceMappingURL=web3_base_provider.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_provider.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_provider.d.ts.map new file mode 100644 index 0000000..500c2ec --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_base_provider.d.ts","sourceRoot":"","sources":["../../src/web3_base_provider.ts"],"names":[],"mappings":";AAgBA,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAE7B,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAE9D,OAAO,EACN,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,wBAAwB,EACxB,yBAAyB,EACzB,aAAa,EACb,yBAAyB,EACzB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACN,WAAW,EACX,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,gBAAgB,EAChB,eAAe,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,mBAA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C,IAAI,EAAE,SAAS,GAAG,MAAM,EACxB,QAAQ,EAAE,gCAAgC,CAAC,eAAe,CAAC,GAAG,yBAAyB,CAAC,CAAC,CAAC,GACxF,IAAI;aACS,IAAI,CACnB,IAAI,EAAE,SAAS,EACf,QAAQ,EAAE,gCAAgC,CAAC,mBAAmB,CAAC,GAC7D,IAAI;aACS,IAAI,CACnB,IAAI,EAAE,cAAc,EACpB,QAAQ,EAAE,gCAAgC,CAAC,MAAM,CAAC,GAChD,IAAI;aACS,IAAI,CACnB,IAAI,EAAE,iBAAiB,EACvB,QAAQ,EAAE,gCAAgC,CAAC,MAAM,EAAE,CAAC,GAClD,IAAI;aACS,kBAAkB,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;aACvC,OAAO,IAAI,IAAI;aACf,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;aAC9C,KAAK,IAAI,IAAI;CAC7B;AAED,oBAAY,kBAAkB,CAAC,GAAG,SAAS,WAAW,GAAG,mBAAmB,IACzE,eAAe,CAAC,GAAG,CAAC,GACpB,gBAAgB,CAAC,GAAG,CAAC,GACrB,qBAAqB,GACrB,kBAAkB,GAClB,uBAAuB,GACvB,cAAc,CAAC,GAAG,CAAC,GACnB,gBAAgB,CAAC,GAAG,CAAC,CAAC;AAEzB,oBAAY,2BAA2B,GAAG,KAAK,GAAG,SAAS,WAAW,EACrE,GAAG,EAAE,MAAM,EACX,GAAG,CAAC,EAAE,MAAM,KACR,gBAAgB,CAAC,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_wallet.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_wallet.d.ts new file mode 100644 index 0000000..48811be --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_wallet.d.ts @@ -0,0 +1,82 @@ +import { Transaction } from './eth_types.js'; +import { HexString } from './primitives_types.js'; +export declare type Cipher = 'aes-128-ctr' | 'aes-128-cbc' | 'aes-256-cbc'; +export declare type CipherOptions = { + salt?: Uint8Array | string; + iv?: Uint8Array | string; + kdf?: 'scrypt' | 'pbkdf2'; + dklen?: number; + c?: number; + n?: number; + r?: number; + p?: number; +}; +export declare type ScryptParams = { + dklen: number; + n: number; + p: number; + r: number; + salt: Uint8Array | string; +}; +export declare type PBKDF2SHA256Params = { + c: number; + dklen: number; + prf: 'hmac-sha256'; + salt: Uint8Array | string; +}; +export declare type KeyStore = { + crypto: { + cipher: Cipher; + ciphertext: string; + cipherparams: { + iv: string; + }; + kdf: 'pbkdf2' | 'scrypt'; + kdfparams: ScryptParams | PBKDF2SHA256Params; + mac: HexString; + }; + id: string; + version: 3; + address: string; +}; +export interface Web3BaseWalletAccount { + [key: string]: unknown; + readonly address: string; + readonly privateKey: string; + readonly signTransaction: (tx: Transaction) => Promise<{ + readonly messageHash: HexString; + readonly r: HexString; + readonly s: HexString; + readonly v: HexString; + readonly rawTransaction: HexString; + readonly transactionHash: HexString; + }>; + readonly sign: (data: Record | string) => { + readonly messageHash: HexString; + readonly r: HexString; + readonly s: HexString; + readonly v: HexString; + readonly message?: string; + readonly signature: HexString; + }; + readonly encrypt: (password: string, options?: Record) => Promise; +} +export interface Web3AccountProvider { + privateKeyToAccount: (privateKey: string) => T; + create: () => T; + decrypt: (keystore: KeyStore | string, password: string, options?: Record) => Promise; +} +export declare abstract class Web3BaseWallet extends Array { + protected readonly _accountProvider: Web3AccountProvider; + constructor(accountProvider: Web3AccountProvider); + abstract create(numberOfAccounts: number): this; + abstract add(account: T | string): this; + abstract get(addressOrIndex: string | number): T | undefined; + abstract remove(addressOrIndex: string | number): boolean; + abstract clear(): this; + abstract encrypt(password: string, options?: Record): Promise; + abstract decrypt(encryptedWallet: KeyStore[], password: string, options?: Record): Promise; + abstract save(password: string, keyName?: string): Promise; + abstract load(password: string, keyName?: string): Promise; +} +//# sourceMappingURL=web3_base_wallet.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_wallet.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_wallet.d.ts.map new file mode 100644 index 0000000..d58e9a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_base_wallet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_base_wallet.d.ts","sourceRoot":"","sources":["../../src/web3_base_wallet.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD,oBAAY,MAAM,GAAG,aAAa,GAAG,aAAa,GAAG,aAAa,CAAC;AAEnE,oBAAY,aAAa,GAAG;IAC3B,IAAI,CAAC,EAAE,UAAU,GAAG,MAAM,CAAC;IAC3B,EAAE,CAAC,EAAE,UAAU,GAAG,MAAM,CAAC;IACzB,GAAG,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,CAAC,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AAEF,oBAAY,YAAY,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,EAAE,UAAU,GAAG,MAAM,CAAC;CAC1B,CAAC;AACF,oBAAY,kBAAkB,GAAG;IAChC,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,aAAa,CAAC;IACnB,IAAI,EAAE,UAAU,GAAG,MAAM,CAAC;CAC1B,CAAC;AAEF,oBAAY,QAAQ,GAAG;IACtB,MAAM,EAA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AC,GAC/B,OAAO,CAAC,IAAI,CAAC;aACA,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,KAAK,CAAC;aAClE,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC;CAC/E"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_deferred_promise_type.d.ts b/test/merkletreejs/node_modules/web3-types/lib/types/web3_deferred_promise_type.d.ts new file mode 100644 index 0000000..8ee9746 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_deferred_promise_type.d.ts @@ -0,0 +1,7 @@ +export interface Web3DeferredPromiseInterface extends Promise { + state: 'pending' | 'fulfilled' | 'rejected'; + resolve(value: T | PromiseLike): void; + reject(reason?: unknown): void; + startTimer(): void; +} +//# sourceMappingURL=web3_deferred_promise_type.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/lib/types/web3_deferred_promise_type.d.ts.map b/test/merkletreejs/node_modules/web3-types/lib/types/web3_deferred_promise_type.d.ts.map new file mode 100644 index 0000000..de815eb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/lib/types/web3_deferred_promise_type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_deferred_promise_type.d.ts","sourceRoot":"","sources":["../../src/web3_deferred_promise_type.ts"],"names":[],"mappings":"AAiBA,MAAM,WAAW,4BAA4B,CAAC,CAAC,CAAE,SAAQ,OAAO,CAAC,CAAC,CAAC;IAClE,KAAK,EAAE,SAAS,GAAG,WAAW,GAAG,UAAU,CAAC;IAC5C,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IACzC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B,UAAU,IAAI,IAAI,CAAC;CACnB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-types/package.json b/test/merkletreejs/node_modules/web3-types/package.json new file mode 100644 index 0000000..1241632 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/package.json @@ -0,0 +1,60 @@ +{ + "name": "web3-types", + "version": "1.3.1", + "description": "Provide the common data structures and interfaces for web3 modules.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --passWithNoTests --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js --passWithNoTests", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "devDependencies": { + "@humeris/espresso-shot": "^4.0.0", + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "gitHead": "a616752f406a8f52f754c5d2fb7343ff8c811b23" +} diff --git a/test/merkletreejs/node_modules/web3-types/src/apis/eth_execution_api.ts b/test/merkletreejs/node_modules/web3-types/src/apis/eth_execution_api.ts new file mode 100644 index 0000000..e015e6b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/apis/eth_execution_api.ts @@ -0,0 +1,294 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { + Address, + HexString32Bytes, + Uint, + HexStringBytes, + HexStringSingleByte, + HexString256Bytes, + FeeHistoryBase, + HexString8Bytes, + Uint256, + BlockNumberOrTag, + Filter, + AccessList, + TransactionHash, + TransactionReceiptBase, + BlockBase, + LogBase, +} from '../eth_types.js'; +import { HexString } from '../primitives_types.js'; + +// The types are generated manually by referring to following doc +// https://github.com/ethereum/execution-apis +// These types follow closely to the v1.0.0-alpha.9 Ethereum spec +export interface TransactionCallAPI { + readonly from?: Address; + readonly to: Address; + readonly gas?: Uint; + readonly gasPrice?: Uint; + readonly value?: Uint; + readonly data?: HexStringBytes; + readonly type?: HexStringSingleByte; + readonly maxFeePerGas?: Uint; + readonly maxPriorityFeePerGas?: Uint; + readonly accessList?: AccessList; +} + +export interface BaseTransactionAPI { + // eslint-disable-next-line @typescript-eslint/ban-types + readonly to?: Address | null; + readonly type: HexStringSingleByte; + readonly nonce: Uint; + readonly gas: Uint; + readonly value: Uint; + // TODO - https://github.com/ethereum/execution-apis/pull/201 + readonly input: HexStringBytes; + readonly data?: HexStringBytes; + readonly chainId?: Uint; + readonly hash?: HexString32Bytes; +} + +export interface Transaction1559UnsignedAPI extends BaseTransactionAPI { + readonly maxFeePerGas: Uint; + readonly maxPriorityFeePerGas: Uint; + readonly accessList: AccessList; + readonly gasPrice: Uint; +} + +export interface Transaction1559SignedAPI extends Transaction1559UnsignedAPI { + readonly yParity: Uint; + readonly r: Uint; + readonly s: Uint; + readonly v?: never; +} + +export interface Transaction2930UnsignedAPI extends BaseTransactionAPI { + readonly gasPrice: Uint; + readonly accessList: AccessList; + readonly maxFeePerGas?: never; + readonly maxPriorityFeePerGas?: never; +} + +export interface Transaction2930SignedAPI extends Transaction2930UnsignedAPI { + readonly yParity: Uint; + readonly r: Uint; + readonly s: Uint; + readonly v?: never; +} + +export interface TransactionLegacyUnsignedAPI extends BaseTransactionAPI { + readonly gasPrice: Uint; + readonly accessList?: never; + readonly maxFeePerGas?: never; + readonly maxPriorityFeePerGas?: never; +} + +export interface TransactionLegacySignedAPI extends TransactionLegacyUnsignedAPI { + readonly v: Uint; + readonly r: Uint; + readonly s: Uint; +} + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml#L144 +export type TransactionUnsignedAPI = + | Transaction1559UnsignedAPI + | Transaction2930UnsignedAPI + | TransactionLegacyUnsignedAPI; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml#L211 +export type TransactionSignedAPI = + | Transaction1559SignedAPI + | Transaction2930SignedAPI + | TransactionLegacySignedAPI; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml#L216 +export type TransactionInfoAPI = TransactionSignedAPI & { + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: Uint; + readonly from: Address; + readonly hash: HexString32Bytes; + readonly transactionIndex?: Uint; +}; + +export interface SignedTransactionInfoAPI { + raw: HexStringBytes; + tx: TransactionSignedAPI; +} + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml#L244 +export type TransactionWithSenderAPI = TransactionUnsignedAPI & { from: Address }; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/block.yaml#L2 +export type BlockAPI = BlockBase< + HexString32Bytes, + HexString, + Uint, + HexStringBytes, + TransactionHash[] | TransactionInfoAPI[], + HexString256Bytes +>; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/receipt.yaml#L2 +export type LogAPI = LogBase; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/receipt.yaml#L36 +export type TransactionReceiptAPI = TransactionReceiptBase< + Uint, + HexString32Bytes, + HexString256Bytes, + LogAPI +>; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/client.yaml#L2 +export type SyncingStatusAPI = + | { startingBlock: Uint; currentBlock: Uint; highestBlock: Uint } + | boolean; + +// https://github.com/ethereum/execution-apis/blob/main/src/eth/fee_market.yaml#L42 +export type FeeHistoryResultAPI = FeeHistoryBase; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/filter.yaml#L2 +export type FilterResultsAPI = HexString32Bytes[] | LogAPI[]; + +export interface CompileResultAPI { + readonly code: HexStringBytes; + readonly info: { + readonly source: string; + readonly language: string; + readonly languageVersion: string; + readonly compilerVersion: string; + readonly abiDefinition: Record[]; + readonly userDoc: { + readonly methods: Record; + }; + readonly developerDoc: { + readonly methods: Record; + }; + }; +} + +/* eslint-disable camelcase */ +export type EthExecutionAPI = { + // https://github.com/ethereum/execution-apis/blob/main/src/eth/block.yaml + eth_getBlockByHash: (blockHash: HexString32Bytes, hydrated: boolean) => BlockAPI; + eth_getBlockByNumber: (blockNumber: BlockNumberOrTag, hydrated: boolean) => BlockAPI; + eth_getBlockTransactionCountByHash: (blockHash: HexString32Bytes) => Uint; + eth_getBlockTransactionCountByNumber: (blockNumber: BlockNumberOrTag) => Uint; + eth_getUncleCountByBlockHash: (blockHash: HexString32Bytes) => Uint; + eth_getUncleCountByBlockNumber: (blockNumber: BlockNumberOrTag) => Uint; + eth_getUncleByBlockHashAndIndex: (blockHash: HexString32Bytes, uncleIndex: Uint) => BlockAPI; + eth_getUncleByBlockNumberAndIndex: ( + blockNumber: BlockNumberOrTag, + uncleIndex: Uint, + ) => BlockAPI; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/transaction.yaml + eth_getTransactionByHash: (transactionHash: HexString32Bytes) => TransactionInfoAPI | undefined; + eth_getTransactionByBlockHashAndIndex: ( + blockHash: HexString32Bytes, + transactionIndex: Uint, + ) => TransactionInfoAPI | undefined; + eth_getTransactionByBlockNumberAndIndex: ( + blockNumber: BlockNumberOrTag, + transactionIndex: Uint, + ) => TransactionInfoAPI | undefined; + eth_getTransactionReceipt: ( + transactionHash: HexString32Bytes, + ) => TransactionReceiptAPI | undefined; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/client.yaml + eth_protocolVersion: () => string; + eth_syncing: () => SyncingStatusAPI; + eth_coinbase: () => Address; + eth_accounts: () => Address[]; + eth_blockNumber: () => Uint; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/execute.yaml + eth_call: (transaction: TransactionCallAPI, blockNumber: BlockNumberOrTag) => HexStringBytes; + eth_estimateGas: ( + transaction: Partial, + blockNumber: BlockNumberOrTag, + ) => Uint; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/fee_market.yaml + eth_gasPrice: () => Uint; + eth_feeHistory: ( + blockCount: Uint, + newestBlock: BlockNumberOrTag, + rewardPercentiles: number[], + ) => FeeHistoryResultAPI; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/filter.yaml + eth_newFilter: (filter: Filter) => Uint; + eth_newBlockFilter: () => Uint; + eth_newPendingTransactionFilter: () => Uint; + eth_uninstallFilter: (filterIdentifier: Uint) => boolean; + eth_getFilterChanges: (filterIdentifier: Uint) => FilterResultsAPI; + eth_getFilterLogs: (filterIdentifier: Uint) => FilterResultsAPI; + eth_getLogs: (filter: Filter) => FilterResultsAPI; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/mining.yaml + eth_mining: () => boolean; + eth_hashrate: () => Uint; + eth_getWork: () => [HexString32Bytes, HexString32Bytes, HexString32Bytes]; + eth_submitWork: ( + nonce: HexString8Bytes, + hash: HexString32Bytes, + digest: HexString32Bytes, + ) => boolean; + eth_submitHashrate: (hashRate: HexString32Bytes, id: HexString32Bytes) => boolean; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/sign.yaml + eth_sign: (address: Address, message: HexStringBytes) => HexString256Bytes; + eth_signTransaction: ( + transaction: TransactionWithSenderAPI | Partial, + ) => HexStringBytes | SignedTransactionInfoAPI; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/state.yaml + eth_getBalance: (address: Address, blockNumber: BlockNumberOrTag) => Uint; + eth_getStorageAt: ( + address: Address, + storageSlot: Uint256, + blockNumber: BlockNumberOrTag, + ) => HexStringBytes; + eth_getTransactionCount: (address: Address, blockNumber: BlockNumberOrTag) => Uint; + eth_getCode: (address: Address, blockNumber: BlockNumberOrTag) => HexStringBytes; + + // https://github.com/ethereum/execution-apis/blob/main/src/eth/submit.yaml + eth_sendTransaction: ( + transaction: TransactionWithSenderAPI | Partial, + ) => HexString32Bytes; + eth_sendRawTransaction: (transaction: HexStringBytes) => HexString32Bytes; + + // https://geth.ethereum.org/docs/rpc/pubsub + eth_subscribe: ( + ...params: + | ['newHeads'] + | ['newPendingTransactions'] + | ['syncing'] + | ['logs', { address?: HexString; topics?: HexString[] }] + ) => HexString; + eth_unsubscribe: (subscriptionId: HexString) => HexString; + eth_clearSubscriptions: (keepSyncing?: boolean) => void; + // Non-supported by execution-apis specs + eth_getCompilers: () => string[]; + eth_compileSolidity: (code: string) => CompileResultAPI; + eth_compileLLL: (code: string) => HexStringBytes; + eth_compileSerpent: (code: string) => HexStringBytes; +}; diff --git a/test/merkletreejs/node_modules/web3-types/src/apis/eth_personal_api.ts b/test/merkletreejs/node_modules/web3-types/src/apis/eth_personal_api.ts new file mode 100644 index 0000000..cab41b2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/apis/eth_personal_api.ts @@ -0,0 +1,30 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Address, Transaction } from '../eth_types.js'; +import { HexString } from '../primitives_types.js'; + +export type EthPersonalAPI = { + personal_listAccounts: () => Address[]; + personal_newAccount: (password: string) => Address; + personal_unlockAccount: (address: Address, password: string, unlockDuration: number) => boolean; + personal_lockAccount: (address: Address) => boolean; + personal_importRawKey: (keyData: HexString, passphrase: string) => HexString; + personal_sendTransaction: (tx: Transaction, passphrase: string) => HexString; + personal_signTransaction: (tx: Transaction, passphrase: string) => HexString; + personal_sign: (data: HexString, address: Address, passphrase: string) => HexString; + personal_ecRecover: (signedData: HexString, signature: HexString) => Address; +}; diff --git a/test/merkletreejs/node_modules/web3-types/src/apis/web3_eth_execution_api.ts b/test/merkletreejs/node_modules/web3-types/src/apis/web3_eth_execution_api.ts new file mode 100644 index 0000000..fde1250 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/apis/web3_eth_execution_api.ts @@ -0,0 +1,60 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { EthExecutionAPI } from './eth_execution_api.js'; +import { + AccountObject, + Address, + BlockNumberOrTag, + Eip712TypedData, + HexString256Bytes, + HexString32Bytes, + TransactionInfo, + Uint, +} from '../eth_types.js'; + +export type Web3EthExecutionAPI = EthExecutionAPI & { + eth_pendingTransactions: () => TransactionInfo[]; + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md + eth_requestAccounts: () => Address[]; + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md + eth_chainId: () => Uint; + + web3_clientVersion: () => string; + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md + eth_getProof: ( + address: Address, + storageKeys: HexString32Bytes[], + blockNumber: BlockNumberOrTag, + ) => AccountObject; + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md + eth_signTypedData: ( + address: Address, + typedData: Eip712TypedData, + useLegacy: true, + ) => HexString256Bytes; + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md + eth_signTypedData_v4: ( + address: Address, + typedData: Eip712TypedData, + useLegacy: false | undefined, + ) => HexString256Bytes; +}; diff --git a/test/merkletreejs/node_modules/web3-types/src/apis/web3_net_api.ts b/test/merkletreejs/node_modules/web3-types/src/apis/web3_net_api.ts new file mode 100644 index 0000000..2cb3566 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/apis/web3_net_api.ts @@ -0,0 +1,23 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { HexString } from '../primitives_types.js'; + +export type Web3NetAPI = { + net_version: () => string; // https://eth.wiki/json-rpc/API#net_version + net_peerCount: () => HexString; // https://eth.wiki/json-rpc/API#net_peercount + net_listening: () => boolean; // https://eth.wiki/json-rpc/API#net_listening +}; diff --git a/test/merkletreejs/node_modules/web3-types/src/data_format_types.ts b/test/merkletreejs/node_modules/web3-types/src/data_format_types.ts new file mode 100644 index 0000000..f0ffe3b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/data_format_types.ts @@ -0,0 +1,60 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Bytes, HexString, Numbers } from './primitives_types.js'; + +export enum FMT_NUMBER { + NUMBER = 'NUMBER_NUMBER', + HEX = 'NUMBER_HEX', + STR = 'NUMBER_STR', + BIGINT = 'NUMBER_BIGINT', +} + +export type NumberTypes = { + [FMT_NUMBER.NUMBER]: number; + [FMT_NUMBER.HEX]: HexString; + [FMT_NUMBER.STR]: string; + [FMT_NUMBER.BIGINT]: bigint; +}; + +export enum FMT_BYTES { + HEX = 'BYTES_HEX', + UINT8ARRAY = 'BYTES_UINT8ARRAY', +} + +export type ByteTypes = { + [FMT_BYTES.HEX]: HexString; + [FMT_BYTES.UINT8ARRAY]: Uint8Array; +}; + +export type DataFormat = { + readonly number: FMT_NUMBER; + readonly bytes: FMT_BYTES; +}; + +export const DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX } as const; +export const ETH_DATA_FORMAT = { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX } as const; + +export type FormatType = number extends Extract + ? NumberTypes[F['number']] | Exclude + : Uint8Array extends Extract + ? ByteTypes[F['bytes']] | Exclude + : T extends object | undefined + ? { + [P in keyof T]: FormatType; + } + : T; diff --git a/test/merkletreejs/node_modules/web3-types/src/error_types.ts b/test/merkletreejs/node_modules/web3-types/src/error_types.ts new file mode 100644 index 0000000..4891b87 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/error_types.ts @@ -0,0 +1,39 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export interface Web3Error extends Error { + readonly name: string; + readonly code: number; + readonly stack?: string; +} + +export type Web3ValidationErrorObject< + K extends string = string, + P = Record, + S = unknown, +> = { + keyword: K; + instancePath: string; + schemaPath: string; + params: P; + // Added to validation errors of "propertyNames" keyword schema + propertyName?: string; + // Excluded if option `messages` set to false. + message?: string; + schema?: S; + data?: unknown; +}; diff --git a/test/merkletreejs/node_modules/web3-types/src/eth_abi_types.ts b/test/merkletreejs/node_modules/web3-types/src/eth_abi_types.ts new file mode 100644 index 0000000..acd75e5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/eth_abi_types.ts @@ -0,0 +1,364 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Address } from './eth_types.js'; +import { Bytes, Numbers } from './primitives_types.js'; +import { FixedSizeArray } from './utility_types.js'; + +type _SolidityIndexRange = + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 18 + | 19 + | 20 + | 21 + | 22 + | 25 + | 26 + | 27 + | 28 + | 29 + | 30; + +export type ConvertToNumber< + T extends string, + Range extends number = _SolidityIndexRange, +> = Range extends unknown ? (`${Range}` extends T ? Range : never) : never; + +export type Components = { + name: string; + type: string; + indexed?: boolean; + components?: Components[]; +}; + +export interface AbiStruct { + [key: string]: unknown; + name: string; + type: string; +} + +export interface AbiCoderStruct extends AbiStruct { + [key: string]: unknown; + components?: Array; +} + +// https://docs.soliditylang.org/en/latest/abi-spec.html#json +export type AbiParameter = { + readonly name: string; + readonly type: string; + readonly baseType?: string; + readonly indexed?: boolean; + readonly components?: ReadonlyArray; + readonly arrayLength?: number; + readonly arrayChildren?: ReadonlyArray; + readonly internalType?: string; +}; + +type FragmentTypes = 'constructor' | 'event' | 'function' | 'fallback' | 'receive'; + +export type AbiBaseFragment = { + // type will default to string if passed ABI is declared without "as const" + readonly type: string | FragmentTypes; +}; + +// To assign an ABI which is not declared `as const` need to specify a generic string + +// https://docs.soliditylang.org/en/latest/abi-spec.html#json +export type AbiConstructorFragment = AbiBaseFragment & { + readonly type: string | 'constructor'; + readonly stateMutability: string | 'nonpayable' | 'payable'; + readonly inputs?: ReadonlyArray; +}; + +// https://docs.soliditylang.org/en/latest/abi-spec.html#json +export type AbiFunctionFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'function'; + readonly stateMutability?: string | 'nonpayable' | 'payable' | 'pure' | 'view'; + readonly inputs?: ReadonlyArray; + readonly outputs?: ReadonlyArray; + + readonly constant?: boolean; // stateMutability == 'pure' or stateMutability == 'view' + readonly payable?: boolean; // stateMutability == 'payable' +}; + +export type AbiFallbackFragment = AbiBaseFragment & { + readonly name: never; + readonly type: string | 'fallback'; + readonly stateMutability: string | 'nonpayable' | 'payable' | 'pure' | 'view'; + readonly inputs: never; + readonly outputs: never; + + // legacy properties + readonly constant?: boolean; // stateMutability == 'pure' or stateMutability == 'view' + readonly payable?: boolean; // stateMutability == 'payable' +}; + +// https://docs.soliditylang.org/en/latest/abi-spec.html#json +export type AbiEventFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'event'; + readonly inputs?: ReadonlyArray; + readonly anonymous?: boolean; +}; + +// https://docs.soliditylang.org/en/latest/abi-spec.html#errors +export type AbiErrorFragment = AbiBaseFragment & { + readonly name: string; + readonly type: string | 'error'; + readonly inputs?: ReadonlyArray; +}; + +// https://docs.soliditylang.org/en/latest/abi-spec.html#json +export type AbiFragment = + | AbiConstructorFragment + | AbiFunctionFragment + | AbiEventFragment + | AbiErrorFragment + | AbiFallbackFragment; + +export type ContractAbi = ReadonlyArray; + +export type AbiInput = + | string + | AbiParameter + | { + name: string; + type: string; + components?: Components; + index?: boolean; + internalType?: string; + } + | { readonly [key: string]: unknown }; + +// https://docs.soliditylang.org/en/develop/abi-spec.html#json +export type JsonFunctionInterface = { + type: 'function'; + name: string; + inputs: Components[]; + outputs?: AbiInput[]; + stateMutability?: string; +}; + +export type JsonEventInterface = { + type: 'event'; + name: string; + inputs: Components[]; + indexed: boolean; + anonymous: boolean; +}; + +export type FilterAbis = Abi extends Filter + ? Abi + : never; + +type _TypedArray = Size extends '' + ? Type[] + : FixedSizeArray>; + +export type PrimitiveAddressType = Type extends `address[${infer Size}]` + ? _TypedArray + : Type extends 'address' + ? Address + : never; + +export type PrimitiveStringType = Type extends `string${string}[${infer Size}]` + ? _TypedArray + : Type extends 'string' | `string${string}` + ? string + : never; + +export type PrimitiveBooleanType = Type extends `bool[${infer Size}]` + ? _TypedArray + : Type extends 'bool' + ? boolean + : never; + +export type PrimitiveIntegerType = Type extends + | `uint${string}[${infer Size}]` + | `int${string}[${infer Size}]` + ? _TypedArray + : Type extends 'uint' | 'int' | `int${string}` | `uint${string}` + ? Numbers + : never; + +export type PrimitiveBytesType = Type extends `bytes${string}[${infer Size}]` + ? _TypedArray + : Type extends 'bytes' | `bytes${string}` + ? Bytes + : never; + +export type PrimitiveTupleType< + Type extends string, + TypeComponents extends ReadonlyArray | undefined | unknown = [], +> = TypeComponents extends ReadonlyArray + ? Type extends 'tuple' + ? { + // eslint-disable-next-line no-use-before-define + [Param in TypeComponents[number] as Param['name']]: MatchPrimitiveType< + Param['type'], + Param['components'] + >; + } + : Type extends `tuple[${infer Size}]` + ? _TypedArray< + { + // eslint-disable-next-line no-use-before-define + [Param in TypeComponents[number] as Param['name']]: MatchPrimitiveType< + Param['type'], + Param['components'] + >; + }, + Size + > + : never + : never; + +type ObjectToArray = T extends [...infer R, infer A] + ? Record & ObjectToArray + : T; +type ArrToObjectWithFunctions = Array & ObjectToArray; + +export type MatchPrimitiveType< + Type extends string, + TypeComponents extends ReadonlyArray | undefined | unknown, +> = + | PrimitiveAddressType + | PrimitiveStringType + | PrimitiveBooleanType + | PrimitiveIntegerType + | PrimitiveBytesType + | PrimitiveTupleType + | never; + +type ContractMethodOutputParametersRecursiveArray< + Params extends ReadonlyArray | undefined, +> = + // check if params are empty array + Params extends readonly [] + ? [] + : Params extends readonly [infer H, ...infer R] // check if Params is an array + ? H extends AbiParameter + ? [ + MatchPrimitiveType, + ...ContractMethodOutputParametersRecursiveArray, + ] + : [] + : []; + +type ContractMethodOutputParametersRecursiveRecord< + Params extends ReadonlyArray | undefined, +> = + // check if params are empty array + Params extends readonly [] + ? [] + : Params extends readonly [infer H, ...infer R] // check if Params is an array + ? H extends AbiParameter + ? H['name'] extends '' // check if output param name is empty string + ? ContractMethodOutputParametersRecursiveRecord + : Record> & // sets key-value pair of output param name and type + ContractMethodOutputParametersRecursiveRecord + : ContractMethodOutputParametersRecursiveRecord + : Params extends undefined | unknown // param is not array, check if undefined + ? [] + : Params; + +export type ContractMethodOutputParameters | undefined> = + // check if params are empty array + Params extends readonly [] + ? void + : Params extends readonly [infer H, ...infer R] // check if Params is an array + ? R extends readonly [] // if only one output in array + ? H extends AbiParameter + ? MatchPrimitiveType + : [] + : // if more than one output + ArrToObjectWithFunctions<[...ContractMethodOutputParametersRecursiveArray]> & + ContractMethodOutputParametersRecursiveRecord + : []; + +export type ContractMethodInputParameters | undefined> = + Params extends readonly [] + ? [] + : Params extends readonly [infer H, ...infer R] + ? H extends AbiParameter + ? // TODO: Find a way to set name for tuple item + [MatchPrimitiveType, ...ContractMethodInputParameters] + : ContractMethodInputParameters + : Params extends undefined | unknown + ? [] + : Params; + +export type ContractConstructor = { + [Abi in FilterAbis as 'constructor']: { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; + }; +}['constructor']; + +export type ContractConstructorArgs = { + [Abi in FilterAbis< + Abis, + AbiConstructorFragment & { type: 'constructor' } + > as 'constructor']: ContractMethodInputParameters; +}['constructor']; + +export type ContractMethod = { + readonly Abi: Abi; + + readonly Inputs: ContractMethodInputParameters; + readonly Outputs: ContractMethodOutputParameters; +}; + +export type ContractMethods = { + [Abi in FilterAbis< + Abis, + AbiFunctionFragment & { type: 'function' } + > as Abi['name']]: ContractMethod; +}; + +export type ContractEvent = { + readonly Abi: Abi; + readonly Inputs: ContractMethodInputParameters; +}; + +export type ContractEvents = { + [Abi in FilterAbis< + Abis, + AbiEventFragment & { type: 'event' } + > as Abi['name']]: ContractEvent; +}; + +export interface DecodedParams extends Record { + __length__: number; +} diff --git a/test/merkletreejs/node_modules/web3-types/src/eth_contract_types.ts b/test/merkletreejs/node_modules/web3-types/src/eth_contract_types.ts new file mode 100644 index 0000000..15d23b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/eth_contract_types.ts @@ -0,0 +1,158 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Address, Uint } from './eth_types.js'; +import { SupportedProviders } from './web3_base_provider.js'; +import { Bytes, HexString } from './primitives_types.js'; +import { EthExecutionAPI } from './apis/eth_execution_api.js'; +import { AbiFragment, ContractAbi } from './eth_abi_types.js'; + +export interface ContractInitOptions { + /** + * The maximum gas provided for a transaction (gas limit). + */ + readonly gas?: Uint; + readonly gasLimit?: Uint; + /** + * The gas price in wei to use for transactions. + */ + readonly gasPrice?: Uint; + /** + * The address transactions should be made from + */ + readonly from?: Address; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly data?: Bytes; + readonly input?: Bytes; + + readonly provider?: SupportedProviders | string; + /** + * If `true`, the defaults of the contract instance will be updated automatically based on the changes of the context used to instantiate the contract. + */ + readonly syncWithContext?: boolean; + + readonly dataInputFill?: 'data' | 'input' | 'both'; + /** + * this will make calls default to `data`, `input` or `both` + */ +} + +export interface NonPayableCallOptions { + nonce?: HexString; + /** + * The address which is the call (the transaction) should be made from. For calls the `from` property is optional however it is + * highly recommended to explicitly set it or it may default to address(0) depending on your node or provider. + */ + from?: Address; + /** + * The maximum gas (gas limit) provided for this call (this transaction) + */ + gas?: string; + maxPriorityFeePerGas?: HexString; + maxFeePerGas?: HexString; + /** + * The gas price in wei to use for this call `transaction`. + */ + gasPrice?: string; + type?: string | number; + data?: HexString; + input?: HexString; +} + +export interface PayableCallOptions extends NonPayableCallOptions { + /** + * + */ + value?: string; +} + +export type ContractAbiWithSignature = ReadonlyArray; +export interface ContractOptions { + /** + * The maximum gas provided for a transaction (gas limit). + */ + readonly gas?: Uint; + /** + * The gas price in wei to use for transactions. + */ + readonly gasPrice?: Uint; + /** + * The address transactions should be made from. + */ + readonly from?: Address; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly input?: Bytes; + /** + * The byte code of the contract. Used when the contract gets {@link Contract.deploy | deployed} + */ + readonly data?: Bytes; + /** + * The {@doclink glossary/json_interface | json interface} object derived from the [ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) of this contract. + * + * Re-setting this will regenerate the methods and events of the contract instance. + * + * ```ts + * myContract.options.jsonInterface; + * > [{ + * "type":"function", + * "name":"foo", + * "inputs": [{"name":"a","type":"uint256"}], + * "outputs": [{"name":"b","type":"address"}], + * "signature": "0x...", + * },{ + * "type":"event", + * "name":"Event", + * "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}], + * "signature": "0x...", + * }] + * + * // Set a new ABI interface + * // Note: the "signature" of every function and event's ABI is not needed to be provided when assigning. + * // It will be calculated and set automatically inside the setter. + * myContract.options.jsonInterface = [...]; + * ``` + */ + get jsonInterface(): ContractAbiWithSignature; + set jsonInterface(value: ContractAbi); + + /** + * The address used for this contract instance. All transactions generated by web3.js from this contract will contain this address as the `to`. + * + * The address will be stored in lowercase. + * + * ```ts + * myContract.options.address; + * > '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae' + * + * // set a new address + * myContract.options.address = '0x1234FFDD...'; + * ``` + */ + address?: Address; // All transactions generated by web3.js from this contract will contain this address as the "to". + /** + * The max priority fee per gas to use for transactions. + */ + maxPriorityFeePerGas?: Uint; + /** + * The max fee per gas to use for transactions. + */ + maxFeePerGas?: Uint; +} diff --git a/test/merkletreejs/node_modules/web3-types/src/eth_types.ts b/test/merkletreejs/node_modules/web3-types/src/eth_types.ts new file mode 100644 index 0000000..8c59752 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/eth_types.ts @@ -0,0 +1,531 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Bytes, HexString, Numbers } from './primitives_types.js'; + +export type ValueTypes = 'address' | 'bool' | 'string' | 'int256' | 'uint256' | 'bytes' | 'bigint'; +// Hex encoded 32 bytes +export type HexString32Bytes = HexString; +// Hex encoded 16 bytes +export type HexString16Bytes = HexString; +// Hex encoded 8 bytes +export type HexString8Bytes = HexString; +// Hex encoded 1 byte +export type HexStringSingleByte = HexString; +// Hex encoded 1 byte +export type HexStringBytes = HexString; +// Hex encoded 256 byte +export type HexString256Bytes = HexString; +// Hex encoded unsigned integer +export type Uint = HexString; +// Hex encoded unsigned integer 32 bytes +export type Uint256 = HexString; +// Hex encoded address +export type Address = HexString; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/filter.json#L59 +export type Topic = HexString32Bytes; + +export type TransactionHash = HexString; +export type Uncles = HexString32Bytes[]; +export enum BlockTags { + EARLIEST = 'earliest', + LATEST = 'latest', + PENDING = 'pending', + SAFE = 'safe', + FINALIZED = 'finalized', +} +export type BlockTag = `${BlockTags}`; + +export type BlockNumberOrTag = Numbers | BlockTag; + +export interface Proof { + readonly address: HexString; + readonly nonce: string; + readonly balance: string; +} + +export interface TransactionInput { + readonly [key: string]: unknown; + readonly to?: HexString; // If its a contract creation tx then no address wil be specified. + readonly from?: HexString; + readonly data?: string; + readonly input?: string; + readonly gas: HexString; + readonly gasLimit?: string; + readonly gasPrice?: string; + readonly maxPriorityFeePerGas?: string; + readonly maxFeePerGas?: string; + readonly nonce: string; + readonly value: string; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly type?: HexString; + readonly chainId?: HexString; +} + +export type TransactionOutput = { + readonly [key: string]: unknown; + readonly to?: HexString; // If its a contract creation tx then no address wil be specified. + readonly from?: HexString; + readonly input: string; + readonly gas?: Numbers; + readonly gasLimit?: string; + readonly nonce: Numbers; + readonly value: Numbers; + readonly blockNumber?: Numbers; + readonly transactionIndex?: Numbers; +} & ( + | { maxPriorityFeePerGas: Numbers; maxFeePerGas: Numbers; gasPrice?: never } + | { maxPriorityFeePerGas?: never; maxFeePerGas?: never; gasPrice: Numbers } +); + +export interface LogsInput { + readonly blockHash?: HexString; + readonly transactionHash?: HexString; + readonly logIndex?: HexString; + readonly id?: string; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly address: HexString; + readonly topics: HexString[]; + readonly data: HexString; +} +export interface LogsOutput { + readonly id?: string; + readonly removed: boolean; + readonly logIndex?: Numbers; + readonly transactionIndex?: Numbers; + readonly transactionHash?: HexString32Bytes; + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: Numbers; + readonly address: string; + readonly topics: HexString[]; + readonly data: HexString; +} + +export interface BlockInput { + readonly gasLimit: HexString; + readonly gasUsed: HexString; + readonly size: HexString; + readonly timestamp: HexString; + readonly number?: HexString; + readonly difficulty?: HexString; + readonly totalDifficulty?: HexString; + readonly transactions?: TransactionInput[]; + readonly miner?: HexString; + readonly baseFeePerGas?: HexString; +} + +export interface BlockOutput { + readonly gasLimit: bigint | number; + readonly gasUsed: bigint | number; + readonly size: bigint | number; + readonly timestamp: bigint | number; + readonly number?: bigint | number; + readonly difficulty?: bigint | number; + readonly totalDifficulty?: bigint | number; + readonly transactions?: TransactionOutput[]; + readonly miner?: HexString; + readonly baseFeePerGas?: bigint | number; + readonly parentHash?: HexString32Bytes; +} + +export interface Withdrawals { + readonly index: Numbers; + readonly validatorIndex: Numbers; + readonly address: Address; + readonly amount: Numbers; +} + +export interface BlockHeaderOutput { + readonly hash?: HexString32Bytes; + readonly parentHash?: HexString32Bytes; + readonly receiptsRoot?: HexString32Bytes; + readonly miner?: HexString; + readonly stateRoot?: HexString32Bytes; + readonly transactionsRoot?: HexString32Bytes; + readonly withdrawalsRoot?: HexString32Bytes; + readonly logsBloom?: Bytes; + readonly difficulty?: Numbers; + readonly number?: Numbers; + readonly gasLimit: Numbers; + readonly gasUsed: Numbers; + readonly timestamp: Numbers; + readonly extraData?: Bytes; + readonly nonce?: Numbers; + readonly sha3Uncles: HexString32Bytes[]; + readonly baseFeePerGas?: Numbers; + + // These fields are returned when the RPC client is Nethermind, + // but aren't available in other clients such as Geth + readonly author?: Address; + readonly totalDifficulty?: Numbers; + readonly size?: Numbers; + readonly excessDataGas?: Numbers; + readonly mixHash?: HexString32Bytes; + readonly transactions?: TransactionOutput[]; + readonly uncles?: Uncles; + readonly withdrawals?: Withdrawals[]; +} + +export interface ReceiptInput { + readonly [x: string]: unknown; + readonly blockNumber?: HexString; + readonly transactionIndex?: HexString; + readonly cumulativeGasUsed: HexString; + readonly gasUsed: HexString; + readonly logs?: LogsInput[]; + readonly contractAddress?: HexString; + readonly status?: string; + readonly effectiveGasPrice?: HexString; +} + +export interface ReceiptOutput { + readonly blockNumber?: bigint | number; + readonly transactionIndex?: bigint | number; + readonly cumulativeGasUsed: bigint | number; + readonly gasUsed: bigint | number; + readonly logs?: LogsOutput[]; + readonly contractAddress?: HexString; + readonly status: boolean; + readonly effectiveGasPrice?: bigint | number; +} + +export interface PostInput { + readonly ttl?: HexString; + readonly workToProve?: HexString; + readonly priority?: HexString; + readonly expiry?: HexString; + readonly sent?: HexString; + readonly workProved?: HexString; + readonly topics?: HexString[]; +} + +export interface PostOutput { + readonly ttl?: bigint | number; + readonly workToProve?: bigint | number; + readonly priority?: bigint | number; + readonly expiry?: bigint | number; + readonly sent?: bigint | number; + readonly workProved?: bigint | number; + readonly topics?: string[]; +} + +export interface SyncInput { + readonly startingBlock: HexString; + readonly currentBlock: HexString; + readonly highestBlock: HexString; + readonly knownStates?: HexString; + readonly pulledStates?: HexString; +} + +export interface SyncOutput { + readonly startingBlock: Numbers; + readonly currentBlock: Numbers; + readonly highestBlock: Numbers; + readonly knownStates?: Numbers; + readonly pulledStates?: Numbers; +} + +export type Receipt = Record; + +type FilterOption = Record; + +// https://github.com/ethereum/execution-apis/blob/main/src/schemas/filter.json#L28 +export interface Filter { + readonly fromBlock?: BlockNumberOrTag; + readonly toBlock?: BlockNumberOrTag; + readonly address?: Address | Address[]; + readonly blockHash?: Address; + // Using "null" type intentionally to match specifications + // eslint-disable-next-line @typescript-eslint/ban-types + readonly topics?: (null | Topic | Topic[])[]; + readonly filter?: FilterOption; +} + +export interface AccessListEntry { + readonly address?: Address; + readonly storageKeys?: HexString32Bytes[]; +} +export type AccessList = AccessListEntry[]; + +export type AccessListResult = { + readonly accessList?: AccessList; + readonly gasUsed?: Numbers; +}; + +export type ValidChains = 'goerli' | 'kovan' | 'mainnet' | 'rinkeby' | 'ropsten' | 'sepolia'; + +// This list of hardforks is expected to be in order +// keep this in mind when making changes to it +export enum HardforksOrdered { + chainstart = 'chainstart', + frontier = 'frontier', + homestead = 'homestead', + dao = 'dao', + tangerineWhistle = 'tangerineWhistle', + spuriousDragon = 'spuriousDragon', + byzantium = 'byzantium', + constantinople = 'constantinople', + petersburg = 'petersburg', + istanbul = 'istanbul', + muirGlacier = 'muirGlacier', + berlin = 'berlin', + london = 'london', + altair = 'altair', + arrowGlacier = 'arrowGlacier', + grayGlacier = 'grayGlacier', + bellatrix = 'bellatrix', + merge = 'merge', + capella = 'capella', + shanghai = 'shanghai', +} + +export type Hardfork = `${HardforksOrdered}`; + +export interface LogBase { + readonly removed?: boolean; + readonly logIndex?: NumberType; + readonly transactionIndex?: NumberType; + readonly transactionHash?: ByteType; + readonly blockHash?: ByteType; + readonly blockNumber?: NumberType; + readonly address?: Address; + readonly data?: ByteType; + readonly topics?: ByteType[]; + readonly id?: string; +} +export interface Log extends LogBase { + readonly id?: string; +} + +export interface EventLog { + readonly event: string; + readonly id?: string; + readonly logIndex?: bigint | number | string; + readonly transactionIndex?: bigint | number | string; + readonly transactionHash?: HexString32Bytes; + readonly blockHash?: HexString32Bytes; + readonly blockNumber?: bigint | number | string; + readonly address: string; + readonly topics: HexString[]; + readonly data: HexString; + readonly raw?: { data: string; topics: unknown[] }; + readonly returnValues: Record; + readonly signature?: HexString; +} + +export interface TransactionReceiptBase { + readonly transactionHash: hashByteType; + readonly transactionIndex: numberType; + readonly blockHash: hashByteType; + readonly blockNumber: numberType; + readonly from: Address; + readonly to: Address; + readonly cumulativeGasUsed: numberType; + readonly gasUsed: numberType; + readonly effectiveGasPrice?: numberType; + readonly contractAddress?: Address; + readonly logs: logsType[]; + readonly logsBloom: logsBloomByteType; + readonly root: hashByteType; + readonly status: numberType; + readonly type?: numberType; + events?: { [key: string]: EventLog }; +} + +export type TransactionReceipt = TransactionReceiptBase; + +export interface CustomChain { + name?: string; + networkId: Numbers; + chainId: Numbers; +} + +export interface Common { + customChain: CustomChain; + baseChain?: ValidChains; + hardfork?: Hardfork; +} + +interface TransactionBase { + value?: Numbers; + accessList?: AccessList; + common?: Common; + gas?: Numbers; + gasPrice?: Numbers; + type?: Numbers; + maxFeePerGas?: Numbers; + maxPriorityFeePerGas?: Numbers; + data?: Bytes; + input?: Bytes; + nonce?: Numbers; + chain?: ValidChains; + hardfork?: Hardfork; + chainId?: Numbers; + networkId?: Numbers; + gasLimit?: Numbers; + yParity?: Uint; + v?: Numbers; + r?: Bytes; + s?: Bytes; +} + +export interface Transaction extends TransactionBase { + from?: Address; + // eslint-disable-next-line @typescript-eslint/ban-types + to?: Address | null; +} + +export interface TransactionForAccessList extends Transaction { + from: Address; +} + +export interface TransactionCall extends Transaction { + to: Address; +} + +export interface TransactionWithFromLocalWalletIndex extends Omit { + from: Numbers; +} + +export interface TransactionWithToLocalWalletIndex extends Omit { + to: Numbers; +} + +export interface TransactionWithFromAndToLocalWalletIndex extends Omit { + from: Numbers; + to: Numbers; +} + +export interface TransactionInfo extends Transaction { + readonly blockHash?: Bytes; + readonly blockNumber?: Numbers; + readonly from: Address; + readonly hash: Bytes; + readonly transactionIndex?: Numbers; +} + +export interface PopulatedUnsignedBaseTransaction { + from: Address; + to?: Address; + value: Numbers; + gas?: Numbers; + gasPrice: Numbers; + type: Numbers; + input?: Bytes; + data?: Bytes; + nonce: Numbers; + networkId: Numbers; + chain: ValidChains; + hardfork: Hardfork; + chainId: Numbers; + common: Common; + gasLimit: Numbers; +} + +export interface PopulatedUnsignedEip2930Transaction extends PopulatedUnsignedBaseTransaction { + accessList: AccessList; +} + +export interface PopulatedUnsignedEip1559Transaction extends PopulatedUnsignedEip2930Transaction { + gasPrice: never; + maxFeePerGas: Numbers; + maxPriorityFeePerGas: Numbers; +} +export type PopulatedUnsignedTransaction = + | PopulatedUnsignedBaseTransaction + | PopulatedUnsignedEip2930Transaction + | PopulatedUnsignedEip1559Transaction; + +export interface BlockBase< + ByteType, + HexStringType, + NumberType, + extraDataType, + TransactionTypes, + logsBloomType, +> { + readonly parentHash: ByteType; + readonly sha3Uncles: ByteType; + readonly miner: HexStringType; + readonly stateRoot: ByteType; + readonly transactionsRoot: ByteType; + readonly receiptsRoot: ByteType; + readonly logsBloom?: logsBloomType; + readonly difficulty?: NumberType; + readonly number: NumberType; + readonly gasLimit: NumberType; + readonly gasUsed: NumberType; + readonly timestamp: NumberType; + readonly extraData: extraDataType; + readonly mixHash: ByteType; + readonly nonce: NumberType; + readonly totalDifficulty: NumberType; + readonly baseFeePerGas?: NumberType; + readonly size: NumberType; + readonly transactions: TransactionTypes; + readonly uncles: Uncles; + readonly hash?: ByteType; +} + +export type Block = BlockBase< + Bytes, + Bytes, + Numbers, + Bytes, + TransactionHash[] | TransactionInfo[], + Bytes +>; + +export interface FeeHistoryBase { + readonly oldestBlock: NumberType; + readonly baseFeePerGas: NumberType; + readonly reward: NumberType[][]; + readonly gasUsedRatio: NumberType[]; +} + +export type FeeHistory = FeeHistoryBase; + +export interface StorageProof { + readonly key: Bytes; + readonly value: Numbers; + readonly proof: Bytes[]; +} + +export interface AccountObject { + readonly balance: Numbers; + readonly codeHash: Bytes; + readonly nonce: Numbers; + readonly storageHash: Bytes; + readonly accountProof: Bytes[]; + readonly storageProof: StorageProof[]; +} + +export interface Eip712TypeDetails { + name: string; + type: string; +} +export interface Eip712TypedData { + readonly types: { + EIP712Domain: Eip712TypeDetails[]; + [key: string]: Eip712TypeDetails[]; + }; + readonly primaryType: string; + readonly domain: Record; + readonly message: Record; +} diff --git a/test/merkletreejs/node_modules/web3-types/src/index.ts b/test/merkletreejs/node_modules/web3-types/src/index.ts new file mode 100644 index 0000000..694ffea --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/index.ts @@ -0,0 +1,33 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './error_types.js'; +export * from './apis/eth_execution_api.js'; +export * from './apis/web3_eth_execution_api.js'; +export * from './apis/web3_net_api.js'; +export * from './apis/eth_personal_api.js'; +export * from './data_format_types.js'; +export * from './eth_types.js'; +export * from './eth_abi_types.js'; +export * from './eth_contract_types.js'; +export * from './json_rpc_types.js'; +export * from './primitives_types.js'; +export * from './utility_types.js'; +export * from './web3_api_types.js'; +export * from './web3_base_provider.js'; +export * from './web3_base_wallet.js'; +export * from './web3_deferred_promise_type.js'; diff --git a/test/merkletreejs/node_modules/web3-types/src/json_rpc_types.ts b/test/merkletreejs/node_modules/web3-types/src/json_rpc_types.ts new file mode 100644 index 0000000..a361d01 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/json_rpc_types.ts @@ -0,0 +1,94 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export type JsonRpcId = string | number | undefined; +export type JsonRpcResult = string | number | boolean | Record; +export type JsonRpcIdentifier = string & ('2.0' | '1.0'); + +export interface JsonRpcError { + readonly code: number; + readonly message: string; + readonly data?: T; +} + +export interface JsonRpcResponseWithError { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly error: JsonRpcError; + readonly result?: never; +} + +export interface JsonRpcResponseWithResult { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly error?: never; + readonly result: T; +} + +export interface SubscriptionParams { + readonly subscription: string; // for subscription id + readonly result: T; +} + +export interface JsonRpcSubscriptionResultOld { + readonly error?: never; + readonly params?: never; + readonly type: string; + readonly data: SubscriptionParams; +} + +export interface JsonRpcNotification { + readonly id?: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly method: string; // for subscription + readonly params: SubscriptionParams; // for subscription results + readonly result: never; + readonly data?: never; +} + +export interface JsonRpcSubscriptionResult { + readonly id: number; + readonly jsonrpc: string; + readonly result: string; + readonly method: never; + readonly params: never; + readonly data?: never; +} + +export interface JsonRpcRequest { + readonly id: JsonRpcId; + readonly jsonrpc: JsonRpcIdentifier; + readonly method: string; + readonly params?: T; +} + +export interface JsonRpcOptionalRequest + extends Omit, 'id' | 'jsonrpc'> { + readonly id?: JsonRpcId; + readonly jsonrpc?: JsonRpcIdentifier; +} + +export type JsonRpcBatchRequest = JsonRpcRequest[]; + +export type JsonRpcPayload = JsonRpcRequest | JsonRpcBatchRequest; + +export type JsonRpcBatchResponse = + | (JsonRpcResponseWithError | JsonRpcResponseWithResult)[]; + +export type JsonRpcResponse = + | JsonRpcResponseWithError + | JsonRpcResponseWithResult + | JsonRpcBatchResponse; diff --git a/test/merkletreejs/node_modules/web3-types/src/primitives_types.ts b/test/merkletreejs/node_modules/web3-types/src/primitives_types.ts new file mode 100644 index 0000000..387900e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/primitives_types.ts @@ -0,0 +1,23 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export type HexString = string; +export type Bytes = Uint8Array | HexString; +export type Numbers = number | bigint | string | HexString; + +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment +export const TypedArray = Object.getPrototypeOf(Uint8Array); diff --git a/test/merkletreejs/node_modules/web3-types/src/utility_types.ts b/test/merkletreejs/node_modules/web3-types/src/utility_types.ts new file mode 100644 index 0000000..168201f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/utility_types.ts @@ -0,0 +1,61 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Numbers } from './primitives_types.js'; + +// Make each attribute mutable by removing `readonly` +export type Mutable = { + -readonly [P in keyof T]: T[P]; +}; + +export type ConnectionEvent = { + code: number; + reason: string; + wasClean?: boolean; // if WS connection was closed properly +}; + +export type Optional = Pick, K> & Omit; +export type EncodingTypes = Numbers | boolean | Numbers[] | boolean[]; + +export type TypedObject = { + type: string; + value: EncodingTypes; +}; + +export type TypedObjectAbbreviated = { + t: string; + v: EncodingTypes; +}; + +export type Sha3Input = TypedObject | TypedObjectAbbreviated | Numbers | boolean | object; + +export type IndexKeysForArray = Exclude; + +export type ArrayToIndexObject> = { + [K in IndexKeysForArray]: T[K]; +}; + +type _Grow> = ((x: T, ...xs: A) => void) extends (...a: infer X) => void + ? X + : never; + +export type GrowToSize, N extends number> = { + 0: A; + 1: GrowToSize, N>; +}[A['length'] extends N ? 0 : 1]; + +export type FixedSizeArray = GrowToSize; diff --git a/test/merkletreejs/node_modules/web3-types/src/web3_api_types.ts b/test/merkletreejs/node_modules/web3-types/src/web3_api_types.ts new file mode 100644 index 0000000..2fd94c9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/web3_api_types.ts @@ -0,0 +1,65 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { JsonRpcId, JsonRpcIdentifier } from './json_rpc_types.js'; + +export interface ProviderMessage { + readonly type: string; + readonly data: unknown; +} + +export interface EthSubscription extends ProviderMessage { + readonly type: 'eth_subscription'; + readonly data: { + readonly subscription: string; + readonly result: unknown; + }; +} + +export interface ProviderRpcError extends Error { + code: number; + data?: unknown; +} + +export interface ProviderConnectInfo { + readonly chainId: string; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type Web3APISpec = Record any> | unknown; +export type Web3APIMethod = string & keyof Exclude; +export type Web3APIParams< + API extends Web3APISpec, + Method extends Web3APIMethod, +> = API extends Exclude ? Parameters : unknown; + +export interface Web3APIRequest> { + method: Method | string; + params?: Web3APIParams | readonly unknown[] | object; +} + +export interface Web3APIPayload> + extends Web3APIRequest { + readonly jsonrpc?: JsonRpcIdentifier; + readonly id?: JsonRpcId; + readonly requestOptions?: unknown; +} + +export type Web3APIReturnType< + API extends Web3APISpec, + Method extends Web3APIMethod, + // eslint-disable-next-line @typescript-eslint/no-explicit-any +> = API extends Record any> ? ReturnType : any; diff --git a/test/merkletreejs/node_modules/web3-types/src/web3_base_provider.ts b/test/merkletreejs/node_modules/web3-types/src/web3_base_provider.ts new file mode 100644 index 0000000..5f840aa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/web3_base_provider.ts @@ -0,0 +1,351 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Socket } from 'net'; + +import { Web3Error } from './error_types.js'; +import { EthExecutionAPI } from './apis/eth_execution_api.js'; +// eslint-disable-next-line require-extensions/require-extensions +import { + JsonRpcNotification, + JsonRpcPayload, + JsonRpcResponse, + JsonRpcResponseWithError, + JsonRpcResponseWithResult, + JsonRpcResult, + JsonRpcSubscriptionResult, +} from './json_rpc_types'; +// eslint-disable-next-line require-extensions/require-extensions +import { + Web3APISpec, + Web3APIMethod, + Web3APIReturnType, + Web3APIPayload, + ProviderConnectInfo, + ProviderRpcError, + ProviderMessage, +} from './web3_api_types'; +// eslint-disable-next-line require-extensions/require-extensions +import { Web3EthExecutionAPI } from './apis/web3_eth_execution_api'; +// eslint-disable-next-line require-extensions/require-extensions +import { Web3DeferredPromiseInterface } from './web3_deferred_promise_type'; + +const symbol = Symbol.for('web3/base-provider'); + +export interface SocketRequestItem< + API extends Web3APISpec, + Method extends Web3APIMethod, + ResponseType, +> { + payload: Web3APIPayload; + deferredPromise: Web3DeferredPromiseInterface; +} + +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#connectivity +export type Web3ProviderStatus = 'connecting' | 'connected' | 'disconnected'; + +export type Web3ProviderEventCallback = ( + error: Error | ProviderRpcError | undefined, + result?: JsonRpcSubscriptionResult | JsonRpcNotification, +) => void; + +export type Web3ProviderMessageEventCallback = ( + result?: JsonRpcSubscriptionResult | JsonRpcNotification, +) => void; + +export type Web3Eip1193ProviderEventCallback = (data: T) => void; + +export type Web3ProviderRequestCallback = ( + // Used "null" value to match the legacy version + // eslint-disable-next-line @typescript-eslint/ban-types + err?: Error | Web3Error | null | JsonRpcResponseWithError, + response?: JsonRpcResponseWithResult, +) => void; + +export interface LegacySendProvider { + send( + payload: JsonRpcPayload

, + // Used "null" value to match the legacy version + // eslint-disable-next-line @typescript-eslint/ban-types + callback: (err: Error | null, response?: JsonRpcResponse) => void, + ): void; +} + +export interface LegacySendAsyncProvider { + sendAsync( + payload: JsonRpcPayload

, + ): Promise>; +} + +export interface LegacyRequestProvider { + request( + payload: JsonRpcPayload

, + // eslint-disable-next-line @typescript-eslint/ban-types + callback: (err: Error | null, response: JsonRpcResponse) => void, + ): void; +} + +export interface SimpleProvider { + request, ResponseType = Web3APIReturnType>( + args: Web3APIPayload, + ): Promise | unknown>; +} + +export interface ProviderInfo { + chainId: string; +} + +export type ProviderChainId = string; + +export type ProviderAccounts = string[]; + + +export type Eip1193EventName = + | 'connect' + | 'disconnect' + | 'message' + | 'chainChanged' + | 'accountsChanged'; + +export interface EIP1193Provider extends SimpleProvider { + on(event: 'connect', listener: (info: ProviderInfo) => void): void; + on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + on(event: 'message', listener: (message: ProviderMessage) => void): void; + on(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + on(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + + removeListener(event: 'connect', listener: (info: ProviderInfo) => void): void; + removeListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + removeListener(event: 'message', listener: (message: ProviderMessage) => void): void; + removeListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + removeListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; +} + +export interface MetaMaskProvider extends SimpleProvider { + on(event: 'connect', listener: (info: ProviderInfo) => void): void; + on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + on(event: 'message', listener: (message: ProviderMessage) => void): void; + on(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + on(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + + removeListener(event: 'connect', listener: (info: ProviderInfo) => void): void; + removeListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void; + removeListener(event: 'message', listener: (message: ProviderMessage) => void): void; + removeListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void; + removeListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void; + isMetaMask: boolean; +} + + +export type Eip1193Compatible = Omit< + // eslint-disable-next-line no-use-before-define + Omit, + 'asEIP1193Provider' +> & { + request< + Method extends Web3APIMethod, + ResultType = Web3APIReturnType | unknown, + >( + request: Web3APIPayload, + ): Promise; +}; + +// Provider interface compatible with EIP-1193 +// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md +export abstract class Web3BaseProvider + implements LegacySendProvider, LegacySendAsyncProvider, EIP1193Provider +{ + public static isWeb3Provider(provider: unknown) { + return ( + provider instanceof Web3BaseProvider || + Boolean(provider && (provider as { [symbol]: boolean })[symbol]) + ); + } + + // To match an object "instanceof" does not work if + // matcher class and object is using different package versions + // to overcome this bottleneck used this approach. + // The symbol value for one string will always remain same regardless of package versions + // eslint-disable-next-line class-methods-use-this + public get [symbol]() { + return true; + } + + public abstract getStatus(): Web3ProviderStatus; + public abstract supportsSubscriptions(): boolean; + + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + * @param callback - Callback + */ + public send( + payload: JsonRpcPayload

, + // eslint-disable-next-line @typescript-eslint/ban-types + callback: (err: Error | null, response?: JsonRpcResponse) => void, + ) { + this.request, ResultType>( + payload as Web3APIPayload>, + ) + .then(response => { + // eslint-disable-next-line no-null/no-null + callback(null, response); + }) + .catch((err: Error | Web3Error) => { + callback(err); + }); + } + + /** + * @deprecated Please use `.request` instead. + * @param payload - Request Payload + */ + public async sendAsync(payload: JsonRpcPayload

) { + return this.request(payload as Web3APIPayload>) as Promise< + JsonRpcResponse + >; + } + + /** + * Modify the return type of the request method to be fully compatible with EIP-1193 + * + * [deprecated] In the future major releases (\>= v5) all providers are supposed to be fully compatible with EIP-1193. + * So this method will not be needed and would not be available in the future. + * + * @returns A new instance of the provider with the request method fully compatible with EIP-1193 + * + * @example + * ```ts + * const provider = new Web3HttpProvider('http://localhost:8545'); + * const fullyCompatibleProvider = provider.asEIP1193Provider(); + * const result = await fullyCompatibleProvider.request({ method: 'eth_getBalance' }); + * console.log(result); // '0x0234c8a3397aab58' or something like that + * ``` + */ + public asEIP1193Provider(): Eip1193Compatible { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const newObj = Object.create(this) as Eip1193Compatible; + // eslint-disable-next-line @typescript-eslint/unbound-method + const originalRequest = newObj.request; + newObj.request = async function request( + args: Web3APIPayload>, + ): Promise { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + const response = (await originalRequest(args)) as JsonRpcResponseWithResult; + return response.result; + } as typeof newObj.request; + // @ts-expect-error the property should not be available in the new object because of using Object.create(this). + // But it is available if we do not delete it. + newObj.asEIP1193Provider = undefined; // to prevent the user for calling this method again + return newObj; + } + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#request + public abstract request< + Method extends Web3APIMethod, + ResultType = Web3APIReturnType | unknown, + >(args: Web3APIPayload): Promise>; + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#events + + public abstract on( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract on( + type: 'message' | string, + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + // for old providers + public abstract on( + type: 'data' | string, + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + public abstract on( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract on( + type: 'chainChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract on( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract removeListener( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract removeListener( + type: 'message' | string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public abstract removeListener( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract removeListener( + type: 'chainChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract removeListener( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract once( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract once( + type: 'message' | string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public abstract once( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract once( + type: 'chainChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract once( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public abstract removeAllListeners?(type: string): void; + public abstract connect(): void; + public abstract disconnect(code?: number, data?: string): void; + public abstract reset(): void; +} + +export type SupportedProviders = + | EIP1193Provider + | Web3BaseProvider + | LegacyRequestProvider + | LegacySendProvider + | LegacySendAsyncProvider + | SimpleProvider + | MetaMaskProvider; + +export type Web3BaseProviderConstructor = new ( + url: string, + net?: Socket, +) => Web3BaseProvider; diff --git a/test/merkletreejs/node_modules/web3-types/src/web3_base_wallet.ts b/test/merkletreejs/node_modules/web3-types/src/web3_base_wallet.ts new file mode 100644 index 0000000..484e807 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/web3_base_wallet.ts @@ -0,0 +1,120 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Transaction } from './eth_types.js'; +import { HexString } from './primitives_types.js'; + +export type Cipher = 'aes-128-ctr' | 'aes-128-cbc' | 'aes-256-cbc'; + +export type CipherOptions = { + salt?: Uint8Array | string; + iv?: Uint8Array | string; + kdf?: 'scrypt' | 'pbkdf2'; + dklen?: number; + c?: number; // iterrations + n?: number; // cpu/memory cost + r?: number; // block size + p?: number; // parallelization cost +}; + +export type ScryptParams = { + dklen: number; + n: number; + p: number; + r: number; + salt: Uint8Array | string; +}; +export type PBKDF2SHA256Params = { + c: number; // iterations + dklen: number; + prf: 'hmac-sha256'; + salt: Uint8Array | string; +}; + +export type KeyStore = { + crypto: { + cipher: Cipher; + ciphertext: string; + cipherparams: { + iv: string; + }; + kdf: 'pbkdf2' | 'scrypt'; + kdfparams: ScryptParams | PBKDF2SHA256Params; + mac: HexString; + }; + id: string; + version: 3; + address: string; +}; + +export interface Web3BaseWalletAccount { + [key: string]: unknown; + readonly address: string; + readonly privateKey: string; + readonly signTransaction: (tx: Transaction) => Promise<{ + readonly messageHash: HexString; + readonly r: HexString; + readonly s: HexString; + readonly v: HexString; + readonly rawTransaction: HexString; + readonly transactionHash: HexString; + }>; + readonly sign: (data: Record | string) => { + readonly messageHash: HexString; + readonly r: HexString; + readonly s: HexString; + readonly v: HexString; + readonly message?: string; + readonly signature: HexString; + }; + readonly encrypt: (password: string, options?: Record) => Promise; +} + +export interface Web3AccountProvider { + privateKeyToAccount: (privateKey: string) => T; + create: () => T; + decrypt: ( + keystore: KeyStore | string, + password: string, + options?: Record, + ) => Promise; +} + +export abstract class Web3BaseWallet extends Array { + protected readonly _accountProvider: Web3AccountProvider; + + public constructor(accountProvider: Web3AccountProvider) { + super(); + this._accountProvider = accountProvider; + } + + public abstract create(numberOfAccounts: number): this; + public abstract add(account: T | string): this; + public abstract get(addressOrIndex: string | number): T | undefined; + public abstract remove(addressOrIndex: string | number): boolean; + public abstract clear(): this; + public abstract encrypt( + password: string, + options?: Record, + ): Promise; + public abstract decrypt( + encryptedWallet: KeyStore[], + password: string, + options?: Record, + ): Promise; + public abstract save(password: string, keyName?: string): Promise; + public abstract load(password: string, keyName?: string): Promise; +} diff --git a/test/merkletreejs/node_modules/web3-types/src/web3_deferred_promise_type.ts b/test/merkletreejs/node_modules/web3-types/src/web3_deferred_promise_type.ts new file mode 100644 index 0000000..eadd39d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-types/src/web3_deferred_promise_type.ts @@ -0,0 +1,23 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export interface Web3DeferredPromiseInterface extends Promise { + state: 'pending' | 'fulfilled' | 'rejected'; + resolve(value: T | PromiseLike): void; + reject(reason?: unknown): void; + startTimer(): void; +} diff --git a/test/merkletreejs/node_modules/web3-utils/LICENSE b/test/merkletreejs/node_modules/web3-utils/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-utils/README.md b/test/merkletreejs/node_modules/web3-utils/README.md new file mode 100644 index 0000000..78cce56 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/README.md @@ -0,0 +1,72 @@ +

+ web3.js +

+ +# web3-utils + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-utils` This contains useful utility functions for Dapp developers. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-utils) or using [Yarn](https://yarnpkg.com/package/web3-utils) + +### Using NPM + +```bash +npm install web3-utils +``` + +### Using Yarn + +```bash +yarn add web3-utils +``` + +## Usage + +```js +const Web3Utils = require('web3-utils'); +console.log(Web3Utils); +{ + sha3: function(){}, + soliditySha3: function(){}, + isAddress: function(){}, + ... +} +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-utils +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-utils%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-utils +[downloads-image]: https://img.shields.io/npm/dm/web3-utils?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.d.ts new file mode 100644 index 0000000..987826a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.d.ts @@ -0,0 +1,14 @@ +/// +import { JsonRpcResponse } from 'web3-types'; +import { EventEmitter } from 'events'; +export declare class ChunkResponseParser { + private lastChunk; + private lastChunkTimeout; + private _clearQueues; + private readonly eventEmitter; + private readonly autoReconnect; + constructor(eventEmitter: EventEmitter, autoReconnect: boolean); + private clearQueues; + onError(clearQueues?: () => void): void; + parseResponse(data: string): JsonRpcResponse[]; +} diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.js new file mode 100644 index 0000000..55b9cb6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChunkResponseParser = void 0; +const web3_errors_1 = require("web3-errors"); +class ChunkResponseParser { + constructor(eventEmitter, autoReconnect) { + this.eventEmitter = eventEmitter; + this.autoReconnect = autoReconnect; + } + clearQueues() { + if (typeof this._clearQueues === 'function') { + this._clearQueues(); + } + } + onError(clearQueues) { + this._clearQueues = clearQueues; + } + parseResponse(data) { + const returnValues = []; + // DE-CHUNKER + const dechunkedData = data + .replace(/\}[\n\r]?\{/g, '}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{ + .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{ + .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{ + .split('|--|'); + dechunkedData.forEach(_chunkData => { + // prepend the last chunk + let chunkData = _chunkData; + if (this.lastChunk) { + chunkData = this.lastChunk + chunkData; + } + let result; + try { + result = JSON.parse(chunkData); + } + catch (e) { + this.lastChunk = chunkData; + // start timeout to cancel all requests + if (this.lastChunkTimeout) { + clearTimeout(this.lastChunkTimeout); + } + this.lastChunkTimeout = setTimeout(() => { + if (this.autoReconnect) + return; + this.clearQueues(); + this.eventEmitter.emit('error', new web3_errors_1.InvalidResponseError({ + id: 1, + jsonrpc: '2.0', + error: { code: 2, message: 'Chunk timeout' }, + })); + }, 1000 * 15); + return; + } + // cancel timeout and set chunk to null + clearTimeout(this.lastChunkTimeout); + this.lastChunk = undefined; + if (result) + returnValues.push(result); + }); + return returnValues; + } +} +exports.ChunkResponseParser = ChunkResponseParser; +//# sourceMappingURL=chunk_response_parser.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.js.map new file mode 100644 index 0000000..3715318 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/chunk_response_parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk_response_parser.js","sourceRoot":"","sources":["../../src/chunk_response_parser.ts"],"names":[],"mappings":";;;AAiBA,6CAAmD;AAInD,MAAa,mBAAmB;IAO/B,YAAmB,YAA0B,EAAE,aAAsB;QACpE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACpC,CAAC;IACO,WAAW;QAClB,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU,EAAE;YAC5C,IAAI,CAAC,YAAY,EAAE,CAAC;SACpB;IACF,CAAC;IAEM,OAAO,CAAC,WAAwB;QACtC,IAAI,CAAC,YAAY,GAA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F,CAAC;gBACH,CAAC,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;gBACd,OAAO;aACP;YAED,uCAAuC;YACvC,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YACpC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;YAE3B,IAAI,MAAM;gBAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;QAEH,OAAO,YAAY,CAAC;IACrB,CAAC;CACD;AA3ED,kDA2EC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.d.ts new file mode 100644 index 0000000..eaaf0a3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.d.ts @@ -0,0 +1,279 @@ +import { utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { Address, Bytes, HexString, Numbers, ValueTypes } from 'web3-types'; +/** @internal */ +export declare const ethUnitMap: { + noether: bigint; + wei: bigint; + kwei: bigint; + Kwei: bigint; + babbage: bigint; + femtoether: bigint; + mwei: bigint; + Mwei: bigint; + lovelace: bigint; + picoether: bigint; + gwei: bigint; + Gwei: bigint; + shannon: bigint; + nanoether: bigint; + nano: bigint; + szabo: bigint; + microether: bigint; + micro: bigint; + finney: bigint; + milliether: bigint; + milli: bigint; + ether: bigint; + kether: bigint; + grand: bigint; + mether: bigint; + gether: bigint; + tether: bigint; +}; +export declare type EtherUnits = keyof typeof ethUnitMap; +/** + * Convert a value from bytes to Uint8Array + * @param data - Data to be converted + * @returns - The Uint8Array representation of the input data + * + * @example + * ```ts + * console.log(web3.utils.bytesToUint8Array("0xab"))); + * > Uint8Array(1) [ 171 ] + * ``` + */ +export declare const bytesToUint8Array: (data: Bytes) => Uint8Array | never; +/** + * Convert a byte array to a hex string + * @param bytes - Byte array to be converted + * @returns - The hex string representation of the input byte array + * + * @example + * ```ts + * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12]))); + * > "0x480c" + * + */ +export declare const bytesToHex: (bytes: Bytes) => HexString; +/** + * Convert a hex string to a byte array + * @param hex - Hex string to be converted + * @returns - The byte array representation of the input hex string + * + * @example + * ```ts + * console.log(web3.utils.hexToBytes('0x74657374')); + * > Uint8Array(4) [ 116, 101, 115, 116 ] + * ``` + */ +export declare const hexToBytes: (bytes: HexString) => Uint8Array; +/** + * Converts value to it's number representation + * @param value - Hex string to be converted + * @returns - The number representation of the input value + * + * @example + * ```ts + * conoslle.log(web3.utils.hexToNumber('0xa')); + * > 10 + * ``` + */ +export declare const hexToNumber: (value: HexString) => bigint | number; +/** + * Converts value to it's number representation @alias `hexToNumber` + */ +export declare const toDecimal: (value: HexString) => bigint | number; +/** + * Converts value to it's hex representation + * @param value - Value to be converted + * @param hexstrict - Add padding to converted value if odd, to make it hexstrict + * @returns - The hex representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.numberToHex(10)); + * > "0xa" + * ``` + */ +export declare const numberToHex: (value: Numbers, hexstrict?: boolean) => HexString; +/** + * Converts value to it's hex representation @alias `numberToHex` + * + */ +export declare const fromDecimal: (value: Numbers, hexstrict?: boolean) => HexString; +/** + * Converts value to it's decimal representation in string + * @param value - Hex string to be converted + * @returns - The decimal representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.hexToNumberString('0xa')); + * > "10" + * ``` + */ +export declare const hexToNumberString: (data: HexString) => string; +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * @param str - Utf8 string to be converted + * @returns - The hex representation of the input string + * + * @example + * ```ts + * console.log(utf8ToHex('web3.js')); + * > "0x776562332e6a73" + * + */ +export declare const utf8ToHex: (str: string) => HexString; +/** + * @alias utf8ToHex + */ +export declare const fromUtf8: (str: string) => HexString; +/** + * @alias utf8ToHex + */ +export declare const stringToHex: (str: string) => HexString; +/** + * Should be called to get utf8 from it's hex representation + * @param str - Hex string to be converted + * @returns - Utf8 string + * + * @example + * ```ts + * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export declare const hexToUtf8: (str: HexString) => string; +/** + * @alias hexToUtf8 + */ +export declare const toUtf8: (input: HexString | Uint8Array) => string; +export declare const utf8ToBytes: typeof ecUtf8ToBytes; +/** + * @alias hexToUtf8 + */ +export declare const hexToString: (str: HexString) => string; +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * @param str - String to be converted to hex + * @returns - Hex string + * + * @example + * ```ts + * console.log(web3.utils.asciiToHex('Hello World')); + * > 0x48656c6c6f20576f726c64 + * ``` + */ +export declare const asciiToHex: (str: string) => HexString; +/** + * @alias asciiToHex + */ +export declare const fromAscii: (str: string) => HexString; +/** + * Should be called to get ascii from it's hex representation + * @param str - Hex string to be converted to ascii + * @returns - Ascii string + * + * @example + * ```ts + * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export declare const hexToAscii: (str: HexString) => string; +/** + * @alias hexToAscii + */ +export declare const toAscii: (str: HexString) => string; +/** + * Auto converts any given value into it's hex representation. + * @param value - Value to be converted to hex + * @param returnType - If true, it will return the type of the value + * + * @example + * ```ts + * console.log(web3.utils.toHex(10)); + * > 0xa + * + * console.log(web3.utils.toHex('0x123', true)); + * > bytes + *``` + */ +export declare const toHex: (value: Numbers | Bytes | Address | boolean | object, returnType?: boolean) => HexString | ValueTypes; +/** + * Converts any given value into it's number representation, if possible, else into it's bigint representation. + * @param value - The value to convert + * @returns - Returns the value in number or bigint representation + * + * @example + * ```ts + * console.log(web3.utils.toNumber(1)); + * > 1 + * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER)); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER))); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1))); + * > 9007199254740992n + * + * ``` + */ +export declare const toNumber: (value: Numbers) => number | bigint; +/** + * Auto converts any given value into it's bigint representation + * + * @param value - The value to convert + * @returns - Returns the value in bigint representation + + * @example + * ```ts + * console.log(web3.utils.toBigInt(1)); + * > 1n + * ``` + */ +export declare const toBigInt: (value: unknown) => bigint; +/** + * Takes a number of wei and converts it to any other ether unit. + * @param number - The value in wei + * @param unit - The unit to convert to + * @returns - Returns the converted value in the given unit + * + * @example + * ```ts + * console.log(web3.utils.fromWei("1", "ether")); + * > 0.000000000000000001 + * + * console.log(web3.utils.fromWei("1", "shannon")); + * > 0.000000001 + * ``` + */ +export declare const fromWei: (number: Numbers, unit: EtherUnits) => string; +/** + * Takes a number of a unit and converts it to wei. + * + * @param number - The number to convert. + * @param unit - {@link EtherUnits} The unit of the number passed. + * @returns The number converted to wei. + * + * @example + * ```ts + * console.log(web3.utils.toWei("0.001", "ether")); + * > 1000000000000000 //(wei) + * ``` + */ +export declare const toWei: (number: Numbers, unit: EtherUnits) => string; +/** + * Will convert an upper or lowercase Ethereum address to a checksum address. + * @param address - An address string + * @returns The checksum address + * @example + * ```ts + * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d'); + * > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" + * ``` + */ +export declare const toChecksumAddress: (address: Address) => string; +export declare const toBool: (value: boolean | string | number | unknown) => boolean; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.js new file mode 100644 index 0000000..f5a3170 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.js @@ -0,0 +1,562 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toBool = exports.toChecksumAddress = exports.toWei = exports.fromWei = exports.toBigInt = exports.toNumber = exports.toHex = exports.toAscii = exports.hexToAscii = exports.fromAscii = exports.asciiToHex = exports.hexToString = exports.utf8ToBytes = exports.toUtf8 = exports.hexToUtf8 = exports.stringToHex = exports.fromUtf8 = exports.utf8ToHex = exports.hexToNumberString = exports.fromDecimal = exports.numberToHex = exports.toDecimal = exports.hexToNumber = exports.hexToBytes = exports.bytesToHex = exports.bytesToUint8Array = exports.ethUnitMap = void 0; +/** + * @module Utils + */ +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const utils_js_1 = require("ethereum-cryptography/utils.js"); +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +// Ref: https://ethdocs.org/en/latest/ether.html +// Note: this could be simplified using ** operator, but babel does not handle it well (https://github.com/babel/babel/issues/13109) +/** @internal */ +exports.ethUnitMap = { + noether: BigInt(0), + wei: BigInt(1), + kwei: BigInt(1000), + Kwei: BigInt(1000), + babbage: BigInt(1000), + femtoether: BigInt(1000), + mwei: BigInt(1000000), + Mwei: BigInt(1000000), + lovelace: BigInt(1000000), + picoether: BigInt(1000000), + gwei: BigInt(1000000000), + Gwei: BigInt(1000000000), + shannon: BigInt(1000000000), + nanoether: BigInt(1000000000), + nano: BigInt(1000000000), + szabo: BigInt(1000000000000), + microether: BigInt(1000000000000), + micro: BigInt(1000000000000), + finney: BigInt(1000000000000000), + milliether: BigInt(1000000000000000), + milli: BigInt(1000000000000000), + ether: BigInt('1000000000000000000'), + kether: BigInt('1000000000000000000000'), + grand: BigInt('1000000000000000000000'), + mether: BigInt('1000000000000000000000000'), + gether: BigInt('1000000000000000000000000000'), + tether: BigInt('1000000000000000000000000000000'), +}; +/** + * Convert a value from bytes to Uint8Array + * @param data - Data to be converted + * @returns - The Uint8Array representation of the input data + * + * @example + * ```ts + * console.log(web3.utils.bytesToUint8Array("0xab"))); + * > Uint8Array(1) [ 171 ] + * ``` + */ +const bytesToUint8Array = (data) => { + web3_validator_1.validator.validate(['bytes'], [data]); + if (data instanceof Uint8Array) { + return data; + } + if (Array.isArray(data)) { + return new Uint8Array(data); + } + if (typeof data === 'string') { + return web3_validator_1.utils.hexToUint8Array(data); + } + throw new web3_errors_1.InvalidBytesError(data); +}; +exports.bytesToUint8Array = bytesToUint8Array; +/** + * @internal + */ +const { uint8ArrayToHexString } = web3_validator_1.utils; +/** + * Convert a byte array to a hex string + * @param bytes - Byte array to be converted + * @returns - The hex string representation of the input byte array + * + * @example + * ```ts + * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12]))); + * > "0x480c" + * + */ +const bytesToHex = (bytes) => uint8ArrayToHexString((0, exports.bytesToUint8Array)(bytes)); +exports.bytesToHex = bytesToHex; +/** + * Convert a hex string to a byte array + * @param hex - Hex string to be converted + * @returns - The byte array representation of the input hex string + * + * @example + * ```ts + * console.log(web3.utils.hexToBytes('0x74657374')); + * > Uint8Array(4) [ 116, 101, 115, 116 ] + * ``` + */ +const hexToBytes = (bytes) => { + if (typeof bytes === 'string' && bytes.slice(0, 2).toLowerCase() !== '0x') { + return (0, exports.bytesToUint8Array)(`0x${bytes}`); + } + return (0, exports.bytesToUint8Array)(bytes); +}; +exports.hexToBytes = hexToBytes; +/** + * Converts value to it's number representation + * @param value - Hex string to be converted + * @returns - The number representation of the input value + * + * @example + * ```ts + * conoslle.log(web3.utils.hexToNumber('0xa')); + * > 10 + * ``` + */ +const hexToNumber = (value) => { + web3_validator_1.validator.validate(['hex'], [value]); + // To avoid duplicate code and circular dependency we will + // use `hexToNumber` implementation from `web3-validator` + return web3_validator_1.utils.hexToNumber(value); +}; +exports.hexToNumber = hexToNumber; +/** + * Converts value to it's number representation @alias `hexToNumber` + */ +exports.toDecimal = exports.hexToNumber; +/** + * Converts value to it's hex representation + * @param value - Value to be converted + * @param hexstrict - Add padding to converted value if odd, to make it hexstrict + * @returns - The hex representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.numberToHex(10)); + * > "0xa" + * ``` + */ +const numberToHex = (value, hexstrict) => { + if (typeof value !== 'bigint') + web3_validator_1.validator.validate(['int'], [value]); + // To avoid duplicate code and circular dependency we will + // use `numberToHex` implementation from `web3-validator` + let updatedValue = web3_validator_1.utils.numberToHex(value); + if (hexstrict) { + if (!updatedValue.startsWith('-') && updatedValue.length % 2 === 1) { + // To avoid duplicate a circular dependancy we will not be using the padLeft method + updatedValue = '0x0'.concat(updatedValue.slice(2)); + } + else if (updatedValue.length % 2 === 0 && updatedValue.startsWith('-')) + updatedValue = '-0x0'.concat(updatedValue.slice(3)); + } + return updatedValue; +}; +exports.numberToHex = numberToHex; +/** + * Converts value to it's hex representation @alias `numberToHex` + * + */ +exports.fromDecimal = exports.numberToHex; +/** + * Converts value to it's decimal representation in string + * @param value - Hex string to be converted + * @returns - The decimal representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.hexToNumberString('0xa')); + * > "10" + * ``` + */ +const hexToNumberString = (data) => (0, exports.hexToNumber)(data).toString(); +exports.hexToNumberString = hexToNumberString; +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * @param str - Utf8 string to be converted + * @returns - The hex representation of the input string + * + * @example + * ```ts + * console.log(utf8ToHex('web3.js')); + * > "0x776562332e6a73" + * + */ +const utf8ToHex = (str) => { + web3_validator_1.validator.validate(['string'], [str]); + // To be compatible with 1.x trim null character + // eslint-disable-next-line no-control-regex + let strWithoutNullCharacter = str.replace(/^(?:\u0000)/, ''); + // eslint-disable-next-line no-control-regex + strWithoutNullCharacter = strWithoutNullCharacter.replace(/(?:\u0000)$/, ''); + return (0, exports.bytesToHex)(new TextEncoder().encode(strWithoutNullCharacter)); +}; +exports.utf8ToHex = utf8ToHex; +/** + * @alias utf8ToHex + */ +exports.fromUtf8 = exports.utf8ToHex; +/** + * @alias utf8ToHex + */ +exports.stringToHex = exports.utf8ToHex; +/** + * Should be called to get utf8 from it's hex representation + * @param str - Hex string to be converted + * @returns - Utf8 string + * + * @example + * ```ts + * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +const hexToUtf8 = (str) => (0, utils_js_1.bytesToUtf8)((0, exports.hexToBytes)(str)); +exports.hexToUtf8 = hexToUtf8; +/** + * @alias hexToUtf8 + */ +const toUtf8 = (input) => { + if (typeof input === 'string') { + return (0, exports.hexToUtf8)(input); + } + web3_validator_1.validator.validate(['bytes'], [input]); + return (0, utils_js_1.bytesToUtf8)(input); +}; +exports.toUtf8 = toUtf8; +exports.utf8ToBytes = utils_js_1.utf8ToBytes; +/** + * @alias hexToUtf8 + */ +exports.hexToString = exports.hexToUtf8; +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * @param str - String to be converted to hex + * @returns - Hex string + * + * @example + * ```ts + * console.log(web3.utils.asciiToHex('Hello World')); + * > 0x48656c6c6f20576f726c64 + * ``` + */ +const asciiToHex = (str) => { + web3_validator_1.validator.validate(['string'], [str]); + let hexString = ''; + for (let i = 0; i < str.length; i += 1) { + const hexCharCode = str.charCodeAt(i).toString(16); + // might need a leading 0 + hexString += hexCharCode.length % 2 !== 0 ? `0${hexCharCode}` : hexCharCode; + } + return `0x${hexString}`; +}; +exports.asciiToHex = asciiToHex; +/** + * @alias asciiToHex + */ +exports.fromAscii = exports.asciiToHex; +/** + * Should be called to get ascii from it's hex representation + * @param str - Hex string to be converted to ascii + * @returns - Ascii string + * + * @example + * ```ts + * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +const hexToAscii = (str) => { + const decoder = new TextDecoder('ascii'); + return decoder.decode((0, exports.hexToBytes)(str)); +}; +exports.hexToAscii = hexToAscii; +/** + * @alias hexToAscii + */ +exports.toAscii = exports.hexToAscii; +/** + * Auto converts any given value into it's hex representation. + * @param value - Value to be converted to hex + * @param returnType - If true, it will return the type of the value + * + * @example + * ```ts + * console.log(web3.utils.toHex(10)); + * > 0xa + * + * console.log(web3.utils.toHex('0x123', true)); + * > bytes + *``` + */ +const toHex = (value, returnType) => { + if (typeof value === 'string' && (0, web3_validator_1.isAddress)(value)) { + return returnType ? 'address' : `0x${value.toLowerCase().replace(/^0x/i, '')}`; + } + if (typeof value === 'boolean') { + // eslint-disable-next-line no-nested-ternary + return returnType ? 'bool' : value ? '0x01' : '0x00'; + } + if (typeof value === 'number') { + // eslint-disable-next-line no-nested-ternary + return returnType ? (value < 0 ? 'int256' : 'uint256') : (0, exports.numberToHex)(value); + } + if (typeof value === 'bigint') { + return returnType ? 'bigint' : (0, exports.numberToHex)(value); + } + if (typeof value === 'object' && !!value) { + return returnType ? 'string' : (0, exports.utf8ToHex)(JSON.stringify(value)); + } + if (typeof value === 'string') { + if (value.startsWith('-0x') || value.startsWith('-0X')) { + return returnType ? 'int256' : (0, exports.numberToHex)(value); + } + if ((0, web3_validator_1.isHexStrict)(value)) { + return returnType ? 'bytes' : value; + } + if ((0, web3_validator_1.isHex)(value) && !(0, web3_validator_1.isInt)(value)) { + return returnType ? 'bytes' : `0x${value}`; + } + if (!Number.isFinite(value)) { + return returnType ? 'string' : (0, exports.utf8ToHex)(value); + } + } + throw new web3_errors_1.HexProcessingError(value); +}; +exports.toHex = toHex; +/** + * Converts any given value into it's number representation, if possible, else into it's bigint representation. + * @param value - The value to convert + * @returns - Returns the value in number or bigint representation + * + * @example + * ```ts + * console.log(web3.utils.toNumber(1)); + * > 1 + * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER)); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER))); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1))); + * > 9007199254740992n + * + * ``` + */ +const toNumber = (value) => { + if (typeof value === 'number') { + return value; + } + if (typeof value === 'bigint') { + return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER + ? Number(value) + : value; + } + if (typeof value === 'string' && (0, web3_validator_1.isHexStrict)(value)) { + return (0, exports.hexToNumber)(value); + } + try { + return (0, exports.toNumber)(BigInt(value)); + } + catch (_a) { + throw new web3_errors_1.InvalidNumberError(value); + } +}; +exports.toNumber = toNumber; +/** + * Auto converts any given value into it's bigint representation + * + * @param value - The value to convert + * @returns - Returns the value in bigint representation + + * @example + * ```ts + * console.log(web3.utils.toBigInt(1)); + * > 1n + * ``` + */ +const toBigInt = (value) => { + if (typeof value === 'number') { + return BigInt(value); + } + if (typeof value === 'bigint') { + return value; + } + // isHex passes for dec, too + if (typeof value === 'string' && (0, web3_validator_1.isHex)(value)) { + if (value.startsWith('-')) { + return -BigInt(value.substring(1)); + } + return BigInt(value); + } + throw new web3_errors_1.InvalidNumberError(value); +}; +exports.toBigInt = toBigInt; +/** + * Takes a number of wei and converts it to any other ether unit. + * @param number - The value in wei + * @param unit - The unit to convert to + * @returns - Returns the converted value in the given unit + * + * @example + * ```ts + * console.log(web3.utils.fromWei("1", "ether")); + * > 0.000000000000000001 + * + * console.log(web3.utils.fromWei("1", "shannon")); + * > 0.000000001 + * ``` + */ +const fromWei = (number, unit) => { + const denomination = exports.ethUnitMap[unit]; + if (!denomination) { + throw new web3_errors_1.InvalidUnitError(unit); + } + // value in wei would always be integer + // 13456789, 1234 + const value = String((0, exports.toNumber)(number)); + // count number of zeros in denomination + // 1000000 -> 6 + const numberOfZerosInDenomination = denomination.toString().length - 1; + if (numberOfZerosInDenomination <= 0) { + return value.toString(); + } + // pad the value with required zeros + // 13456789 -> 13456789, 1234 -> 001234 + const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, '0'); + // get the integer part of value by counting number of zeros from start + // 13456789 -> '13' + // 001234 -> '' + const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination); + // get the fraction part of value by counting number of zeros backward + // 13456789 -> '456789' + // 001234 -> '001234' + const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, ''); + if (integer === '') { + return `0.${fraction}`; + } + if (fraction === '') { + return integer; + } + return `${integer}.${fraction}`; +}; +exports.fromWei = fromWei; +/** + * Takes a number of a unit and converts it to wei. + * + * @param number - The number to convert. + * @param unit - {@link EtherUnits} The unit of the number passed. + * @returns The number converted to wei. + * + * @example + * ```ts + * console.log(web3.utils.toWei("0.001", "ether")); + * > 1000000000000000 //(wei) + * ``` + */ +// todo in 1.x unit defaults to 'ether' +const toWei = (number, unit) => { + web3_validator_1.validator.validate(['number'], [number]); + const denomination = exports.ethUnitMap[unit]; + if (!denomination) { + throw new web3_errors_1.InvalidUnitError(unit); + } + // if value is decimal e.g. 24.56 extract `integer` and `fraction` part + // to avoid `fraction` to be null use `concat` with empty string + const [integer, fraction] = String(typeof number === 'string' && !(0, web3_validator_1.isHexStrict)(number) ? number : (0, exports.toNumber)(number)) + .split('.') + .concat(''); + // join the value removing `.` from + // 24.56 -> 2456 + const value = BigInt(`${integer}${fraction}`); + // multiply value with denomination + // 2456 * 1000000 -> 2456000000 + const updatedValue = value * denomination; + // count number of zeros in denomination + const numberOfZerosInDenomination = denomination.toString().length - 1; + // check which either `fraction` or `denomination` have lower number of zeros + const decimals = Math.min(fraction.length, numberOfZerosInDenomination); + if (decimals === 0) { + return updatedValue.toString(); + } + // Add zeros to make length equal to required decimal points + // If string is larger than decimal points required then remove last zeros + return updatedValue.toString().padStart(decimals, '0').slice(0, -decimals); +}; +exports.toWei = toWei; +/** + * Will convert an upper or lowercase Ethereum address to a checksum address. + * @param address - An address string + * @returns The checksum address + * @example + * ```ts + * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d'); + * > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" + * ``` + */ +const toChecksumAddress = (address) => { + if (!(0, web3_validator_1.isAddress)(address, false)) { + throw new web3_errors_1.InvalidAddressError(address); + } + const lowerCaseAddress = address.toLowerCase().replace(/^0x/i, ''); + const hash = web3_validator_1.utils.uint8ArrayToHexString((0, keccak_js_1.keccak256)((0, exports.utf8ToBytes)(lowerCaseAddress))); + if ((0, web3_validator_1.isNullish)(hash) || + hash === '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470') + return ''; // // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data + let checksumAddress = '0x'; + const addressHash = hash.replace(/^0x/i, ''); + for (let i = 0; i < lowerCaseAddress.length; i += 1) { + // If ith character is 8 to f then make it uppercase + if (parseInt(addressHash[i], 16) > 7) { + checksumAddress += lowerCaseAddress[i].toUpperCase(); + } + else { + checksumAddress += lowerCaseAddress[i]; + } + } + return checksumAddress; +}; +exports.toChecksumAddress = toChecksumAddress; +const toBool = (value) => { + if (typeof value === 'boolean') { + return value; + } + if (typeof value === 'number' && (value === 0 || value === 1)) { + return Boolean(value); + } + if (typeof value === 'bigint' && (value === BigInt(0) || value === BigInt(1))) { + return Boolean(value); + } + if (typeof value === 'string' && + !(0, web3_validator_1.isHexStrict)(value) && + (value === '1' || value === '0' || value === 'false' || value === 'true')) { + if (value === 'true') { + return true; + } + if (value === 'false') { + return false; + } + return Boolean(Number(value)); + } + if (typeof value === 'string' && (0, web3_validator_1.isHexStrict)(value) && (value === '0x1' || value === '0x0')) { + return Boolean((0, exports.toNumber)(value)); + } + throw new web3_errors_1.InvalidBooleanError(value); +}; +exports.toBool = toBool; +//# sourceMappingURL=converters.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.js.map new file mode 100644 index 0000000..52c47fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/converters.js.map @@ -0,0 +1 @@ +{"version":3,"file":"converters.js","sourceRoot":"","sources":["../../src/converters.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF;;GAEG;AAEH,+DAA4D;AAC5D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,CAAC,CAAC,CAAC;KAC9B;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,IAAA,4BAAW,EAAC,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK,CAAC,EAAE;QAC5F,OAAO,OAAO,CAAC,IAAA,gBAAQ,EAAC,KAAK,CAAC,CAAC,CAAC;KAChC;IAED,MAAM,IAAI,iCAAmB,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC,CAAC;AAhCW,QAAA,MAAM,UAgCjB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.d.ts new file mode 100644 index 0000000..e74e33f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.d.ts @@ -0,0 +1,6 @@ +/// +import { EventEmitter as EventEmitterAtNode } from 'events'; +declare let EventEmitterType: typeof EventEmitterAtNode; +export declare class EventEmitter extends EventEmitterType { +} +export {}; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.js new file mode 100644 index 0000000..9051715 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.js @@ -0,0 +1,119 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventEmitter = void 0; +const events_1 = require("events"); +const wrapFunction = (fn) => (params) => fn(params.detail); +/** + * This class copy the behavior of Node.js EventEmitter class. + * It is used to provide the same interface for the browser environment. + */ +class EventEmitterAtBrowser extends EventTarget { + constructor() { + super(...arguments); + this._listeners = {}; + this.maxListeners = Number.MAX_SAFE_INTEGER; + } + on(eventName, fn) { + this.addEventListener(eventName, fn); + return this; + } + once(eventName, fn) { + const onceCallback = (params) => __awaiter(this, void 0, void 0, function* () { + this.off(eventName, onceCallback); + yield fn(params); + }); + return this.on(eventName, onceCallback); + } + off(eventName, fn) { + this.removeEventListener(eventName, fn); + return this; + } + emit(eventName, params) { + const event = new CustomEvent(eventName, { detail: params }); + return super.dispatchEvent(event); + } + listenerCount(eventName) { + const eventListeners = this._listeners[eventName]; + return eventListeners ? eventListeners.length : 0; + } + listeners(eventName) { + return this._listeners[eventName].map(value => value[0]) || []; + } + eventNames() { + return Object.keys(this._listeners); + } + removeAllListeners() { + Object.keys(this._listeners).forEach(event => { + this._listeners[event].forEach((listener) => { + super.removeEventListener(event, listener[1]); + }); + }); + this._listeners = {}; + return this; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + getMaxListeners() { + return this.maxListeners; + } + addEventListener(eventName, fn) { + const wrappedFn = wrapFunction(fn); + super.addEventListener(eventName, wrappedFn); + if (!this._listeners[eventName]) { + this._listeners[eventName] = []; + } + this._listeners[eventName].push([fn, wrappedFn]); + } + removeEventListener(eventName, fn) { + const eventListeners = this._listeners[eventName]; + if (eventListeners) { + const index = eventListeners.findIndex(item => item[0] === fn); + if (index !== -1) { + super.removeEventListener(eventName, eventListeners[index][1]); + eventListeners.splice(index, 1); + } + } + } +} +// eslint-disable-next-line import/no-mutable-exports +let EventEmitterType; +// Check if the code is running in a Node.js environment +if (typeof window === 'undefined') { + EventEmitterType = events_1.EventEmitter; +} +else { + // Fallback for the browser environment + EventEmitterType = EventEmitterAtBrowser; +} +class EventEmitter extends EventEmitterType { +} +exports.EventEmitter = EventEmitter; +//# sourceMappingURL=event_emitter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.js.map new file mode 100644 index 0000000..454022d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/event_emitter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event_emitter.js","sourceRoot":"","sources":["../../src/event_emitter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;AACF,yCAAyC;;;;;;;;;;;;AAEzC,mCAA4D;AAO5D,MAAM,YAAY,GACjB,CAAC,EAAY,EAAuB,EAAE,CACtC,CAAC,MAAmB,EAAE,EAAE,CACvB,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAEpB;;;GAGG;AACH,MAAM,qBAAsB,SAAQ,WAAW;IAA/C;;QACS,eAAU,GAAkE,EAAE,CAAC;QAC/E,iBAAY,GAAG,MAAM,CAAC,gBAAgB,CAAC;IA+EhD,CAAC;IA7EO,EAAE,CAAC,SAAiB,EAAE,EAAY;QACxC,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QACrC,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,IAAI,CAAC,SAAiB,EAAE,EAAY;QAC1C,MAAM,YAAY,GAAG,CAAO,MAAgB,EAAE,EAAE;YAC/C,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;YAClC,MAAM,EAAE,CAAC,M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GAAG,qBAAkB,CAAC;CACtC;KAAM;IACN,uCAAuC;IACvC,gBAAgB,GAAG,qBAA6D,CAAC;CACjF;AAED,MAAa,YAAa,SAAQ,gBAAgB;CAAG;AAArD,oCAAqD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.d.ts new file mode 100644 index 0000000..3a3cc56 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.d.ts @@ -0,0 +1,22 @@ +import { DataFormat, FormatType } from 'web3-types'; +import { JsonSchema, ValidationSchemaInput } from 'web3-validator'; +export declare const isDataFormat: (dataFormat: unknown) => dataFormat is DataFormat; +/** + * Converts a value depending on the format + * @param value - value to convert + * @param ethType - The type of the value to be parsed + * @param format - The format to be converted to + * @returns - The value converted to the specified format + */ +export declare const convertScalarValue: (value: unknown, ethType: string, format: DataFormat) => unknown; +/** + * Converts the data to the specified format + * @param data - data to convert + * @param schema - The JSON schema that describes the structure of the data + * @param dataPath - A string array that specifies the path to the data within the JSON schema + * @param format - The format to be converted to + * @param oneOfPath - An optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns - The data converted to the specified format + */ +export declare const convert: (data: Record | unknown[] | unknown, schema: JsonSchema, dataPath: string[], format: DataFormat, oneOfPath?: [string, number][]) => unknown; +export declare const format: (schema: ValidationSchemaInput | JsonSchema, data: DataType, returnFormat: ReturnType_1) => FormatType; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.js new file mode 100644 index 0000000..bb9a358 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.js @@ -0,0 +1,249 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.format = exports.convert = exports.convertScalarValue = exports.isDataFormat = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const converters_js_1 = require("./converters.js"); +const objects_js_1 = require("./objects.js"); +const string_manipulation_js_1 = require("./string_manipulation.js"); +const uint8array_js_1 = require("./uint8array.js"); +const { parseBaseType } = web3_validator_1.utils; +const isDataFormat = (dataFormat) => typeof dataFormat === 'object' && + !(0, web3_validator_1.isNullish)(dataFormat) && + 'number' in dataFormat && + 'bytes' in dataFormat; +exports.isDataFormat = isDataFormat; +/** + * Finds the schema that corresponds to a specific data path within a larger JSON schema. + * It works by iterating over the dataPath array and traversing the JSON schema one step at a time until it reaches the end of the path. + * + * @param schema - represents a JSON schema, which is an object that describes the structure of JSON data + * @param dataPath - represents an array of strings that specifies the path to the data within the JSON schema + * @param oneOfPath - represents an optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns the JSON schema that matches the data path + * + */ +const findSchemaByDataPath = (schema, dataPath, oneOfPath = []) => { + let result = Object.assign({}, schema); + let previousDataPath; + for (const dataPart of dataPath) { + if (result.oneOf && previousDataPath) { + const path = oneOfPath.find(function (element) { + return this === element[0]; + }, previousDataPath !== null && previousDataPath !== void 0 ? previousDataPath : ''); + if (path && path[0] === previousDataPath) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access + result = result.oneOf[path[1]]; + } + } + if (!result.properties && !result.items) { + return undefined; + } + if (result.properties) { + result = result.properties[dataPart]; + } + else if (result.items && result.items.properties) { + const node = result.items.properties; + if (!node) { + return undefined; + } + result = node[dataPart]; + } + else if (result.items && (0, web3_validator_1.isObject)(result.items)) { + result = result.items; + } + else if (result.items && Array.isArray(result.items)) { + result = result.items[parseInt(dataPart, 10)]; + } + if (result && dataPart) + previousDataPath = dataPart; + } + return result; +}; +/** + * Converts a value depending on the format + * @param value - value to convert + * @param ethType - The type of the value to be parsed + * @param format - The format to be converted to + * @returns - The value converted to the specified format + */ +const convertScalarValue = (value, ethType, format) => { + try { + const { baseType, baseTypeSize } = parseBaseType(ethType); + if (baseType === 'int' || baseType === 'uint') { + switch (format.number) { + case web3_types_1.FMT_NUMBER.NUMBER: + return Number((0, converters_js_1.toBigInt)(value)); + case web3_types_1.FMT_NUMBER.HEX: + return (0, converters_js_1.numberToHex)((0, converters_js_1.toBigInt)(value)); + case web3_types_1.FMT_NUMBER.STR: + return (0, converters_js_1.toBigInt)(value).toString(); + case web3_types_1.FMT_NUMBER.BIGINT: + return (0, converters_js_1.toBigInt)(value); + default: + throw new web3_errors_1.FormatterError(`Invalid format: ${String(format.number)}`); + } + } + if (baseType === 'bytes') { + let paddedValue; + if (baseTypeSize) { + if (typeof value === 'string') + paddedValue = (0, string_manipulation_js_1.padLeft)(value, baseTypeSize * 2); + else if (value instanceof Uint8Array) { + paddedValue = (0, uint8array_js_1.uint8ArrayConcat)(new Uint8Array(baseTypeSize - value.length), value); + } + } + else { + paddedValue = value; + } + switch (format.bytes) { + case web3_types_1.FMT_BYTES.HEX: + return (0, converters_js_1.bytesToHex)((0, converters_js_1.bytesToUint8Array)(paddedValue)); + case web3_types_1.FMT_BYTES.UINT8ARRAY: + return (0, converters_js_1.bytesToUint8Array)(paddedValue); + default: + throw new web3_errors_1.FormatterError(`Invalid format: ${String(format.bytes)}`); + } + } + } + catch (error) { + // If someone didn't use `eth` keyword we can return original value + // as the scope of this code is formatting not validation + return value; + } + return value; +}; +exports.convertScalarValue = convertScalarValue; +/** + * Converts the data to the specified format + * @param data - data to convert + * @param schema - The JSON schema that describes the structure of the data + * @param dataPath - A string array that specifies the path to the data within the JSON schema + * @param format - The format to be converted to + * @param oneOfPath - An optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns - The data converted to the specified format + */ +const convert = (data, schema, dataPath, format, oneOfPath = []) => { + var _a, _b; + // If it's a scalar value + if (!(0, web3_validator_1.isObject)(data) && !Array.isArray(data)) { + return (0, exports.convertScalarValue)(data, schema === null || schema === void 0 ? void 0 : schema.format, format); + } + const object = data; + for (const [key, value] of Object.entries(object)) { + dataPath.push(key); + const schemaProp = findSchemaByDataPath(schema, dataPath, oneOfPath); + // If value is a scaler value + if ((0, web3_validator_1.isNullish)(schemaProp)) { + delete object[key]; + dataPath.pop(); + continue; + } + // If value is an object, recurse into it + if ((0, web3_validator_1.isObject)(value)) { + (0, exports.convert)(value, schema, dataPath, format); + dataPath.pop(); + continue; + } + // If value is an array + if (Array.isArray(value)) { + let _schemaProp = schemaProp; + // TODO This is a naive approach to solving the issue of + // a schema using oneOf. This chunk of code was intended to handle + // BlockSchema.transactions + // TODO BlockSchema.transactions are not being formatted + if ((schemaProp === null || schemaProp === void 0 ? void 0 : schemaProp.oneOf) !== undefined) { + // The following code is basically saying: + // if the schema specifies oneOf, then we are to loop + // over each possible schema and check if they type of the schema + // matches the type of value[0], and if so we use the oneOfSchemaProp + // as the schema for formatting + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + schemaProp.oneOf.forEach((oneOfSchemaProp, index) => { + var _a, _b; + if (!Array.isArray(schemaProp === null || schemaProp === void 0 ? void 0 : schemaProp.items) && + ((typeof value[0] === 'object' && + ((_a = oneOfSchemaProp === null || oneOfSchemaProp === void 0 ? void 0 : oneOfSchemaProp.items) === null || _a === void 0 ? void 0 : _a.type) === 'object') || + (typeof value[0] === 'string' && + ((_b = oneOfSchemaProp === null || oneOfSchemaProp === void 0 ? void 0 : oneOfSchemaProp.items) === null || _b === void 0 ? void 0 : _b.type) !== 'object'))) { + _schemaProp = oneOfSchemaProp; + oneOfPath.push([key, index]); + } + }); + } + if ((0, web3_validator_1.isNullish)(_schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items)) { + // Can not find schema for array item, delete that item + delete object[key]; + dataPath.pop(); + continue; + } + // If schema for array items is a single type + if ((0, web3_validator_1.isObject)(_schemaProp.items) && !(0, web3_validator_1.isNullish)(_schemaProp.items.format)) { + for (let i = 0; i < value.length; i += 1) { + object[key][i] = (0, exports.convertScalarValue)(value[i], + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + (_a = _schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items) === null || _a === void 0 ? void 0 : _a.format, format); + } + dataPath.pop(); + continue; + } + // If schema for array items is an object + if (!Array.isArray(_schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items) && ((_b = _schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items) === null || _b === void 0 ? void 0 : _b.type) === 'object') { + for (const arrObject of value) { + (0, exports.convert)(arrObject, schema, dataPath, format, oneOfPath); + } + dataPath.pop(); + continue; + } + // If schema for array is a tuple + if (Array.isArray(_schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items)) { + for (let i = 0; i < value.length; i += 1) { + object[key][i] = (0, exports.convertScalarValue)(value[i], _schemaProp.items[i].format, format); + } + dataPath.pop(); + continue; + } + } + object[key] = (0, exports.convertScalarValue)(value, schemaProp.format, format); + dataPath.pop(); + } + return object; +}; +exports.convert = convert; +const format = (schema, data, returnFormat) => { + let dataToParse; + if ((0, web3_validator_1.isObject)(data)) { + dataToParse = (0, objects_js_1.mergeDeep)({}, data); + } + else if (Array.isArray(data)) { + dataToParse = [...data]; + } + else { + dataToParse = data; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const jsonSchema = (0, web3_validator_1.isObject)(schema) ? schema : web3_validator_1.utils.ethAbiToJsonSchema(schema); + if (!jsonSchema.properties && !jsonSchema.items && !jsonSchema.format) { + throw new web3_errors_1.FormatterError('Invalid json schema for formatting'); + } + return (0, exports.convert)(dataToParse, jsonSchema, [], returnFormat); +}; +exports.format = format; +//# sourceMappingURL=formatter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.js.map new file mode 100644 index 0000000..6efd51d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/formatter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatter.js","sourceRoot":"","sources":["../../src/formatter.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAA6C;AAC7C,2CAAkF;AAClF,mDAA+F;AAC/F,mDAAuF;AACvF,6CAAyC;AACzC,qEAAmD;AACnD,mDAAmD;AAEnD,MAAM,EAAE,aAAa,EAAE,GAAG,sBAAK,CAAC;AAEzB,MAAM,YAAY,GAAG,CAAC,UAAmB,EAA4B,EAAE,CAC7E,OAAO,UAAU,KAAK,QAAQ;IAC9B,CAAC,IAAA,0BAAS,EAAC,UAAU,CAAC;IACtB,QAAQ,IAAI,UAAU;IACtB,OAAO,IAAI,UAAU,CAAC;AAJV,QAAA,YAAY,gBAIF;AAEvB;;;;;;;;;GASG;AACH,MAAM,oBAAoB,GAAG,CAC5B,MAAkB,EAClB,QAAkB,EAClB,YAAgC,EAAE,EACT,EAAE;IAC3B,IAAI,MAAM,GAAe,kBAAK,MAAM,CAAgB,CAAC;IACrD,IAAI,gBAAoC,CAAC;IAEzC,KAAK,MAAM,QAAQ,IAAI,QAAQ,EAAE;QAChC,IAAI,MAAM,CAAC,KAAK,IAAI,gBAAgB,EAAE;YACrC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,UAAU,OAAyB;gBAC9D,OAAQ,IAA0B,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;YACnD,CAAC,EAAE,gBAAgB,aAAhB,gBAAgB,cAAhB,gBAAgB,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ff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.d.ts new file mode 100644 index 0000000..4cfca8f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.d.ts @@ -0,0 +1,94 @@ +import { Bytes, Numbers, Sha3Input, TypedObject, TypedObjectAbbreviated } from 'web3-types'; +/** + * computes the Keccak-256 hash of the input and returns a hexstring + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.sha3('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3('')); + * > undefined + * ``` + */ +export declare const sha3: (data: Bytes) => string | undefined; +/** + * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed. + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * conosle.log(web3.utils.sha3Raw('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3Raw('')); + * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 + * ``` + */ +export declare const sha3Raw: (data: Bytes) => string; +/** + * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array` + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.keccak256Wrapper('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.keccak256Wrapper(1)); + * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6 + * + * console.log(web3.utils.keccak256Wrapper(0xaf12fd)); + * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c + * ``` + */ +export declare const keccak256Wrapper: (data: Bytes | Numbers | string | ReadonlyArray) => string; +export { keccak256Wrapper as keccak256 }; +/** + * returns a string of the tightly packed value given based on the type + * @param arg - the input to return the tightly packed value + * @returns - the tightly packed value + */ +export declare const processSolidityEncodePackedArgs: (arg: Sha3Input) => string; +/** + * Encode packed arguments to a hexstring + */ +export declare const encodePacked: (...values: Sha3Input[]) => string; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, or null if input is empty + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log([{ type: 'string', value: '31323334' }]); + * console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" })); + * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b + * ``` + */ +export declare const soliditySha3: (...values: Sha3Input[]) => string | undefined; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" })) + * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0 + * ``` + */ +export declare const soliditySha3Raw: (...values: TypedObject[] | TypedObjectAbbreviated[]) => string; +/** + * Get slot number for storage long string in contract. Basically for getStorage method + * returns slotNumber where will data placed + * @param mainSlotNumber - the slot number where will be stored hash of long string + * @returns - the slot number where will be stored long string + */ +export declare const getStorageSlotNumForLongString: (mainSlotNumber: number | string) => string | undefined; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.js new file mode 100644 index 0000000..8bf35bc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.js @@ -0,0 +1,327 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStorageSlotNumForLongString = exports.soliditySha3Raw = exports.soliditySha3 = exports.encodePacked = exports.processSolidityEncodePackedArgs = exports.keccak256 = exports.keccak256Wrapper = exports.sha3Raw = exports.sha3 = void 0; +/** + * @module Utils + */ +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const utils_js_1 = require("ethereum-cryptography/utils.js"); +const web3_errors_1 = require("web3-errors"); +const web3_validator_1 = require("web3-validator"); +const converters_js_1 = require("./converters.js"); +const string_manipulation_js_1 = require("./string_manipulation.js"); +const SHA3_EMPTY_BYTES = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; +/** + * computes the Keccak-256 hash of the input and returns a hexstring + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.sha3('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3('')); + * > undefined + * ``` + */ +const sha3 = (data) => { + let updatedData; + if (typeof data === 'string') { + if (data.startsWith('0x') && (0, web3_validator_1.isHexStrict)(data)) { + updatedData = (0, converters_js_1.hexToBytes)(data); + } + else { + updatedData = (0, utils_js_1.utf8ToBytes)(data); + } + } + else { + updatedData = data; + } + const hash = (0, converters_js_1.bytesToHex)((0, keccak_js_1.keccak256)(updatedData)); + // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data + return hash === SHA3_EMPTY_BYTES ? undefined : hash; +}; +exports.sha3 = sha3; +/** + * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed. + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * conosle.log(web3.utils.sha3Raw('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3Raw('')); + * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 + * ``` + */ +const sha3Raw = (data) => { + const hash = (0, exports.sha3)(data); + if ((0, web3_validator_1.isNullish)(hash)) { + return SHA3_EMPTY_BYTES; + } + return hash; +}; +exports.sha3Raw = sha3Raw; +/** + * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array` + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.keccak256Wrapper('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.keccak256Wrapper(1)); + * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6 + * + * console.log(web3.utils.keccak256Wrapper(0xaf12fd)); + * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c + * ``` + */ +const keccak256Wrapper = (data) => { + let processedData; + if (typeof data === 'bigint' || typeof data === 'number') { + processedData = (0, utils_js_1.utf8ToBytes)(data.toString()); + } + else if (Array.isArray(data)) { + processedData = new Uint8Array(data); + } + else if (typeof data === 'string' && !(0, web3_validator_1.isHexStrict)(data)) { + processedData = (0, utils_js_1.utf8ToBytes)(data); + } + else { + processedData = (0, converters_js_1.bytesToUint8Array)(data); + } + return (0, converters_js_1.bytesToHex)((0, keccak_js_1.keccak256)(processedData)); +}; +exports.keccak256Wrapper = keccak256Wrapper; +exports.keccak256 = exports.keccak256Wrapper; +/** + * returns type and value + * @param arg - the input to return the type and value + * @returns - the type and value of the input + */ +const getType = (arg) => { + if (Array.isArray(arg)) { + throw new Error('Autodetection of array types is not supported.'); + } + let type; + let value; + // if type is given + if (typeof arg === 'object' && + ('t' in arg || 'type' in arg) && + ('v' in arg || 'value' in arg)) { + type = 't' in arg ? arg.t : arg.type; + value = 'v' in arg ? arg.v : arg.value; + type = type.toLowerCase() === 'bigint' ? 'int' : type; + } + else if (typeof arg === 'bigint') { + return ['int', arg]; + } + // otherwise try to guess the type + else { + type = (0, converters_js_1.toHex)(arg, true); + value = (0, converters_js_1.toHex)(arg); + if (!type.startsWith('int') && !type.startsWith('uint')) { + type = 'bytes'; + } + } + if ((type.startsWith('int') || type.startsWith('uint')) && + typeof value === 'string' && + !/^(-)?0x/i.test(value)) { + value = (0, converters_js_1.toBigInt)(value); + } + return [type, value]; +}; +/** + * returns the type with size if uint or int + * @param name - the input to return the type with size + * @returns - the type with size of the input + */ +const elementaryName = (name) => { + if (name.startsWith('int[')) { + return `int256${name.slice(3)}`; + } + if (name === 'int') { + return 'int256'; + } + if (name.startsWith('uint[')) { + return `uint256'${name.slice(4)}`; + } + if (name === 'uint') { + return 'uint256'; + } + return name; +}; +/** + * returns the size of the value of type 'byte' + */ +const parseTypeN = (value, typeLength) => { + const typesize = /^(\d+).*$/.exec(value.slice(typeLength)); + return typesize ? parseInt(typesize[1], 10) : 0; +}; +/** + * returns the bit length of the value + * @param value - the input to return the bit length + * @returns - the bit length of the input + */ +const bitLength = (value) => { + const updatedVal = value.toString(2); + return updatedVal.length; +}; +/** + * Pads the value based on size and type + * returns a string of the padded value + * @param type - the input to pad + * @returns = the padded value + */ +const solidityPack = (type, val) => { + const value = val.toString(); + if (type === 'string') { + if (typeof val === 'string') + return (0, converters_js_1.utf8ToHex)(val); + throw new web3_errors_1.InvalidStringError(val); + } + if (type === 'bool' || type === 'boolean') { + if (typeof val === 'boolean') + return val ? '01' : '00'; + throw new web3_errors_1.InvalidBooleanError(val); + } + if (type === 'address') { + if (!(0, web3_validator_1.isAddress)(value)) { + throw new web3_errors_1.InvalidAddressError(value); + } + return value; + } + const name = elementaryName(type); + if (type.startsWith('uint')) { + const size = parseTypeN(name, 'uint'.length); + if (size % 8 || size < 8 || size > 256) { + throw new web3_errors_1.InvalidSizeError(value); + } + const num = (0, converters_js_1.toNumber)(value); + if (bitLength(num) > size) { + throw new web3_errors_1.InvalidLargeValueError(value); + } + if (num < BigInt(0)) { + throw new web3_errors_1.InvalidUnsignedIntegerError(value); + } + return size ? (0, string_manipulation_js_1.leftPad)(num.toString(16), (size / 8) * 2) : num.toString(16); + } + if (type.startsWith('int')) { + const size = parseTypeN(name, 'int'.length); + if (size % 8 || size < 8 || size > 256) { + throw new web3_errors_1.InvalidSizeError(type); + } + const num = (0, converters_js_1.toNumber)(value); + if (bitLength(num) > size) { + throw new web3_errors_1.InvalidLargeValueError(value); + } + if (num < BigInt(0)) { + return (0, string_manipulation_js_1.toTwosComplement)(num.toString(), (size / 8) * 2); + } + return size ? (0, string_manipulation_js_1.leftPad)(num.toString(16), size / 4) : num.toString(16); + } + if (name === 'bytes') { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new web3_errors_1.InvalidBytesError(value); + } + return value; + } + if (type.startsWith('bytes')) { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new web3_errors_1.InvalidBytesError(value); + } + const size = parseTypeN(type, 'bytes'.length); + if (!size || size < 1 || size > 64 || size < value.replace(/^0x/i, '').length / 2) { + throw new web3_errors_1.InvalidBytesError(value); + } + return (0, string_manipulation_js_1.rightPad)(value, size * 2); + } + return ''; +}; +/** + * returns a string of the tightly packed value given based on the type + * @param arg - the input to return the tightly packed value + * @returns - the tightly packed value + */ +const processSolidityEncodePackedArgs = (arg) => { + const [type, val] = getType(arg); + // array case + if (Array.isArray(val)) { + // go through each element of the array and use map function to create new hexarg list + const hexArg = val.map((v) => solidityPack(type, v).replace('0x', '')); + return hexArg.join(''); + } + const hexArg = solidityPack(type, val); + return hexArg.replace('0x', ''); +}; +exports.processSolidityEncodePackedArgs = processSolidityEncodePackedArgs; +/** + * Encode packed arguments to a hexstring + */ +const encodePacked = (...values) => { + const hexArgs = values.map(exports.processSolidityEncodePackedArgs); + return `0x${hexArgs.join('').toLowerCase()}`; +}; +exports.encodePacked = encodePacked; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, or null if input is empty + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log([{ type: 'string', value: '31323334' }]); + * console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" })); + * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b + * ``` + */ +const soliditySha3 = (...values) => (0, exports.sha3)((0, exports.encodePacked)(...values)); +exports.soliditySha3 = soliditySha3; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" })) + * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0 + * ``` + */ +const soliditySha3Raw = (...values) => (0, exports.sha3Raw)((0, exports.encodePacked)(...values)); +exports.soliditySha3Raw = soliditySha3Raw; +/** + * Get slot number for storage long string in contract. Basically for getStorage method + * returns slotNumber where will data placed + * @param mainSlotNumber - the slot number where will be stored hash of long string + * @returns - the slot number where will be stored long string + */ +const getStorageSlotNumForLongString = (mainSlotNumber) => (0, exports.sha3)(`0x${(typeof mainSlotNumber === 'number' + ? mainSlotNumber.toString() + : mainSlotNumber).padStart(64, '0')}`); +exports.getStorageSlotNumForLongString = getStorageSlotNumForLongString; +//# sourceMappingURL=hash.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/hash.js.map new file mode 100644 index 0000000..51c12a5 --- /dev/null +++ b/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EAAC,IAAA,oBAAY,EAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AADlB,QAAA,YAAY,gBACM;AAE/B;;;;;;;;;;;GAWG;AACI,MAAM,eAAe,GAAG,CAAC,GAAG,MAAgD,EAAU,EAAE,CAC9F,IAAA,eAAO,EAAC,IAAA,oBAAY,EAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AADrB,QAAA,eAAe,mBACM;AAElC;;;;;GAKG;AACI,MAAM,8BAA8B,GAAG,CAAC,cAA+B,EAAE,EAAE,CACjF,IAAA,YAAI,EACH,KAAK,CAAC,OAAO,cAAc,KAAK,QAAQ;IACvC,CAAC,CAAC,cAAc,CAAC,QAAQ,EAAE;IAC3B,CAAC,CAAC,cAAc,CAChB,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,CACrB,CAAC;AANU,QAAA,8BAA8B,kCAMxC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.d.ts new file mode 100644 index 0000000..4bbcc4e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.d.ts @@ -0,0 +1,17 @@ +export * from './converters.js'; +export * from './event_emitter.js'; +export * from './validation.js'; +export * from './formatter.js'; +export * from './hash.js'; +export * from './random.js'; +export * from './string_manipulation.js'; +export * from './objects.js'; +export * from './promise_helpers.js'; +export * from './json_rpc.js'; +export * as jsonRpc from './json_rpc.js'; +export * from './web3_deferred_promise.js'; +export * from './chunk_response_parser.js'; +export * from './uuid.js'; +export * from './web3_eip1193_provider.js'; +export * from './socket_provider.js'; +export * from './uint8array.js'; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.js new file mode 100644 index 0000000..4a1fd56 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.js @@ -0,0 +1,63 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jsonRpc = void 0; +__exportStar(require("./converters.js"), exports); +__exportStar(require("./event_emitter.js"), exports); +__exportStar(require("./validation.js"), exports); +__exportStar(require("./formatter.js"), exports); +__exportStar(require("./hash.js"), exports); +__exportStar(require("./random.js"), exports); +__exportStar(require("./string_manipulation.js"), exports); +__exportStar(require("./objects.js"), exports); +__exportStar(require("./promise_helpers.js"), exports); +__exportStar(require("./json_rpc.js"), exports); +exports.jsonRpc = __importStar(require("./json_rpc.js")); +__exportStar(require("./web3_deferred_promise.js"), exports); +__exportStar(require("./chunk_response_parser.js"), exports); +__exportStar(require("./uuid.js"), exports); +__exportStar(require("./web3_eip1193_provider.js"), exports); +__exportStar(require("./socket_provider.js"), exports); +__exportStar(require("./uint8array.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.js.map new file mode 100644 index 0000000..8b62962 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,kDAAgC;AAChC,qDAAmC;AACnC,kDAAgC;AAChC,iDAA+B;AAC/B,4CAA0B;AAC1B,8CAA4B;AAC5B,2DAAyC;AACzC,+CAA6B;AAC7B,uDAAqC;AACrC,gDAA8B;AAC9B,yDAAyC;AACzC,6DAA2C;AAC3C,6DAA2C;AAC3C,4CAA0B;AAC1B,6DAA2C;AAC3C,uDAAqC;AACrC,kDAAgC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.d.ts new file mode 100644 index 0000000..a22e8ca --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.d.ts @@ -0,0 +1,21 @@ +import { JsonRpcPayload, JsonRpcResponse, JsonRpcResponseWithResult, JsonRpcResponseWithError, JsonRpcOptionalRequest, JsonRpcBatchRequest, JsonRpcNotification, JsonRpcRequest, JsonRpcBatchResponse, JsonRpcSubscriptionResult } from 'web3-types'; +export declare const isResponseRpcError: (rpcError: JsonRpcResponseWithError) => boolean; +export declare const isResponseWithResult: (response: JsonRpcResponse) => response is JsonRpcResponseWithResult; +export declare const isResponseWithError: (response: JsonRpcResponse) => response is JsonRpcResponseWithError; +export declare const isResponseWithNotification: (response: JsonRpcNotification | JsonRpcSubscriptionResult) => response is JsonRpcNotification; +export declare const isSubscriptionResult: (response: JsonRpcSubscriptionResult | JsonRpcNotification) => response is JsonRpcSubscriptionResult; +export declare const validateResponse: (response: JsonRpcResponse) => boolean; +export declare const isValidResponse: (response: JsonRpcResponse) => boolean; +export declare const isBatchResponse: (response: JsonRpcResponse) => response is JsonRpcBatchResponse; +/** + * Optionally use to make the jsonrpc `id` start from a specific number. + * Without calling this function, the `id` will be filled with a Uuid. + * But after this being called with a number, the `id` will be a number staring from the provided `start` variable. + * However, if `undefined` was passed to this function, the `id` will be a Uuid again. + * @param start - a number to start incrementing from. + * Or `undefined` to use a new Uuid (this is the default behavior) + */ +export declare const setRequestIdStart: (start: number | undefined) => void; +export declare const toPayload: (request: JsonRpcOptionalRequest) => JsonRpcPayload; +export declare const toBatchPayload: (requests: JsonRpcOptionalRequest[]) => JsonRpcBatchRequest; +export declare const isBatchRequest: (request: JsonRpcBatchRequest | JsonRpcRequest | JsonRpcOptionalRequest) => request is JsonRpcBatchRequest; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.js new file mode 100644 index 0000000..c583260 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.js @@ -0,0 +1,96 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBatchRequest = exports.toBatchPayload = exports.toPayload = exports.setRequestIdStart = exports.isBatchResponse = exports.isValidResponse = exports.validateResponse = exports.isSubscriptionResult = exports.isResponseWithNotification = exports.isResponseWithError = exports.isResponseWithResult = exports.isResponseRpcError = void 0; +const web3_validator_1 = require("web3-validator"); +const web3_errors_1 = require("web3-errors"); +const uuid_js_1 = require("./uuid.js"); +// check if code is a valid rpc server error code +const isResponseRpcError = (rpcError) => { + const errorCode = rpcError.error.code; + return web3_errors_1.rpcErrorsMap.has(errorCode) || (errorCode >= -32099 && errorCode <= -32000); +}; +exports.isResponseRpcError = isResponseRpcError; +const isResponseWithResult = (response) => !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + // JSON RPC consider "null" as valid response + 'result' in response && + (0, web3_validator_1.isNullish)(response.error) && + (typeof response.id === 'number' || typeof response.id === 'string'); +exports.isResponseWithResult = isResponseWithResult; +// To avoid circular package dependency, copied to code here. If you update this please update same function in `response_errors.ts` +const isResponseWithError = (response) => !Array.isArray(response) && + response.jsonrpc === '2.0' && + !!response && + (0, web3_validator_1.isNullish)(response.result) && + // JSON RPC consider "null" as valid response + 'error' in response && + (typeof response.id === 'number' || typeof response.id === 'string'); +exports.isResponseWithError = isResponseWithError; +const isResponseWithNotification = (response) => !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + !(0, web3_validator_1.isNullish)(response.params) && + !(0, web3_validator_1.isNullish)(response.method); +exports.isResponseWithNotification = isResponseWithNotification; +const isSubscriptionResult = (response) => !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + 'id' in response && + // JSON RPC consider "null" as valid response + 'result' in response; +exports.isSubscriptionResult = isSubscriptionResult; +const validateResponse = (response) => (0, exports.isResponseWithResult)(response) || (0, exports.isResponseWithError)(response); +exports.validateResponse = validateResponse; +const isValidResponse = (response) => Array.isArray(response) ? response.every(exports.validateResponse) : (0, exports.validateResponse)(response); +exports.isValidResponse = isValidResponse; +const isBatchResponse = (response) => Array.isArray(response) && response.length > 0 && (0, exports.isValidResponse)(response); +exports.isBatchResponse = isBatchResponse; +// internal optional variable to increment and use for the jsonrpc `id` +let requestIdSeed; +/** + * Optionally use to make the jsonrpc `id` start from a specific number. + * Without calling this function, the `id` will be filled with a Uuid. + * But after this being called with a number, the `id` will be a number staring from the provided `start` variable. + * However, if `undefined` was passed to this function, the `id` will be a Uuid again. + * @param start - a number to start incrementing from. + * Or `undefined` to use a new Uuid (this is the default behavior) + */ +const setRequestIdStart = (start) => { + requestIdSeed = start; +}; +exports.setRequestIdStart = setRequestIdStart; +const toPayload = (request) => { + var _a, _b, _c, _d; + if (typeof requestIdSeed !== 'undefined') { + requestIdSeed += 1; + } + return { + jsonrpc: (_a = request.jsonrpc) !== null && _a !== void 0 ? _a : '2.0', + id: (_c = (_b = request.id) !== null && _b !== void 0 ? _b : requestIdSeed) !== null && _c !== void 0 ? _c : (0, uuid_js_1.uuidV4)(), + method: request.method, + params: (_d = request.params) !== null && _d !== void 0 ? _d : undefined, + }; +}; +exports.toPayload = toPayload; +const toBatchPayload = (requests) => requests.map(request => (0, exports.toPayload)(request)); +exports.toBatchPayload = toBatchPayload; +const isBatchRequest = (request) => Array.isArray(request) && request.length > 0; +exports.isBatchRequest = isBatchRequest; +//# sourceMappingURL=json_rpc.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.js.map new file mode 100644 index 0000000..a3d7746 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/json_rpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json_rpc.js","sourceRoot":"","sources":["../../src/json_rpc.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,mDAA2C;AAa3C,6CAA2C;AAC3C,uCAAmC;AAEnC,iDAAiD;AAC1C,MAAM,kBAAkB,GAAG,CAAC,QAAkC,EAAE,EAAE;IACxE,MA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IAAI,OAAO,aAAa,KAAK,WAAW,EAAE;QACzC,aAAa,IAAI,CAAC,CAAC;KACnB;IACD,OAAO;QACN,OAAO,EAAE,MAAA,OAAO,CAAC,OAAO,mCAAI,KAAK;QACjC,EAAE,EAAE,MAAA,MAAA,OAAO,CAAC,EAAE,mCAAI,aAAa,mCAAI,IAAA,gBAAM,GAAE;QAC3C,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,MAAM,EAAE,MAAA,OAAO,CAAC,MAAM,mCAAI,SAAS;KACnC,CAAC;AACH,CAAC,CAAC;AAZW,QAAA,SAAS,aAYpB;AAEK,MAAM,cAAc,GAAG,CAAC,QAA2C,EAAuB,EAAE,CAClG,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,IAAA,iBAAS,EAAU,OAAO,CAAC,CAAwB,CAAC;AADhE,QAAA,cAAc,kBACkD;AAEtE,MAAM,cAAc,GAAG,CAC7B,OAAwF,EACvD,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAFrE,QAAA,cAAc,kBAEuD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.d.ts new file mode 100644 index 0000000..30a7441 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.d.ts @@ -0,0 +1,7 @@ +/** + * Deep merge two objects. + * @param destination - The destination object. + * @param sources - An array of source objects. + * @returns - The merged object. + */ +export declare const mergeDeep: (destination: Record, ...sources: Record[]) => Record; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.js new file mode 100644 index 0000000..44b750e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.js @@ -0,0 +1,61 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mergeDeep = void 0; +const web3_types_1 = require("web3-types"); +const web3_validator_1 = require("web3-validator"); +const isIterable = (item) => typeof item === 'object' && + !(0, web3_validator_1.isNullish)(item) && + !Array.isArray(item) && + !(item instanceof web3_types_1.TypedArray); +// The following code is a derivative work of the code from the "LiskHQ/lisk-sdk" project, +// which is licensed under Apache version 2. +/** + * Deep merge two objects. + * @param destination - The destination object. + * @param sources - An array of source objects. + * @returns - The merged object. + */ +const mergeDeep = (destination, ...sources) => { + const result = destination; // clone deep here + if (!isIterable(result)) { + return result; + } + for (const src of sources) { + // eslint-disable-next-line no-restricted-syntax + for (const key in src) { + if (isIterable(src[key])) { + if (!result[key]) { + result[key] = {}; + } + (0, exports.mergeDeep)(result[key], src[key]); + } + else if (!(0, web3_validator_1.isNullish)(src[key]) && Object.hasOwnProperty.call(src, key)) { + if (Array.isArray(src[key]) || src[key] instanceof web3_types_1.TypedArray) { + result[key] = src[key].slice(0); + } + else { + result[key] = src[key]; + } + } + } + } + return result; +}; +exports.mergeDeep = mergeDeep; +//# sourceMappingURL=objects.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.js.map new file mode 100644 index 0000000..4847efc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/objects.js.map @@ -0,0 +1 @@ +{"version":3,"file":"objects.js","sourceRoot":"","sources":["../../src/objects.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAe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AM;oBACN,MAAM,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;iBACvB;aACD;SACD;KACD;IACD,OAAO,MAAM,CAAC;AACf,CAAC,CAAC;AA7BW,QAAA,SAAS,aA6BpB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.d.ts new file mode 100644 index 0000000..bfb5e99 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.d.ts @@ -0,0 +1,47 @@ +export declare type Timer = ReturnType; +export declare type Timeout = ReturnType; +/** + * An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser. + * @param object - to check if it is a `Promise` + * @returns `true` if it is an `object` or a `function` that has a `then` function. And returns `false` otherwise. + */ +export declare function isPromise(object: unknown): boolean; +export declare type AsyncFunction = (...args: K[]) => Promise; +export declare function waitWithTimeout(awaitable: Promise | AsyncFunction, timeout: number, error: Error): Promise; +export declare function waitWithTimeout(awaitable: Promise | AsyncFunction, timeout: number): Promise; +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. It returns promise and intervalId. + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export declare function pollTillDefinedAndReturnIntervalId(func: AsyncFunction, interval: number): [Promise>, Timer]; +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. + * pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result. + * This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId(). + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export declare function pollTillDefined(func: AsyncFunction, interval: number): Promise>; +/** + * Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete + * @param timeout - The timeout to enforced in milliseconds. + * @param error - The error to throw if the timeout is reached. + * @returns A tuple of the timeout id and the promise that will be rejected if the timeout is reached. + * + * @example + * ```ts + * const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out')); + * ``` + */ +export declare function rejectIfTimeout(timeout: number, error: Error): [Timer, Promise]; +/** + * Sets an interval that repeatedly executes the given cond function with the specified interval between each call. + * If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned. + * @param cond - The function/confition to call. + * @param interval - The interval in milliseconds. + * @returns - an array with the interval ID and the Promise. + */ +export declare function rejectIfConditionAtInterval(cond: AsyncFunction, interval: number): [Timer, Promise]; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.js new file mode 100644 index 0000000..2881aac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.js @@ -0,0 +1,155 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rejectIfConditionAtInterval = exports.rejectIfTimeout = exports.pollTillDefined = exports.pollTillDefinedAndReturnIntervalId = exports.waitWithTimeout = exports.isPromise = void 0; +const web3_validator_1 = require("web3-validator"); +/** + * An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser. + * @param object - to check if it is a `Promise` + * @returns `true` if it is an `object` or a `function` that has a `then` function. And returns `false` otherwise. + */ +function isPromise(object) { + return ((typeof object === 'object' || typeof object === 'function') && + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof object.then === 'function'); +} +exports.isPromise = isPromise; +/** + * Wait for a promise but interrupt it if it did not resolve within a given timeout. + * If the timeout reached, before the promise code resolve, either throw an error if an error object was provided, or return `undefined`. + * @param awaitable - The promise or function to wait for. + * @param timeout - The timeout in milliseconds. + * @param error - (Optional) The error to throw if the timeout reached. + */ +function waitWithTimeout(awaitable, timeout, error) { + return __awaiter(this, void 0, void 0, function* () { + let timeoutId; + const result = yield Promise.race([ + awaitable instanceof Promise ? awaitable : awaitable(), + new Promise((resolve, reject) => { + timeoutId = setTimeout(() => (error ? reject(error) : resolve(undefined)), timeout); + }), + ]); + if (timeoutId) { + clearTimeout(timeoutId); + } + if (result instanceof Error) { + throw result; + } + return result; + }); +} +exports.waitWithTimeout = waitWithTimeout; +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. It returns promise and intervalId. + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +function pollTillDefinedAndReturnIntervalId(func, interval) { + let intervalId; + const polledRes = new Promise((resolve, reject) => { + intervalId = setInterval(function intervalCallbackFunc() { + (() => __awaiter(this, void 0, void 0, function* () { + try { + const res = yield waitWithTimeout(func, interval); + if (!(0, web3_validator_1.isNullish)(res)) { + clearInterval(intervalId); + resolve(res); + } + } + catch (error) { + clearInterval(intervalId); + reject(error); + } + }))(); + return intervalCallbackFunc; + }() // this will immediate invoke first call + , interval); + }); + return [polledRes, intervalId]; +} +exports.pollTillDefinedAndReturnIntervalId = pollTillDefinedAndReturnIntervalId; +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. + * pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result. + * This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId(). + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +function pollTillDefined(func, interval) { + return __awaiter(this, void 0, void 0, function* () { + return pollTillDefinedAndReturnIntervalId(func, interval)[0]; + }); +} +exports.pollTillDefined = pollTillDefined; +/** + * Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete + * @param timeout - The timeout to enforced in milliseconds. + * @param error - The error to throw if the timeout is reached. + * @returns A tuple of the timeout id and the promise that will be rejected if the timeout is reached. + * + * @example + * ```ts + * const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out')); + * ``` + */ +function rejectIfTimeout(timeout, error) { + let timeoutId; + const rejectOnTimeout = new Promise((_, reject) => { + timeoutId = setTimeout(() => { + reject(error); + }, timeout); + }); + return [timeoutId, rejectOnTimeout]; +} +exports.rejectIfTimeout = rejectIfTimeout; +/** + * Sets an interval that repeatedly executes the given cond function with the specified interval between each call. + * If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned. + * @param cond - The function/confition to call. + * @param interval - The interval in milliseconds. + * @returns - an array with the interval ID and the Promise. + */ +function rejectIfConditionAtInterval(cond, interval) { + let intervalId; + const rejectIfCondition = new Promise((_, reject) => { + intervalId = setInterval(() => { + (() => __awaiter(this, void 0, void 0, function* () { + const error = yield cond(); + if (error) { + clearInterval(intervalId); + reject(error); + } + }))(); + }, interval); + }); + return [intervalId, rejectIfCondition]; +} +exports.rejectIfConditionAtInterval = rejectIfConditionAtInterval; +//# sourceMappingURL=promise_helpers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.js.map new file mode 100644 index 0000000..0f91dc9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/promise_helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promise_helpers.js","sourceRoot":"","sources":["../../src/promise_helpers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,mDAA2C;AAM3C;;;;GAIG;AACH,SAAgB,SAAS,CAAC,MAAe;IACxC,OAAO,CACN,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,UAAU,CAAC;QAC5D,sEAAsE;QACtE,OAAQ,MAA4B,CAAC,IAAI,KAAK,UAAU,CACxD,CAAC;AACH,CAAC;AAND,8BAMC;AAcD;;;;;;GAMG;AACH,SAAsB,eAAe,CACpC,SAAwC,EACxC,OAAe,EACf,KAAa;;QAEb,IAAI,SAA8B,CAAC;QACnC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;YACjC,SAAS,YAAY,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,EAAE;YACtD,IAAI,OAAO,CAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBAClD,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;YACrF,CAAC,CAAC;SACF,CAAC,CAAC;QACH,IAAI,SAAS,EAAE;YACd,YAAY,CAAC,SAAS,CAAC,CAAC;SACxB;QACD,IAAI,MAAM,YAAY,KAAK,EAAE;YAC5B,MAAM,MAAM,CAAC;SACb;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CAAA;AAnBD,0CAmBC;AAGD;;;;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AAC,CAAC;IACb,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,SAAU,EAAE,eAAe,CAAC,CAAC;AACtC,CAAC;AARD,0CAQC;AACD;;;;;;GAMG;AACH,SAAgB,2BAA2B,CAC1C,IAAkC,EAClC,QAAgB;IAEhB,IAAI,UAA6B,CAAC;IAClC,MAAM,iBAAiB,GAAG,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;QAC1D,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE;YAC7B,CAAC,GAAS,EAAE;gBACX,MAAM,KAAK,GAAG,MAAM,IAAI,EAAE,CAAC;gBAC3B,IAAI,KAAK,EAAE;oBACV,aAAa,CAAC,UAAU,CAAC,CAAC;oBAC1B,MAAM,CAAC,KAAK,CAAC,CAAC;iBACd;YACF,CAAC,CAAA,CAAC,EAAa,CAAC;QACjB,CAAC,EAAE,QAAQ,CAAC,CAAC;IACd,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,UAAW,EAAE,iBAAiB,CAAC,CAAC;AACzC,CAAC;AAjBD,kEAiBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.d.ts new file mode 100644 index 0000000..67e0b54 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.d.ts @@ -0,0 +1,28 @@ +/** + * Returns a random byte array by the given bytes size + * @param size - The size of the random byte array returned + * @returns - random byte array + * + * @example + * ```ts + * console.log(web3.utils.randomBytes(32)); + * > Uint8Array(32) [ + * 93, 172, 226, 32, 33, 176, 156, 156, + * 182, 30, 240, 2, 69, 96, 174, 197, + * 33, 136, 194, 241, 197, 156, 110, 111, + * 66, 87, 17, 88, 67, 48, 245, 183 + * ] + * ``` + */ +export declare const randomBytes: (size: number) => Uint8Array; +/** + * Returns a random hex string by the given bytes size + * @param byteSize - The size of the random hex string returned + * @returns - random hex string + * + * ```ts + * console.log(web3.utils.randomHex(32)); + * > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e + * ``` + */ +export declare const randomHex: (byteSize: number) => string; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.js new file mode 100644 index 0000000..e4464da --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.js @@ -0,0 +1,52 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomHex = exports.randomBytes = void 0; +const random_js_1 = require("ethereum-cryptography/random.js"); +const converters_js_1 = require("./converters.js"); +/** + * Returns a random byte array by the given bytes size + * @param size - The size of the random byte array returned + * @returns - random byte array + * + * @example + * ```ts + * console.log(web3.utils.randomBytes(32)); + * > Uint8Array(32) [ + * 93, 172, 226, 32, 33, 176, 156, 156, + * 182, 30, 240, 2, 69, 96, 174, 197, + * 33, 136, 194, 241, 197, 156, 110, 111, + * 66, 87, 17, 88, 67, 48, 245, 183 + * ] + * ``` + */ +const randomBytes = (size) => (0, random_js_1.getRandomBytesSync)(size); +exports.randomBytes = randomBytes; +/** + * Returns a random hex string by the given bytes size + * @param byteSize - The size of the random hex string returned + * @returns - random hex string + * + * ```ts + * console.log(web3.utils.randomHex(32)); + * > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e + * ``` + */ +const randomHex = (byteSize) => (0, converters_js_1.bytesToHex)((0, exports.randomBytes)(byteSize)); +exports.randomHex = randomHex; +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.js.map new file mode 100644 index 0000000..d1e1f36 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/random.js.map @@ -0,0 +1 @@ +{"version":3,"file":"random.js","sourceRoot":"","sources":["../../src/random.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,+DAAqE;AACrE,mDAA6C;AAE7C;;;;;;;;;;;;;;;GAeG;AACI,MAAM,WAAW,GAAG,CAAC,IAAY,EAAc,EAAE,CAAC,IAAA,8BAAkB,EAAC,IAAI,CAAC,CAAC;AAArE,QAAA,WAAW,eAA0D;AAElF;;;;;;;;;GASG;AACI,MAAM,SAAS,GAAG,CAAC,QAAgB,EAAU,EAAE,CAAC,IAAA,0BAAU,EAAC,IAAA,mBAAW,EAAC,QAAQ,CAAC,CAAC,CAAC;AAA5E,QAAA,SAAS,aAAmE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.d.ts new file mode 100644 index 0000000..388dabf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.d.ts @@ -0,0 +1,128 @@ +import { ConnectionEvent, EthExecutionAPI, JsonRpcId, JsonRpcResponse, JsonRpcResponseWithResult, JsonRpcResult, ProviderConnectInfo, ProviderMessage, ProviderRpcError, SocketRequestItem, Web3APIMethod, Web3APIPayload, Web3APIReturnType, Web3APISpec, Web3Eip1193ProviderEventCallback, Web3ProviderEventCallback, Web3ProviderMessageEventCallback, Web3ProviderStatus } from 'web3-types'; +import { Eip1193Provider } from './web3_eip1193_provider.js'; +import { ChunkResponseParser } from './chunk_response_parser.js'; +export declare type ReconnectOptions = { + autoReconnect: boolean; + delay: number; + maxAttempts: number; +}; +export declare abstract class SocketProvider extends Eip1193Provider { + protected isReconnecting: boolean; + protected readonly _socketPath: string; + protected readonly chunkResponseParser: ChunkResponseParser; + protected readonly _pendingRequestsQueue: Map>; + protected readonly _sentRequestsQueue: Map>; + protected _reconnectAttempts: number; + protected readonly _socketOptions?: unknown; + protected readonly _reconnectOptions: ReconnectOptions; + protected _socketConnection?: unknown; + get SocketConnection(): unknown; + protected _connectionStatus: Web3ProviderStatus; + protected readonly _onMessageHandler: (event: MessageEvent) => void; + protected readonly _onOpenHandler: () => void; + protected readonly _onCloseHandler: (event: CloseEvent) => void; + protected readonly _onErrorHandler: (event: ErrorEvent) => void; + /** + * This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546) + * @param socketOptions - The options for the socket connection. Its type is supposed to be specified in the inherited classes. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath: string, socketOptions?: unknown, reconnectOptions?: Partial); + protected _init(): void; + /** + * Try to establish a connection to the socket + */ + connect(): void; + protected abstract _openSocketConnection(): void; + protected abstract _addSocketListeners(): void; + protected abstract _removeSocketListeners(): void; + protected abstract _onCloseEvent(_event: unknown): void; + protected abstract _sendToSocket(_payload: Web3APIPayload): void; + protected abstract _parseResponses(_event: MessageEvent): JsonRpcResponse[]; + protected abstract _closeSocketConnection(_code?: number, _data?: string): void; + protected _validateProviderPath(path: string): boolean; + /** + * + * @returns the pendingRequestQueue size + */ + getPendingRequestQueueSize(): number; + /** + * + * @returns the sendPendingRequests size + */ + getSentRequestsQueueSize(): number; + /** + * + * @returns `true` if the socket supports subscriptions + */ + supportsSubscriptions(): boolean; + /** + * Registers a listener for the specified event type. + * @param type - The event type to listen for + * @param listener - The callback to be invoked when the event is emitted + */ + on(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'message', listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + on(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + /** + * Registers a listener for the specified event type that will be invoked at most once. + * @param type - The event type to listen for + * @param listener - The callback to be invoked when the event is emitted + */ + once(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'message', listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + once(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + /** + * Removes a listener for the specified event type. + * @param type - The event type to remove the listener for + * @param listener - The callback to be executed + */ + removeListener(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'message', listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + removeListener(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + protected _onDisconnect(code: number, data?: string): void; + /** + * Disconnects the socket + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + disconnect(code?: number, data?: string): void; + /** + * Safely disconnects the socket, async and waits for request size to be 0 before disconnecting + * @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0 + * @param ms - Determines the ms of setInterval + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + safeDisconnect(code?: number, data?: string, forceDisconnect?: boolean, ms?: number): Promise; + /** + * Removes all listeners for the specified event type. + * @param type - The event type to remove the listeners for + */ + removeAllListeners(type: string): void; + protected _onError(event: ErrorEvent): void; + /** + * Resets the socket, removing all listeners and pending requests + */ + reset(): void; + protected _reconnect(): void; + /** + * Creates a request object to be sent to the server + */ + request, ResultType = Web3APIReturnType>(request: Web3APIPayload): Promise>; + protected _onConnect(): void; + private _sendPendingRequests; + protected _onMessage(event: MessageEvent): void; + clearQueues(event?: ConnectionEvent): void; + protected _clearQueues(event?: ConnectionEvent): void; +} diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.js new file mode 100644 index 0000000..0299159 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.js @@ -0,0 +1,348 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SocketProvider = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_eip1193_provider_js_1 = require("./web3_eip1193_provider.js"); +const chunk_response_parser_js_1 = require("./chunk_response_parser.js"); +const validation_js_1 = require("./validation.js"); +const web3_deferred_promise_js_1 = require("./web3_deferred_promise.js"); +const jsonRpc = __importStar(require("./json_rpc.js")); +const DEFAULT_RECONNECTION_OPTIONS = { + autoReconnect: true, + delay: 5000, + maxAttempts: 5, +}; +const NORMAL_CLOSE_CODE = 1000; // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close +class SocketProvider extends web3_eip1193_provider_js_1.Eip1193Provider { + /** + * This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546) + * @param socketOptions - The options for the socket connection. Its type is supposed to be specified in the inherited classes. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath, socketOptions, reconnectOptions) { + super(); + this._connectionStatus = 'connecting'; + // Message handlers. Due to bounding of `this` and removing the listeners we have to keep it's reference. + this._onMessageHandler = this._onMessage.bind(this); + this._onOpenHandler = this._onConnect.bind(this); + this._onCloseHandler = this._onCloseEvent.bind(this); + this._onErrorHandler = this._onError.bind(this); + if (!this._validateProviderPath(socketPath)) + throw new web3_errors_1.InvalidClientError(socketPath); + this._socketPath = socketPath; + this._socketOptions = socketOptions; + this._reconnectOptions = Object.assign(Object.assign({}, DEFAULT_RECONNECTION_OPTIONS), (reconnectOptions !== null && reconnectOptions !== void 0 ? reconnectOptions : {})); + this._pendingRequestsQueue = new Map(); + this._sentRequestsQueue = new Map(); + this._init(); + this.connect(); + this.chunkResponseParser = new chunk_response_parser_js_1.ChunkResponseParser(this._eventEmitter, this._reconnectOptions.autoReconnect); + this.chunkResponseParser.onError(() => { + this._clearQueues(); + }); + this.isReconnecting = false; + } + get SocketConnection() { + return this._socketConnection; + } + _init() { + this._reconnectAttempts = 0; + } + /** + * Try to establish a connection to the socket + */ + connect() { + try { + this._openSocketConnection(); + this._connectionStatus = 'connecting'; + this._addSocketListeners(); + } + catch (e) { + if (!this.isReconnecting) { + this._connectionStatus = 'disconnected'; + if (e && e.message) { + throw new web3_errors_1.ConnectionError(`Error while connecting to ${this._socketPath}. Reason: ${e.message}`); + } + else { + throw new web3_errors_1.InvalidClientError(this._socketPath); + } + } + else { + setImmediate(() => { + this._reconnect(); + }); + } + } + } + // eslint-disable-next-line class-methods-use-this + _validateProviderPath(path) { + return !!path; + } + /** + * + * @returns the pendingRequestQueue size + */ + // eslint-disable-next-line class-methods-use-this + getPendingRequestQueueSize() { + return this._pendingRequestsQueue.size; + } + /** + * + * @returns the sendPendingRequests size + */ + // eslint-disable-next-line class-methods-use-this + getSentRequestsQueueSize() { + return this._sentRequestsQueue.size; + } + /** + * + * @returns `true` if the socket supports subscriptions + */ + // eslint-disable-next-line class-methods-use-this + supportsSubscriptions() { + return true; + } + on(type, listener) { + this._eventEmitter.on(type, listener); + } + once(type, listener) { + this._eventEmitter.once(type, listener); + } + removeListener(type, listener) { + this._eventEmitter.removeListener(type, listener); + } + _onDisconnect(code, data) { + this._connectionStatus = 'disconnected'; + super._onDisconnect(code, data); + } + /** + * Disconnects the socket + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + disconnect(code, data) { + const disconnectCode = code !== null && code !== void 0 ? code : NORMAL_CLOSE_CODE; + this._removeSocketListeners(); + if (this.getStatus() !== 'disconnected') { + this._closeSocketConnection(disconnectCode, data); + } + this._onDisconnect(disconnectCode, data); + } + /** + * Safely disconnects the socket, async and waits for request size to be 0 before disconnecting + * @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0 + * @param ms - Determines the ms of setInterval + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + safeDisconnect(code, data, forceDisconnect = false, ms = 1000) { + return __awaiter(this, void 0, void 0, function* () { + let retryAttempt = 0; + const checkQueue = () => __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => { + const interval = setInterval(() => { + if (forceDisconnect && retryAttempt === 5) { + this.clearQueues(); + } + if (this.getPendingRequestQueueSize() === 0 && this.getSentRequestsQueueSize() === 0) { + clearInterval(interval); + resolve(true); + } + retryAttempt += 1; + }, ms); + }); + }); + yield checkQueue(); + this.disconnect(code, data); + }); + } + /** + * Removes all listeners for the specified event type. + * @param type - The event type to remove the listeners for + */ + removeAllListeners(type) { + this._eventEmitter.removeAllListeners(type); + } + _onError(event) { + // do not emit error while trying to reconnect + if (this.isReconnecting) { + this._reconnect(); + } + else { + this._eventEmitter.emit('error', event); + } + } + /** + * Resets the socket, removing all listeners and pending requests + */ + reset() { + this._sentRequestsQueue.clear(); + this._pendingRequestsQueue.clear(); + this._init(); + this._removeSocketListeners(); + this._addSocketListeners(); + } + _reconnect() { + if (this.isReconnecting) { + return; + } + this.isReconnecting = true; + if (this._sentRequestsQueue.size > 0) { + this._sentRequestsQueue.forEach((request, key) => { + request.deferredPromise.reject(new web3_errors_1.PendingRequestsOnReconnectingError()); + this._sentRequestsQueue.delete(key); + }); + } + if (this._reconnectAttempts < this._reconnectOptions.maxAttempts) { + this._reconnectAttempts += 1; + setTimeout(() => { + this._removeSocketListeners(); + this.connect(); + this.isReconnecting = false; + }, this._reconnectOptions.delay); + } + else { + this.isReconnecting = false; + this._clearQueues(); + this._removeSocketListeners(); + this._eventEmitter.emit('error', new web3_errors_1.MaxAttemptsReachedOnReconnectingError(this._reconnectOptions.maxAttempts)); + } + } + /** + * Creates a request object to be sent to the server + */ + request(request) { + return __awaiter(this, void 0, void 0, function* () { + if ((0, validation_js_1.isNullish)(this._socketConnection)) { + throw new Error('Connection is undefined'); + } + // if socket disconnected - open connection + if (this.getStatus() === 'disconnected') { + this.connect(); + } + const requestId = jsonRpc.isBatchRequest(request) + ? request[0].id + : request.id; + if (!requestId) { + throw new web3_errors_1.Web3WSProviderError('Request Id not defined'); + } + if (this._sentRequestsQueue.has(requestId)) { + throw new web3_errors_1.RequestAlreadySentError(requestId); + } + const deferredPromise = new web3_deferred_promise_js_1.Web3DeferredPromise(); + deferredPromise.catch(error => { + this._eventEmitter.emit('error', error); + }); + const reqItem = { + payload: request, + deferredPromise, + }; + if (this.getStatus() === 'connecting') { + this._pendingRequestsQueue.set(requestId, reqItem); + return reqItem.deferredPromise; + } + this._sentRequestsQueue.set(requestId, reqItem); + try { + this._sendToSocket(reqItem.payload); + } + catch (error) { + this._sentRequestsQueue.delete(requestId); + this._eventEmitter.emit('error', error); + } + return deferredPromise; + }); + } + _onConnect() { + this._connectionStatus = 'connected'; + this._reconnectAttempts = 0; + super._onConnect(); + this._sendPendingRequests(); + } + _sendPendingRequests() { + for (const [id, value] of this._pendingRequestsQueue.entries()) { + this._sendToSocket(value.payload); + this._pendingRequestsQueue.delete(id); + this._sentRequestsQueue.set(id, value); + } + } + _onMessage(event) { + const responses = this._parseResponses(event); + if ((0, validation_js_1.isNullish)(responses) || responses.length === 0) { + return; + } + for (const response of responses) { + if (jsonRpc.isResponseWithNotification(response) && + response.method.endsWith('_subscription')) { + this._eventEmitter.emit('message', response); + return; + } + const requestId = jsonRpc.isBatchResponse(response) + ? response[0].id + : response.id; + const requestItem = this._sentRequestsQueue.get(requestId); + if (!requestItem) { + return; + } + if (jsonRpc.isBatchResponse(response) || + jsonRpc.isResponseWithResult(response) || + jsonRpc.isResponseWithError(response)) { + this._eventEmitter.emit('message', response); + requestItem.deferredPromise.resolve(response); + } + this._sentRequestsQueue.delete(requestId); + } + } + clearQueues(event) { + this._clearQueues(event); + } + _clearQueues(event) { + if (this._pendingRequestsQueue.size > 0) { + this._pendingRequestsQueue.forEach((request, key) => { + request.deferredPromise.reject(new web3_errors_1.ConnectionNotOpenError(event)); + this._pendingRequestsQueue.delete(key); + }); + } + if (this._sentRequestsQueue.size > 0) { + this._sentRequestsQueue.forEach((request, key) => { + request.deferredPromise.reject(new web3_errors_1.ConnectionNotOpenError(event)); + this._sentRequestsQueue.delete(key); + }); + } + this._removeSocketListeners(); + } +} +exports.SocketProvider = SocketProvider; +//# sourceMappingURL=socket_provider.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.js.map new file mode 100644 index 0000000..389ac3f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/socket_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"socket_provider.js","sourceRoot":"","sources":["../../src/socket_provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,6CAQqB;AACrB,yEAA6D;AAC7D,yEAAiE;AACjE,mDAA4C;AAC5C,yEAAiE;AACjE,uDAAyC;AAQzC,MAAM,4BAA4B,GAAG;IACpC,aAAa,EAAE,IAAI;IACnB,KAAK,EAAE,IAAI;IACX,WAAW,EAAE,CAAC;CACd,CAAC;AAEF,MAAM,iBAAiB,GAAG,IAAI,CAAC,CAAC,mEAAmE;AAEnG,MAAsB,cAKpB,SAAQ,0CAAoB;IAqB7B;;;;;OAKG;IACH,YACC,UAAkB,EAClB,aAAuB,EACvB,gBAA4C;QAE5C,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,iBAAiB,GAAG,YAAY,CAAC;QAEtC,yGAAyG;QACzG,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACpD,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjD,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CA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AAE,GAAc,EAAE,EAAE;gBAC7D,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,IAAI,oCAAsB,CAAC,KAAK,CAAC,CAAC,CAAC;gBAClE,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACxC,CAAC,CACD,CAAC;SACF;QAED,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC,EAAE;YACrC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAC9B,CAAC,OAAyC,EAAE,GAAc,EAAE,EAAE;gBAC7D,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,IAAI,oCAAsB,CAAC,KAAK,CAAC,CAAC,CAAC;gBAClE,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACrC,CAAC,CACD,CAAC;SACF;QAED,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAC/B,CAAC;CACD;AAxfD,wCAwfC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.d.ts new file mode 100644 index 0000000..1e58531 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.d.ts @@ -0,0 +1,77 @@ +import { Numbers } from 'web3-types'; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * + * console.log(web3.utils.padLeft('0x123', 10)); + * >0x0000000123 + * ``` + */ +export declare const padLeft: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * console.log(web3.utils.padRight('0x123', 10)); + * > 0x1230000000 + * + * console.log(web3.utils.padRight('0x123', 10, '1')); + * > 0x1231111111 + * ``` + */ +export declare const padRight: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight` + */ +export declare const rightPad: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft` + */ +export declare const leftPad: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * + * @returns The hex string of the two’s complement. + * + * @example + * ```ts + * console.log(web3.utils.toTwosComplement(13, 32)); + * > 0x0000000000000000000000000000000d + * + * console.log(web3.utils.toTwosComplement('-0x1', 32)); + * > 0xffffffffffffffffffffffffffffffff + * + * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32)); + * > 0x00000000000000000020000000000000 + * ``` + */ +export declare const toTwosComplement: (value: Numbers, nibbleWidth?: number) => string; +/** + * Converts the twos complement into a decimal number or big int. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * @returns The decimal number or big int. + * + * @example + * ```ts + * console.log(web3.utils.fromTwosComplement(''0x0000000000000000000000000000000d', 32')); + * > 13 + * + * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32)); + * > 9007199254740992n + * ``` + */ +export declare const fromTwosComplement: (value: Numbers, nibbleWidth?: number) => number | bigint; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.js new file mode 100644 index 0000000..6c95670 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.js @@ -0,0 +1,147 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromTwosComplement = exports.toTwosComplement = exports.leftPad = exports.rightPad = exports.padRight = exports.padLeft = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_validator_1 = require("web3-validator"); +const converters_js_1 = require("./converters.js"); +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * + * console.log(web3.utils.padLeft('0x123', 10)); + * >0x0000000123 + * ``` + */ +const padLeft = (value, characterAmount, sign = '0') => { + // To avoid duplicate code and circular dependency we will + // use `padLeft` implementation from `web3-validator` + if (typeof value === 'string') { + if (!(0, web3_validator_1.isHexStrict)(value)) { + return value.padStart(characterAmount, sign); + } + return web3_validator_1.utils.padLeft(value, characterAmount, sign); + } + web3_validator_1.validator.validate(['int'], [value]); + return web3_validator_1.utils.padLeft(value, characterAmount, sign); +}; +exports.padLeft = padLeft; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * console.log(web3.utils.padRight('0x123', 10)); + * > 0x1230000000 + * + * console.log(web3.utils.padRight('0x123', 10, '1')); + * > 0x1231111111 + * ``` + */ +const padRight = (value, characterAmount, sign = '0') => { + if (typeof value === 'string' && !(0, web3_validator_1.isHexStrict)(value)) { + return value.padEnd(characterAmount, sign); + } + web3_validator_1.validator.validate(['int'], [value]); + const hexString = typeof value === 'string' && (0, web3_validator_1.isHexStrict)(value) ? value : (0, converters_js_1.numberToHex)(value); + const prefixLength = hexString.startsWith('-') ? 3 : 2; + return hexString.padEnd(characterAmount + prefixLength, sign); +}; +exports.padRight = padRight; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight` + */ +exports.rightPad = exports.padRight; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft` + */ +exports.leftPad = exports.padLeft; +/** + * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * + * @returns The hex string of the two’s complement. + * + * @example + * ```ts + * console.log(web3.utils.toTwosComplement(13, 32)); + * > 0x0000000000000000000000000000000d + * + * console.log(web3.utils.toTwosComplement('-0x1', 32)); + * > 0xffffffffffffffffffffffffffffffff + * + * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32)); + * > 0x00000000000000000020000000000000 + * ``` + */ +const toTwosComplement = (value, nibbleWidth = 64) => { + web3_validator_1.validator.validate(['int'], [value]); + const val = (0, converters_js_1.toNumber)(value); + if (val >= 0) + return (0, exports.padLeft)((0, converters_js_1.toHex)(val), nibbleWidth); + const largestBit = (0, web3_validator_1.bigintPower)(BigInt(2), BigInt(nibbleWidth * 4)); + if (-val >= largestBit) { + throw new web3_errors_1.NibbleWidthError(`value: ${value}, nibbleWidth: ${nibbleWidth}`); + } + const updatedVal = BigInt(val); + const complement = updatedVal + largestBit; + return (0, exports.padLeft)((0, converters_js_1.numberToHex)(complement), nibbleWidth); +}; +exports.toTwosComplement = toTwosComplement; +/** + * Converts the twos complement into a decimal number or big int. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * @returns The decimal number or big int. + * + * @example + * ```ts + * console.log(web3.utils.fromTwosComplement(''0x0000000000000000000000000000000d', 32')); + * > 13 + * + * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32)); + * > 9007199254740992n + * ``` + */ +const fromTwosComplement = (value, nibbleWidth = 64) => { + web3_validator_1.validator.validate(['int'], [value]); + const val = (0, converters_js_1.toNumber)(value); + if (val < 0) + return val; + const largestBit = Math.ceil(Math.log(Number(val)) / Math.log(2)); + if (largestBit > nibbleWidth * 4) + throw new web3_errors_1.NibbleWidthError(`value: "${value}", nibbleWidth: "${nibbleWidth}"`); + // check the largest bit to see if negative + if (nibbleWidth * 4 !== largestBit) + return val; + const complement = (0, web3_validator_1.bigintPower)(BigInt(2), BigInt(nibbleWidth) * BigInt(4)); + return (0, converters_js_1.toNumber)(BigInt(val) - complement); +}; +exports.fromTwosComplement = fromTwosComplement; +//# sourceMappingURL=string_manipulation.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.js.map new file mode 100644 index 0000000..b208f4b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/string_manipulation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string_manipulation.js","sourceRoot":"","sources":["../../src/string_manipulation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,6CAA+C;AAC/C,mDAA8F;AAC9F,mDAA+D;AAE/D;;;;;;;;;;;;;GAaG;AACI,MAAM,OAAO,GAAG,CAAC,KAAc,EAAE,eAAuB,EAAE,IAAI,GAAG,GAAG,EAAU,EAAE;IACtF,0DAA0D;IAC1D,qDAAqD;IAErD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,EAAE;YACxB,OAAO,KAAK,CAAC,QAAQ,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;SAC7C;QACD,OAAO,sBAAc,CAAC,OAAO,CAAC,KAAK,EAAE,eAAe,EAAE,IAAI,CAAC,CAAC;KAC5D;IAED,0BAAS,CAAC,QAAQ,C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AAoB,WAAW,GAAG,CAAC,CAAC;IAEhF,2CAA2C;IAC3C,IAAI,WAAW,GAAG,CAAC,KAAK,UAAU;QAAE,OAAO,GAAG,CAAC;IAE/C,MAAM,UAAU,GAAG,IAAA,4BAAW,EAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3E,OAAO,IAAA,wBAAQ,EAAC,MAAM,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC;AAC3C,CAAC,CAAC;AAlBW,QAAA,kBAAkB,sBAkB7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.d.ts new file mode 100644 index 0000000..be059a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.d.ts @@ -0,0 +1,5 @@ +export declare function uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array; +/** + * Returns true if the two passed Uint8Arrays have the same content + */ +export declare function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.js new file mode 100644 index 0000000..ff4cbb4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uint8ArrayEquals = exports.uint8ArrayConcat = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +function uint8ArrayConcat(...parts) { + const length = parts.reduce((prev, part) => { + const agg = prev + part.length; + return agg; + }, 0); + const result = new Uint8Array(length); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.length; + } + return result; +} +exports.uint8ArrayConcat = uint8ArrayConcat; +/** + * Returns true if the two passed Uint8Arrays have the same content + */ +function uint8ArrayEquals(a, b) { + if (a === b) { + return true; + } + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i += 1) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} +exports.uint8ArrayEquals = uint8ArrayEquals; +//# sourceMappingURL=uint8array.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.js.map new file mode 100644 index 0000000..16b3aa8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uint8array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uint8array.js","sourceRoot":"","sources":["../../src/uint8array.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,SAAgB,gBAAgB,CAAC,GAAG,KAAmB;IACtD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;QAC/B,OAAO,GAAG,CAAC;IACZ,CAAC,EAAE,CAAC,CAAC,CAAC;IACN,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACtC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACzB,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACzB,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC;KACtB;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAZD,4CAYC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,CAAa,EAAE,CAAa;IAC5D,IAAI,CAAC,KAAK,CAAC,EAAE;QACZ,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,CAAC,CAAC,UAAU,KAAK,CAAC,CAAC,UAAU,EAAE;QAClC,OAAO,KAAK,CAAC;KACb;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC,EAAE;QACzC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;YAClB,OAAO,KAAK,CAAC;SACb;KACD;IAED,OAAO,IAAI,CAAC;AACb,CAAC;AAhBD,4CAgBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.d.ts new file mode 100644 index 0000000..0b7ca9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.d.ts @@ -0,0 +1,11 @@ +/** + * Generate a version 4 (random) uuid + * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5 + * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx + * @example + * ```ts + * console.log(web3.utils.uuidV4()); + * > "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed" + * ``` + */ +export declare const uuidV4: () => string; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.js new file mode 100644 index 0000000..796dcdd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.js @@ -0,0 +1,54 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uuidV4 = void 0; +const converters_js_1 = require("./converters.js"); +const random_js_1 = require("./random.js"); +/** + * Generate a version 4 (random) uuid + * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5 + * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx + * @example + * ```ts + * console.log(web3.utils.uuidV4()); + * > "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed" + * ``` + */ +const uuidV4 = () => { + const bytes = (0, random_js_1.randomBytes)(16); + // https://github.com/ethers-io/ethers.js/blob/ce8f1e4015c0f27bf178238770b1325136e3351a/packages/json-wallets/src.ts/utils.ts#L54 + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + /* eslint-disable-next-line */ + bytes[6] = (bytes[6] & 0x0f) | 0x40; + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + /* eslint-disable-next-line */ + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hexString = (0, converters_js_1.bytesToHex)(bytes); + return [ + hexString.substring(2, 10), + hexString.substring(10, 14), + hexString.substring(14, 18), + hexString.substring(18, 22), + hexString.substring(22, 34), + ].join('-'); +}; +exports.uuidV4 = uuidV4; +//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.js.map new file mode 100644 index 0000000..e44e938 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../../src/uuid.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,mDAA6C;AAC7C,2CAA0C;AAE1C;;;;;;;;;GASG;AACI,MAAM,MAAM,GAAG,GAAW,EAAE;IAClC,MAAM,KAAK,GAAG,IAAA,uBAAW,EAAC,EAAE,CAAC,CAAC;IAE9B,iIAAiI;IACjI,kBAAkB;IAClB,wCAAwC;IACxC,8BAA8B;IAC9B,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAEpC,cAAc;IACd,uCAAuC;IACvC,uCAAuC;IACvC,8BAA8B;IAC9B,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAEpC,MAAM,SAAS,GAAG,IAAA,0BAAU,EAAC,KAAK,CAAC,CAAC;IAEpC,OAAO;QACN,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;QAC1B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QAC3B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QAC3B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QAC3B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;KAC3B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACb,CAAC,CAAC;AAxBW,QAAA,MAAM,UAwBjB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.d.ts new file mode 100644 index 0000000..c29786a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.d.ts @@ -0,0 +1,82 @@ +import { BlockNumberOrTag, ContractInitOptions } from 'web3-types'; +/** + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isHexStrict: (hex: import("web3-validator").ValidInputTypes) => boolean; +/** + * returns true if input is a hexstring, number or bigint + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isHex: (hex: import("web3-validator").ValidInputTypes) => boolean; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const checkAddressCheckSum: (data: string) => boolean; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isAddress: (value: import("web3-validator").ValidInputTypes, checkChecksum?: boolean | undefined) => boolean; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isBloom: (bloom: import("web3-validator").ValidInputTypes) => boolean; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isInBloom: (bloom: string, value: string | Uint8Array) => boolean; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isUserEthereumAddressInBloom: (bloom: string, ethereumAddress: string) => boolean; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isContractAddressInBloom: (bloom: string, contractAddress: string) => boolean; +/** + * Checks if its a valid topic + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isTopic: (topic: string) => boolean; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isTopicInBloom: (bloom: string, topic: string) => boolean; +/** + * Compares between block A and block B + * @param blockA - Block number or string + * @param blockB - Block number or string + * + * @returns - Returns -1 if a \< b, returns 1 if a \> b and returns 0 if a == b + * + * @example + * ```ts + * console.log(web3.utils.compareBlockNumbers('latest', 'pending')); + * > -1 + * + * console.log(web3.utils.compareBlockNumbers(12, 11)); + * > 1 + * ``` + */ +export declare const compareBlockNumbers: (blockA: BlockNumberOrTag, blockB: BlockNumberOrTag) => 0 | 1 | -1; +export declare const isContractInitOptions: (options: unknown) => options is ContractInitOptions; +export declare const isNullish: (item: unknown) => item is null | undefined; diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.js new file mode 100644 index 0000000..6c9d55e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.js @@ -0,0 +1,160 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNullish = exports.isContractInitOptions = exports.compareBlockNumbers = exports.isTopicInBloom = exports.isTopic = exports.isContractAddressInBloom = exports.isUserEthereumAddressInBloom = exports.isInBloom = exports.isBloom = exports.isAddress = exports.checkAddressCheckSum = exports.isHex = exports.isHexStrict = void 0; +const web3_errors_1 = require("web3-errors"); +const web3_validator_1 = require("web3-validator"); +const web3_types_1 = require("web3-types"); +/** + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isHexStrict = web3_validator_1.isHexStrict; +/** + * returns true if input is a hexstring, number or bigint + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isHex = web3_validator_1.isHex; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.checkAddressCheckSum = web3_validator_1.checkAddressCheckSum; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isAddress = web3_validator_1.isAddress; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isBloom = web3_validator_1.isBloom; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isInBloom = web3_validator_1.isInBloom; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isUserEthereumAddressInBloom = web3_validator_1.isUserEthereumAddressInBloom; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isContractAddressInBloom = web3_validator_1.isContractAddressInBloom; +/** + * Checks if its a valid topic + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isTopic = web3_validator_1.isTopic; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +exports.isTopicInBloom = web3_validator_1.isTopicInBloom; +/** + * Compares between block A and block B + * @param blockA - Block number or string + * @param blockB - Block number or string + * + * @returns - Returns -1 if a \< b, returns 1 if a \> b and returns 0 if a == b + * + * @example + * ```ts + * console.log(web3.utils.compareBlockNumbers('latest', 'pending')); + * > -1 + * + * console.log(web3.utils.compareBlockNumbers(12, 11)); + * > 1 + * ``` + */ +const compareBlockNumbers = (blockA, blockB) => { + const isABlockTag = typeof blockA === 'string' && (0, web3_validator_1.isBlockTag)(blockA); + const isBBlockTag = typeof blockB === 'string' && (0, web3_validator_1.isBlockTag)(blockB); + if (blockA === blockB || + ((blockA === 'earliest' || blockA === 0) && (blockB === 'earliest' || blockB === 0)) // only exception compare blocktag with number + ) { + return 0; + } + if (blockA === 'earliest' && blockB > 0) { + return -1; + } + if (blockB === 'earliest' && blockA > 0) { + return 1; + } + if (isABlockTag && isBBlockTag) { + // Increasing order: earliest, finalized , safe, latest, pending + const tagsOrder = { + [web3_types_1.BlockTags.EARLIEST]: 1, + [web3_types_1.BlockTags.FINALIZED]: 2, + [web3_types_1.BlockTags.SAFE]: 3, + [web3_types_1.BlockTags.LATEST]: 4, + [web3_types_1.BlockTags.PENDING]: 5, + }; + if (tagsOrder[blockA] < tagsOrder[blockB]) { + return -1; + } + return 1; + } + if ((isABlockTag && !isBBlockTag) || (!isABlockTag && isBBlockTag)) { + throw new web3_errors_1.InvalidBlockError('Cannot compare blocktag with provided non-blocktag input.'); + } + const bigIntA = BigInt(blockA); + const bigIntB = BigInt(blockB); + if (bigIntA < bigIntB) { + return -1; + } + if (bigIntA === bigIntB) { + return 0; + } + return 1; +}; +exports.compareBlockNumbers = compareBlockNumbers; +const isContractInitOptions = (options) => typeof options === 'object' && + !(0, web3_validator_1.isNullish)(options) && + Object.keys(options).length !== 0 && + [ + 'input', + 'data', + 'from', + 'gas', + 'gasPrice', + 'gasLimit', + 'address', + 'jsonInterface', + 'syncWithContext', + 'dataInputFill', + ].some(key => key in options); +exports.isContractInitOptions = isContractInitOptions; +exports.isNullish = web3_validator_1.isNullish; +//# sourceMappingURL=validation.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.js.map new file mode 100644 index 0000000..2a8b2a5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/validation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/validation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAAgD;AAChD,mDAawB;AACxB,2CAA8E;AAE9E;;GAEG;AACU,QAAA,WAAW,GAAG,4BAAoB,CAAC;AAEhD;;;;GAIG;AACU,QAAA,KAAK,GAAG,sBAAc,CAAC;AAEpC;;;;GAIG;AACU,QAAA,oBAAoB,GAAG,qCAA6B,CAAC;AAElE;;;;GAIG;AACU,QAAA,SAAS,GAAG,0BAAkB,CAAC;AAE5C;;;;;GAKG;AACU,QAAA,OAAO,GAAG,wBAAgB,CAAC;AAExC;;;;;GAKG;AACU,QAAA,SAAS,GAAG,0BAAkB,CAAC;AAE5C;;;;GAIG;AACU,QAAA,4BAA4B,GAAG,6CAAqC,CAAC;AAElF;;;;;GAKG;AACU,QAAA,wBAAwB,GAAG,yCAAiC,CAAC;AAE1E;;;;GAIG;AACU,QAAA,OAAO,GAAG,wBAAgB,CAAC;AAExC;;;;;GAKG;AACU,QAAA,cAAc,GAAG,+BAAuB,CAAC;AAEtD;;;;;;;;;;;;;;;GAeG;AACI,MAAM,mBAAmB,GAAG,CAAC,MAAwB,EAAE,MAAwB,EAAE,EAAE;IACzF,MAAM,WAAW,GAAG,OAAO,MAAM,KAAK,QAAQ,IAAI,IAAA,2BAAU,EAAC,MAAM,CAAC,CAAC;IACrE,MAAM,WAAW,GAAG,OAAO,MAAM,KAAK,QAAQ,IAAI,IAAA,2BAAU,EAAC,MAAM,CAAC,CAAC;IAErE,IACC,MAAM,KAAK,MAAM;QACjB,CAAC,CAAC,MAAM,KAAK,UAAU,IAAI,MAAM,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,UAAU,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,8CAA8C;MAClI;QACD,OAAO,CAAC,CAAC;KACT;IACD,IAAI,MAAM,KAAK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AC;IAC5B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC;IACjC;QACC,OAAO;QACP,MAAM;QACN,MAAM;QACN,KAAK;QACL,UAAU;QACV,UAAU;QACV,SAAS;QACT,eAAe;QACf,iBAAiB;QACjB,eAAe;KACf,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,OAAO,CAAC,CAAC;AAflB,QAAA,qBAAqB,yBAeH;AAElB,QAAA,SAAS,GAAG,0BAAkB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.d.ts new file mode 100644 index 0000000..ef298b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.d.ts @@ -0,0 +1,67 @@ +import { Web3DeferredPromiseInterface } from 'web3-types'; +/** + * The class is a simple implementation of a deferred promise with optional timeout functionality, + * which can be useful when dealing with asynchronous tasks. + * + */ +export declare class Web3DeferredPromise implements Promise, Web3DeferredPromiseInterface { + [Symbol.toStringTag]: 'Promise'; + private readonly _promise; + private _resolve; + private _reject; + private _state; + private _timeoutId?; + private readonly _timeoutInterval?; + private readonly _timeoutMessage; + /** + * + * @param timeout - (optional) The timeout in milliseconds. + * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created. + * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out. + */ + constructor({ timeout, eagerStart, timeoutMessage, }?: { + timeout: number; + eagerStart: boolean; + timeoutMessage: string; + }); + /** + * Returns the current state of the promise. + * @returns 'pending' | 'fulfilled' | 'rejected' + */ + get state(): 'pending' | 'fulfilled' | 'rejected'; + /** + * + * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled. + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + then(onfulfilled?: (value: T) => TResult1 | PromiseLike, onrejected?: (reason: unknown) => TResult2 | PromiseLike): Promise; + /** + * + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + catch(onrejected?: (reason: any) => TResult | PromiseLike): Promise; + /** + * + * @param onfinally - (optional) The callback to execute when the promise is settled (fulfilled or rejected). + * @returns + */ + finally(onfinally?: (() => void) | undefined): Promise; + /** + * Resolves the current promise. + * @param value - The value to resolve the promise with. + */ + resolve(value: T | PromiseLike): void; + /** + * Rejects the current promise. + * @param reason - The reason to reject the promise with. + */ + reject(reason?: unknown): void; + /** + * Starts the timeout timer for the promise. + */ + startTimer(): void; + private _checkTimeout; + private _clearTimeout; +} diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.js new file mode 100644 index 0000000..877c60d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.js @@ -0,0 +1,141 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3DeferredPromise = void 0; +const web3_errors_1 = require("web3-errors"); +/** + * The class is a simple implementation of a deferred promise with optional timeout functionality, + * which can be useful when dealing with asynchronous tasks. + * + */ +class Web3DeferredPromise { + /** + * + * @param timeout - (optional) The timeout in milliseconds. + * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created. + * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out. + */ + constructor({ timeout, eagerStart, timeoutMessage, } = { + timeout: 0, + eagerStart: false, + timeoutMessage: 'DeferredPromise timed out', + }) { + // public tag to treat object as promise by different libs + // eslint-disable-next-line @typescript-eslint/prefer-as-const + this[_a] = 'Promise'; + this._state = 'pending'; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + this._timeoutMessage = timeoutMessage; + this._timeoutInterval = timeout; + if (eagerStart) { + this.startTimer(); + } + } + /** + * Returns the current state of the promise. + * @returns 'pending' | 'fulfilled' | 'rejected' + */ + get state() { + return this._state; + } + /** + * + * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled. + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + then(onfulfilled, onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.then(onfulfilled, onrejected); + }); + } + /** + * + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + catch( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.catch(onrejected); + }); + } + /** + * + * @param onfinally - (optional) The callback to execute when the promise is settled (fulfilled or rejected). + * @returns + */ + finally(onfinally) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.finally(onfinally); + }); + } + /** + * Resolves the current promise. + * @param value - The value to resolve the promise with. + */ + resolve(value) { + this._resolve(value); + this._state = 'fulfilled'; + this._clearTimeout(); + } + /** + * Rejects the current promise. + * @param reason - The reason to reject the promise with. + */ + reject(reason) { + this._reject(reason); + this._state = 'rejected'; + this._clearTimeout(); + } + /** + * Starts the timeout timer for the promise. + */ + startTimer() { + if (this._timeoutInterval && this._timeoutInterval > 0) { + this._timeoutId = setTimeout(this._checkTimeout.bind(this), this._timeoutInterval); + } + } + _checkTimeout() { + if (this._state === 'pending' && this._timeoutId) { + this.reject(new web3_errors_1.OperationTimeoutError(this._timeoutMessage)); + } + } + _clearTimeout() { + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + } +} +exports.Web3DeferredPromise = Web3DeferredPromise; +_a = Symbol.toStringTag; +//# sourceMappingURL=web3_deferred_promise.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.js.map new file mode 100644 index 0000000..dc1d0f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_deferred_promise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_deferred_promise.js","sourceRoot":"","sources":["../../src/web3_deferred_promise.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;AAEF,6CAAoD;AAIpD;;;;GAIG;AACH,MAAa,mBAAmB;IAa/B;;;;;OAKG;IACH,YACC,EACC,OAAO,EACP,UAAU,EACV,cAAc,MACuD;QACrE,OAAO,EAAE,CAAC;QACV,UAAU,EAAE,KAAK;QACjB,cAAc,EAAE,2BAA2B;KAC3C;QA3BF,0DAA0D;QAC1D,8DAA8D;QACvD,QAAoB,GAAc,SAAS,CAAC;QAK3C,WAAM,GAAyC,SAAS,CAAC;QAsBhE,IAAI,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;YACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACvB,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;QACtC,IAAI,CAAC,gBAAgB,GAAG,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K,SAAS,IAAI,IAAI,CAAC,UAAU,EAAE;YACjD,IAAI,CAAC,MAAM,CAAC,IAAI,mCAAqB,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;SAC7D;IACF,CAAC;IAEO,aAAa;QACpB,IAAI,IAAI,CAAC,UAAU,EAAE;YACpB,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;SAC9B;IACF,CAAC;CACD;AA1HD,kDA0HC;KAvHQ,MAAM,CAAC,WAAW"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.d.ts new file mode 100644 index 0000000..18fede5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.d.ts @@ -0,0 +1,16 @@ +/// +import { EthExecutionAPI, Web3APISpec, Web3BaseProvider } from 'web3-types'; +import { EventEmitter } from 'events'; +/** + * This is an abstract class, which extends {@link Web3BaseProvider} class. This class is used to implement a provider that adheres to the EIP-1193 standard for Ethereum providers. + */ +export declare abstract class Eip1193Provider extends Web3BaseProvider { + protected readonly _eventEmitter: EventEmitter; + private _chainId; + private _accounts; + private _getChainId; + private _getAccounts; + protected _onConnect(): void; + protected _onDisconnect(code: number, data?: unknown): void; + private _onAccountsChanged; +} diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.js b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.js new file mode 100644 index 0000000..e960bea --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.js @@ -0,0 +1,109 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Eip1193Provider = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_types_1 = require("web3-types"); +const events_1 = require("events"); +const web3_errors_1 = require("web3-errors"); +const json_rpc_js_1 = require("./json_rpc.js"); +/** + * This is an abstract class, which extends {@link Web3BaseProvider} class. This class is used to implement a provider that adheres to the EIP-1193 standard for Ethereum providers. + */ +class Eip1193Provider extends web3_types_1.Web3BaseProvider { + constructor() { + super(...arguments); + this._eventEmitter = new events_1.EventEmitter(); + this._chainId = ''; + this._accounts = []; + } + _getChainId() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const data = yield this.request((0, json_rpc_js_1.toPayload)({ + method: 'eth_chainId', + params: [], + })); + return (_a = data === null || data === void 0 ? void 0 : data.result) !== null && _a !== void 0 ? _a : ''; + }); + } + _getAccounts() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const data = yield this.request((0, json_rpc_js_1.toPayload)({ + method: 'eth_accounts', + params: [], + })); + return (_a = data === null || data === void 0 ? void 0 : data.result) !== null && _a !== void 0 ? _a : []; + }); + } + _onConnect() { + Promise.all([ + this._getChainId() + .then(chainId => { + if (chainId !== this._chainId) { + this._chainId = chainId; + this._eventEmitter.emit('chainChanged', this._chainId); + } + }) + .catch(err => { + // todo: add error handler + console.error(err); + }), + this._getAccounts() + .then(accounts => { + if (!(this._accounts.length === accounts.length && + accounts.every(v => accounts.includes(v)))) { + this._accounts = accounts; + this._onAccountsChanged(); + } + }) + .catch(err => { + // todo: add error handler + // eslint-disable-next-line no-console + console.error(err); + }), + ]) + .then(() => this._eventEmitter.emit('connect', { + chainId: this._chainId, + })) + .catch(err => { + // todo: add error handler + // eslint-disable-next-line no-console + console.error(err); + }); + } + // todo this must be ProvideRpcError with a message too + _onDisconnect(code, data) { + this._eventEmitter.emit('disconnect', new web3_errors_1.EIP1193ProviderRpcError(code, data)); + } + _onAccountsChanged() { + // get chainId and safe to local + this._eventEmitter.emit('accountsChanged', this._accounts); + } +} +exports.Eip1193Provider = Eip1193Provider; +//# sourceMappingURL=web3_eip1193_provider.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.js.map b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.js.map new file mode 100644 index 0000000..dd5419e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/commonjs/web3_eip1193_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eip1193_provider.js","sourceRoot":"","sources":["../../src/web3_eip1193_provider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,2CAQoB;AACpB,mCAAsC;AACtC,6CAAsD;AACtD,+CAA0C;AAE1C;;GAEG;AACH,MAAsB,eAEpB,SAAQ,6BAAqB;IAF/B;;QAGoB,kBAAa,GAAiB,IAAI,qBAAY,EAAE,CAAC;QAC5D,aAAQ,GAAc,EAAE,CAAC;QACzB,cAAS,GAAgB,EAAE,CAAC;IA8ErC,CAAC;IA5Ec,WAAW;;;YACxB,MAAM,IAAI,GAAG,MAAO,IAA8B,CAAC,OAAO,CAIzD,IAAA,uBAAS,EAAC;gBACT,MAAM,EAAE,aAAa;gBACrB,MAAM,EAAE,EAAE;aACV,CAA4C,CAC7C,CAAC;YACF,OAAO,MAAA,IAAI,aAAJ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C;YACpB,CAAC,CAAC;SACH,CAAC;aACA,IAAI,CAAC,GAAG,EAAE,CACV,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,SAAS,EAAE;YAClC,OAAO,EAAE,IAAI,CAAC,QAAQ;SACC,CAAC,CACzB;aACA,KAAK,CAAC,GAAG,CAAC,EAAE;YACZ,0BAA0B;YAC1B,sCAAsC;YACtC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACpB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,uDAAuD;IAC7C,aAAa,CAAC,IAAY,EAAE,IAAc;QACnD,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,qCAAuB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;IAChF,CAAC;IAEO,kBAAkB;QACzB,gCAAgC;QAChC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC;CACD;AAnFD,0CAmFC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/chunk_response_parser.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/chunk_response_parser.js new file mode 100644 index 0000000..7b25f90 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/chunk_response_parser.js @@ -0,0 +1,61 @@ +import { InvalidResponseError } from 'web3-errors'; +export class ChunkResponseParser { + constructor(eventEmitter, autoReconnect) { + this.eventEmitter = eventEmitter; + this.autoReconnect = autoReconnect; + } + clearQueues() { + if (typeof this._clearQueues === 'function') { + this._clearQueues(); + } + } + onError(clearQueues) { + this._clearQueues = clearQueues; + } + parseResponse(data) { + const returnValues = []; + // DE-CHUNKER + const dechunkedData = data + .replace(/\}[\n\r]?\{/g, '}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{ + .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{ + .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{ + .split('|--|'); + dechunkedData.forEach(_chunkData => { + // prepend the last chunk + let chunkData = _chunkData; + if (this.lastChunk) { + chunkData = this.lastChunk + chunkData; + } + let result; + try { + result = JSON.parse(chunkData); + } + catch (e) { + this.lastChunk = chunkData; + // start timeout to cancel all requests + if (this.lastChunkTimeout) { + clearTimeout(this.lastChunkTimeout); + } + this.lastChunkTimeout = setTimeout(() => { + if (this.autoReconnect) + return; + this.clearQueues(); + this.eventEmitter.emit('error', new InvalidResponseError({ + id: 1, + jsonrpc: '2.0', + error: { code: 2, message: 'Chunk timeout' }, + })); + }, 1000 * 15); + return; + } + // cancel timeout and set chunk to null + clearTimeout(this.lastChunkTimeout); + this.lastChunk = undefined; + if (result) + returnValues.push(result); + }); + return returnValues; + } +} +//# sourceMappingURL=chunk_response_parser.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/chunk_response_parser.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/chunk_response_parser.js.map new file mode 100644 index 0000000..700b9eb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/chunk_response_parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk_response_parser.js","sourceRoot":"","sources":["../../src/chunk_response_parser.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAInD,MAAM,OAAO,mBAAmB;IAO/B,YAAmB,YAA0B,EAAE,aAAsB;QACpE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACpC,CAAC;IACO,WAAW;QAClB,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU,EAAE;YAC5C,IAAI,CAAC,YAAY,EAAE,CAAC;SACpB;IACF,CAAC;IAEM,OAAO,CAAC,WAAwB;QACtC,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IACjC,CAAC;IAEM,aAAa,CAAC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,CAAC,CAAC;gBACd,OAAO;aACP;YAED,uCAAuC;YACvC,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YACpC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;YAE3B,IAAI,MAAM;gBAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;QAEH,OAAO,YAAY,CAAC;IACrB,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/converters.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/converters.js new file mode 100644 index 0000000..f6b9843 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/converters.js @@ -0,0 +1,541 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * @module Utils + */ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { bytesToUtf8, utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { isAddress, isHex, isHexStrict, isInt, isNullish, utils, utils as validatorUtils, validator, } from 'web3-validator'; +import { HexProcessingError, InvalidAddressError, InvalidBooleanError, InvalidBytesError, InvalidNumberError, InvalidUnitError, } from 'web3-errors'; +// Ref: https://ethdocs.org/en/latest/ether.html +// Note: this could be simplified using ** operator, but babel does not handle it well (https://github.com/babel/babel/issues/13109) +/** @internal */ +export const ethUnitMap = { + noether: BigInt(0), + wei: BigInt(1), + kwei: BigInt(1000), + Kwei: BigInt(1000), + babbage: BigInt(1000), + femtoether: BigInt(1000), + mwei: BigInt(1000000), + Mwei: BigInt(1000000), + lovelace: BigInt(1000000), + picoether: BigInt(1000000), + gwei: BigInt(1000000000), + Gwei: BigInt(1000000000), + shannon: BigInt(1000000000), + nanoether: BigInt(1000000000), + nano: BigInt(1000000000), + szabo: BigInt(1000000000000), + microether: BigInt(1000000000000), + micro: BigInt(1000000000000), + finney: BigInt(1000000000000000), + milliether: BigInt(1000000000000000), + milli: BigInt(1000000000000000), + ether: BigInt('1000000000000000000'), + kether: BigInt('1000000000000000000000'), + grand: BigInt('1000000000000000000000'), + mether: BigInt('1000000000000000000000000'), + gether: BigInt('1000000000000000000000000000'), + tether: BigInt('1000000000000000000000000000000'), +}; +/** + * Convert a value from bytes to Uint8Array + * @param data - Data to be converted + * @returns - The Uint8Array representation of the input data + * + * @example + * ```ts + * console.log(web3.utils.bytesToUint8Array("0xab"))); + * > Uint8Array(1) [ 171 ] + * ``` + */ +export const bytesToUint8Array = (data) => { + validator.validate(['bytes'], [data]); + if (data instanceof Uint8Array) { + return data; + } + if (Array.isArray(data)) { + return new Uint8Array(data); + } + if (typeof data === 'string') { + return validatorUtils.hexToUint8Array(data); + } + throw new InvalidBytesError(data); +}; +/** + * @internal + */ +const { uint8ArrayToHexString } = validatorUtils; +/** + * Convert a byte array to a hex string + * @param bytes - Byte array to be converted + * @returns - The hex string representation of the input byte array + * + * @example + * ```ts + * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12]))); + * > "0x480c" + * + */ +export const bytesToHex = (bytes) => uint8ArrayToHexString(bytesToUint8Array(bytes)); +/** + * Convert a hex string to a byte array + * @param hex - Hex string to be converted + * @returns - The byte array representation of the input hex string + * + * @example + * ```ts + * console.log(web3.utils.hexToBytes('0x74657374')); + * > Uint8Array(4) [ 116, 101, 115, 116 ] + * ``` + */ +export const hexToBytes = (bytes) => { + if (typeof bytes === 'string' && bytes.slice(0, 2).toLowerCase() !== '0x') { + return bytesToUint8Array(`0x${bytes}`); + } + return bytesToUint8Array(bytes); +}; +/** + * Converts value to it's number representation + * @param value - Hex string to be converted + * @returns - The number representation of the input value + * + * @example + * ```ts + * conoslle.log(web3.utils.hexToNumber('0xa')); + * > 10 + * ``` + */ +export const hexToNumber = (value) => { + validator.validate(['hex'], [value]); + // To avoid duplicate code and circular dependency we will + // use `hexToNumber` implementation from `web3-validator` + return validatorUtils.hexToNumber(value); +}; +/** + * Converts value to it's number representation @alias `hexToNumber` + */ +export const toDecimal = hexToNumber; +/** + * Converts value to it's hex representation + * @param value - Value to be converted + * @param hexstrict - Add padding to converted value if odd, to make it hexstrict + * @returns - The hex representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.numberToHex(10)); + * > "0xa" + * ``` + */ +export const numberToHex = (value, hexstrict) => { + if (typeof value !== 'bigint') + validator.validate(['int'], [value]); + // To avoid duplicate code and circular dependency we will + // use `numberToHex` implementation from `web3-validator` + let updatedValue = validatorUtils.numberToHex(value); + if (hexstrict) { + if (!updatedValue.startsWith('-') && updatedValue.length % 2 === 1) { + // To avoid duplicate a circular dependancy we will not be using the padLeft method + updatedValue = '0x0'.concat(updatedValue.slice(2)); + } + else if (updatedValue.length % 2 === 0 && updatedValue.startsWith('-')) + updatedValue = '-0x0'.concat(updatedValue.slice(3)); + } + return updatedValue; +}; +/** + * Converts value to it's hex representation @alias `numberToHex` + * + */ +export const fromDecimal = numberToHex; +/** + * Converts value to it's decimal representation in string + * @param value - Hex string to be converted + * @returns - The decimal representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.hexToNumberString('0xa')); + * > "10" + * ``` + */ +export const hexToNumberString = (data) => hexToNumber(data).toString(); +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * @param str - Utf8 string to be converted + * @returns - The hex representation of the input string + * + * @example + * ```ts + * console.log(utf8ToHex('web3.js')); + * > "0x776562332e6a73" + * + */ +export const utf8ToHex = (str) => { + validator.validate(['string'], [str]); + // To be compatible with 1.x trim null character + // eslint-disable-next-line no-control-regex + let strWithoutNullCharacter = str.replace(/^(?:\u0000)/, ''); + // eslint-disable-next-line no-control-regex + strWithoutNullCharacter = strWithoutNullCharacter.replace(/(?:\u0000)$/, ''); + return bytesToHex(new TextEncoder().encode(strWithoutNullCharacter)); +}; +/** + * @alias utf8ToHex + */ +export const fromUtf8 = utf8ToHex; +/** + * @alias utf8ToHex + */ +export const stringToHex = utf8ToHex; +/** + * Should be called to get utf8 from it's hex representation + * @param str - Hex string to be converted + * @returns - Utf8 string + * + * @example + * ```ts + * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export const hexToUtf8 = (str) => bytesToUtf8(hexToBytes(str)); +/** + * @alias hexToUtf8 + */ +export const toUtf8 = (input) => { + if (typeof input === 'string') { + return hexToUtf8(input); + } + validator.validate(['bytes'], [input]); + return bytesToUtf8(input); +}; +export const utf8ToBytes = ecUtf8ToBytes; +/** + * @alias hexToUtf8 + */ +export const hexToString = hexToUtf8; +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * @param str - String to be converted to hex + * @returns - Hex string + * + * @example + * ```ts + * console.log(web3.utils.asciiToHex('Hello World')); + * > 0x48656c6c6f20576f726c64 + * ``` + */ +export const asciiToHex = (str) => { + validator.validate(['string'], [str]); + let hexString = ''; + for (let i = 0; i < str.length; i += 1) { + const hexCharCode = str.charCodeAt(i).toString(16); + // might need a leading 0 + hexString += hexCharCode.length % 2 !== 0 ? `0${hexCharCode}` : hexCharCode; + } + return `0x${hexString}`; +}; +/** + * @alias asciiToHex + */ +export const fromAscii = asciiToHex; +/** + * Should be called to get ascii from it's hex representation + * @param str - Hex string to be converted to ascii + * @returns - Ascii string + * + * @example + * ```ts + * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export const hexToAscii = (str) => { + const decoder = new TextDecoder('ascii'); + return decoder.decode(hexToBytes(str)); +}; +/** + * @alias hexToAscii + */ +export const toAscii = hexToAscii; +/** + * Auto converts any given value into it's hex representation. + * @param value - Value to be converted to hex + * @param returnType - If true, it will return the type of the value + * + * @example + * ```ts + * console.log(web3.utils.toHex(10)); + * > 0xa + * + * console.log(web3.utils.toHex('0x123', true)); + * > bytes + *``` + */ +export const toHex = (value, returnType) => { + if (typeof value === 'string' && isAddress(value)) { + return returnType ? 'address' : `0x${value.toLowerCase().replace(/^0x/i, '')}`; + } + if (typeof value === 'boolean') { + // eslint-disable-next-line no-nested-ternary + return returnType ? 'bool' : value ? '0x01' : '0x00'; + } + if (typeof value === 'number') { + // eslint-disable-next-line no-nested-ternary + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); + } + if (typeof value === 'bigint') { + return returnType ? 'bigint' : numberToHex(value); + } + if (typeof value === 'object' && !!value) { + return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); + } + if (typeof value === 'string') { + if (value.startsWith('-0x') || value.startsWith('-0X')) { + return returnType ? 'int256' : numberToHex(value); + } + if (isHexStrict(value)) { + return returnType ? 'bytes' : value; + } + if (isHex(value) && !isInt(value)) { + return returnType ? 'bytes' : `0x${value}`; + } + if (!Number.isFinite(value)) { + return returnType ? 'string' : utf8ToHex(value); + } + } + throw new HexProcessingError(value); +}; +/** + * Converts any given value into it's number representation, if possible, else into it's bigint representation. + * @param value - The value to convert + * @returns - Returns the value in number or bigint representation + * + * @example + * ```ts + * console.log(web3.utils.toNumber(1)); + * > 1 + * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER)); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER))); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1))); + * > 9007199254740992n + * + * ``` + */ +export const toNumber = (value) => { + if (typeof value === 'number') { + return value; + } + if (typeof value === 'bigint') { + return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER + ? Number(value) + : value; + } + if (typeof value === 'string' && isHexStrict(value)) { + return hexToNumber(value); + } + try { + return toNumber(BigInt(value)); + } + catch (_a) { + throw new InvalidNumberError(value); + } +}; +/** + * Auto converts any given value into it's bigint representation + * + * @param value - The value to convert + * @returns - Returns the value in bigint representation + + * @example + * ```ts + * console.log(web3.utils.toBigInt(1)); + * > 1n + * ``` + */ +export const toBigInt = (value) => { + if (typeof value === 'number') { + return BigInt(value); + } + if (typeof value === 'bigint') { + return value; + } + // isHex passes for dec, too + if (typeof value === 'string' && isHex(value)) { + if (value.startsWith('-')) { + return -BigInt(value.substring(1)); + } + return BigInt(value); + } + throw new InvalidNumberError(value); +}; +/** + * Takes a number of wei and converts it to any other ether unit. + * @param number - The value in wei + * @param unit - The unit to convert to + * @returns - Returns the converted value in the given unit + * + * @example + * ```ts + * console.log(web3.utils.fromWei("1", "ether")); + * > 0.000000000000000001 + * + * console.log(web3.utils.fromWei("1", "shannon")); + * > 0.000000001 + * ``` + */ +export const fromWei = (number, unit) => { + const denomination = ethUnitMap[unit]; + if (!denomination) { + throw new InvalidUnitError(unit); + } + // value in wei would always be integer + // 13456789, 1234 + const value = String(toNumber(number)); + // count number of zeros in denomination + // 1000000 -> 6 + const numberOfZerosInDenomination = denomination.toString().length - 1; + if (numberOfZerosInDenomination <= 0) { + return value.toString(); + } + // pad the value with required zeros + // 13456789 -> 13456789, 1234 -> 001234 + const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, '0'); + // get the integer part of value by counting number of zeros from start + // 13456789 -> '13' + // 001234 -> '' + const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination); + // get the fraction part of value by counting number of zeros backward + // 13456789 -> '456789' + // 001234 -> '001234' + const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, ''); + if (integer === '') { + return `0.${fraction}`; + } + if (fraction === '') { + return integer; + } + return `${integer}.${fraction}`; +}; +/** + * Takes a number of a unit and converts it to wei. + * + * @param number - The number to convert. + * @param unit - {@link EtherUnits} The unit of the number passed. + * @returns The number converted to wei. + * + * @example + * ```ts + * console.log(web3.utils.toWei("0.001", "ether")); + * > 1000000000000000 //(wei) + * ``` + */ +// todo in 1.x unit defaults to 'ether' +export const toWei = (number, unit) => { + validator.validate(['number'], [number]); + const denomination = ethUnitMap[unit]; + if (!denomination) { + throw new InvalidUnitError(unit); + } + // if value is decimal e.g. 24.56 extract `integer` and `fraction` part + // to avoid `fraction` to be null use `concat` with empty string + const [integer, fraction] = String(typeof number === 'string' && !isHexStrict(number) ? number : toNumber(number)) + .split('.') + .concat(''); + // join the value removing `.` from + // 24.56 -> 2456 + const value = BigInt(`${integer}${fraction}`); + // multiply value with denomination + // 2456 * 1000000 -> 2456000000 + const updatedValue = value * denomination; + // count number of zeros in denomination + const numberOfZerosInDenomination = denomination.toString().length - 1; + // check which either `fraction` or `denomination` have lower number of zeros + const decimals = Math.min(fraction.length, numberOfZerosInDenomination); + if (decimals === 0) { + return updatedValue.toString(); + } + // Add zeros to make length equal to required decimal points + // If string is larger than decimal points required then remove last zeros + return updatedValue.toString().padStart(decimals, '0').slice(0, -decimals); +}; +/** + * Will convert an upper or lowercase Ethereum address to a checksum address. + * @param address - An address string + * @returns The checksum address + * @example + * ```ts + * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d'); + * > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" + * ``` + */ +export const toChecksumAddress = (address) => { + if (!isAddress(address, false)) { + throw new InvalidAddressError(address); + } + const lowerCaseAddress = address.toLowerCase().replace(/^0x/i, ''); + const hash = utils.uint8ArrayToHexString(keccak256(utf8ToBytes(lowerCaseAddress))); + if (isNullish(hash) || + hash === '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470') + return ''; // // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data + let checksumAddress = '0x'; + const addressHash = hash.replace(/^0x/i, ''); + for (let i = 0; i < lowerCaseAddress.length; i += 1) { + // If ith character is 8 to f then make it uppercase + if (parseInt(addressHash[i], 16) > 7) { + checksumAddress += lowerCaseAddress[i].toUpperCase(); + } + else { + checksumAddress += lowerCaseAddress[i]; + } + } + return checksumAddress; +}; +export const toBool = (value) => { + if (typeof value === 'boolean') { + return value; + } + if (typeof value === 'number' && (value === 0 || value === 1)) { + return Boolean(value); + } + if (typeof value === 'bigint' && (value === BigInt(0) || value === BigInt(1))) { + return Boolean(value); + } + if (typeof value === 'string' && + !isHexStrict(value) && + (value === '1' || value === '0' || value === 'false' || value === 'true')) { + if (value === 'true') { + return true; + } + if (value === 'false') { + return false; + } + return Boolean(Number(value)); + } + if (typeof value === 'string' && isHexStrict(value) && (value === '0x1' || value === '0x0')) { + return Boolean(toNumber(value)); + } + throw new InvalidBooleanError(value); +}; +//# sourceMappingURL=converters.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/converters.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/converters.js.map new file mode 100644 index 0000000..3b2933f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/converters.js.map @@ -0,0 +1 @@ +{"version":3,"file":"converters.js","sourceRoot":"","sources":["../../src/converters.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;GAEG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,WAAW,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAE3F,OAAO,EACN,SAAS,EACT,KAAK,EACL,WAAW,EACX,KAAK,EACL,SAAS,EACT,KAAK,EACL,KAAK,IAAI,cAAc,EACvB,SAAS,GACT,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACN,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AAErB,gDAAgD;AAChD,oIAAoI;AACpI,gBAAgB;AAChB,MAAM,CAAC,MAAM,UAAU,GAAG;IACzB,OAAO,EAAE,MAAM,CAAC,CAAC,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K,CAAC;KACb;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;QAC9D,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;KACtB;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;QAC9E,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;KACtB;IAED,IACC,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,WAAW,CAAC,KAAK,CAAC;QACnB,CAAC,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,MAAM,CAAC,EACxE;QACD,IAAI,KAAK,KAAK,MAAM,EAAE;YACrB,OAAO,IAAI,CAAC;SACZ;QACD,IAAI,KAAK,KAAK,OAAO,EAAE;YACtB,OAAO,KAAK,CAAC;SACb;QACD,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;KAC9B;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK,CAAC,EAAE;QAC5F,OAAO,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;KAChC;IAED,MAAM,IAAI,mBAAmB,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/event_emitter.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/event_emitter.js new file mode 100644 index 0000000..809bb54 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/event_emitter.js @@ -0,0 +1,115 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { EventEmitter as EventEmitterAtNode } from 'events'; +const wrapFunction = (fn) => (params) => fn(params.detail); +/** + * This class copy the behavior of Node.js EventEmitter class. + * It is used to provide the same interface for the browser environment. + */ +class EventEmitterAtBrowser extends EventTarget { + constructor() { + super(...arguments); + this._listeners = {}; + this.maxListeners = Number.MAX_SAFE_INTEGER; + } + on(eventName, fn) { + this.addEventListener(eventName, fn); + return this; + } + once(eventName, fn) { + const onceCallback = (params) => __awaiter(this, void 0, void 0, function* () { + this.off(eventName, onceCallback); + yield fn(params); + }); + return this.on(eventName, onceCallback); + } + off(eventName, fn) { + this.removeEventListener(eventName, fn); + return this; + } + emit(eventName, params) { + const event = new CustomEvent(eventName, { detail: params }); + return super.dispatchEvent(event); + } + listenerCount(eventName) { + const eventListeners = this._listeners[eventName]; + return eventListeners ? eventListeners.length : 0; + } + listeners(eventName) { + return this._listeners[eventName].map(value => value[0]) || []; + } + eventNames() { + return Object.keys(this._listeners); + } + removeAllListeners() { + Object.keys(this._listeners).forEach(event => { + this._listeners[event].forEach((listener) => { + super.removeEventListener(event, listener[1]); + }); + }); + this._listeners = {}; + return this; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + getMaxListeners() { + return this.maxListeners; + } + addEventListener(eventName, fn) { + const wrappedFn = wrapFunction(fn); + super.addEventListener(eventName, wrappedFn); + if (!this._listeners[eventName]) { + this._listeners[eventName] = []; + } + this._listeners[eventName].push([fn, wrappedFn]); + } + removeEventListener(eventName, fn) { + const eventListeners = this._listeners[eventName]; + if (eventListeners) { + const index = eventListeners.findIndex(item => item[0] === fn); + if (index !== -1) { + super.removeEventListener(eventName, eventListeners[index][1]); + eventListeners.splice(index, 1); + } + } + } +} +// eslint-disable-next-line import/no-mutable-exports +let EventEmitterType; +// Check if the code is running in a Node.js environment +if (typeof window === 'undefined') { + EventEmitterType = EventEmitterAtNode; +} +else { + // Fallback for the browser environment + EventEmitterType = EventEmitterAtBrowser; +} +export class EventEmitter extends EventEmitterType { +} +//# sourceMappingURL=event_emitter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/event_emitter.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/event_emitter.js.map new file mode 100644 index 0000000..8221216 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/event_emitter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event_emitter.js","sourceRoot":"","sources":["../../src/event_emitter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,yCAAyC;;;;;;;;;;AAEzC,OAAO,EAAE,YAAY,IAAI,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAO5D,MAAM,YAAY,GACjB,CAAC,EAAY,EAAuB,EAAE,CACtC,CAAC,MAAmB,EAAE,EAAE,CACvB,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAEpB;;;GAGG;AACH,MAAM,qBAAsB,SAAQ,WAAW;IAA/C;;QACS,eAAU,GAAkE,EAAE,CAAC;QAC/E,iBAAY,GAAG,MAAM,CAAC,gBA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IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;gBACjB,KAAK,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAkB,CAAC,CAAC;gBAChF,cAAc,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;aAChC;SACD;IACF,CAAC;CACD;AAED,qDAAqD;AACrD,IAAI,gBAA2C,CAAC;AAChD,wDAAwD;AACxD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;IAClC,gBAAgB,GAAG,kBAAkB,CAAC;CACtC;KAAM;IACN,uCAAuC;IACvC,gBAAgB,GAAG,qBAA6D,CAAC;CACjF;AAED,MAAM,OAAO,YAAa,SAAQ,gBAAgB;CAAG"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/formatter.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/formatter.js new file mode 100644 index 0000000..8cf10c4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/formatter.js @@ -0,0 +1,242 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { FormatterError } from 'web3-errors'; +import { FMT_BYTES, FMT_NUMBER } from 'web3-types'; +import { isNullish, isObject, utils } from 'web3-validator'; +import { bytesToUint8Array, bytesToHex, numberToHex, toBigInt } from './converters.js'; +import { mergeDeep } from './objects.js'; +import { padLeft } from './string_manipulation.js'; +import { uint8ArrayConcat } from './uint8array.js'; +const { parseBaseType } = utils; +export const isDataFormat = (dataFormat) => typeof dataFormat === 'object' && + !isNullish(dataFormat) && + 'number' in dataFormat && + 'bytes' in dataFormat; +/** + * Finds the schema that corresponds to a specific data path within a larger JSON schema. + * It works by iterating over the dataPath array and traversing the JSON schema one step at a time until it reaches the end of the path. + * + * @param schema - represents a JSON schema, which is an object that describes the structure of JSON data + * @param dataPath - represents an array of strings that specifies the path to the data within the JSON schema + * @param oneOfPath - represents an optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns the JSON schema that matches the data path + * + */ +const findSchemaByDataPath = (schema, dataPath, oneOfPath = []) => { + let result = Object.assign({}, schema); + let previousDataPath; + for (const dataPart of dataPath) { + if (result.oneOf && previousDataPath) { + const path = oneOfPath.find(function (element) { + return this === element[0]; + }, previousDataPath !== null && previousDataPath !== void 0 ? previousDataPath : ''); + if (path && path[0] === previousDataPath) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access + result = result.oneOf[path[1]]; + } + } + if (!result.properties && !result.items) { + return undefined; + } + if (result.properties) { + result = result.properties[dataPart]; + } + else if (result.items && result.items.properties) { + const node = result.items.properties; + if (!node) { + return undefined; + } + result = node[dataPart]; + } + else if (result.items && isObject(result.items)) { + result = result.items; + } + else if (result.items && Array.isArray(result.items)) { + result = result.items[parseInt(dataPart, 10)]; + } + if (result && dataPart) + previousDataPath = dataPart; + } + return result; +}; +/** + * Converts a value depending on the format + * @param value - value to convert + * @param ethType - The type of the value to be parsed + * @param format - The format to be converted to + * @returns - The value converted to the specified format + */ +export const convertScalarValue = (value, ethType, format) => { + try { + const { baseType, baseTypeSize } = parseBaseType(ethType); + if (baseType === 'int' || baseType === 'uint') { + switch (format.number) { + case FMT_NUMBER.NUMBER: + return Number(toBigInt(value)); + case FMT_NUMBER.HEX: + return numberToHex(toBigInt(value)); + case FMT_NUMBER.STR: + return toBigInt(value).toString(); + case FMT_NUMBER.BIGINT: + return toBigInt(value); + default: + throw new FormatterError(`Invalid format: ${String(format.number)}`); + } + } + if (baseType === 'bytes') { + let paddedValue; + if (baseTypeSize) { + if (typeof value === 'string') + paddedValue = padLeft(value, baseTypeSize * 2); + else if (value instanceof Uint8Array) { + paddedValue = uint8ArrayConcat(new Uint8Array(baseTypeSize - value.length), value); + } + } + else { + paddedValue = value; + } + switch (format.bytes) { + case FMT_BYTES.HEX: + return bytesToHex(bytesToUint8Array(paddedValue)); + case FMT_BYTES.UINT8ARRAY: + return bytesToUint8Array(paddedValue); + default: + throw new FormatterError(`Invalid format: ${String(format.bytes)}`); + } + } + } + catch (error) { + // If someone didn't use `eth` keyword we can return original value + // as the scope of this code is formatting not validation + return value; + } + return value; +}; +/** + * Converts the data to the specified format + * @param data - data to convert + * @param schema - The JSON schema that describes the structure of the data + * @param dataPath - A string array that specifies the path to the data within the JSON schema + * @param format - The format to be converted to + * @param oneOfPath - An optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns - The data converted to the specified format + */ +export const convert = (data, schema, dataPath, format, oneOfPath = []) => { + var _a, _b; + // If it's a scalar value + if (!isObject(data) && !Array.isArray(data)) { + return convertScalarValue(data, schema === null || schema === void 0 ? void 0 : schema.format, format); + } + const object = data; + for (const [key, value] of Object.entries(object)) { + dataPath.push(key); + const schemaProp = findSchemaByDataPath(schema, dataPath, oneOfPath); + // If value is a scaler value + if (isNullish(schemaProp)) { + delete object[key]; + dataPath.pop(); + continue; + } + // If value is an object, recurse into it + if (isObject(value)) { + convert(value, schema, dataPath, format); + dataPath.pop(); + continue; + } + // If value is an array + if (Array.isArray(value)) { + let _schemaProp = schemaProp; + // TODO This is a naive approach to solving the issue of + // a schema using oneOf. This chunk of code was intended to handle + // BlockSchema.transactions + // TODO BlockSchema.transactions are not being formatted + if ((schemaProp === null || schemaProp === void 0 ? void 0 : schemaProp.oneOf) !== undefined) { + // The following code is basically saying: + // if the schema specifies oneOf, then we are to loop + // over each possible schema and check if they type of the schema + // matches the type of value[0], and if so we use the oneOfSchemaProp + // as the schema for formatting + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + schemaProp.oneOf.forEach((oneOfSchemaProp, index) => { + var _a, _b; + if (!Array.isArray(schemaProp === null || schemaProp === void 0 ? void 0 : schemaProp.items) && + ((typeof value[0] === 'object' && + ((_a = oneOfSchemaProp === null || oneOfSchemaProp === void 0 ? void 0 : oneOfSchemaProp.items) === null || _a === void 0 ? void 0 : _a.type) === 'object') || + (typeof value[0] === 'string' && + ((_b = oneOfSchemaProp === null || oneOfSchemaProp === void 0 ? void 0 : oneOfSchemaProp.items) === null || _b === void 0 ? void 0 : _b.type) !== 'object'))) { + _schemaProp = oneOfSchemaProp; + oneOfPath.push([key, index]); + } + }); + } + if (isNullish(_schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items)) { + // Can not find schema for array item, delete that item + delete object[key]; + dataPath.pop(); + continue; + } + // If schema for array items is a single type + if (isObject(_schemaProp.items) && !isNullish(_schemaProp.items.format)) { + for (let i = 0; i < value.length; i += 1) { + object[key][i] = convertScalarValue(value[i], + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + (_a = _schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items) === null || _a === void 0 ? void 0 : _a.format, format); + } + dataPath.pop(); + continue; + } + // If schema for array items is an object + if (!Array.isArray(_schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items) && ((_b = _schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items) === null || _b === void 0 ? void 0 : _b.type) === 'object') { + for (const arrObject of value) { + convert(arrObject, schema, dataPath, format, oneOfPath); + } + dataPath.pop(); + continue; + } + // If schema for array is a tuple + if (Array.isArray(_schemaProp === null || _schemaProp === void 0 ? void 0 : _schemaProp.items)) { + for (let i = 0; i < value.length; i += 1) { + object[key][i] = convertScalarValue(value[i], _schemaProp.items[i].format, format); + } + dataPath.pop(); + continue; + } + } + object[key] = convertScalarValue(value, schemaProp.format, format); + dataPath.pop(); + } + return object; +}; +export const format = (schema, data, returnFormat) => { + let dataToParse; + if (isObject(data)) { + dataToParse = mergeDeep({}, data); + } + else if (Array.isArray(data)) { + dataToParse = [...data]; + } + else { + dataToParse = data; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const jsonSchema = isObject(schema) ? schema : utils.ethAbiToJsonSchema(schema); + if (!jsonSchema.properties && !jsonSchema.items && !jsonSchema.format) { + throw new FormatterError('Invalid json schema for formatting'); + } + return convert(dataToParse, jsonSchema, [], returnFormat); +}; +//# sourceMappingURL=formatter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/formatter.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/formatter.js.map new file mode 100644 index 0000000..4fc5f0b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/formatter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatter.js","sourceRoot":"","sources":["../../src/formatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAqB,SAAS,EAAE,UAAU,EAAc,MAAM,YAAY,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAc,KAAK,EAAyB,MAAM,gBAAgB,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACvF,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,MAAM,EAAE,aAAa,EAAE,GAAG,KAAK,CAAC;AAEhC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,UAAmB,EAA4B,EAAE,CAC7E,OAAO,UAAU,KAAK,QAAQ;IAC9B,CAAC,SAAS,CAAC,UAAU,CAAC;IACtB,QAAQ,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AC,UAAU,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE;QACtE,MAAM,IAAI,cAAc,CAAC,oCAAoC,CAAC,CAAC;KAC/D;IAED,OAAO,OAAO,CAAC,WAAW,EAAE,UAAU,EAAE,EAAE,EAAE,YAAY,CAGvD,CAAC;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/hash.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/hash.js new file mode 100644 index 0000000..7f72f90 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/hash.js @@ -0,0 +1,316 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * @module Utils + */ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { utf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { InvalidAddressError, InvalidBooleanError, InvalidBytesError, InvalidLargeValueError, InvalidSizeError, InvalidStringError, InvalidUnsignedIntegerError, } from 'web3-errors'; +import { isAddress, isNullish, isHexStrict } from 'web3-validator'; +import { bytesToUint8Array, bytesToHex, hexToBytes, toBigInt, toHex, toNumber, utf8ToHex, } from './converters.js'; +import { leftPad, rightPad, toTwosComplement } from './string_manipulation.js'; +const SHA3_EMPTY_BYTES = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; +/** + * computes the Keccak-256 hash of the input and returns a hexstring + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.sha3('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3('')); + * > undefined + * ``` + */ +export const sha3 = (data) => { + let updatedData; + if (typeof data === 'string') { + if (data.startsWith('0x') && isHexStrict(data)) { + updatedData = hexToBytes(data); + } + else { + updatedData = utf8ToBytes(data); + } + } + else { + updatedData = data; + } + const hash = bytesToHex(keccak256(updatedData)); + // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data + return hash === SHA3_EMPTY_BYTES ? undefined : hash; +}; +/** + * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed. + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * conosle.log(web3.utils.sha3Raw('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3Raw('')); + * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 + * ``` + */ +export const sha3Raw = (data) => { + const hash = sha3(data); + if (isNullish(hash)) { + return SHA3_EMPTY_BYTES; + } + return hash; +}; +/** + * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array` + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.keccak256Wrapper('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.keccak256Wrapper(1)); + * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6 + * + * console.log(web3.utils.keccak256Wrapper(0xaf12fd)); + * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c + * ``` + */ +export const keccak256Wrapper = (data) => { + let processedData; + if (typeof data === 'bigint' || typeof data === 'number') { + processedData = utf8ToBytes(data.toString()); + } + else if (Array.isArray(data)) { + processedData = new Uint8Array(data); + } + else if (typeof data === 'string' && !isHexStrict(data)) { + processedData = utf8ToBytes(data); + } + else { + processedData = bytesToUint8Array(data); + } + return bytesToHex(keccak256(processedData)); +}; +export { keccak256Wrapper as keccak256 }; +/** + * returns type and value + * @param arg - the input to return the type and value + * @returns - the type and value of the input + */ +const getType = (arg) => { + if (Array.isArray(arg)) { + throw new Error('Autodetection of array types is not supported.'); + } + let type; + let value; + // if type is given + if (typeof arg === 'object' && + ('t' in arg || 'type' in arg) && + ('v' in arg || 'value' in arg)) { + type = 't' in arg ? arg.t : arg.type; + value = 'v' in arg ? arg.v : arg.value; + type = type.toLowerCase() === 'bigint' ? 'int' : type; + } + else if (typeof arg === 'bigint') { + return ['int', arg]; + } + // otherwise try to guess the type + else { + type = toHex(arg, true); + value = toHex(arg); + if (!type.startsWith('int') && !type.startsWith('uint')) { + type = 'bytes'; + } + } + if ((type.startsWith('int') || type.startsWith('uint')) && + typeof value === 'string' && + !/^(-)?0x/i.test(value)) { + value = toBigInt(value); + } + return [type, value]; +}; +/** + * returns the type with size if uint or int + * @param name - the input to return the type with size + * @returns - the type with size of the input + */ +const elementaryName = (name) => { + if (name.startsWith('int[')) { + return `int256${name.slice(3)}`; + } + if (name === 'int') { + return 'int256'; + } + if (name.startsWith('uint[')) { + return `uint256'${name.slice(4)}`; + } + if (name === 'uint') { + return 'uint256'; + } + return name; +}; +/** + * returns the size of the value of type 'byte' + */ +const parseTypeN = (value, typeLength) => { + const typesize = /^(\d+).*$/.exec(value.slice(typeLength)); + return typesize ? parseInt(typesize[1], 10) : 0; +}; +/** + * returns the bit length of the value + * @param value - the input to return the bit length + * @returns - the bit length of the input + */ +const bitLength = (value) => { + const updatedVal = value.toString(2); + return updatedVal.length; +}; +/** + * Pads the value based on size and type + * returns a string of the padded value + * @param type - the input to pad + * @returns = the padded value + */ +const solidityPack = (type, val) => { + const value = val.toString(); + if (type === 'string') { + if (typeof val === 'string') + return utf8ToHex(val); + throw new InvalidStringError(val); + } + if (type === 'bool' || type === 'boolean') { + if (typeof val === 'boolean') + return val ? '01' : '00'; + throw new InvalidBooleanError(val); + } + if (type === 'address') { + if (!isAddress(value)) { + throw new InvalidAddressError(value); + } + return value; + } + const name = elementaryName(type); + if (type.startsWith('uint')) { + const size = parseTypeN(name, 'uint'.length); + if (size % 8 || size < 8 || size > 256) { + throw new InvalidSizeError(value); + } + const num = toNumber(value); + if (bitLength(num) > size) { + throw new InvalidLargeValueError(value); + } + if (num < BigInt(0)) { + throw new InvalidUnsignedIntegerError(value); + } + return size ? leftPad(num.toString(16), (size / 8) * 2) : num.toString(16); + } + if (type.startsWith('int')) { + const size = parseTypeN(name, 'int'.length); + if (size % 8 || size < 8 || size > 256) { + throw new InvalidSizeError(type); + } + const num = toNumber(value); + if (bitLength(num) > size) { + throw new InvalidLargeValueError(value); + } + if (num < BigInt(0)) { + return toTwosComplement(num.toString(), (size / 8) * 2); + } + return size ? leftPad(num.toString(16), size / 4) : num.toString(16); + } + if (name === 'bytes') { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new InvalidBytesError(value); + } + return value; + } + if (type.startsWith('bytes')) { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new InvalidBytesError(value); + } + const size = parseTypeN(type, 'bytes'.length); + if (!size || size < 1 || size > 64 || size < value.replace(/^0x/i, '').length / 2) { + throw new InvalidBytesError(value); + } + return rightPad(value, size * 2); + } + return ''; +}; +/** + * returns a string of the tightly packed value given based on the type + * @param arg - the input to return the tightly packed value + * @returns - the tightly packed value + */ +export const processSolidityEncodePackedArgs = (arg) => { + const [type, val] = getType(arg); + // array case + if (Array.isArray(val)) { + // go through each element of the array and use map function to create new hexarg list + const hexArg = val.map((v) => solidityPack(type, v).replace('0x', '')); + return hexArg.join(''); + } + const hexArg = solidityPack(type, val); + return hexArg.replace('0x', ''); +}; +/** + * Encode packed arguments to a hexstring + */ +export const encodePacked = (...values) => { + const hexArgs = values.map(processSolidityEncodePackedArgs); + return `0x${hexArgs.join('').toLowerCase()}`; +}; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, or null if input is empty + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log([{ type: 'string', value: '31323334' }]); + * console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" })); + * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b + * ``` + */ +export const soliditySha3 = (...values) => sha3(encodePacked(...values)); +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" })) + * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0 + * ``` + */ +export const soliditySha3Raw = (...values) => sha3Raw(encodePacked(...values)); +/** + * Get slot number for storage long string in contract. Basically for getStorage method + * returns slotNumber where will data placed + * @param mainSlotNumber - the slot number where will be stored hash of long string + * @returns - the slot number where will be stored long string + */ +export const getStorageSlotNumForLongString = (mainSlotNumber) => sha3(`0x${(typeof mainSlotNumber === 'number' + ? mainSlotNumber.toString() + : mainSlotNumber).padStart(64, '0')}`); +//# sourceMappingURL=hash.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/hash.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/hash.js.map new file mode 100644 index 0000000..d25acb4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/hash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/hash.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;GAEG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,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AAC,CAAC,CAAC;AAE/B;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAG,MAAgD,EAAU,EAAE,CAC9F,OAAO,CAAC,YAAY,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AAElC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,cAA+B,EAAE,EAAE,CACjF,IAAI,CACH,KAAK,CAAC,OAAO,cAAc,KAAK,QAAQ;IACvC,CAAC,CAAC,cAAc,CAAC,QAAQ,EAAE;IAC3B,CAAC,CAAC,cAAc,CAChB,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,CACrB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/index.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/index.js new file mode 100644 index 0000000..b452cee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/index.js @@ -0,0 +1,34 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './converters.js'; +export * from './event_emitter.js'; +export * from './validation.js'; +export * from './formatter.js'; +export * from './hash.js'; +export * from './random.js'; +export * from './string_manipulation.js'; +export * from './objects.js'; +export * from './promise_helpers.js'; +export * from './json_rpc.js'; +export * as jsonRpc from './json_rpc.js'; +export * from './web3_deferred_promise.js'; +export * from './chunk_response_parser.js'; +export * from './uuid.js'; +export * from './web3_eip1193_provider.js'; +export * from './socket_provider.js'; +export * from './uint8array.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/index.js.map new file mode 100644 index 0000000..19aaa45 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,cAAc,sBAAsB,CAAC;AACrC,cAAc,eAAe,CAAC;AAC9B,OAAO,KAAK,OAAO,MAAM,eAAe,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,WAAW,CAAC;AAC1B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/json_rpc.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/json_rpc.js new file mode 100644 index 0000000..28a8b86 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/json_rpc.js @@ -0,0 +1,81 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isNullish } from 'web3-validator'; +import { rpcErrorsMap } from 'web3-errors'; +import { uuidV4 } from './uuid.js'; +// check if code is a valid rpc server error code +export const isResponseRpcError = (rpcError) => { + const errorCode = rpcError.error.code; + return rpcErrorsMap.has(errorCode) || (errorCode >= -32099 && errorCode <= -32000); +}; +export const isResponseWithResult = (response) => !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + // JSON RPC consider "null" as valid response + 'result' in response && + isNullish(response.error) && + (typeof response.id === 'number' || typeof response.id === 'string'); +// To avoid circular package dependency, copied to code here. If you update this please update same function in `response_errors.ts` +export const isResponseWithError = (response) => !Array.isArray(response) && + response.jsonrpc === '2.0' && + !!response && + isNullish(response.result) && + // JSON RPC consider "null" as valid response + 'error' in response && + (typeof response.id === 'number' || typeof response.id === 'string'); +export const isResponseWithNotification = (response) => !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + !isNullish(response.params) && + !isNullish(response.method); +export const isSubscriptionResult = (response) => !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + 'id' in response && + // JSON RPC consider "null" as valid response + 'result' in response; +export const validateResponse = (response) => isResponseWithResult(response) || isResponseWithError(response); +export const isValidResponse = (response) => Array.isArray(response) ? response.every(validateResponse) : validateResponse(response); +export const isBatchResponse = (response) => Array.isArray(response) && response.length > 0 && isValidResponse(response); +// internal optional variable to increment and use for the jsonrpc `id` +let requestIdSeed; +/** + * Optionally use to make the jsonrpc `id` start from a specific number. + * Without calling this function, the `id` will be filled with a Uuid. + * But after this being called with a number, the `id` will be a number staring from the provided `start` variable. + * However, if `undefined` was passed to this function, the `id` will be a Uuid again. + * @param start - a number to start incrementing from. + * Or `undefined` to use a new Uuid (this is the default behavior) + */ +export const setRequestIdStart = (start) => { + requestIdSeed = start; +}; +export const toPayload = (request) => { + var _a, _b, _c, _d; + if (typeof requestIdSeed !== 'undefined') { + requestIdSeed += 1; + } + return { + jsonrpc: (_a = request.jsonrpc) !== null && _a !== void 0 ? _a : '2.0', + id: (_c = (_b = request.id) !== null && _b !== void 0 ? _b : requestIdSeed) !== null && _c !== void 0 ? _c : uuidV4(), + method: request.method, + params: (_d = request.params) !== null && _d !== void 0 ? _d : undefined, + }; +}; +export const toBatchPayload = (requests) => requests.map(request => toPayload(request)); +export const isBatchRequest = (request) => Array.isArray(request) && request.length > 0; +//# sourceMappingURL=json_rpc.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/json_rpc.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/json_rpc.js.map new file mode 100644 index 0000000..5ba30fd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/json_rpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json_rpc.js","sourceRoot":"","sources":["../../src/json_rpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAa3C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,iDAAiD;AACjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,QAAkC,EAAE,EAAE;IACxE,MAAM,SAAS,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;IACtC,OAAO,YAAY,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,KAAK,IAAI,SAAS,IAAI,CAAC,KAAK,CAAC,CAAC;AACpF,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CACnC,QAAwC,EACQ,EAAE,CAClD,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;IACxB,CAAC,CAAC,QAAQ;IACV,QAAQ,CAAC,OAAO,KAAK,KAAK;IAC1B,6CAA6C;IAC7C,QAAQ,IAAI,QAAQ;IACpB,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC;IACzB,CAAC,OAAO,QAAQ,CAAC,EAAE,KAAK,QAAQ,IAAI,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modules/web3-utils/lib/esm/objects.js new file mode 100644 index 0000000..5378e4d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/objects.js @@ -0,0 +1,57 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { TypedArray } from 'web3-types'; +import { isNullish } from 'web3-validator'; +const isIterable = (item) => typeof item === 'object' && + !isNullish(item) && + !Array.isArray(item) && + !(item instanceof TypedArray); +// The following code is a derivative work of the code from the "LiskHQ/lisk-sdk" project, +// which is licensed under Apache version 2. +/** + * Deep merge two objects. + * @param destination - The destination object. + * @param sources - An array of source objects. + * @returns - The merged object. + */ +export const mergeDeep = (destination, ...sources) => { + const result = destination; // clone deep here + if (!isIterable(result)) { + return result; + } + for (const src of sources) { + // eslint-disable-next-line no-restricted-syntax + for (const key in src) { + if (isIterable(src[key])) { + if (!result[key]) { + result[key] = {}; + } + mergeDeep(result[key], src[key]); + } + else if (!isNullish(src[key]) && Object.hasOwnProperty.call(src, key)) { + if (Array.isArray(src[key]) || src[key] instanceof TypedArray) { + result[key] = src[key].slice(0); + } + else { + result[key] = src[key]; + } + } + } + } + return result; +}; +//# sourceMappingURL=objects.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/objects.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/objects.js.map new file mode 100644 index 0000000..9a43e91 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/objects.js.map @@ -0,0 +1 @@ +{"version":3,"file":"objects.js","sourceRoot":"","sources":["../../src/objects.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;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AC,GAAG,CAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;iBAC/C;qBAAM;oBACN,MAAM,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;iBACvB;aACD;SACD;KACD;IACD,OAAO,MAAM,CAAC;AACf,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/package.json b/test/merkletreejs/node_modules/web3-utils/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/promise_helpers.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/promise_helpers.js new file mode 100644 index 0000000..3a32d0e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/promise_helpers.js @@ -0,0 +1,146 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { isNullish } from 'web3-validator'; +/** + * An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser. + * @param object - to check if it is a `Promise` + * @returns `true` if it is an `object` or a `function` that has a `then` function. And returns `false` otherwise. + */ +export function isPromise(object) { + return ((typeof object === 'object' || typeof object === 'function') && + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof object.then === 'function'); +} +/** + * Wait for a promise but interrupt it if it did not resolve within a given timeout. + * If the timeout reached, before the promise code resolve, either throw an error if an error object was provided, or return `undefined`. + * @param awaitable - The promise or function to wait for. + * @param timeout - The timeout in milliseconds. + * @param error - (Optional) The error to throw if the timeout reached. + */ +export function waitWithTimeout(awaitable, timeout, error) { + return __awaiter(this, void 0, void 0, function* () { + let timeoutId; + const result = yield Promise.race([ + awaitable instanceof Promise ? awaitable : awaitable(), + new Promise((resolve, reject) => { + timeoutId = setTimeout(() => (error ? reject(error) : resolve(undefined)), timeout); + }), + ]); + if (timeoutId) { + clearTimeout(timeoutId); + } + if (result instanceof Error) { + throw result; + } + return result; + }); +} +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. It returns promise and intervalId. + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export function pollTillDefinedAndReturnIntervalId(func, interval) { + let intervalId; + const polledRes = new Promise((resolve, reject) => { + intervalId = setInterval(function intervalCallbackFunc() { + (() => __awaiter(this, void 0, void 0, function* () { + try { + const res = yield waitWithTimeout(func, interval); + if (!isNullish(res)) { + clearInterval(intervalId); + resolve(res); + } + } + catch (error) { + clearInterval(intervalId); + reject(error); + } + }))(); + return intervalCallbackFunc; + }() // this will immediate invoke first call + , interval); + }); + return [polledRes, intervalId]; +} +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. + * pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result. + * This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId(). + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export function pollTillDefined(func, interval) { + return __awaiter(this, void 0, void 0, function* () { + return pollTillDefinedAndReturnIntervalId(func, interval)[0]; + }); +} +/** + * Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete + * @param timeout - The timeout to enforced in milliseconds. + * @param error - The error to throw if the timeout is reached. + * @returns A tuple of the timeout id and the promise that will be rejected if the timeout is reached. + * + * @example + * ```ts + * const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out')); + * ``` + */ +export function rejectIfTimeout(timeout, error) { + let timeoutId; + const rejectOnTimeout = new Promise((_, reject) => { + timeoutId = setTimeout(() => { + reject(error); + }, timeout); + }); + return [timeoutId, rejectOnTimeout]; +} +/** + * Sets an interval that repeatedly executes the given cond function with the specified interval between each call. + * If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned. + * @param cond - The function/confition to call. + * @param interval - The interval in milliseconds. + * @returns - an array with the interval ID and the Promise. + */ +export function rejectIfConditionAtInterval(cond, interval) { + let intervalId; + const rejectIfCondition = new Promise((_, reject) => { + intervalId = setInterval(() => { + (() => __awaiter(this, void 0, void 0, function* () { + const error = yield cond(); + if (error) { + clearInterval(intervalId); + reject(error); + } + }))(); + }, interval); + }); + return [intervalId, rejectIfCondition]; +} +//# sourceMappingURL=promise_helpers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/promise_helpers.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/promise_helpers.js.map new file mode 100644 index 0000000..4141307 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/promise_helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promise_helpers.js","sourceRoot":"","sources":["../../src/promise_helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAM3C;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,MAAe;IACxC,OAAO,CACN,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,UAAU,CAAC;Q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CAAC;iBACd;YACF,CAAC,CAAA,CAAC,EAAa,CAAC;QACjB,CAAC,EAAE,QAAQ,CAAC,CAAC;IACd,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,UAAW,EAAE,iBAAiB,CAAC,CAAC;AACzC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/random.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/random.js new file mode 100644 index 0000000..88702d7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/random.js @@ -0,0 +1,47 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { getRandomBytesSync } from 'ethereum-cryptography/random.js'; +import { bytesToHex } from './converters.js'; +/** + * Returns a random byte array by the given bytes size + * @param size - The size of the random byte array returned + * @returns - random byte array + * + * @example + * ```ts + * console.log(web3.utils.randomBytes(32)); + * > Uint8Array(32) [ + * 93, 172, 226, 32, 33, 176, 156, 156, + * 182, 30, 240, 2, 69, 96, 174, 197, + * 33, 136, 194, 241, 197, 156, 110, 111, + * 66, 87, 17, 88, 67, 48, 245, 183 + * ] + * ``` + */ +export const randomBytes = (size) => getRandomBytesSync(size); +/** + * Returns a random hex string by the given bytes size + * @param byteSize - The size of the random hex string returned + * @returns - random hex string + * + * ```ts + * console.log(web3.utils.randomHex(32)); + * > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e + * ``` + */ +export const randomHex = (byteSize) => bytesToHex(randomBytes(byteSize)); +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/random.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/random.js.map new file mode 100644 index 0000000..c995781 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/random.js.map @@ -0,0 +1 @@ +{"version":3,"file":"random.js","sourceRoot":"","sources":["../../src/random.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,IAAY,EAAc,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAElF;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAgB,EAAU,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/socket_provider.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/socket_provider.js new file mode 100644 index 0000000..26a3904 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/socket_provider.js @@ -0,0 +1,321 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { ConnectionError, ConnectionNotOpenError, InvalidClientError, MaxAttemptsReachedOnReconnectingError, PendingRequestsOnReconnectingError, RequestAlreadySentError, Web3WSProviderError, } from 'web3-errors'; +import { Eip1193Provider } from './web3_eip1193_provider.js'; +import { ChunkResponseParser } from './chunk_response_parser.js'; +import { isNullish } from './validation.js'; +import { Web3DeferredPromise } from './web3_deferred_promise.js'; +import * as jsonRpc from './json_rpc.js'; +const DEFAULT_RECONNECTION_OPTIONS = { + autoReconnect: true, + delay: 5000, + maxAttempts: 5, +}; +const NORMAL_CLOSE_CODE = 1000; // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close +export class SocketProvider extends Eip1193Provider { + /** + * This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546) + * @param socketOptions - The options for the socket connection. Its type is supposed to be specified in the inherited classes. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath, socketOptions, reconnectOptions) { + super(); + this._connectionStatus = 'connecting'; + // Message handlers. Due to bounding of `this` and removing the listeners we have to keep it's reference. + this._onMessageHandler = this._onMessage.bind(this); + this._onOpenHandler = this._onConnect.bind(this); + this._onCloseHandler = this._onCloseEvent.bind(this); + this._onErrorHandler = this._onError.bind(this); + if (!this._validateProviderPath(socketPath)) + throw new InvalidClientError(socketPath); + this._socketPath = socketPath; + this._socketOptions = socketOptions; + this._reconnectOptions = Object.assign(Object.assign({}, DEFAULT_RECONNECTION_OPTIONS), (reconnectOptions !== null && reconnectOptions !== void 0 ? reconnectOptions : {})); + this._pendingRequestsQueue = new Map(); + this._sentRequestsQueue = new Map(); + this._init(); + this.connect(); + this.chunkResponseParser = new ChunkResponseParser(this._eventEmitter, this._reconnectOptions.autoReconnect); + this.chunkResponseParser.onError(() => { + this._clearQueues(); + }); + this.isReconnecting = false; + } + get SocketConnection() { + return this._socketConnection; + } + _init() { + this._reconnectAttempts = 0; + } + /** + * Try to establish a connection to the socket + */ + connect() { + try { + this._openSocketConnection(); + this._connectionStatus = 'connecting'; + this._addSocketListeners(); + } + catch (e) { + if (!this.isReconnecting) { + this._connectionStatus = 'disconnected'; + if (e && e.message) { + throw new ConnectionError(`Error while connecting to ${this._socketPath}. Reason: ${e.message}`); + } + else { + throw new InvalidClientError(this._socketPath); + } + } + else { + setImmediate(() => { + this._reconnect(); + }); + } + } + } + // eslint-disable-next-line class-methods-use-this + _validateProviderPath(path) { + return !!path; + } + /** + * + * @returns the pendingRequestQueue size + */ + // eslint-disable-next-line class-methods-use-this + getPendingRequestQueueSize() { + return this._pendingRequestsQueue.size; + } + /** + * + * @returns the sendPendingRequests size + */ + // eslint-disable-next-line class-methods-use-this + getSentRequestsQueueSize() { + return this._sentRequestsQueue.size; + } + /** + * + * @returns `true` if the socket supports subscriptions + */ + // eslint-disable-next-line class-methods-use-this + supportsSubscriptions() { + return true; + } + on(type, listener) { + this._eventEmitter.on(type, listener); + } + once(type, listener) { + this._eventEmitter.once(type, listener); + } + removeListener(type, listener) { + this._eventEmitter.removeListener(type, listener); + } + _onDisconnect(code, data) { + this._connectionStatus = 'disconnected'; + super._onDisconnect(code, data); + } + /** + * Disconnects the socket + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + disconnect(code, data) { + const disconnectCode = code !== null && code !== void 0 ? code : NORMAL_CLOSE_CODE; + this._removeSocketListeners(); + if (this.getStatus() !== 'disconnected') { + this._closeSocketConnection(disconnectCode, data); + } + this._onDisconnect(disconnectCode, data); + } + /** + * Safely disconnects the socket, async and waits for request size to be 0 before disconnecting + * @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0 + * @param ms - Determines the ms of setInterval + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + safeDisconnect(code, data, forceDisconnect = false, ms = 1000) { + return __awaiter(this, void 0, void 0, function* () { + let retryAttempt = 0; + const checkQueue = () => __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => { + const interval = setInterval(() => { + if (forceDisconnect && retryAttempt === 5) { + this.clearQueues(); + } + if (this.getPendingRequestQueueSize() === 0 && this.getSentRequestsQueueSize() === 0) { + clearInterval(interval); + resolve(true); + } + retryAttempt += 1; + }, ms); + }); + }); + yield checkQueue(); + this.disconnect(code, data); + }); + } + /** + * Removes all listeners for the specified event type. + * @param type - The event type to remove the listeners for + */ + removeAllListeners(type) { + this._eventEmitter.removeAllListeners(type); + } + _onError(event) { + // do not emit error while trying to reconnect + if (this.isReconnecting) { + this._reconnect(); + } + else { + this._eventEmitter.emit('error', event); + } + } + /** + * Resets the socket, removing all listeners and pending requests + */ + reset() { + this._sentRequestsQueue.clear(); + this._pendingRequestsQueue.clear(); + this._init(); + this._removeSocketListeners(); + this._addSocketListeners(); + } + _reconnect() { + if (this.isReconnecting) { + return; + } + this.isReconnecting = true; + if (this._sentRequestsQueue.size > 0) { + this._sentRequestsQueue.forEach((request, key) => { + request.deferredPromise.reject(new PendingRequestsOnReconnectingError()); + this._sentRequestsQueue.delete(key); + }); + } + if (this._reconnectAttempts < this._reconnectOptions.maxAttempts) { + this._reconnectAttempts += 1; + setTimeout(() => { + this._removeSocketListeners(); + this.connect(); + this.isReconnecting = false; + }, this._reconnectOptions.delay); + } + else { + this.isReconnecting = false; + this._clearQueues(); + this._removeSocketListeners(); + this._eventEmitter.emit('error', new MaxAttemptsReachedOnReconnectingError(this._reconnectOptions.maxAttempts)); + } + } + /** + * Creates a request object to be sent to the server + */ + request(request) { + return __awaiter(this, void 0, void 0, function* () { + if (isNullish(this._socketConnection)) { + throw new Error('Connection is undefined'); + } + // if socket disconnected - open connection + if (this.getStatus() === 'disconnected') { + this.connect(); + } + const requestId = jsonRpc.isBatchRequest(request) + ? request[0].id + : request.id; + if (!requestId) { + throw new Web3WSProviderError('Request Id not defined'); + } + if (this._sentRequestsQueue.has(requestId)) { + throw new RequestAlreadySentError(requestId); + } + const deferredPromise = new Web3DeferredPromise(); + deferredPromise.catch(error => { + this._eventEmitter.emit('error', error); + }); + const reqItem = { + payload: request, + deferredPromise, + }; + if (this.getStatus() === 'connecting') { + this._pendingRequestsQueue.set(requestId, reqItem); + return reqItem.deferredPromise; + } + this._sentRequestsQueue.set(requestId, reqItem); + try { + this._sendToSocket(reqItem.payload); + } + catch (error) { + this._sentRequestsQueue.delete(requestId); + this._eventEmitter.emit('error', error); + } + return deferredPromise; + }); + } + _onConnect() { + this._connectionStatus = 'connected'; + this._reconnectAttempts = 0; + super._onConnect(); + this._sendPendingRequests(); + } + _sendPendingRequests() { + for (const [id, value] of this._pendingRequestsQueue.entries()) { + this._sendToSocket(value.payload); + this._pendingRequestsQueue.delete(id); + this._sentRequestsQueue.set(id, value); + } + } + _onMessage(event) { + const responses = this._parseResponses(event); + if (isNullish(responses) || responses.length === 0) { + return; + } + for (const response of responses) { + if (jsonRpc.isResponseWithNotification(response) && + response.method.endsWith('_subscription')) { + this._eventEmitter.emit('message', response); + return; + } + const requestId = jsonRpc.isBatchResponse(response) + ? response[0].id + : response.id; + const requestItem = this._sentRequestsQueue.get(requestId); + if (!requestItem) { + return; + } + if (jsonRpc.isBatchResponse(response) || + jsonRpc.isResponseWithResult(response) || + jsonRpc.isResponseWithError(response)) { + this._eventEmitter.emit('message', response); + requestItem.deferredPromise.resolve(response); + } + this._sentRequestsQueue.delete(requestId); + } + } + clearQueues(event) { + this._clearQueues(event); + } + _clearQueues(event) { + if (this._pendingRequestsQueue.size > 0) { + this._pendingRequestsQueue.forEach((request, key) => { + request.deferredPromise.reject(new ConnectionNotOpenError(event)); + this._pendingRequestsQueue.delete(key); + }); + } + if (this._sentRequestsQueue.size > 0) { + this._sentRequestsQueue.forEach((request, key) => { + request.deferredPromise.reject(new ConnectionNotOpenError(event)); + this._sentRequestsQueue.delete(key); + }); + } + this._removeSocketListeners(); + } +} +//# sourceMappingURL=socket_provider.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/socket_provider.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/socket_provider.js.map new file mode 100644 index 0000000..dfaaeb7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/socket_provider.js.map @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AAC,CAAC;YACxC,CAAC,CACD,CAAC;SACF;QAED,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC,EAAE;YACrC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAC9B,CAAC,OAAyC,EAAE,GAAc,EAAE,EAAE;gBAC7D,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,IAAI,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC;gBAClE,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACrC,CAAC,CACD,CAAC;SACF;QAED,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAC/B,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/string_manipulation.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/string_manipulation.js new file mode 100644 index 0000000..3d354e5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/string_manipulation.js @@ -0,0 +1,140 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { NibbleWidthError } from 'web3-errors'; +import { isHexStrict, validator, utils as validatorUtils, bigintPower } from 'web3-validator'; +import { numberToHex, toHex, toNumber } from './converters.js'; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * + * console.log(web3.utils.padLeft('0x123', 10)); + * >0x0000000123 + * ``` + */ +export const padLeft = (value, characterAmount, sign = '0') => { + // To avoid duplicate code and circular dependency we will + // use `padLeft` implementation from `web3-validator` + if (typeof value === 'string') { + if (!isHexStrict(value)) { + return value.padStart(characterAmount, sign); + } + return validatorUtils.padLeft(value, characterAmount, sign); + } + validator.validate(['int'], [value]); + return validatorUtils.padLeft(value, characterAmount, sign); +}; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * console.log(web3.utils.padRight('0x123', 10)); + * > 0x1230000000 + * + * console.log(web3.utils.padRight('0x123', 10, '1')); + * > 0x1231111111 + * ``` + */ +export const padRight = (value, characterAmount, sign = '0') => { + if (typeof value === 'string' && !isHexStrict(value)) { + return value.padEnd(characterAmount, sign); + } + validator.validate(['int'], [value]); + const hexString = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value); + const prefixLength = hexString.startsWith('-') ? 3 : 2; + return hexString.padEnd(characterAmount + prefixLength, sign); +}; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight` + */ +export const rightPad = padRight; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft` + */ +export const leftPad = padLeft; +/** + * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * + * @returns The hex string of the two’s complement. + * + * @example + * ```ts + * console.log(web3.utils.toTwosComplement(13, 32)); + * > 0x0000000000000000000000000000000d + * + * console.log(web3.utils.toTwosComplement('-0x1', 32)); + * > 0xffffffffffffffffffffffffffffffff + * + * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32)); + * > 0x00000000000000000020000000000000 + * ``` + */ +export const toTwosComplement = (value, nibbleWidth = 64) => { + validator.validate(['int'], [value]); + const val = toNumber(value); + if (val >= 0) + return padLeft(toHex(val), nibbleWidth); + const largestBit = bigintPower(BigInt(2), BigInt(nibbleWidth * 4)); + if (-val >= largestBit) { + throw new NibbleWidthError(`value: ${value}, nibbleWidth: ${nibbleWidth}`); + } + const updatedVal = BigInt(val); + const complement = updatedVal + largestBit; + return padLeft(numberToHex(complement), nibbleWidth); +}; +/** + * Converts the twos complement into a decimal number or big int. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * @returns The decimal number or big int. + * + * @example + * ```ts + * console.log(web3.utils.fromTwosComplement(''0x0000000000000000000000000000000d', 32')); + * > 13 + * + * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32)); + * > 9007199254740992n + * ``` + */ +export const fromTwosComplement = (value, nibbleWidth = 64) => { + validator.validate(['int'], [value]); + const val = toNumber(value); + if (val < 0) + return val; + const largestBit = Math.ceil(Math.log(Number(val)) / Math.log(2)); + if (largestBit > nibbleWidth * 4) + throw new NibbleWidthError(`value: "${value}", nibbleWidth: "${nibbleWidth}"`); + // check the largest bit to see if negative + if (nibbleWidth * 4 !== largestBit) + return val; + const complement = bigintPower(BigInt(2), BigInt(nibbleWidth) * BigInt(4)); + return toNumber(BigInt(val) - complement); +}; +//# sourceMappingURL=string_manipulation.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/string_manipulation.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/string_manipulation.js.map new file mode 100644 index 0000000..721c524 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/string_manipulation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string_manipulation.js","sourceRoot":"","sources":["../../src/string_manipulation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,IAAI,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ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AAC;IAErC,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAE5B,IAAI,GAAG,GAAG,CAAC;QAAE,OAAO,GAAG,CAAC;IAExB,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAElE,IAAI,UAAU,GAAG,WAAW,GAAG,CAAC;QAC/B,MAAM,IAAI,gBAAgB,CAAC,WAAW,KAAK,oBAAoB,WAAW,GAAG,CAAC,CAAC;IAEhF,2CAA2C;IAC3C,IAAI,WAAW,GAAG,CAAC,KAAK,UAAU;QAAE,OAAO,GAAG,CAAC;IAE/C,MAAM,UAAU,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3E,OAAO,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC;AAC3C,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/uint8array.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/uint8array.js new file mode 100644 index 0000000..b81e9d4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/uint8array.js @@ -0,0 +1,47 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export function uint8ArrayConcat(...parts) { + const length = parts.reduce((prev, part) => { + const agg = prev + part.length; + return agg; + }, 0); + const result = new Uint8Array(length); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.length; + } + return result; +} +/** + * Returns true if the two passed Uint8Arrays have the same content + */ +export function uint8ArrayEquals(a, b) { + if (a === b) { + return true; + } + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i += 1) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} +//# sourceMappingURL=uint8array.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/uint8array.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/uint8array.js.map new file mode 100644 index 0000000..37f06e4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/uint8array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uint8array.js","sourceRoot":"","sources":["../../src/uint8array.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,MAAM,UAAU,gBAAgB,CAAC,GAAG,KAAmB;IACtD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;QAC/B,OAAO,GAAG,CAAC;IACZ,CAAC,EAAE,CAAC,CAAC,CAAC;IACN,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACtC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACzB,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACzB,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC;KACtB;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,CAAa,EAAE,CAAa;IAC5D,IAAI,CAAC,KAAK,CAAC,EAAE;QACZ,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,CAAC,CAAC,UAAU,KAAK,CAAC,CAAC,UAAU,EAAE;QAClC,OAAO,KAAK,CAAC;KACb;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC,EAAE;QACzC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;YAClB,OAAO,KAAK,CAAC;SACb;KACD;IAED,OAAO,IAAI,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/uuid.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/uuid.js new file mode 100644 index 0000000..e47c359 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/uuid.js @@ -0,0 +1,50 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { bytesToHex } from './converters.js'; +import { randomBytes } from './random.js'; +/** + * Generate a version 4 (random) uuid + * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5 + * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx + * @example + * ```ts + * console.log(web3.utils.uuidV4()); + * > "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed" + * ``` + */ +export const uuidV4 = () => { + const bytes = randomBytes(16); + // https://github.com/ethers-io/ethers.js/blob/ce8f1e4015c0f27bf178238770b1325136e3351a/packages/json-wallets/src.ts/utils.ts#L54 + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + /* eslint-disable-next-line */ + bytes[6] = (bytes[6] & 0x0f) | 0x40; + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + /* eslint-disable-next-line */ + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hexString = bytesToHex(bytes); + return [ + hexString.substring(2, 10), + hexString.substring(10, 14), + hexString.substring(14, 18), + hexString.substring(18, 22), + hexString.substring(22, 34), + ].join('-'); +}; +//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/uuid.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/uuid.js.map new file mode 100644 index 0000000..c3dd5c3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../../src/uuid.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,GAAW,EAAE;IAClC,MAAM,KAAK,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;IAE9B,iIAAiI;IACjI,kBAAkB;IAClB,wCAAwC;IACxC,8BAA8B;IAC9B,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAEpC,cAAc;IACd,uCAAuC;IACvC,uCAAuC;IACvC,8BAA8B;IAC9B,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAEpC,MAAM,SAAS,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;IAEpC,OAAO;QACN,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;QAC1B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QAC3B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QAC3B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QAC3B,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;KAC3B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACb,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/validation.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/validation.js new file mode 100644 index 0000000..8fe3a95 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/validation.js @@ -0,0 +1,155 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { InvalidBlockError } from 'web3-errors'; +import { checkAddressCheckSum as checkAddressCheckSumValidator, isAddress as isAddressValidator, isBlockTag, isBloom as isBloomValidator, isContractAddressInBloom as isContractAddressInBloomValidator, isHex as isHexValidator, isHexStrict as isHexStrictValidator, isInBloom as isInBloomValidator, isNullish as isNullishValidator, isTopic as isTopicValidator, isTopicInBloom as isTopicInBloomValidator, isUserEthereumAddressInBloom as isUserEthereumAddressInBloomValidator, } from 'web3-validator'; +import { BlockTags } from 'web3-types'; +/** + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isHexStrict = isHexStrictValidator; +/** + * returns true if input is a hexstring, number or bigint + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isHex = isHexValidator; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const checkAddressCheckSum = checkAddressCheckSumValidator; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isAddress = isAddressValidator; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isBloom = isBloomValidator; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isInBloom = isInBloomValidator; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isUserEthereumAddressInBloom = isUserEthereumAddressInBloomValidator; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isContractAddressInBloom = isContractAddressInBloomValidator; +/** + * Checks if its a valid topic + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isTopic = isTopicValidator; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isTopicInBloom = isTopicInBloomValidator; +/** + * Compares between block A and block B + * @param blockA - Block number or string + * @param blockB - Block number or string + * + * @returns - Returns -1 if a \< b, returns 1 if a \> b and returns 0 if a == b + * + * @example + * ```ts + * console.log(web3.utils.compareBlockNumbers('latest', 'pending')); + * > -1 + * + * console.log(web3.utils.compareBlockNumbers(12, 11)); + * > 1 + * ``` + */ +export const compareBlockNumbers = (blockA, blockB) => { + const isABlockTag = typeof blockA === 'string' && isBlockTag(blockA); + const isBBlockTag = typeof blockB === 'string' && isBlockTag(blockB); + if (blockA === blockB || + ((blockA === 'earliest' || blockA === 0) && (blockB === 'earliest' || blockB === 0)) // only exception compare blocktag with number + ) { + return 0; + } + if (blockA === 'earliest' && blockB > 0) { + return -1; + } + if (blockB === 'earliest' && blockA > 0) { + return 1; + } + if (isABlockTag && isBBlockTag) { + // Increasing order: earliest, finalized , safe, latest, pending + const tagsOrder = { + [BlockTags.EARLIEST]: 1, + [BlockTags.FINALIZED]: 2, + [BlockTags.SAFE]: 3, + [BlockTags.LATEST]: 4, + [BlockTags.PENDING]: 5, + }; + if (tagsOrder[blockA] < tagsOrder[blockB]) { + return -1; + } + return 1; + } + if ((isABlockTag && !isBBlockTag) || (!isABlockTag && isBBlockTag)) { + throw new InvalidBlockError('Cannot compare blocktag with provided non-blocktag input.'); + } + const bigIntA = BigInt(blockA); + const bigIntB = BigInt(blockB); + if (bigIntA < bigIntB) { + return -1; + } + if (bigIntA === bigIntB) { + return 0; + } + return 1; +}; +export const isContractInitOptions = (options) => typeof options === 'object' && + !isNullishValidator(options) && + Object.keys(options).length !== 0 && + [ + 'input', + 'data', + 'from', + 'gas', + 'gasPrice', + 'gasLimit', + 'address', + 'jsonInterface', + 'syncWithContext', + 'dataInputFill', + ].some(key => key in options); +export const isNullish = isNullishValidator; +//# sourceMappingURL=validation.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/validation.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/validation.js.map new file mode 100644 index 0000000..2dbcd13 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/validation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/validation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EACN,oBAAoB,IAAI,6BAA6B,EACrD,SAAS,IAAI,kBAAkB,EAC/B,UAAU,EACV,O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OAAO,KAAK,OAAO,EAAE;QACxB,OAAO,CAAC,CAAC;KACT;IACD,OAAO,CAAC,CAAC;AACV,CAAC,CAAC;AAGF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,OAAgB,EAAkC,EAAE,CACzF,OAAO,OAAO,KAAK,QAAQ;IAC3B,CAAC,kBAAkB,CAAC,OAAO,CAAC;IAC5B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC;IACjC;QACC,OAAO;QACP,MAAM;QACN,MAAM;QACN,KAAK;QACL,UAAU;QACV,UAAU;QACV,SAAS;QACT,eAAe;QACf,iBAAiB;QACjB,eAAe;KACf,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,OAAO,CAAC,CAAC;AAE/B,MAAM,CAAC,MAAM,SAAS,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_deferred_promise.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_deferred_promise.js new file mode 100644 index 0000000..a3d3901 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_deferred_promise.js @@ -0,0 +1,137 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +import { OperationTimeoutError } from 'web3-errors'; +/** + * The class is a simple implementation of a deferred promise with optional timeout functionality, + * which can be useful when dealing with asynchronous tasks. + * + */ +export class Web3DeferredPromise { + /** + * + * @param timeout - (optional) The timeout in milliseconds. + * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created. + * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out. + */ + constructor({ timeout, eagerStart, timeoutMessage, } = { + timeout: 0, + eagerStart: false, + timeoutMessage: 'DeferredPromise timed out', + }) { + // public tag to treat object as promise by different libs + // eslint-disable-next-line @typescript-eslint/prefer-as-const + this[_a] = 'Promise'; + this._state = 'pending'; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + this._timeoutMessage = timeoutMessage; + this._timeoutInterval = timeout; + if (eagerStart) { + this.startTimer(); + } + } + /** + * Returns the current state of the promise. + * @returns 'pending' | 'fulfilled' | 'rejected' + */ + get state() { + return this._state; + } + /** + * + * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled. + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + then(onfulfilled, onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.then(onfulfilled, onrejected); + }); + } + /** + * + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + catch( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onrejected) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.catch(onrejected); + }); + } + /** + * + * @param onfinally - (optional) The callback to execute when the promise is settled (fulfilled or rejected). + * @returns + */ + finally(onfinally) { + return __awaiter(this, void 0, void 0, function* () { + return this._promise.finally(onfinally); + }); + } + /** + * Resolves the current promise. + * @param value - The value to resolve the promise with. + */ + resolve(value) { + this._resolve(value); + this._state = 'fulfilled'; + this._clearTimeout(); + } + /** + * Rejects the current promise. + * @param reason - The reason to reject the promise with. + */ + reject(reason) { + this._reject(reason); + this._state = 'rejected'; + this._clearTimeout(); + } + /** + * Starts the timeout timer for the promise. + */ + startTimer() { + if (this._timeoutInterval && this._timeoutInterval > 0) { + this._timeoutId = setTimeout(this._checkTimeout.bind(this), this._timeoutInterval); + } + } + _checkTimeout() { + if (this._state === 'pending' && this._timeoutId) { + this.reject(new OperationTimeoutError(this._timeoutMessage)); + } + } + _clearTimeout() { + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + } +} +_a = Symbol.toStringTag; +//# sourceMappingURL=web3_deferred_promise.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_deferred_promise.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_deferred_promise.js.map new file mode 100644 index 0000000..5723183 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_deferred_promise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_deferred_promise.js","sourceRoot":"","sources":["../../src/web3_deferred_promise.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;AAEF,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAIpD;;;;GAIG;AACH,MAAM,OAAO,mBAAmB;IAa/B;;;;;OAKG;IACH,YACC,EACC,OAAO,EACP,UAAU,EACV,cAAc,MACuD;QACrE,OAAO,EAAE,CAAC;QACV,UAAU,EAAE,KAAK;QACjB,cAAc,EAAE,2BAA2B;KAC3C;QA3BF,0DAA0D;QAC1D,8DAA8D;QACvD,QAAoB,GAAc,SAAS,CAAC;QAK3C,WAAM,GAAyC,SAAS,CAAC;QAsBhE,IAAI,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;YACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACvB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AAI,CAAC,gBAAgB,CAAC,CAAC;SACnF;IACF,CAAC;IAEO,aAAa;QACpB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,UAAU,EAAE;YACjD,IAAI,CAAC,MAAM,CAAC,IAAI,qBAAqB,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;SAC7D;IACF,CAAC;IAEO,aAAa;QACpB,IAAI,IAAI,CAAC,UAAU,EAAE;YACpB,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;SAC9B;IACF,CAAC;CACD;KAvHQ,MAAM,CAAC,WAAW"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_eip1193_provider.js b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_eip1193_provider.js new file mode 100644 index 0000000..61978aa --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_eip1193_provider.js @@ -0,0 +1,105 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3BaseProvider, } from 'web3-types'; +import { EventEmitter } from 'events'; +import { EIP1193ProviderRpcError } from 'web3-errors'; +import { toPayload } from './json_rpc.js'; +/** + * This is an abstract class, which extends {@link Web3BaseProvider} class. This class is used to implement a provider that adheres to the EIP-1193 standard for Ethereum providers. + */ +export class Eip1193Provider extends Web3BaseProvider { + constructor() { + super(...arguments); + this._eventEmitter = new EventEmitter(); + this._chainId = ''; + this._accounts = []; + } + _getChainId() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const data = yield this.request(toPayload({ + method: 'eth_chainId', + params: [], + })); + return (_a = data === null || data === void 0 ? void 0 : data.result) !== null && _a !== void 0 ? _a : ''; + }); + } + _getAccounts() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const data = yield this.request(toPayload({ + method: 'eth_accounts', + params: [], + })); + return (_a = data === null || data === void 0 ? void 0 : data.result) !== null && _a !== void 0 ? _a : []; + }); + } + _onConnect() { + Promise.all([ + this._getChainId() + .then(chainId => { + if (chainId !== this._chainId) { + this._chainId = chainId; + this._eventEmitter.emit('chainChanged', this._chainId); + } + }) + .catch(err => { + // todo: add error handler + console.error(err); + }), + this._getAccounts() + .then(accounts => { + if (!(this._accounts.length === accounts.length && + accounts.every(v => accounts.includes(v)))) { + this._accounts = accounts; + this._onAccountsChanged(); + } + }) + .catch(err => { + // todo: add error handler + // eslint-disable-next-line no-console + console.error(err); + }), + ]) + .then(() => this._eventEmitter.emit('connect', { + chainId: this._chainId, + })) + .catch(err => { + // todo: add error handler + // eslint-disable-next-line no-console + console.error(err); + }); + } + // todo this must be ProvideRpcError with a message too + _onDisconnect(code, data) { + this._eventEmitter.emit('disconnect', new EIP1193ProviderRpcError(code, data)); + } + _onAccountsChanged() { + // get chainId and safe to local + this._eventEmitter.emit('accountsChanged', this._accounts); + } +} +//# sourceMappingURL=web3_eip1193_provider.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_eip1193_provider.js.map b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_eip1193_provider.js.map new file mode 100644 index 0000000..c7d1700 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/esm/web3_eip1193_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eip1193_provider.js","sourceRoot":"","sources":["../../src/web3_eip1193_provider.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,OAAO,EAON,gBAAgB,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C;;GAEG;AACH,MAAM,OAAgB,eAEpB,SAAQ,gBAAqB;IAF/B;;QAGoB,kBAAa,GAAiB,IAAI,YAAY,EAAE,CAAC;QAC5D,aAAQ,GAAc,EAAE,CAAC;QACzB,cAAS,GAAgB,EAAE,CAAC;IA8ErC,CAAC;IA5Ec,WAAW;;;YACxB,MAAM,IAAI,GAAG,MAAO,IAA8B,CAAC,OAAO,CAIzD,SAAS,CAAC;gBACT,MAAM,EAAE,aAAa;gBACrB,MAAM,EAAE,EAAE;aACV,CAA4C,CAC7C,CAAC;YACF,OAAO,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,mCAAI,EAAE,CAAC;;KAC1B;IAEa,YAAY;;;YACzB,MAAM,IAAI,GAAG,MAAO,IAA8B,CAAC,OAAO,CACzD,SAAS,CAAC;gBACT,MAAM,EAAE,cAAc;gBACtB,MAAM,EAAE,EAAE;aACV,CAA4C,CAC7C,CAAC;YACF,OAAO,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,mCAAI,EAAE,CAAC;;KAC1B;IAES,UAAU;QACnB,OAAO,CAAC,GAAG,CAAC;YACX,IAAI,CAAC,WAAW,EAAE;iBAChB,IAAI,CAAC,OAAO,CAAC,EAAE;gBACf,IAAI,OAAO,KAAK,IAAI,CAAC,QAAQ,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AAC,CAAC;IAChF,CAAC;IAEO,kBAAkB;QACzB,gCAAgC;QAChC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/chunk_response_parser.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/chunk_response_parser.d.ts new file mode 100644 index 0000000..93f318d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/chunk_response_parser.d.ts @@ -0,0 +1,15 @@ +/// +import { JsonRpcResponse } from 'web3-types'; +import { EventEmitter } from 'events'; +export declare class ChunkResponseParser { + private lastChunk; + private lastChunkTimeout; + private _clearQueues; + private readonly eventEmitter; + private readonly autoReconnect; + constructor(eventEmitter: EventEmitter, autoReconnect: boolean); + private clearQueues; + onError(clearQueues?: () => void): void; + parseResponse(data: string): JsonRpcResponse[]; +} +//# sourceMappingURL=chunk_response_parser.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/chunk_response_parser.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/chunk_response_parser.d.ts.map new file mode 100644 index 0000000..18371b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/chunk_response_parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk_response_parser.d.ts","sourceRoot":"","sources":["../../src/chunk_response_parser.ts"],"names":[],"mappings":";AAgBA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,qBAAa,mBAAmB;IAC/B,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,gBAAgB,CAAsB;IAC9C,OAAO,CAAC,YAAY,CAA2B;IAC/C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAe;IAC5C,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAU;gBAErB,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,OAAO;IAIrE,OAAO,CAAC,WAAW;IAMZ,OAAO,CAAC,WAAW,CAAC,EAAE,MAAM,IAAI;IAIhC,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,EAAE;CAsDrD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/converters.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/converters.d.ts new file mode 100644 index 0000000..3605701 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/converters.d.ts @@ -0,0 +1,280 @@ +import { utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { Address, Bytes, HexString, Numbers, ValueTypes } from 'web3-types'; +/** @internal */ +export declare const ethUnitMap: { + noether: bigint; + wei: bigint; + kwei: bigint; + Kwei: bigint; + babbage: bigint; + femtoether: bigint; + mwei: bigint; + Mwei: bigint; + lovelace: bigint; + picoether: bigint; + gwei: bigint; + Gwei: bigint; + shannon: bigint; + nanoether: bigint; + nano: bigint; + szabo: bigint; + microether: bigint; + micro: bigint; + finney: bigint; + milliether: bigint; + milli: bigint; + ether: bigint; + kether: bigint; + grand: bigint; + mether: bigint; + gether: bigint; + tether: bigint; +}; +export declare type EtherUnits = keyof typeof ethUnitMap; +/** + * Convert a value from bytes to Uint8Array + * @param data - Data to be converted + * @returns - The Uint8Array representation of the input data + * + * @example + * ```ts + * console.log(web3.utils.bytesToUint8Array("0xab"))); + * > Uint8Array(1) [ 171 ] + * ``` + */ +export declare const bytesToUint8Array: (data: Bytes) => Uint8Array | never; +/** + * Convert a byte array to a hex string + * @param bytes - Byte array to be converted + * @returns - The hex string representation of the input byte array + * + * @example + * ```ts + * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12]))); + * > "0x480c" + * + */ +export declare const bytesToHex: (bytes: Bytes) => HexString; +/** + * Convert a hex string to a byte array + * @param hex - Hex string to be converted + * @returns - The byte array representation of the input hex string + * + * @example + * ```ts + * console.log(web3.utils.hexToBytes('0x74657374')); + * > Uint8Array(4) [ 116, 101, 115, 116 ] + * ``` + */ +export declare const hexToBytes: (bytes: HexString) => Uint8Array; +/** + * Converts value to it's number representation + * @param value - Hex string to be converted + * @returns - The number representation of the input value + * + * @example + * ```ts + * conoslle.log(web3.utils.hexToNumber('0xa')); + * > 10 + * ``` + */ +export declare const hexToNumber: (value: HexString) => bigint | number; +/** + * Converts value to it's number representation @alias `hexToNumber` + */ +export declare const toDecimal: (value: HexString) => bigint | number; +/** + * Converts value to it's hex representation + * @param value - Value to be converted + * @param hexstrict - Add padding to converted value if odd, to make it hexstrict + * @returns - The hex representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.numberToHex(10)); + * > "0xa" + * ``` + */ +export declare const numberToHex: (value: Numbers, hexstrict?: boolean) => HexString; +/** + * Converts value to it's hex representation @alias `numberToHex` + * + */ +export declare const fromDecimal: (value: Numbers, hexstrict?: boolean) => HexString; +/** + * Converts value to it's decimal representation in string + * @param value - Hex string to be converted + * @returns - The decimal representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.hexToNumberString('0xa')); + * > "10" + * ``` + */ +export declare const hexToNumberString: (data: HexString) => string; +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * @param str - Utf8 string to be converted + * @returns - The hex representation of the input string + * + * @example + * ```ts + * console.log(utf8ToHex('web3.js')); + * > "0x776562332e6a73" + * + */ +export declare const utf8ToHex: (str: string) => HexString; +/** + * @alias utf8ToHex + */ +export declare const fromUtf8: (str: string) => HexString; +/** + * @alias utf8ToHex + */ +export declare const stringToHex: (str: string) => HexString; +/** + * Should be called to get utf8 from it's hex representation + * @param str - Hex string to be converted + * @returns - Utf8 string + * + * @example + * ```ts + * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export declare const hexToUtf8: (str: HexString) => string; +/** + * @alias hexToUtf8 + */ +export declare const toUtf8: (input: HexString | Uint8Array) => string; +export declare const utf8ToBytes: typeof ecUtf8ToBytes; +/** + * @alias hexToUtf8 + */ +export declare const hexToString: (str: HexString) => string; +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * @param str - String to be converted to hex + * @returns - Hex string + * + * @example + * ```ts + * console.log(web3.utils.asciiToHex('Hello World')); + * > 0x48656c6c6f20576f726c64 + * ``` + */ +export declare const asciiToHex: (str: string) => HexString; +/** + * @alias asciiToHex + */ +export declare const fromAscii: (str: string) => HexString; +/** + * Should be called to get ascii from it's hex representation + * @param str - Hex string to be converted to ascii + * @returns - Ascii string + * + * @example + * ```ts + * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export declare const hexToAscii: (str: HexString) => string; +/** + * @alias hexToAscii + */ +export declare const toAscii: (str: HexString) => string; +/** + * Auto converts any given value into it's hex representation. + * @param value - Value to be converted to hex + * @param returnType - If true, it will return the type of the value + * + * @example + * ```ts + * console.log(web3.utils.toHex(10)); + * > 0xa + * + * console.log(web3.utils.toHex('0x123', true)); + * > bytes + *``` + */ +export declare const toHex: (value: Numbers | Bytes | Address | boolean | object, returnType?: boolean) => HexString | ValueTypes; +/** + * Converts any given value into it's number representation, if possible, else into it's bigint representation. + * @param value - The value to convert + * @returns - Returns the value in number or bigint representation + * + * @example + * ```ts + * console.log(web3.utils.toNumber(1)); + * > 1 + * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER)); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER))); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1))); + * > 9007199254740992n + * + * ``` + */ +export declare const toNumber: (value: Numbers) => number | bigint; +/** + * Auto converts any given value into it's bigint representation + * + * @param value - The value to convert + * @returns - Returns the value in bigint representation + + * @example + * ```ts + * console.log(web3.utils.toBigInt(1)); + * > 1n + * ``` + */ +export declare const toBigInt: (value: unknown) => bigint; +/** + * Takes a number of wei and converts it to any other ether unit. + * @param number - The value in wei + * @param unit - The unit to convert to + * @returns - Returns the converted value in the given unit + * + * @example + * ```ts + * console.log(web3.utils.fromWei("1", "ether")); + * > 0.000000000000000001 + * + * console.log(web3.utils.fromWei("1", "shannon")); + * > 0.000000001 + * ``` + */ +export declare const fromWei: (number: Numbers, unit: EtherUnits) => string; +/** + * Takes a number of a unit and converts it to wei. + * + * @param number - The number to convert. + * @param unit - {@link EtherUnits} The unit of the number passed. + * @returns The number converted to wei. + * + * @example + * ```ts + * console.log(web3.utils.toWei("0.001", "ether")); + * > 1000000000000000 //(wei) + * ``` + */ +export declare const toWei: (number: Numbers, unit: EtherUnits) => string; +/** + * Will convert an upper or lowercase Ethereum address to a checksum address. + * @param address - An address string + * @returns The checksum address + * @example + * ```ts + * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d'); + * > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" + * ``` + */ +export declare const toChecksumAddress: (address: Address) => string; +export declare const toBool: (value: boolean | string | number | unknown) => boolean; +//# sourceMappingURL=converters.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/converters.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/converters.d.ts.map new file mode 100644 index 0000000..ad78c30 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/converters.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"converters.d.ts","sourceRoot":"","sources":["../../src/converters.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAe,WAAW,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC3F,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAuB5E,gBAAgB;AAChB,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtB,CAAC;AAEF,oBAAY,UAAU,G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G,SASxC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,QAdU,MAAM,KAAG,SAcN,CAAC;AAEpC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU,QAAS,SAAS,KAAG,MAG3C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,OAAO,QARY,SAAS,KAAG,MAQX,CAAC;AAElC;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,KAAK,UACV,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,eACtC,OAAO,KAClB,SAAS,GAAG,UAyCd,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,QAAQ,UAAW,OAAO,KAAG,MAAM,GAAG,MAoBlD,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,UAAW,OAAO,KAAG,MAkBzC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,WAAY,OAAO,QAAQ,UAAU,KAAG,MA0C3D,CAAC;AAEF;;;;;;;;;;;;GAYG;AAEH,eAAO,MAAM,KAAK,WAAY,OAAO,QAAQ,UAAU,KAAG,MAsCzD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,iBAAiB,YAAa,OAAO,KAAG,MA4BpD,CAAC;AAEF,eAAO,MAAM,MAAM,UAAW,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,KAAG,OAgCnE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/event_emitter.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/event_emitter.d.ts new file mode 100644 index 0000000..6846a3e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/event_emitter.d.ts @@ -0,0 +1,7 @@ +/// +import { EventEmitter as EventEmitterAtNode } from 'events'; +declare let EventEmitterType: typeof EventEmitterAtNode; +export declare class EventEmitter extends EventEmitterType { +} +export {}; +//# sourceMappingURL=event_emitter.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/event_emitter.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/event_emitter.d.ts.map new file mode 100644 index 0000000..b19fb31 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/event_emitter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"event_emitter.d.ts","sourceRoot":"","sources":["../../src/event_emitter.ts"],"names":[],"mappings":";AAkBA,OAAO,EAAE,YAAY,IAAI,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAoG5D,QAAA,IAAI,gBAAgB,EAAE,OAAO,kBAAkB,CAAC;AAShD,qBAAa,YAAa,SAAQ,gBAAgB;CAAG"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/formatter.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/formatter.d.ts new file mode 100644 index 0000000..1c5d0c4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/formatter.d.ts @@ -0,0 +1,23 @@ +import { DataFormat, FormatType } from 'web3-types'; +import { JsonSchema, ValidationSchemaInput } from 'web3-validator'; +export declare const isDataFormat: (dataFormat: unknown) => dataFormat is DataFormat; +/** + * Converts a value depending on the format + * @param value - value to convert + * @param ethType - The type of the value to be parsed + * @param format - The format to be converted to + * @returns - The value converted to the specified format + */ +export declare const convertScalarValue: (value: unknown, ethType: string, format: DataFormat) => unknown; +/** + * Converts the data to the specified format + * @param data - data to convert + * @param schema - The JSON schema that describes the structure of the data + * @param dataPath - A string array that specifies the path to the data within the JSON schema + * @param format - The format to be converted to + * @param oneOfPath - An optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns - The data converted to the specified format + */ +export declare const convert: (data: Record | unknown[] | unknown, schema: JsonSchema, dataPath: string[], format: DataFormat, oneOfPath?: [string, number][]) => unknown; +export declare const format: (schema: ValidationSchemaInput | JsonSchema, data: DataType, returnFormat: ReturnType_1) => FormatType; +//# sourceMappingURL=formatter.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/formatter.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/formatter.d.ts.map new file mode 100644 index 0000000..2722127 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/formatter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"formatter.d.ts","sourceRoot":"","sources":["../../src/formatter.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAS,UAAU,EAAyB,UAAU,EAAE,MAAM,YAAY,CAAC;AAClF,OAAO,EAAuB,UAAU,EAAS,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAQ/F,eAAO,MAAM,YAAY,eAAgB,OAAO,6BAI1B,CAAC;AAwDvB;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,UAAW,OAAO,WAAW,MAAM,UAAU,UAAU,YA8CrF,CAAC;AACF;;;;;;;;GAQG;AACH,eAAO,MAAM,OAAO,SACb,OAAO,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,EAAE,GAAG,OAAO,UAC3C,UAAU,YACR,MAAM,EAAE,UACV,UAAU,cACP,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,YAqH7B,CAAC;AAEF,eAAO,MAAM,MAAM,sEAIV,qBAAqB,GAAG,UAAU,mFAyB1C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/hash.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/hash.d.ts new file mode 100644 index 0000000..f90ad18 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/hash.d.ts @@ -0,0 +1,95 @@ +import { Bytes, Numbers, Sha3Input, TypedObject, TypedObjectAbbreviated } from 'web3-types'; +/** + * computes the Keccak-256 hash of the input and returns a hexstring + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.sha3('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3('')); + * > undefined + * ``` + */ +export declare const sha3: (data: Bytes) => string | undefined; +/** + * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed. + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * conosle.log(web3.utils.sha3Raw('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3Raw('')); + * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 + * ``` + */ +export declare const sha3Raw: (data: Bytes) => string; +/** + * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array` + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.keccak256Wrapper('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.keccak256Wrapper(1)); + * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6 + * + * console.log(web3.utils.keccak256Wrapper(0xaf12fd)); + * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c + * ``` + */ +export declare const keccak256Wrapper: (data: Bytes | Numbers | string | ReadonlyArray) => string; +export { keccak256Wrapper as keccak256 }; +/** + * returns a string of the tightly packed value given based on the type + * @param arg - the input to return the tightly packed value + * @returns - the tightly packed value + */ +export declare const processSolidityEncodePackedArgs: (arg: Sha3Input) => string; +/** + * Encode packed arguments to a hexstring + */ +export declare const encodePacked: (...values: Sha3Input[]) => string; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, or null if input is empty + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log([{ type: 'string', value: '31323334' }]); + * console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" })); + * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b + * ``` + */ +export declare const soliditySha3: (...values: Sha3Input[]) => string | undefined; +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" })) + * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0 + * ``` + */ +export declare const soliditySha3Raw: (...values: TypedObject[] | TypedObjectAbbreviated[]) => string; +/** + * Get slot number for storage long string in contract. Basically for getStorage method + * returns slotNumber where will data placed + * @param mainSlotNumber - the slot number where will be stored hash of long string + * @returns - the slot number where will be stored long string + */ +export declare const getStorageSlotNumForLongString: (mainSlotNumber: number | string) => string | undefined; +//# sourceMappingURL=hash.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/hash.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/hash.d.ts.map new file mode 100644 index 0000000..3975aaf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/hash.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../../src/hash.ts"],"names":[],"mappings":"AAgCA,OAAO,EACN,KAAK,EAEL,OAAO,EACP,SAAS,EACT,WAAW,EACX,sBAAsB,EACtB,MAAM,YAAY,CAAC;AAgBpB;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,IAAI,SAAU,KAAK,KAAG,MAAM,GAAG,SAgB3C,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,OAAO,SAAU,KAAK,KAAG,MAOrC,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,gBAAgB,SACtB,KAAK,GAAG,OAAO,GAAG,MAAM,GAAG,cAAc,MAAM,CAAC,KACpD,MAYF,CAAC;AAEF,OAAO,EAAE,gBAAgB,IAAI,SAAS,EAAE,CAAC;AAsKzC;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,QAAS,SAAS,KAAG,MAYhE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,cAAe,SAAS,EAAE,KAAG,MAGrD,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,cAAe,SAAS,EAAE,KAAG,MAAM,GAAG,SACjC,CAAC;AAE/B;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,cAAe,WAAW,EAAE,GAAG,sBAAsB,EAAE,KAAG,MACrD,CAAC;AAElC;;;;;GAKG;AACH,eAAO,MAAM,8BAA8B,mBAAoB,MAAM,GAAG,MAAM,uBAM5E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/index.d.ts new file mode 100644 index 0000000..b3e923d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/index.d.ts @@ -0,0 +1,18 @@ +export * from './converters.js'; +export * from './event_emitter.js'; +export * from './validation.js'; +export * from './formatter.js'; +export * from './hash.js'; +export * from './random.js'; +export * from './string_manipulation.js'; +export * from './objects.js'; +export * from './promise_helpers.js'; +export * from './json_rpc.js'; +export * as jsonRpc from './json_rpc.js'; +export * from './web3_deferred_promise.js'; +export * from './chunk_response_parser.js'; +export * from './uuid.js'; +export * from './web3_eip1193_provider.js'; +export * from './socket_provider.js'; +export * from './uint8array.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/index.d.ts.map new file mode 100644 index 0000000..89851ed --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,cAAc,sBAAsB,CAAC;AACrC,cAAc,eAAe,CAAC;AAC9B,OAAO,KAAK,OAAO,MAAM,eAAe,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,WAAW,CAAC;AAC1B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/json_rpc.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/json_rpc.d.ts new file mode 100644 index 0000000..725a7b8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/json_rpc.d.ts @@ -0,0 +1,22 @@ +import { JsonRpcPayload, JsonRpcResponse, JsonRpcResponseWithResult, JsonRpcResponseWithError, JsonRpcOptionalRequest, JsonRpcBatchRequest, JsonRpcNotification, JsonRpcRequest, JsonRpcBatchResponse, JsonRpcSubscriptionResult } from 'web3-types'; +export declare const isResponseRpcError: (rpcError: JsonRpcResponseWithError) => boolean; +export declare const isResponseWithResult: (response: JsonRpcResponse) => response is JsonRpcResponseWithResult; +export declare const isResponseWithError: (response: JsonRpcResponse) => response is JsonRpcResponseWithError; +export declare const isResponseWithNotification: (response: JsonRpcNotification | JsonRpcSubscriptionResult) => response is JsonRpcNotification; +export declare const isSubscriptionResult: (response: JsonRpcSubscriptionResult | JsonRpcNotification) => response is JsonRpcSubscriptionResult; +export declare const validateResponse: (response: JsonRpcResponse) => boolean; +export declare const isValidResponse: (response: JsonRpcResponse) => boolean; +export declare const isBatchResponse: (response: JsonRpcResponse) => response is JsonRpcBatchResponse; +/** + * Optionally use to make the jsonrpc `id` start from a specific number. + * Without calling this function, the `id` will be filled with a Uuid. + * But after this being called with a number, the `id` will be a number staring from the provided `start` variable. + * However, if `undefined` was passed to this function, the `id` will be a Uuid again. + * @param start - a number to start incrementing from. + * Or `undefined` to use a new Uuid (this is the default behavior) + */ +export declare const setRequestIdStart: (start: number | undefined) => void; +export declare const toPayload: (request: JsonRpcOptionalRequest) => JsonRpcPayload; +export declare const toBatchPayload: (requests: JsonRpcOptionalRequest[]) => JsonRpcBatchRequest; +export declare const isBatchRequest: (request: JsonRpcBatchRequest | JsonRpcRequest | JsonRpcOptionalRequest) => request is JsonRpcBatchRequest; +//# sourceMappingURL=json_rpc.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/json_rpc.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/json_rpc.d.ts.map new file mode 100644 index 0000000..0984ebc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/json_rpc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json_rpc.d.ts","sourceRoot":"","sources":["../../src/json_rpc.ts"],"names":[],"mappings":"AAkBA,OAAO,EACN,cAAc,EACd,eAAe,EACf,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,oBAAoB,EACpB,yBAAyB,EACzB,MAAM,YAAY,CAAC;AAKpB,eAAO,MAAM,kBAAkB,aAAc,wBAAwB,YAGpE,CAAC;AAEF,eAAO,MAAM,oBAAoB,oIASoC,CAAC;AAGtE,eAAO,MAAM,mBAAmB,oIASqC,CAAC;AAEtE,eAAO,MAAM,0BAA0B,wHAOX,CAAC;AAE7B,eAAO,MAAM,oBAAoB,sHAQZ,CAAC;AAEtB,eAAO,MAAM,gBAAgB,uFAE1B,OAAyF,CAAC;AAE7F,eAAO,MAAM,eAAe,uFAEzB,OACqF,CAAC;AAEzF,eAAO,MAAM,eAAe,wIAGgD,CAAC;AAK7E;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,UAAW,MAAM,GAAG,SAAS,SAE1D,CAAC;AAEF,eAAO,MAAM,SAAS,kGAYrB,CAAC;AAEF,eAAO,MAAM,cAAc,aAAc,uBAAuB,OAAO,CAAC,EAAE,wBACE,CAAC;AAE7E,eAAO,MAAM,cAAc,YACjB,mBAAmB,GAAG,eAAe,OAAO,CAAC,GAAG,uBAAuB,OAAO,CAAC,mCACR,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/objects.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/objects.d.ts new file mode 100644 index 0000000..51a1329 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/objects.d.ts @@ -0,0 +1,8 @@ +/** + * Deep merge two objects. + * @param destination - The destination object. + * @param sources - An array of source objects. + * @returns - The merged object. + */ +export declare const mergeDeep: (destination: Record, ...sources: Record[]) => Record; +//# sourceMappingURL=objects.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/objects.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/objects.d.ts.map new file mode 100644 index 0000000..a679407 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/objects.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"objects.d.ts","sourceRoot":"","sources":["../../src/objects.ts"],"names":[],"mappings":"AA4BA;;;;;GAKG;AACH,eAAO,MAAM,SAAS,gBACR,OAAO,MAAM,EAAE,OAAO,CAAC,cACxB,OAAO,MAAM,EAAE,OAAO,CAAC,EAAE,KACnC,OAAO,MAAM,EAAE,OAAO,CA0BxB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/promise_helpers.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/promise_helpers.d.ts new file mode 100644 index 0000000..97c1e9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/promise_helpers.d.ts @@ -0,0 +1,48 @@ +export declare type Timer = ReturnType; +export declare type Timeout = ReturnType; +/** + * An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser. + * @param object - to check if it is a `Promise` + * @returns `true` if it is an `object` or a `function` that has a `then` function. And returns `false` otherwise. + */ +export declare function isPromise(object: unknown): boolean; +export declare type AsyncFunction = (...args: K[]) => Promise; +export declare function waitWithTimeout(awaitable: Promise | AsyncFunction, timeout: number, error: Error): Promise; +export declare function waitWithTimeout(awaitable: Promise | AsyncFunction, timeout: number): Promise; +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. It returns promise and intervalId. + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export declare function pollTillDefinedAndReturnIntervalId(func: AsyncFunction, interval: number): [Promise>, Timer]; +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. + * pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result. + * This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId(). + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export declare function pollTillDefined(func: AsyncFunction, interval: number): Promise>; +/** + * Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete + * @param timeout - The timeout to enforced in milliseconds. + * @param error - The error to throw if the timeout is reached. + * @returns A tuple of the timeout id and the promise that will be rejected if the timeout is reached. + * + * @example + * ```ts + * const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out')); + * ``` + */ +export declare function rejectIfTimeout(timeout: number, error: Error): [Timer, Promise]; +/** + * Sets an interval that repeatedly executes the given cond function with the specified interval between each call. + * If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned. + * @param cond - The function/confition to call. + * @param interval - The interval in milliseconds. + * @returns - an array with the interval ID and the Promise. + */ +export declare function rejectIfConditionAtInterval(cond: AsyncFunction, interval: number): [Timer, Promise]; +//# sourceMappingURL=promise_helpers.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/promise_helpers.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/promise_helpers.d.ts.map new file mode 100644 index 0000000..1f95027 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/promise_helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise_helpers.d.ts","sourceRoot":"","sources":["../../src/promise_helpers.ts"],"names":[],"mappings":"AAmBA,oBAAY,KAAK,GAAG,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;AACnD,oBAAY,OAAO,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;AAGpD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAMlD;AAED,oBAAY,aAAa,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;AAEzE,wBAAgB,eAAe,CAAC,CAAC,EAChC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,EACxC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,KAAK,GACV,OAAO,CAAC,CAAC,CAAC,CAAC;AACd,wBAAgB,eAAe,CAAC,CAAC,EAChC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,EACxC,OAAO,EAAE,MAAM,GACb,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;AA+B1B;;;;;GAKG;AACH,wBAAgB,kCAAkC,CAAC,CAAC,EACnD,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EACtB,QAAQ,EAAE,MAAM,GACd,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAuBzC;AAED;;;;;;;GAOG;AACH,wBAAsB,eAAe,CAAC,CAAC,EACtC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EACtB,QAAQ,EAAE,MAAM,GACd,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAEhC;AACD;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAQtF;AACD;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CAAC,CAAC,EAC5C,IAAI,EAAE,aAAa,CAAC,CAAC,GAAG,SAAS,CAAC,EAClC,QAAQ,EAAE,MAAM,GACd,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAczB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/random.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/random.d.ts new file mode 100644 index 0000000..f453c3b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/random.d.ts @@ -0,0 +1,29 @@ +/** + * Returns a random byte array by the given bytes size + * @param size - The size of the random byte array returned + * @returns - random byte array + * + * @example + * ```ts + * console.log(web3.utils.randomBytes(32)); + * > Uint8Array(32) [ + * 93, 172, 226, 32, 33, 176, 156, 156, + * 182, 30, 240, 2, 69, 96, 174, 197, + * 33, 136, 194, 241, 197, 156, 110, 111, + * 66, 87, 17, 88, 67, 48, 245, 183 + * ] + * ``` + */ +export declare const randomBytes: (size: number) => Uint8Array; +/** + * Returns a random hex string by the given bytes size + * @param byteSize - The size of the random hex string returned + * @returns - random hex string + * + * ```ts + * console.log(web3.utils.randomHex(32)); + * > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e + * ``` + */ +export declare const randomHex: (byteSize: number) => string; +//# sourceMappingURL=random.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/random.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/random.d.ts.map new file mode 100644 index 0000000..49846a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/random.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.d.ts","sourceRoot":"","sources":["../../src/random.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW,SAAU,MAAM,KAAG,UAAsC,CAAC;AAElF;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS,aAAc,MAAM,KAAG,MAA2C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/socket_provider.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/socket_provider.d.ts new file mode 100644 index 0000000..f1b8d5a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/socket_provider.d.ts @@ -0,0 +1,129 @@ +import { ConnectionEvent, EthExecutionAPI, JsonRpcId, JsonRpcResponse, JsonRpcResponseWithResult, JsonRpcResult, ProviderConnectInfo, ProviderMessage, ProviderRpcError, SocketRequestItem, Web3APIMethod, Web3APIPayload, Web3APIReturnType, Web3APISpec, Web3Eip1193ProviderEventCallback, Web3ProviderEventCallback, Web3ProviderMessageEventCallback, Web3ProviderStatus } from 'web3-types'; +import { Eip1193Provider } from './web3_eip1193_provider.js'; +import { ChunkResponseParser } from './chunk_response_parser.js'; +export declare type ReconnectOptions = { + autoReconnect: boolean; + delay: number; + maxAttempts: number; +}; +export declare abstract class SocketProvider extends Eip1193Provider { + protected isReconnecting: boolean; + protected readonly _socketPath: string; + protected readonly chunkResponseParser: ChunkResponseParser; + protected readonly _pendingRequestsQueue: Map>; + protected readonly _sentRequestsQueue: Map>; + protected _reconnectAttempts: number; + protected readonly _socketOptions?: unknown; + protected readonly _reconnectOptions: ReconnectOptions; + protected _socketConnection?: unknown; + get SocketConnection(): unknown; + protected _connectionStatus: Web3ProviderStatus; + protected readonly _onMessageHandler: (event: MessageEvent) => void; + protected readonly _onOpenHandler: () => void; + protected readonly _onCloseHandler: (event: CloseEvent) => void; + protected readonly _onErrorHandler: (event: ErrorEvent) => void; + /** + * This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546) + * @param socketOptions - The options for the socket connection. Its type is supposed to be specified in the inherited classes. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + constructor(socketPath: string, socketOptions?: unknown, reconnectOptions?: Partial); + protected _init(): void; + /** + * Try to establish a connection to the socket + */ + connect(): void; + protected abstract _openSocketConnection(): void; + protected abstract _addSocketListeners(): void; + protected abstract _removeSocketListeners(): void; + protected abstract _onCloseEvent(_event: unknown): void; + protected abstract _sendToSocket(_payload: Web3APIPayload): void; + protected abstract _parseResponses(_event: MessageEvent): JsonRpcResponse[]; + protected abstract _closeSocketConnection(_code?: number, _data?: string): void; + protected _validateProviderPath(path: string): boolean; + /** + * + * @returns the pendingRequestQueue size + */ + getPendingRequestQueueSize(): number; + /** + * + * @returns the sendPendingRequests size + */ + getSentRequestsQueueSize(): number; + /** + * + * @returns `true` if the socket supports subscriptions + */ + supportsSubscriptions(): boolean; + /** + * Registers a listener for the specified event type. + * @param type - The event type to listen for + * @param listener - The callback to be invoked when the event is emitted + */ + on(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + on(type: 'message', listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + on(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + /** + * Registers a listener for the specified event type that will be invoked at most once. + * @param type - The event type to listen for + * @param listener - The callback to be invoked when the event is emitted + */ + once(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + once(type: 'message', listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + once(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + /** + * Removes a listener for the specified event type. + * @param type - The event type to remove the listener for + * @param listener - The callback to be executed + */ + removeListener(type: 'disconnect', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'connect', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + removeListener(type: 'message', listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; + removeListener(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; + protected _onDisconnect(code: number, data?: string): void; + /** + * Disconnects the socket + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + disconnect(code?: number, data?: string): void; + /** + * Safely disconnects the socket, async and waits for request size to be 0 before disconnecting + * @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0 + * @param ms - Determines the ms of setInterval + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + safeDisconnect(code?: number, data?: string, forceDisconnect?: boolean, ms?: number): Promise; + /** + * Removes all listeners for the specified event type. + * @param type - The event type to remove the listeners for + */ + removeAllListeners(type: string): void; + protected _onError(event: ErrorEvent): void; + /** + * Resets the socket, removing all listeners and pending requests + */ + reset(): void; + protected _reconnect(): void; + /** + * Creates a request object to be sent to the server + */ + request, ResultType = Web3APIReturnType>(request: Web3APIPayload): Promise>; + protected _onConnect(): void; + private _sendPendingRequests; + protected _onMessage(event: MessageEvent): void; + clearQueues(event?: ConnectionEvent): void; + protected _clearQueues(event?: ConnectionEvent): void; +} +//# sourceMappingURL=socket_provider.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/socket_provider.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/socket_provider.d.ts.map new file mode 100644 index 0000000..8cb2ea3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/socket_provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"socket_provider.d.ts","sourceRoot":"","sources":["../../src/socket_provider.ts"],"names":[],"mappings":"AAgBA,OAAO,EACN,eAAe,EAEf,eAAe,EAGf,SAAS,EAGT,eAAe,EACf,yBAAyB,EACzB,aAAa,EACb,mBAAmB,EACnB,eAAe,EACf,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,iBAAiB,EACjB,WAAW,EACX,gCAAgC,EAChC,yBAAyB,EACzB,gCAAgC,EAChC,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAUpB,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAKjE,oBAAY,gBAAgB,GAAG;IAC9B,aAAa,EAAE,OAAO,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;CACpB,CAAC;AAUF,8BAAsB,cAAc,CACnC,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,SAAS,WAAW,GAAG,eAAe,CACxC,SAAQ,eAAe,CAAC,GAAG,CAAC;IAC7B,SAAS,CAAC,cAAc,EAAE,OAAO,CAAC;IAClC,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IACvC,SAAS,CAAC,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;IAE5D,SAAS,CAAC,QAA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c,CAAC,CAAC,GAAG,aAAa,EACtC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,gCAAgC,CAAC,OAAO,CAAC,GAAG,yBAAyB,CAAC,CAAC,CAAC,GAChF,IAAI;IAWP,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM;IAKnD;;;;OAIG;IACI,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;IASrD;;;;;;OAMG;IACU,cAAc,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,eAAe,UAAQ,EAAC,EAAE,SAAO;IAqB3F;;;OAGG;IACI,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI7C,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;IAS3C;;OAEG;IACI,KAAK,IAAI,IAAI;IASpB,SAAS,CAAC,UAAU,IAAI,IAAI;IAiC5B;;OAEG;IACU,OAAO,CACnB,MAAM,SAAS,aAAa,CAAC,GAAG,CAAC,EACjC,UAAU,GAAG,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,EAC1C,OAAO,EAAE,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,yBAAyB,CAAC,UAAU,CAAC,CAAC;IAiDvF,SAAS,CAAC,UAAU;IAOpB,OAAO,CAAC,oBAAoB;IAQ5B,SAAS,CAAC,UAAU,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAsCxC,WAAW,CAAC,KAAK,CAAC,EAAE,eAAe;IAI1C,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,eAAe;CAqB9C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/string_manipulation.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/string_manipulation.d.ts new file mode 100644 index 0000000..f1bccd7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/string_manipulation.d.ts @@ -0,0 +1,78 @@ +import { Numbers } from 'web3-types'; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * + * console.log(web3.utils.padLeft('0x123', 10)); + * >0x0000000123 + * ``` + */ +export declare const padLeft: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * console.log(web3.utils.padRight('0x123', 10)); + * > 0x1230000000 + * + * console.log(web3.utils.padRight('0x123', 10, '1')); + * > 0x1231111111 + * ``` + */ +export declare const padRight: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight` + */ +export declare const rightPad: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft` + */ +export declare const leftPad: (value: Numbers, characterAmount: number, sign?: string) => string; +/** + * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * + * @returns The hex string of the two’s complement. + * + * @example + * ```ts + * console.log(web3.utils.toTwosComplement(13, 32)); + * > 0x0000000000000000000000000000000d + * + * console.log(web3.utils.toTwosComplement('-0x1', 32)); + * > 0xffffffffffffffffffffffffffffffff + * + * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32)); + * > 0x00000000000000000020000000000000 + * ``` + */ +export declare const toTwosComplement: (value: Numbers, nibbleWidth?: number) => string; +/** + * Converts the twos complement into a decimal number or big int. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * @returns The decimal number or big int. + * + * @example + * ```ts + * console.log(web3.utils.fromTwosComplement(''0x0000000000000000000000000000000d', 32')); + * > 13 + * + * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32)); + * > 9007199254740992n + * ``` + */ +export declare const fromTwosComplement: (value: Numbers, nibbleWidth?: number) => number | bigint; +//# sourceMappingURL=string_manipulation.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/string_manipulation.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/string_manipulation.d.ts.map new file mode 100644 index 0000000..91d679c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/string_manipulation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string_manipulation.d.ts","sourceRoot":"","sources":["../../src/string_manipulation.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAKrC;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,OAAO,UAAW,OAAO,mBAAmB,MAAM,oBAAe,MAc7E,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,QAAQ,UAAW,OAAO,mBAAmB,MAAM,oBAAe,MAW9E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ,UAhBW,OAAO,mBAAmB,MAAM,oBAAe,MAgB/C,CAAC;AAEjC;;GAEG;AACH,eAAO,MAAM,OAAO,UArDW,OAAO,mBAAmB,MAAM,oBAAe,MAqDhD,CAAC;AAE/B;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,UAAW,OAAO,2BAAqB,MAgBnE,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,kBAAkB,UAAW,OAAO,2BAAqB,MAAM,GAAG,MAkB9E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/uint8array.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/uint8array.d.ts new file mode 100644 index 0000000..518b1da --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/uint8array.d.ts @@ -0,0 +1,6 @@ +export declare function uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array; +/** + * Returns true if the two passed Uint8Arrays have the same content + */ +export declare function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean; +//# sourceMappingURL=uint8array.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/uint8array.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/uint8array.d.ts.map new file mode 100644 index 0000000..f0a22a6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/uint8array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uint8array.d.ts","sourceRoot":"","sources":["../../src/uint8array.ts"],"names":[],"mappings":"AAgBA,wBAAgB,gBAAgB,CAAC,GAAG,KAAK,EAAE,UAAU,EAAE,GAAG,UAAU,CAYnE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,OAAO,CAgBtE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/uuid.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/uuid.d.ts new file mode 100644 index 0000000..be80628 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/uuid.d.ts @@ -0,0 +1,12 @@ +/** + * Generate a version 4 (random) uuid + * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5 + * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx + * @example + * ```ts + * console.log(web3.utils.uuidV4()); + * > "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed" + * ``` + */ +export declare const uuidV4: () => string; +//# sourceMappingURL=uuid.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/uuid.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/uuid.d.ts.map new file mode 100644 index 0000000..36a2970 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/uuid.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid.d.ts","sourceRoot":"","sources":["../../src/uuid.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,QAAO,MAwBzB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/validation.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/validation.d.ts new file mode 100644 index 0000000..18ce94d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/validation.d.ts @@ -0,0 +1,83 @@ +import { BlockNumberOrTag, ContractInitOptions } from 'web3-types'; +/** + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isHexStrict: (hex: import("web3-validator").ValidInputTypes) => boolean; +/** + * returns true if input is a hexstring, number or bigint + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isHex: (hex: import("web3-validator").ValidInputTypes) => boolean; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const checkAddressCheckSum: (data: string) => boolean; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isAddress: (value: import("web3-validator").ValidInputTypes, checkChecksum?: boolean | undefined) => boolean; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isBloom: (bloom: import("web3-validator").ValidInputTypes) => boolean; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isInBloom: (bloom: string, value: string | Uint8Array) => boolean; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isUserEthereumAddressInBloom: (bloom: string, ethereumAddress: string) => boolean; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isContractAddressInBloom: (bloom: string, contractAddress: string) => boolean; +/** + * Checks if its a valid topic + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isTopic: (topic: string) => boolean; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export declare const isTopicInBloom: (bloom: string, topic: string) => boolean; +/** + * Compares between block A and block B + * @param blockA - Block number or string + * @param blockB - Block number or string + * + * @returns - Returns -1 if a \< b, returns 1 if a \> b and returns 0 if a == b + * + * @example + * ```ts + * console.log(web3.utils.compareBlockNumbers('latest', 'pending')); + * > -1 + * + * console.log(web3.utils.compareBlockNumbers(12, 11)); + * > 1 + * ``` + */ +export declare const compareBlockNumbers: (blockA: BlockNumberOrTag, blockB: BlockNumberOrTag) => 0 | 1 | -1; +export declare const isContractInitOptions: (options: unknown) => options is ContractInitOptions; +export declare const isNullish: (item: unknown) => item is null | undefined; +//# sourceMappingURL=validation.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/validation.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/validation.d.ts.map new file mode 100644 index 0000000..7bc26b8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/validation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/validation.ts"],"names":[],"mappings":"AAgCA,OAAO,EAAE,gBAAgB,EAAa,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE9E;;GAEG;AACH,eAAO,MAAM,WAAW,4DAAuB,CAAC;AAEhD;;;;GAIG;AACH,eAAO,MAAM,KAAK,4DAAiB,CAAC;AAEpC;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,2BAAgC,CAAC;AAElE;;;;GAIG;AACH,eAAO,MAAM,SAAS,mGAAqB,CAAC;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,OAAO,8DAAmB,CAAC;AAExC;;;;;GAKG;AACH,eAAO,MAAM,SAAS,wDAAqB,CAAC;AAE5C;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,qDAAwC,CAAC;AAElF;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,qDAAoC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,OAAO,4BAAmB,CAAC;AAExC;;;;;GAKG;AACH,eAAO,MAAM,cAAc,2CAA0B,CAAC;AAEtD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,mBAAmB,WAAY,gBAAgB,UAAU,gBAAgB,eA+CrF,CAAC;AAGF,eAAO,MAAM,qBAAqB,YAAa,OAAO,mCAexB,CAAC;AAE/B,eAAO,MAAM,SAAS,6CAAqB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/web3_deferred_promise.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_deferred_promise.d.ts new file mode 100644 index 0000000..a362b01 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_deferred_promise.d.ts @@ -0,0 +1,68 @@ +import { Web3DeferredPromiseInterface } from 'web3-types'; +/** + * The class is a simple implementation of a deferred promise with optional timeout functionality, + * which can be useful when dealing with asynchronous tasks. + * + */ +export declare class Web3DeferredPromise implements Promise, Web3DeferredPromiseInterface { + [Symbol.toStringTag]: 'Promise'; + private readonly _promise; + private _resolve; + private _reject; + private _state; + private _timeoutId?; + private readonly _timeoutInterval?; + private readonly _timeoutMessage; + /** + * + * @param timeout - (optional) The timeout in milliseconds. + * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created. + * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out. + */ + constructor({ timeout, eagerStart, timeoutMessage, }?: { + timeout: number; + eagerStart: boolean; + timeoutMessage: string; + }); + /** + * Returns the current state of the promise. + * @returns 'pending' | 'fulfilled' | 'rejected' + */ + get state(): 'pending' | 'fulfilled' | 'rejected'; + /** + * + * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled. + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + then(onfulfilled?: (value: T) => TResult1 | PromiseLike, onrejected?: (reason: unknown) => TResult2 | PromiseLike): Promise; + /** + * + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + catch(onrejected?: (reason: any) => TResult | PromiseLike): Promise; + /** + * + * @param onfinally - (optional) The callback to execute when the promise is settled (fulfilled or rejected). + * @returns + */ + finally(onfinally?: (() => void) | undefined): Promise; + /** + * Resolves the current promise. + * @param value - The value to resolve the promise with. + */ + resolve(value: T | PromiseLike): void; + /** + * Rejects the current promise. + * @param reason - The reason to reject the promise with. + */ + reject(reason?: unknown): void; + /** + * Starts the timeout timer for the promise. + */ + startTimer(): void; + private _checkTimeout; + private _clearTimeout; +} +//# sourceMappingURL=web3_deferred_promise.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/web3_deferred_promise.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_deferred_promise.d.ts.map new file mode 100644 index 0000000..cdf27d6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_deferred_promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_deferred_promise.d.ts","sourceRoot":"","sources":["../../src/web3_deferred_promise.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAG1D;;;;GAIG;AACH,qBAAa,mBAAm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AItE;;;OAGG;IACI,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI;IAM/C;;;OAGG;IACI,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI;IAMrC;;OAEG;IACI,UAAU;IAMjB,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,aAAa;CAKrB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/web3_eip1193_provider.d.ts b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_eip1193_provider.d.ts new file mode 100644 index 0000000..39cc7cb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_eip1193_provider.d.ts @@ -0,0 +1,17 @@ +/// +import { EthExecutionAPI, Web3APISpec, Web3BaseProvider } from 'web3-types'; +import { EventEmitter } from 'events'; +/** + * This is an abstract class, which extends {@link Web3BaseProvider} class. This class is used to implement a provider that adheres to the EIP-1193 standard for Ethereum providers. + */ +export declare abstract class Eip1193Provider extends Web3BaseProvider { + protected readonly _eventEmitter: EventEmitter; + private _chainId; + private _accounts; + private _getChainId; + private _getAccounts; + protected _onConnect(): void; + protected _onDisconnect(code: number, data?: unknown): void; + private _onAccountsChanged; +} +//# sourceMappingURL=web3_eip1193_provider.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/lib/types/web3_eip1193_provider.d.ts.map b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_eip1193_provider.d.ts.map new file mode 100644 index 0000000..0789d35 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/lib/types/web3_eip1193_provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_eip1193_provider.d.ts","sourceRoot":"","sources":["../../src/web3_eip1193_provider.ts"],"names":[],"mappings":";AAgBA,OAAO,EACN,eAAe,EAKf,WAAW,EACX,gBAAgB,EAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAItC;;GAEG;AACH,8BAAsB,eAAe,CACpC,GAAG,SAAS,WAAW,GAAG,eAAe,CACxC,SAAQ,gBAAgB,CAAC,GAAG,CAAC;IAC9B,SAAS,CAAC,QAAQ,CAAC,aAAa,EAAE,YAAY,CAAsB;IACpE,OAAO,CAAC,QAAQ,CAAiB;IACjC,OAAO,CAAC,SAAS,CAAmB;YAEtB,WAAW;YAaX,YAAY;IAU1B,SAAS,CAAC,UAAU;IA6CpB,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO;IAIpD,OAAO,CAAC,kBAAkB;CAI1B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/package.json b/test/merkletreejs/node_modules/web3-utils/package.json new file mode 100644 index 0000000..a9d19b1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/package.json @@ -0,0 +1,72 @@ +{ + "name": "web3-utils", + "sideEffects": false, + "version": "4.1.0", + "description": "Collection of utility functions used in web3.js.", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests", + "test:e2e:electron": "npx cypress run --headless --browser electron", + "test:e2e:chrome": "npx cypress run --headless --browser chrome", + "test:e2e:firefox": "npx cypress run --headless --browser firefox" + }, + "devDependencies": { + "@humeris/espresso-shot": "^4.0.0", + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-environment-jsdom": "^29.7.0", + "jest-extended": "^3.0.1", + "js-sha3": "^0.8.0", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "dependencies": { + "ethereum-cryptography": "^2.0.0", + "web3-errors": "^1.1.4", + "web3-types": "^1.3.1", + "web3-validator": "^2.0.3" + }, + "gitHead": "b9b5fe0210da1a4ebf62e2b54f37a9c747bfa136" +} diff --git a/test/merkletreejs/node_modules/web3-utils/src/chunk_response_parser.ts b/test/merkletreejs/node_modules/web3-utils/src/chunk_response_parser.ts new file mode 100644 index 0000000..d9b37c7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/chunk_response_parser.ts @@ -0,0 +1,97 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { JsonRpcResponse } from 'web3-types'; +import { InvalidResponseError } from 'web3-errors'; +import { EventEmitter } from 'events'; +import { Timeout } from './promise_helpers.js'; + +export class ChunkResponseParser { + private lastChunk: string | undefined; + private lastChunkTimeout: Timeout | undefined; + private _clearQueues: (() => void) | undefined; + private readonly eventEmitter: EventEmitter; + private readonly autoReconnect: boolean; + + public constructor(eventEmitter: EventEmitter, autoReconnect: boolean) { + this.eventEmitter = eventEmitter; + this.autoReconnect = autoReconnect; + } + private clearQueues(): void { + if (typeof this._clearQueues === 'function') { + this._clearQueues(); + } + } + + public onError(clearQueues?: () => void) { + this._clearQueues = clearQueues; + } + + public parseResponse(data: string): JsonRpcResponse[] { + const returnValues: JsonRpcResponse[] = []; + + // DE-CHUNKER + const dechunkedData = data + .replace(/\}[\n\r]?\{/g, '}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{ + .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{ + .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{ + .split('|--|'); + + dechunkedData.forEach(_chunkData => { + // prepend the last chunk + let chunkData = _chunkData; + if (this.lastChunk) { + chunkData = this.lastChunk + chunkData; + } + + let result; + + try { + result = JSON.parse(chunkData) as unknown as JsonRpcResponse; + } catch (e) { + this.lastChunk = chunkData; + + // start timeout to cancel all requests + if (this.lastChunkTimeout) { + clearTimeout(this.lastChunkTimeout); + } + + this.lastChunkTimeout = setTimeout(() => { + if (this.autoReconnect) return; + this.clearQueues(); + this.eventEmitter.emit( + 'error', + new InvalidResponseError({ + id: 1, + jsonrpc: '2.0', + error: { code: 2, message: 'Chunk timeout' }, + }), + ); + }, 1000 * 15); + return; + } + + // cancel timeout and set chunk to null + clearTimeout(this.lastChunkTimeout); + this.lastChunk = undefined; + + if (result) returnValues.push(result); + }); + + return returnValues; + } +} diff --git a/test/merkletreejs/node_modules/web3-utils/src/converters.ts b/test/merkletreejs/node_modules/web3-utils/src/converters.ts new file mode 100644 index 0000000..83cbf61 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/converters.ts @@ -0,0 +1,645 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * @module Utils + */ + +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { bytesToUtf8, utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { Address, Bytes, HexString, Numbers, ValueTypes } from 'web3-types'; +import { + isAddress, + isHex, + isHexStrict, + isInt, + isNullish, + utils, + utils as validatorUtils, + validator, +} from 'web3-validator'; + +import { + HexProcessingError, + InvalidAddressError, + InvalidBooleanError, + InvalidBytesError, + InvalidNumberError, + InvalidUnitError, +} from 'web3-errors'; + +// Ref: https://ethdocs.org/en/latest/ether.html +// Note: this could be simplified using ** operator, but babel does not handle it well (https://github.com/babel/babel/issues/13109) +/** @internal */ +export const ethUnitMap = { + noether: BigInt(0), + wei: BigInt(1), + kwei: BigInt(1000), + Kwei: BigInt(1000), + babbage: BigInt(1000), + femtoether: BigInt(1000), + mwei: BigInt(1000000), + Mwei: BigInt(1000000), + lovelace: BigInt(1000000), + picoether: BigInt(1000000), + gwei: BigInt(1000000000), + Gwei: BigInt(1000000000), + shannon: BigInt(1000000000), + nanoether: BigInt(1000000000), + nano: BigInt(1000000000), + szabo: BigInt(1000000000000), + microether: BigInt(1000000000000), + micro: BigInt(1000000000000), + finney: BigInt(1000000000000000), + milliether: BigInt(1000000000000000), + milli: BigInt(1000000000000000), + ether: BigInt('1000000000000000000'), + kether: BigInt('1000000000000000000000'), + grand: BigInt('1000000000000000000000'), + mether: BigInt('1000000000000000000000000'), + gether: BigInt('1000000000000000000000000000'), + tether: BigInt('1000000000000000000000000000000'), +}; + +export type EtherUnits = keyof typeof ethUnitMap; +/** + * Convert a value from bytes to Uint8Array + * @param data - Data to be converted + * @returns - The Uint8Array representation of the input data + * + * @example + * ```ts + * console.log(web3.utils.bytesToUint8Array("0xab"))); + * > Uint8Array(1) [ 171 ] + * ``` + */ +export const bytesToUint8Array = (data: Bytes): Uint8Array | never => { + validator.validate(['bytes'], [data]); + + if (data instanceof Uint8Array) { + return data; + } + + if (Array.isArray(data)) { + return new Uint8Array(data); + } + + if (typeof data === 'string') { + return validatorUtils.hexToUint8Array(data); + } + + throw new InvalidBytesError(data); +}; + +/** + * @internal + */ +const { uint8ArrayToHexString } = validatorUtils; + +/** + * Convert a byte array to a hex string + * @param bytes - Byte array to be converted + * @returns - The hex string representation of the input byte array + * + * @example + * ```ts + * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12]))); + * > "0x480c" + * + */ +export const bytesToHex = (bytes: Bytes): HexString => + uint8ArrayToHexString(bytesToUint8Array(bytes)); + +/** + * Convert a hex string to a byte array + * @param hex - Hex string to be converted + * @returns - The byte array representation of the input hex string + * + * @example + * ```ts + * console.log(web3.utils.hexToBytes('0x74657374')); + * > Uint8Array(4) [ 116, 101, 115, 116 ] + * ``` + */ +export const hexToBytes = (bytes: HexString): Uint8Array => { + if (typeof bytes === 'string' && bytes.slice(0, 2).toLowerCase() !== '0x') { + return bytesToUint8Array(`0x${bytes}`); + } + return bytesToUint8Array(bytes); +}; + +/** + * Converts value to it's number representation + * @param value - Hex string to be converted + * @returns - The number representation of the input value + * + * @example + * ```ts + * conoslle.log(web3.utils.hexToNumber('0xa')); + * > 10 + * ``` + */ +export const hexToNumber = (value: HexString): bigint | number => { + validator.validate(['hex'], [value]); + + // To avoid duplicate code and circular dependency we will + // use `hexToNumber` implementation from `web3-validator` + return validatorUtils.hexToNumber(value); +}; + +/** + * Converts value to it's number representation @alias `hexToNumber` + */ +export const toDecimal = hexToNumber; + +/** + * Converts value to it's hex representation + * @param value - Value to be converted + * @param hexstrict - Add padding to converted value if odd, to make it hexstrict + * @returns - The hex representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.numberToHex(10)); + * > "0xa" + * ``` + */ +export const numberToHex = (value: Numbers, hexstrict?: boolean): HexString => { + if (typeof value !== 'bigint') validator.validate(['int'], [value]); + // To avoid duplicate code and circular dependency we will + // use `numberToHex` implementation from `web3-validator` + let updatedValue = validatorUtils.numberToHex(value); + if (hexstrict) { + if (!updatedValue.startsWith('-') && updatedValue.length % 2 === 1) { + // To avoid duplicate a circular dependancy we will not be using the padLeft method + updatedValue = '0x0'.concat(updatedValue.slice(2)); + } else if (updatedValue.length % 2 === 0 && updatedValue.startsWith('-')) + updatedValue = '-0x0'.concat(updatedValue.slice(3)); + } + return updatedValue; +}; +/** + * Converts value to it's hex representation @alias `numberToHex` + * + */ +export const fromDecimal = numberToHex; + +/** + * Converts value to it's decimal representation in string + * @param value - Hex string to be converted + * @returns - The decimal representation of the input value + * + * @example + * ```ts + * console.log(web3.utils.hexToNumberString('0xa')); + * > "10" + * ``` + */ +export const hexToNumberString = (data: HexString): string => hexToNumber(data).toString(); + +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * @param str - Utf8 string to be converted + * @returns - The hex representation of the input string + * + * @example + * ```ts + * console.log(utf8ToHex('web3.js')); + * > "0x776562332e6a73" + * + */ +export const utf8ToHex = (str: string): HexString => { + validator.validate(['string'], [str]); + + // To be compatible with 1.x trim null character + // eslint-disable-next-line no-control-regex + let strWithoutNullCharacter = str.replace(/^(?:\u0000)/, ''); + // eslint-disable-next-line no-control-regex + strWithoutNullCharacter = strWithoutNullCharacter.replace(/(?:\u0000)$/, ''); + + return bytesToHex(new TextEncoder().encode(strWithoutNullCharacter)); +}; + +/** + * @alias utf8ToHex + */ + +export const fromUtf8 = utf8ToHex; +/** + * @alias utf8ToHex + */ +export const stringToHex = utf8ToHex; + +/** + * Should be called to get utf8 from it's hex representation + * @param str - Hex string to be converted + * @returns - Utf8 string + * + * @example + * ```ts + * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export const hexToUtf8 = (str: HexString): string => bytesToUtf8(hexToBytes(str)); + +/** + * @alias hexToUtf8 + */ +export const toUtf8 = (input: HexString | Uint8Array) => { + if (typeof input === 'string') { + return hexToUtf8(input); + } + validator.validate(['bytes'], [input]); + return bytesToUtf8(input); +}; + +export const utf8ToBytes = ecUtf8ToBytes; + +/** + * @alias hexToUtf8 + */ +export const hexToString = hexToUtf8; + +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * @param str - String to be converted to hex + * @returns - Hex string + * + * @example + * ```ts + * console.log(web3.utils.asciiToHex('Hello World')); + * > 0x48656c6c6f20576f726c64 + * ``` + */ +export const asciiToHex = (str: string): HexString => { + validator.validate(['string'], [str]); + let hexString = ''; + for (let i = 0; i < str.length; i += 1) { + const hexCharCode = str.charCodeAt(i).toString(16); + // might need a leading 0 + hexString += hexCharCode.length % 2 !== 0 ? `0${hexCharCode}` : hexCharCode; + } + return `0x${hexString}`; +}; + +/** + * @alias asciiToHex + */ +export const fromAscii = asciiToHex; + +/** + * Should be called to get ascii from it's hex representation + * @param str - Hex string to be converted to ascii + * @returns - Ascii string + * + * @example + * ```ts + * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64')); + * > Hello World + * ``` + */ +export const hexToAscii = (str: HexString): string => { + const decoder = new TextDecoder('ascii'); + return decoder.decode(hexToBytes(str)); +}; + +/** + * @alias hexToAscii + */ +export const toAscii = hexToAscii; + +/** + * Auto converts any given value into it's hex representation. + * @param value - Value to be converted to hex + * @param returnType - If true, it will return the type of the value + * + * @example + * ```ts + * console.log(web3.utils.toHex(10)); + * > 0xa + * + * console.log(web3.utils.toHex('0x123', true)); + * > bytes + *``` + */ +export const toHex = ( + value: Numbers | Bytes | Address | boolean | object, + returnType?: boolean, +): HexString | ValueTypes => { + if (typeof value === 'string' && isAddress(value)) { + return returnType ? 'address' : `0x${value.toLowerCase().replace(/^0x/i, '')}`; + } + + if (typeof value === 'boolean') { + // eslint-disable-next-line no-nested-ternary + return returnType ? 'bool' : value ? '0x01' : '0x00'; + } + + if (typeof value === 'number') { + // eslint-disable-next-line no-nested-ternary + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); + } + + if (typeof value === 'bigint') { + return returnType ? 'bigint' : numberToHex(value); + } + + if (typeof value === 'object' && !!value) { + return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); + } + + if (typeof value === 'string') { + if (value.startsWith('-0x') || value.startsWith('-0X')) { + return returnType ? 'int256' : numberToHex(value); + } + + if (isHexStrict(value)) { + return returnType ? 'bytes' : value; + } + if (isHex(value) && !isInt(value)) { + return returnType ? 'bytes' : `0x${value}`; + } + + if (!Number.isFinite(value)) { + return returnType ? 'string' : utf8ToHex(value); + } + } + + throw new HexProcessingError(value); +}; + +/** + * Converts any given value into it's number representation, if possible, else into it's bigint representation. + * @param value - The value to convert + * @returns - Returns the value in number or bigint representation + * + * @example + * ```ts + * console.log(web3.utils.toNumber(1)); + * > 1 + * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER)); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER))); + * > 9007199254740991 + * + * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1))); + * > 9007199254740992n + * + * ``` + */ +export const toNumber = (value: Numbers): number | bigint => { + if (typeof value === 'number') { + return value; + } + + if (typeof value === 'bigint') { + return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER + ? Number(value) + : value; + } + + if (typeof value === 'string' && isHexStrict(value)) { + return hexToNumber(value); + } + + try { + return toNumber(BigInt(value)); + } catch { + throw new InvalidNumberError(value); + } +}; + +/** + * Auto converts any given value into it's bigint representation + * + * @param value - The value to convert + * @returns - Returns the value in bigint representation + + * @example + * ```ts + * console.log(web3.utils.toBigInt(1)); + * > 1n + * ``` + */ +export const toBigInt = (value: unknown): bigint => { + if (typeof value === 'number') { + return BigInt(value); + } + + if (typeof value === 'bigint') { + return value; + } + + // isHex passes for dec, too + if (typeof value === 'string' && isHex(value)) { + if (value.startsWith('-')) { + return -BigInt(value.substring(1)); + } + return BigInt(value); + } + + throw new InvalidNumberError(value); +}; + +/** + * Takes a number of wei and converts it to any other ether unit. + * @param number - The value in wei + * @param unit - The unit to convert to + * @returns - Returns the converted value in the given unit + * + * @example + * ```ts + * console.log(web3.utils.fromWei("1", "ether")); + * > 0.000000000000000001 + * + * console.log(web3.utils.fromWei("1", "shannon")); + * > 0.000000001 + * ``` + */ +export const fromWei = (number: Numbers, unit: EtherUnits): string => { + const denomination = ethUnitMap[unit]; + + if (!denomination) { + throw new InvalidUnitError(unit); + } + + // value in wei would always be integer + // 13456789, 1234 + const value = String(toNumber(number)); + + // count number of zeros in denomination + // 1000000 -> 6 + const numberOfZerosInDenomination = denomination.toString().length - 1; + + if (numberOfZerosInDenomination <= 0) { + return value.toString(); + } + + // pad the value with required zeros + // 13456789 -> 13456789, 1234 -> 001234 + const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, '0'); + + // get the integer part of value by counting number of zeros from start + // 13456789 -> '13' + // 001234 -> '' + const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination); + + // get the fraction part of value by counting number of zeros backward + // 13456789 -> '456789' + // 001234 -> '001234' + const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, ''); + + if (integer === '') { + return `0.${fraction}`; + } + + if (fraction === '') { + return integer; + } + + return `${integer}.${fraction}`; +}; + +/** + * Takes a number of a unit and converts it to wei. + * + * @param number - The number to convert. + * @param unit - {@link EtherUnits} The unit of the number passed. + * @returns The number converted to wei. + * + * @example + * ```ts + * console.log(web3.utils.toWei("0.001", "ether")); + * > 1000000000000000 //(wei) + * ``` + */ +// todo in 1.x unit defaults to 'ether' +export const toWei = (number: Numbers, unit: EtherUnits): string => { + validator.validate(['number'], [number]); + + const denomination = ethUnitMap[unit]; + + if (!denomination) { + throw new InvalidUnitError(unit); + } + + // if value is decimal e.g. 24.56 extract `integer` and `fraction` part + // to avoid `fraction` to be null use `concat` with empty string + const [integer, fraction] = String( + typeof number === 'string' && !isHexStrict(number) ? number : toNumber(number), + ) + .split('.') + .concat(''); + + // join the value removing `.` from + // 24.56 -> 2456 + const value = BigInt(`${integer}${fraction}`); + + // multiply value with denomination + // 2456 * 1000000 -> 2456000000 + const updatedValue = value * denomination; + + // count number of zeros in denomination + const numberOfZerosInDenomination = denomination.toString().length - 1; + + // check which either `fraction` or `denomination` have lower number of zeros + const decimals = Math.min(fraction.length, numberOfZerosInDenomination); + + if (decimals === 0) { + return updatedValue.toString(); + } + + // Add zeros to make length equal to required decimal points + // If string is larger than decimal points required then remove last zeros + return updatedValue.toString().padStart(decimals, '0').slice(0, -decimals); +}; + +/** + * Will convert an upper or lowercase Ethereum address to a checksum address. + * @param address - An address string + * @returns The checksum address + * @example + * ```ts + * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d'); + * > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" + * ``` + */ +export const toChecksumAddress = (address: Address): string => { + if (!isAddress(address, false)) { + throw new InvalidAddressError(address); + } + + const lowerCaseAddress = address.toLowerCase().replace(/^0x/i, ''); + + const hash = utils.uint8ArrayToHexString(keccak256(utf8ToBytes(lowerCaseAddress))); + + if ( + isNullish(hash) || + hash === '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + ) + return ''; // // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data + + let checksumAddress = '0x'; + + const addressHash = hash.replace(/^0x/i, ''); + + for (let i = 0; i < lowerCaseAddress.length; i += 1) { + // If ith character is 8 to f then make it uppercase + if (parseInt(addressHash[i], 16) > 7) { + checksumAddress += lowerCaseAddress[i].toUpperCase(); + } else { + checksumAddress += lowerCaseAddress[i]; + } + } + return checksumAddress; +}; + +export const toBool = (value: boolean | string | number | unknown): boolean => { + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number' && (value === 0 || value === 1)) { + return Boolean(value); + } + + if (typeof value === 'bigint' && (value === BigInt(0) || value === BigInt(1))) { + return Boolean(value); + } + + if ( + typeof value === 'string' && + !isHexStrict(value) && + (value === '1' || value === '0' || value === 'false' || value === 'true') + ) { + if (value === 'true') { + return true; + } + if (value === 'false') { + return false; + } + return Boolean(Number(value)); + } + + if (typeof value === 'string' && isHexStrict(value) && (value === '0x1' || value === '0x0')) { + return Boolean(toNumber(value)); + } + + throw new InvalidBooleanError(value); +}; diff --git a/test/merkletreejs/node_modules/web3-utils/src/event_emitter.ts b/test/merkletreejs/node_modules/web3-utils/src/event_emitter.ts new file mode 100644 index 0000000..7d9c3cc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/event_emitter.ts @@ -0,0 +1,128 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/* eslint-disable max-classes-per-file */ + +import { EventEmitter as EventEmitterAtNode } from 'events'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Callback = (params: any) => void | Promise; + +type EventTargetCallback = (params: CustomEvent) => void; + +const wrapFunction = + (fn: Callback): EventTargetCallback => + (params: CustomEvent) => + fn(params.detail); + +/** + * This class copy the behavior of Node.js EventEmitter class. + * It is used to provide the same interface for the browser environment. + */ +class EventEmitterAtBrowser extends EventTarget { + private _listeners: Record = {}; + private maxListeners = Number.MAX_SAFE_INTEGER; + + public on(eventName: string, fn: Callback) { + this.addEventListener(eventName, fn); + return this; + } + + public once(eventName: string, fn: Callback) { + const onceCallback = async (params: Callback) => { + this.off(eventName, onceCallback); + await fn(params); + }; + return this.on(eventName, onceCallback); + } + + public off(eventName: string, fn: Callback) { + this.removeEventListener(eventName, fn); + return this; + } + + public emit(eventName: string, params: unknown) { + const event = new CustomEvent(eventName, { detail: params }); + return super.dispatchEvent(event); + } + + public listenerCount(eventName: string): number { + const eventListeners = this._listeners[eventName]; + return eventListeners ? eventListeners.length : 0; + } + + public listeners(eventName: string): Callback[] { + return this._listeners[eventName].map(value => value[0]) || []; + } + + public eventNames(): string[] { + return Object.keys(this._listeners); + } + + public removeAllListeners() { + Object.keys(this._listeners).forEach(event => { + this._listeners[event].forEach( + (listener: [key: Callback, value: EventTargetCallback]) => { + super.removeEventListener(event, listener[1] as EventListener); + }, + ); + }); + + this._listeners = {}; + return this; + } + + public setMaxListeners(maxListeners: number) { + this.maxListeners = maxListeners; + return this; + } + + public getMaxListeners(): number { + return this.maxListeners; + } + + public addEventListener(eventName: string, fn: Callback) { + const wrappedFn = wrapFunction(fn); + super.addEventListener(eventName, wrappedFn as EventListener); + if (!this._listeners[eventName]) { + this._listeners[eventName] = []; + } + this._listeners[eventName].push([fn, wrappedFn]); + } + + public removeEventListener(eventName: string, fn: Callback) { + const eventListeners = this._listeners[eventName]; + if (eventListeners) { + const index = eventListeners.findIndex(item => item[0] === fn); + if (index !== -1) { + super.removeEventListener(eventName, eventListeners[index][1] as EventListener); + eventListeners.splice(index, 1); + } + } + } +} + +// eslint-disable-next-line import/no-mutable-exports +let EventEmitterType: typeof EventEmitterAtNode; +// Check if the code is running in a Node.js environment +if (typeof window === 'undefined') { + EventEmitterType = EventEmitterAtNode; +} else { + // Fallback for the browser environment + EventEmitterType = EventEmitterAtBrowser as unknown as typeof EventEmitterAtNode; +} + +export class EventEmitter extends EventEmitterType {} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-utils/src/formatter.ts b/test/merkletreejs/node_modules/web3-utils/src/formatter.ts new file mode 100644 index 0000000..0cfeb60 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/formatter.ts @@ -0,0 +1,303 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { FormatterError } from 'web3-errors'; +import { Bytes, DataFormat, FMT_BYTES, FMT_NUMBER, FormatType } from 'web3-types'; +import { isNullish, isObject, JsonSchema, utils, ValidationSchemaInput } from 'web3-validator'; +import { bytesToUint8Array, bytesToHex, numberToHex, toBigInt } from './converters.js'; +import { mergeDeep } from './objects.js'; +import { padLeft } from './string_manipulation.js'; +import { uint8ArrayConcat } from './uint8array.js'; + +const { parseBaseType } = utils; + +export const isDataFormat = (dataFormat: unknown): dataFormat is DataFormat => + typeof dataFormat === 'object' && + !isNullish(dataFormat) && + 'number' in dataFormat && + 'bytes' in dataFormat; + +/** + * Finds the schema that corresponds to a specific data path within a larger JSON schema. + * It works by iterating over the dataPath array and traversing the JSON schema one step at a time until it reaches the end of the path. + * + * @param schema - represents a JSON schema, which is an object that describes the structure of JSON data + * @param dataPath - represents an array of strings that specifies the path to the data within the JSON schema + * @param oneOfPath - represents an optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns the JSON schema that matches the data path + * + */ +const findSchemaByDataPath = ( + schema: JsonSchema, + dataPath: string[], + oneOfPath: [string, number][] = [], +): JsonSchema | undefined => { + let result: JsonSchema = { ...schema } as JsonSchema; + let previousDataPath: string | undefined; + + for (const dataPart of dataPath) { + if (result.oneOf && previousDataPath) { + const path = oneOfPath.find(function (element: [string, number]) { + return (this as unknown as string) === element[0]; + }, previousDataPath ?? ''); + + if (path && path[0] === previousDataPath) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access + result = result.oneOf[path[1]]; + } + } + if (!result.properties && !result.items) { + return undefined; + } + + if (result.properties) { + result = (result.properties as Record)[dataPart]; + } else if (result.items && (result.items as JsonSchema).properties) { + const node = (result.items as JsonSchema).properties as Record; + + if (!node) { + return undefined; + } + + result = node[dataPart]; + } else if (result.items && isObject(result.items)) { + result = result.items; + } else if (result.items && Array.isArray(result.items)) { + result = result.items[parseInt(dataPart, 10)]; + } + + if (result && dataPart) previousDataPath = dataPart; + } + + return result; +}; +/** + * Converts a value depending on the format + * @param value - value to convert + * @param ethType - The type of the value to be parsed + * @param format - The format to be converted to + * @returns - The value converted to the specified format + */ +export const convertScalarValue = (value: unknown, ethType: string, format: DataFormat) => { + try { + const { baseType, baseTypeSize } = parseBaseType(ethType); + if (baseType === 'int' || baseType === 'uint') { + switch (format.number) { + case FMT_NUMBER.NUMBER: + return Number(toBigInt(value)); + case FMT_NUMBER.HEX: + return numberToHex(toBigInt(value)); + case FMT_NUMBER.STR: + return toBigInt(value).toString(); + case FMT_NUMBER.BIGINT: + return toBigInt(value); + default: + throw new FormatterError(`Invalid format: ${String(format.number)}`); + } + } + if (baseType === 'bytes') { + let paddedValue; + if (baseTypeSize) { + if (typeof value === 'string') paddedValue = padLeft(value, baseTypeSize * 2); + else if (value instanceof Uint8Array) { + paddedValue = uint8ArrayConcat( + new Uint8Array(baseTypeSize - value.length), + value, + ); + } + } else { + paddedValue = value; + } + switch (format.bytes) { + case FMT_BYTES.HEX: + return bytesToHex(bytesToUint8Array(paddedValue as Bytes)); + case FMT_BYTES.UINT8ARRAY: + return bytesToUint8Array(paddedValue as Bytes); + default: + throw new FormatterError(`Invalid format: ${String(format.bytes)}`); + } + } + } catch (error) { + // If someone didn't use `eth` keyword we can return original value + // as the scope of this code is formatting not validation + return value; + } + + return value; +}; +/** + * Converts the data to the specified format + * @param data - data to convert + * @param schema - The JSON schema that describes the structure of the data + * @param dataPath - A string array that specifies the path to the data within the JSON schema + * @param format - The format to be converted to + * @param oneOfPath - An optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas + * @returns - The data converted to the specified format + */ +export const convert = ( + data: Record | unknown[] | unknown, + schema: JsonSchema, + dataPath: string[], + format: DataFormat, + oneOfPath: [string, number][] = [], +) => { + // If it's a scalar value + if (!isObject(data) && !Array.isArray(data)) { + return convertScalarValue(data, schema?.format as string, format); + } + + const object = data as Record; + + for (const [key, value] of Object.entries(object)) { + dataPath.push(key); + const schemaProp = findSchemaByDataPath(schema, dataPath, oneOfPath); + + // If value is a scaler value + if (isNullish(schemaProp)) { + delete object[key]; + dataPath.pop(); + + continue; + } + + // If value is an object, recurse into it + if (isObject(value)) { + convert(value, schema, dataPath, format); + dataPath.pop(); + continue; + } + + // If value is an array + if (Array.isArray(value)) { + let _schemaProp = schemaProp; + + // TODO This is a naive approach to solving the issue of + // a schema using oneOf. This chunk of code was intended to handle + // BlockSchema.transactions + // TODO BlockSchema.transactions are not being formatted + if (schemaProp?.oneOf !== undefined) { + // The following code is basically saying: + // if the schema specifies oneOf, then we are to loop + // over each possible schema and check if they type of the schema + // matches the type of value[0], and if so we use the oneOfSchemaProp + // as the schema for formatting + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + schemaProp.oneOf.forEach((oneOfSchemaProp: JsonSchema, index: number) => { + if ( + !Array.isArray(schemaProp?.items) && + ((typeof value[0] === 'object' && + (oneOfSchemaProp?.items as JsonSchema)?.type === 'object') || + (typeof value[0] === 'string' && + (oneOfSchemaProp?.items as JsonSchema)?.type !== 'object')) + ) { + _schemaProp = oneOfSchemaProp; + oneOfPath.push([key, index]); + } + }); + } + + if (isNullish(_schemaProp?.items)) { + // Can not find schema for array item, delete that item + delete object[key]; + dataPath.pop(); + + continue; + } + + // If schema for array items is a single type + if (isObject(_schemaProp.items) && !isNullish(_schemaProp.items.format)) { + for (let i = 0; i < value.length; i += 1) { + (object[key] as unknown[])[i] = convertScalarValue( + value[i], + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + _schemaProp?.items?.format, + format, + ); + } + + dataPath.pop(); + continue; + } + + // If schema for array items is an object + if (!Array.isArray(_schemaProp?.items) && _schemaProp?.items?.type === 'object') { + for (const arrObject of value) { + convert( + arrObject as Record | unknown[], + schema, + dataPath, + format, + oneOfPath, + ); + } + + dataPath.pop(); + continue; + } + + // If schema for array is a tuple + if (Array.isArray(_schemaProp?.items)) { + for (let i = 0; i < value.length; i += 1) { + (object[key] as unknown[])[i] = convertScalarValue( + value[i], + _schemaProp.items[i].format as string, + format, + ); + } + + dataPath.pop(); + continue; + } + } + + object[key] = convertScalarValue(value, schemaProp.format as string, format); + + dataPath.pop(); + } + + return object; +}; + +export const format = < + DataType extends Record | unknown[] | unknown, + ReturnType extends DataFormat, +>( + schema: ValidationSchemaInput | JsonSchema, + data: DataType, + returnFormat: ReturnType, +): FormatType => { + let dataToParse: Record | unknown[] | unknown; + + if (isObject(data)) { + dataToParse = mergeDeep({}, data); + } else if (Array.isArray(data)) { + dataToParse = [...data]; + } else { + dataToParse = data; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const jsonSchema: JsonSchema = isObject(schema) ? schema : utils.ethAbiToJsonSchema(schema); + + if (!jsonSchema.properties && !jsonSchema.items && !jsonSchema.format) { + throw new FormatterError('Invalid json schema for formatting'); + } + + return convert(dataToParse, jsonSchema, [], returnFormat) as FormatType< + typeof data, + ReturnType + >; +}; diff --git a/test/merkletreejs/node_modules/web3-utils/src/hash.ts b/test/merkletreejs/node_modules/web3-utils/src/hash.ts new file mode 100644 index 0000000..3d8ec86 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/hash.ts @@ -0,0 +1,380 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * @module Utils + */ + +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { utf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { + InvalidAddressError, + InvalidBooleanError, + InvalidBytesError, + InvalidLargeValueError, + InvalidSizeError, + InvalidStringError, + InvalidUnsignedIntegerError, +} from 'web3-errors'; +import { + Bytes, + EncodingTypes, + Numbers, + Sha3Input, + TypedObject, + TypedObjectAbbreviated, +} from 'web3-types'; +import { isAddress, isNullish, isHexStrict } from 'web3-validator'; +import { + bytesToUint8Array, + bytesToHex, + hexToBytes, + toBigInt, + toHex, + toNumber, + utf8ToHex, +} from './converters.js'; +import { leftPad, rightPad, toTwosComplement } from './string_manipulation.js'; + + +const SHA3_EMPTY_BYTES = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; + +/** + * computes the Keccak-256 hash of the input and returns a hexstring + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.sha3('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3('')); + * > undefined + * ``` + */ +export const sha3 = (data: Bytes): string | undefined => { + let updatedData: Uint8Array; + + if (typeof data === 'string') { + if (data.startsWith('0x') && isHexStrict(data)) { + updatedData = hexToBytes(data); + } else { + updatedData = utf8ToBytes(data); + } + } else { + updatedData = data; + } + const hash = bytesToHex(keccak256(updatedData)); + + // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data + return hash === SHA3_EMPTY_BYTES ? undefined : hash; +}; + +/** + * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed. + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * conosle.log(web3.utils.sha3Raw('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.sha3Raw('')); + * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 + * ``` + */ +export const sha3Raw = (data: Bytes): string => { + const hash = sha3(data); + if (isNullish(hash)) { + return SHA3_EMPTY_BYTES; + } + + return hash; +}; + +/** + * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array` + * @param data - the input to hash + * @returns - the Keccak-256 hash of the input + * + * @example + * ```ts + * console.log(web3.utils.keccak256Wrapper('web3.js')); + * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a + * + * console.log(web3.utils.keccak256Wrapper(1)); + * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6 + * + * console.log(web3.utils.keccak256Wrapper(0xaf12fd)); + * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c + * ``` + */ +export const keccak256Wrapper = ( + data: Bytes | Numbers | string | ReadonlyArray, +): string => { + let processedData; + if (typeof data === 'bigint' || typeof data === 'number') { + processedData = utf8ToBytes(data.toString()); + } else if (Array.isArray(data)) { + processedData = new Uint8Array(data); + } else if (typeof data === 'string' && !isHexStrict(data)) { + processedData = utf8ToBytes(data); + } else { + processedData = bytesToUint8Array(data as Bytes); + } + return bytesToHex(keccak256(processedData)); +}; + +export { keccak256Wrapper as keccak256 }; + +/** + * returns type and value + * @param arg - the input to return the type and value + * @returns - the type and value of the input + */ +const getType = (arg: Sha3Input): [string, EncodingTypes] => { + if (Array.isArray(arg)) { + throw new Error('Autodetection of array types is not supported.'); + } + + let type; + let value; + // if type is given + if ( + typeof arg === 'object' && + ('t' in arg || 'type' in arg) && + ('v' in arg || 'value' in arg) + ) { + type = 't' in arg ? arg.t : arg.type; + value = 'v' in arg ? arg.v : arg.value; + + type = type.toLowerCase() === 'bigint' ? 'int' : type; + } else if (typeof arg === 'bigint') { + return ['int', arg]; + } + // otherwise try to guess the type + else { + type = toHex(arg, true); + value = toHex(arg); + + if (!type.startsWith('int') && !type.startsWith('uint')) { + type = 'bytes'; + } + } + + if ( + (type.startsWith('int') || type.startsWith('uint')) && + typeof value === 'string' && + !/^(-)?0x/i.test(value) + ) { + value = toBigInt(value); + } + return [type, value]; +}; + +/** + * returns the type with size if uint or int + * @param name - the input to return the type with size + * @returns - the type with size of the input + */ +const elementaryName = (name: string): string => { + if (name.startsWith('int[')) { + return `int256${name.slice(3)}`; + } + if (name === 'int') { + return 'int256'; + } + if (name.startsWith('uint[')) { + return `uint256'${name.slice(4)}`; + } + if (name === 'uint') { + return 'uint256'; + } + return name; +}; + +/** + * returns the size of the value of type 'byte' + */ +const parseTypeN = (value: string, typeLength: number): number => { + const typesize = /^(\d+).*$/.exec(value.slice(typeLength)); + return typesize ? parseInt(typesize[1], 10) : 0; +}; + +/** + * returns the bit length of the value + * @param value - the input to return the bit length + * @returns - the bit length of the input + */ +const bitLength = (value: bigint | number): number => { + const updatedVal = value.toString(2); + return updatedVal.length; +}; + +/** + * Pads the value based on size and type + * returns a string of the padded value + * @param type - the input to pad + * @returns = the padded value + */ +const solidityPack = (type: string, val: EncodingTypes): string => { + const value = val.toString(); + if (type === 'string') { + if (typeof val === 'string') return utf8ToHex(val); + throw new InvalidStringError(val); + } + if (type === 'bool' || type === 'boolean') { + if (typeof val === 'boolean') return val ? '01' : '00'; + throw new InvalidBooleanError(val); + } + + if (type === 'address') { + if (!isAddress(value)) { + throw new InvalidAddressError(value); + } + return value; + } + const name = elementaryName(type); + if (type.startsWith('uint')) { + const size = parseTypeN(name, 'uint'.length); + + if (size % 8 || size < 8 || size > 256) { + throw new InvalidSizeError(value); + } + const num = toNumber(value); + if (bitLength(num) > size) { + throw new InvalidLargeValueError(value); + } + if (num < BigInt(0)) { + throw new InvalidUnsignedIntegerError(value); + } + + return size ? leftPad(num.toString(16), (size / 8) * 2) : num.toString(16); + } + + if (type.startsWith('int')) { + const size = parseTypeN(name, 'int'.length); + if (size % 8 || size < 8 || size > 256) { + throw new InvalidSizeError(type); + } + + const num = toNumber(value); + if (bitLength(num) > size) { + throw new InvalidLargeValueError(value); + } + if (num < BigInt(0)) { + return toTwosComplement(num.toString(), (size / 8) * 2); + } + return size ? leftPad(num.toString(16), size / 4) : num.toString(16); + } + + if (name === 'bytes') { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new InvalidBytesError(value); + } + return value; + } + + if (type.startsWith('bytes')) { + if (value.replace(/^0x/i, '').length % 2 !== 0) { + throw new InvalidBytesError(value); + } + + const size = parseTypeN(type, 'bytes'.length); + + if (!size || size < 1 || size > 64 || size < value.replace(/^0x/i, '').length / 2) { + throw new InvalidBytesError(value); + } + + return rightPad(value, size * 2); + } + return ''; +}; + +/** + * returns a string of the tightly packed value given based on the type + * @param arg - the input to return the tightly packed value + * @returns - the tightly packed value + */ +export const processSolidityEncodePackedArgs = (arg: Sha3Input): string => { + const [type, val] = getType(arg); + + // array case + if (Array.isArray(val)) { + // go through each element of the array and use map function to create new hexarg list + const hexArg = val.map((v: Numbers | boolean) => solidityPack(type, v).replace('0x', '')); + return hexArg.join(''); + } + + const hexArg = solidityPack(type, val); + return hexArg.replace('0x', ''); +}; + +/** + * Encode packed arguments to a hexstring + */ +export const encodePacked = (...values: Sha3Input[]): string => { + const hexArgs = values.map(processSolidityEncodePackedArgs); + return `0x${hexArgs.join('').toLowerCase()}`; +}; + +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, or null if input is empty + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log([{ type: 'string', value: '31323334' }]); + * console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" })); + * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b + * ``` + */ +export const soliditySha3 = (...values: Sha3Input[]): string | undefined => + sha3(encodePacked(...values)); + +/** + * Will tightly pack values given in the same way solidity would then hash. + * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` + * @param values - the input to return the tightly packed values + * @returns - the keccack246 of the tightly packed values + * + * @example + * ```ts + * console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" })) + * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0 + * ``` + */ +export const soliditySha3Raw = (...values: TypedObject[] | TypedObjectAbbreviated[]): string => + sha3Raw(encodePacked(...values)); + +/** + * Get slot number for storage long string in contract. Basically for getStorage method + * returns slotNumber where will data placed + * @param mainSlotNumber - the slot number where will be stored hash of long string + * @returns - the slot number where will be stored long string + */ +export const getStorageSlotNumForLongString = (mainSlotNumber: number | string) => + sha3( + `0x${(typeof mainSlotNumber === 'number' + ? mainSlotNumber.toString() + : mainSlotNumber + ).padStart(64, '0')}`, + ); diff --git a/test/merkletreejs/node_modules/web3-utils/src/index.ts b/test/merkletreejs/node_modules/web3-utils/src/index.ts new file mode 100644 index 0000000..52bb219 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/index.ts @@ -0,0 +1,34 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './converters.js'; +export * from './event_emitter.js'; +export * from './validation.js'; +export * from './formatter.js'; +export * from './hash.js'; +export * from './random.js'; +export * from './string_manipulation.js'; +export * from './objects.js'; +export * from './promise_helpers.js'; +export * from './json_rpc.js'; +export * as jsonRpc from './json_rpc.js'; +export * from './web3_deferred_promise.js'; +export * from './chunk_response_parser.js'; +export * from './uuid.js'; +export * from './web3_eip1193_provider.js'; +export * from './socket_provider.js'; +export * from './uint8array.js'; diff --git a/test/merkletreejs/node_modules/web3-utils/src/json_rpc.ts b/test/merkletreejs/node_modules/web3-utils/src/json_rpc.ts new file mode 100644 index 0000000..573d391 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/json_rpc.ts @@ -0,0 +1,130 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { isNullish } from 'web3-validator'; +import { + JsonRpcPayload, + JsonRpcResponse, + JsonRpcResponseWithResult, + JsonRpcResponseWithError, + JsonRpcOptionalRequest, + JsonRpcBatchRequest, + JsonRpcNotification, + JsonRpcRequest, + JsonRpcBatchResponse, + JsonRpcSubscriptionResult, +} from 'web3-types'; +import { rpcErrorsMap } from 'web3-errors'; +import { uuidV4 } from './uuid.js'; + +// check if code is a valid rpc server error code +export const isResponseRpcError = (rpcError: JsonRpcResponseWithError) => { + const errorCode = rpcError.error.code; + return rpcErrorsMap.has(errorCode) || (errorCode >= -32099 && errorCode <= -32000); +}; + +export const isResponseWithResult = ( + response: JsonRpcResponse, +): response is JsonRpcResponseWithResult => + !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + // JSON RPC consider "null" as valid response + 'result' in response && + isNullish(response.error) && + (typeof response.id === 'number' || typeof response.id === 'string'); + +// To avoid circular package dependency, copied to code here. If you update this please update same function in `response_errors.ts` +export const isResponseWithError = ( + response: JsonRpcResponse, +): response is JsonRpcResponseWithError => + !Array.isArray(response) && + response.jsonrpc === '2.0' && + !!response && + isNullish(response.result) && + // JSON RPC consider "null" as valid response + 'error' in response && + (typeof response.id === 'number' || typeof response.id === 'string'); + +export const isResponseWithNotification = ( + response: JsonRpcNotification | JsonRpcSubscriptionResult, +): response is JsonRpcNotification => + !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + !isNullish(response.params) && + !isNullish(response.method); + +export const isSubscriptionResult = ( + response: JsonRpcNotification | JsonRpcSubscriptionResult, +): response is JsonRpcSubscriptionResult => + !Array.isArray(response) && + !!response && + response.jsonrpc === '2.0' && + 'id' in response && + // JSON RPC consider "null" as valid response + 'result' in response; + +export const validateResponse = ( + response: JsonRpcResponse, +): boolean => isResponseWithResult(response) || isResponseWithError(response); + +export const isValidResponse = ( + response: JsonRpcResponse, +): boolean => + Array.isArray(response) ? response.every(validateResponse) : validateResponse(response); + +export const isBatchResponse = ( + response: JsonRpcResponse, +): response is JsonRpcBatchResponse => + Array.isArray(response) && response.length > 0 && isValidResponse(response); + +// internal optional variable to increment and use for the jsonrpc `id` +let requestIdSeed: number | undefined; + +/** + * Optionally use to make the jsonrpc `id` start from a specific number. + * Without calling this function, the `id` will be filled with a Uuid. + * But after this being called with a number, the `id` will be a number staring from the provided `start` variable. + * However, if `undefined` was passed to this function, the `id` will be a Uuid again. + * @param start - a number to start incrementing from. + * Or `undefined` to use a new Uuid (this is the default behavior) + */ +export const setRequestIdStart = (start: number | undefined) => { + requestIdSeed = start; +}; + +export const toPayload = ( + request: JsonRpcOptionalRequest, +): JsonRpcPayload => { + if (typeof requestIdSeed !== 'undefined') { + requestIdSeed += 1; + } + return { + jsonrpc: request.jsonrpc ?? '2.0', + id: request.id ?? requestIdSeed ?? uuidV4(), + method: request.method, + params: request.params ?? undefined, + }; +}; + +export const toBatchPayload = (requests: JsonRpcOptionalRequest[]): JsonRpcBatchRequest => + requests.map(request => toPayload(request)) as JsonRpcBatchRequest; + +export const isBatchRequest = ( + request: JsonRpcBatchRequest | JsonRpcRequest | JsonRpcOptionalRequest, +): request is JsonRpcBatchRequest => Array.isArray(request) && request.length > 0; diff --git a/test/merkletreejs/node_modules/web3-utils/src/objects.ts b/test/merkletreejs/node_modules/web3-utils/src/objects.ts new file mode 100644 index 0000000..4ed6c32 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/objects.ts @@ -0,0 +1,64 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { TypedArray } from 'web3-types'; +import { isNullish } from 'web3-validator'; + +const isIterable = (item: unknown): item is Record => + typeof item === 'object' && + !isNullish(item) && + !Array.isArray(item) && + !(item instanceof TypedArray); + +// The following code is a derivative work of the code from the "LiskHQ/lisk-sdk" project, +// which is licensed under Apache version 2. +/** + * Deep merge two objects. + * @param destination - The destination object. + * @param sources - An array of source objects. + * @returns - The merged object. + */ +export const mergeDeep = ( + destination: Record, + ...sources: Record[] +): Record => { + const result = destination; // clone deep here + if (!isIterable(result)) { + return result; + } + for (const src of sources) { + // eslint-disable-next-line no-restricted-syntax + for (const key in src) { + if (isIterable(src[key])) { + if (!result[key]) { + result[key] = {}; + } + mergeDeep( + result[key] as Record, + src[key] as Record, + ); + } else if (!isNullish(src[key]) && Object.hasOwnProperty.call(src, key)) { + if (Array.isArray(src[key]) || src[key] instanceof TypedArray) { + result[key] = (src[key] as unknown[]).slice(0); + } else { + result[key] = src[key]; + } + } + } + } + return result; +}; diff --git a/test/merkletreejs/node_modules/web3-utils/src/promise_helpers.ts b/test/merkletreejs/node_modules/web3-utils/src/promise_helpers.ts new file mode 100644 index 0000000..c8e211f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/promise_helpers.ts @@ -0,0 +1,171 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { isNullish } from 'web3-validator'; + +export type Timer = ReturnType; +export type Timeout = ReturnType; + + +/** + * An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser. + * @param object - to check if it is a `Promise` + * @returns `true` if it is an `object` or a `function` that has a `then` function. And returns `false` otherwise. + */ +export function isPromise(object: unknown): boolean { + return ( + (typeof object === 'object' || typeof object === 'function') && + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + typeof (object as { then: unknown }).then === 'function' + ); +} + +export type AsyncFunction = (...args: K[]) => Promise; + +export function waitWithTimeout( + awaitable: Promise | AsyncFunction, + timeout: number, + error: Error, +): Promise; +export function waitWithTimeout( + awaitable: Promise | AsyncFunction, + timeout: number, +): Promise; + +/** + * Wait for a promise but interrupt it if it did not resolve within a given timeout. + * If the timeout reached, before the promise code resolve, either throw an error if an error object was provided, or return `undefined`. + * @param awaitable - The promise or function to wait for. + * @param timeout - The timeout in milliseconds. + * @param error - (Optional) The error to throw if the timeout reached. + */ +export async function waitWithTimeout( + awaitable: Promise | AsyncFunction, + timeout: number, + error?: Error, +): Promise { + let timeoutId: Timeout | undefined; + const result = await Promise.race([ + awaitable instanceof Promise ? awaitable : awaitable(), + new Promise((resolve, reject) => { + timeoutId = setTimeout(() => (error ? reject(error) : resolve(undefined)), timeout); + }), + ]); + if (timeoutId) { + clearTimeout(timeoutId); + } + if (result instanceof Error) { + throw result; + } + return result; +} + + +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. It returns promise and intervalId. + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export function pollTillDefinedAndReturnIntervalId( + func: AsyncFunction, + interval: number, +): [Promise>, Timer] { + + let intervalId: Timer | undefined; + const polledRes = new Promise>((resolve, reject) => { + intervalId = setInterval(function intervalCallbackFunc(){ + (async () => { + try { + const res = await waitWithTimeout(func, interval); + + if (!isNullish(res)) { + clearInterval(intervalId); + resolve(res as unknown as Exclude); + } + } catch (error) { + clearInterval(intervalId); + reject(error); + } + })() as unknown; + return intervalCallbackFunc;}() // this will immediate invoke first call + , interval); + }); + + return [polledRes as unknown as Promise>, intervalId!]; +} + +/** + * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), + * or until a timeout is reached. + * pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result. + * This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId(). + * @param func - The function to call. + * @param interval - The interval in milliseconds. + */ +export async function pollTillDefined( + func: AsyncFunction, + interval: number, +): Promise> { + return pollTillDefinedAndReturnIntervalId(func, interval)[0]; +} +/** + * Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete + * @param timeout - The timeout to enforced in milliseconds. + * @param error - The error to throw if the timeout is reached. + * @returns A tuple of the timeout id and the promise that will be rejected if the timeout is reached. + * + * @example + * ```ts + * const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out')); + * ``` + */ +export function rejectIfTimeout(timeout: number, error: Error): [Timer, Promise] { + let timeoutId: Timer | undefined; + const rejectOnTimeout = new Promise((_, reject) => { + timeoutId = setTimeout(() => { + reject(error); + }, timeout); + }); + return [timeoutId!, rejectOnTimeout]; +} +/** + * Sets an interval that repeatedly executes the given cond function with the specified interval between each call. + * If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned. + * @param cond - The function/confition to call. + * @param interval - The interval in milliseconds. + * @returns - an array with the interval ID and the Promise. + */ +export function rejectIfConditionAtInterval( + cond: AsyncFunction, + interval: number, +): [Timer, Promise] { + let intervalId: Timer | undefined; + const rejectIfCondition = new Promise((_, reject) => { + intervalId = setInterval(() => { + (async () => { + const error = await cond(); + if (error) { + clearInterval(intervalId); + reject(error); + } + })() as unknown; + }, interval); + }); + return [intervalId!, rejectIfCondition]; +} + diff --git a/test/merkletreejs/node_modules/web3-utils/src/random.ts b/test/merkletreejs/node_modules/web3-utils/src/random.ts new file mode 100644 index 0000000..2898c93 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/random.ts @@ -0,0 +1,49 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { getRandomBytesSync } from 'ethereum-cryptography/random.js'; +import { bytesToHex } from './converters.js'; + +/** + * Returns a random byte array by the given bytes size + * @param size - The size of the random byte array returned + * @returns - random byte array + * + * @example + * ```ts + * console.log(web3.utils.randomBytes(32)); + * > Uint8Array(32) [ + * 93, 172, 226, 32, 33, 176, 156, 156, + * 182, 30, 240, 2, 69, 96, 174, 197, + * 33, 136, 194, 241, 197, 156, 110, 111, + * 66, 87, 17, 88, 67, 48, 245, 183 + * ] + * ``` + */ +export const randomBytes = (size: number): Uint8Array => getRandomBytesSync(size); + +/** + * Returns a random hex string by the given bytes size + * @param byteSize - The size of the random hex string returned + * @returns - random hex string + * + * ```ts + * console.log(web3.utils.randomHex(32)); + * > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e + * ``` + */ +export const randomHex = (byteSize: number): string => bytesToHex(randomBytes(byteSize)); diff --git a/test/merkletreejs/node_modules/web3-utils/src/socket_provider.ts b/test/merkletreejs/node_modules/web3-utils/src/socket_provider.ts new file mode 100644 index 0000000..3c879a2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/socket_provider.ts @@ -0,0 +1,575 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { + ConnectionEvent, + Eip1193EventName, + EthExecutionAPI, + JsonRpcBatchRequest, + JsonRpcBatchResponse, + JsonRpcId, + JsonRpcNotification, + JsonRpcRequest, + JsonRpcResponse, + JsonRpcResponseWithResult, + JsonRpcResult, + ProviderConnectInfo, + ProviderMessage, + ProviderRpcError, + SocketRequestItem, + Web3APIMethod, + Web3APIPayload, + Web3APIReturnType, + Web3APISpec, + Web3Eip1193ProviderEventCallback, + Web3ProviderEventCallback, + Web3ProviderMessageEventCallback, + Web3ProviderStatus, +} from 'web3-types'; +import { + ConnectionError, + ConnectionNotOpenError, + InvalidClientError, + MaxAttemptsReachedOnReconnectingError, + PendingRequestsOnReconnectingError, + RequestAlreadySentError, + Web3WSProviderError, +} from 'web3-errors'; +import { Eip1193Provider } from './web3_eip1193_provider.js'; +import { ChunkResponseParser } from './chunk_response_parser.js'; +import { isNullish } from './validation.js'; +import { Web3DeferredPromise } from './web3_deferred_promise.js'; +import * as jsonRpc from './json_rpc.js'; + +export type ReconnectOptions = { + autoReconnect: boolean; + delay: number; + maxAttempts: number; +}; + +const DEFAULT_RECONNECTION_OPTIONS = { + autoReconnect: true, + delay: 5000, + maxAttempts: 5, +}; + +const NORMAL_CLOSE_CODE = 1000; // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close + +export abstract class SocketProvider< + MessageEvent, + CloseEvent, + ErrorEvent, + API extends Web3APISpec = EthExecutionAPI, +> extends Eip1193Provider { + protected isReconnecting: boolean; + protected readonly _socketPath: string; + protected readonly chunkResponseParser: ChunkResponseParser; + /* eslint-disable @typescript-eslint/no-explicit-any */ + protected readonly _pendingRequestsQueue: Map>; + /* eslint-disable @typescript-eslint/no-explicit-any */ + protected readonly _sentRequestsQueue: Map>; + protected _reconnectAttempts!: number; + protected readonly _socketOptions?: unknown; + protected readonly _reconnectOptions: ReconnectOptions; + protected _socketConnection?: unknown; + public get SocketConnection() { + return this._socketConnection; + } + protected _connectionStatus: Web3ProviderStatus; + protected readonly _onMessageHandler: (event: MessageEvent) => void; + protected readonly _onOpenHandler: () => void; + protected readonly _onCloseHandler: (event: CloseEvent) => void; + protected readonly _onErrorHandler: (event: ErrorEvent) => void; + + /** + * This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}. + * @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546) + * @param socketOptions - The options for the socket connection. Its type is supposed to be specified in the inherited classes. + * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions} + */ + public constructor( + socketPath: string, + socketOptions?: unknown, + reconnectOptions?: Partial, + ) { + super(); + this._connectionStatus = 'connecting'; + + // Message handlers. Due to bounding of `this` and removing the listeners we have to keep it's reference. + this._onMessageHandler = this._onMessage.bind(this); + this._onOpenHandler = this._onConnect.bind(this); + this._onCloseHandler = this._onCloseEvent.bind(this); + this._onErrorHandler = this._onError.bind(this); + + if (!this._validateProviderPath(socketPath)) throw new InvalidClientError(socketPath); + + this._socketPath = socketPath; + this._socketOptions = socketOptions; + + this._reconnectOptions = { + ...DEFAULT_RECONNECTION_OPTIONS, + ...(reconnectOptions ?? {}), + }; + + this._pendingRequestsQueue = new Map>(); + this._sentRequestsQueue = new Map>(); + + this._init(); + this.connect(); + this.chunkResponseParser = new ChunkResponseParser( + this._eventEmitter, + this._reconnectOptions.autoReconnect, + ); + this.chunkResponseParser.onError(() => { + this._clearQueues(); + }); + this.isReconnecting = false; + } + + protected _init() { + this._reconnectAttempts = 0; + } + + /** + * Try to establish a connection to the socket + */ + public connect(): void { + try { + this._openSocketConnection(); + this._connectionStatus = 'connecting'; + this._addSocketListeners(); + } catch (e) { + if (!this.isReconnecting) { + this._connectionStatus = 'disconnected'; + if (e && (e as Error).message) { + throw new ConnectionError( + `Error while connecting to ${this._socketPath}. Reason: ${ + (e as Error).message + }`, + ); + } else { + throw new InvalidClientError(this._socketPath); + } + } else { + setImmediate(() => { + this._reconnect(); + }); + } + } + } + + protected abstract _openSocketConnection(): void; + protected abstract _addSocketListeners(): void; + + protected abstract _removeSocketListeners(): void; + + protected abstract _onCloseEvent(_event: unknown): void; + + protected abstract _sendToSocket(_payload: Web3APIPayload): void; + + protected abstract _parseResponses(_event: MessageEvent): JsonRpcResponse[]; + + protected abstract _closeSocketConnection(_code?: number, _data?: string): void; + + // eslint-disable-next-line class-methods-use-this + protected _validateProviderPath(path: string): boolean { + return !!path; + } + + /** + * + * @returns the pendingRequestQueue size + */ + // eslint-disable-next-line class-methods-use-this + public getPendingRequestQueueSize() { + return this._pendingRequestsQueue.size; + } + + /** + * + * @returns the sendPendingRequests size + */ + // eslint-disable-next-line class-methods-use-this + public getSentRequestsQueueSize() { + return this._sentRequestsQueue.size; + } + + /** + * + * @returns `true` if the socket supports subscriptions + */ + // eslint-disable-next-line class-methods-use-this + public supportsSubscriptions(): boolean { + return true; + } + + /** + * Registers a listener for the specified event type. + * @param type - The event type to listen for + * @param listener - The callback to be invoked when the event is emitted + */ + public on( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public on( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public on(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + public on(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + public on( + type: 'message', + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + public on( + type: string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public on( + type: string | Eip1193EventName, + listener: + | Web3Eip1193ProviderEventCallback

+ | Web3ProviderMessageEventCallback + | Web3ProviderEventCallback, + ): void { + this._eventEmitter.on(type, listener); + } + + /** + * Registers a listener for the specified event type that will be invoked at most once. + * @param type - The event type to listen for + * @param listener - The callback to be invoked when the event is emitted + */ + public once( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public once( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public once(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + public once( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public once( + type: 'message', + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + public once( + type: string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public once( + type: string | Eip1193EventName, + listener: + | Web3Eip1193ProviderEventCallback

+ | Web3ProviderMessageEventCallback + | Web3ProviderEventCallback, + ): void { + this._eventEmitter.once(type, listener); + } + + /** + * Removes a listener for the specified event type. + * @param type - The event type to remove the listener for + * @param listener - The callback to be executed + */ + public removeListener( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: 'chainChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: 'message', + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + public removeListener( + type: string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public removeListener( + type: string | Eip1193EventName, + listener: + | Web3Eip1193ProviderEventCallback

+ | Web3ProviderMessageEventCallback + | Web3ProviderEventCallback, + ): void { + this._eventEmitter.removeListener(type, listener); + } + + protected _onDisconnect(code: number, data?: string) { + this._connectionStatus = 'disconnected'; + super._onDisconnect(code, data); + } + + /** + * Disconnects the socket + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + public disconnect(code?: number, data?: string): void { + const disconnectCode = code ?? NORMAL_CLOSE_CODE; + this._removeSocketListeners(); + if (this.getStatus() !== 'disconnected') { + this._closeSocketConnection(disconnectCode, data); + } + this._onDisconnect(disconnectCode, data); + } + + /** + * Safely disconnects the socket, async and waits for request size to be 0 before disconnecting + * @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0 + * @param ms - Determines the ms of setInterval + * @param code - The code to be sent to the server + * @param data - The data to be sent to the server + */ + public async safeDisconnect(code?: number, data?: string, forceDisconnect = false,ms = 1000) { + let retryAttempt = 0; + const checkQueue = async () => + new Promise(resolve => { + const interval = setInterval(() => { + if (forceDisconnect && retryAttempt === 5) { + this.clearQueues(); + } + if (this.getPendingRequestQueueSize() === 0 && this.getSentRequestsQueueSize() === 0) { + clearInterval(interval); + resolve(true); + } + retryAttempt+=1; + }, ms) + }) + + await checkQueue(); + this.disconnect(code, data); + } + + + /** + * Removes all listeners for the specified event type. + * @param type - The event type to remove the listeners for + */ + public removeAllListeners(type: string): void { + this._eventEmitter.removeAllListeners(type); + } + + protected _onError(event: ErrorEvent): void { + // do not emit error while trying to reconnect + if (this.isReconnecting) { + this._reconnect(); + } else { + this._eventEmitter.emit('error', event); + } + } + + /** + * Resets the socket, removing all listeners and pending requests + */ + public reset(): void { + this._sentRequestsQueue.clear(); + this._pendingRequestsQueue.clear(); + + this._init(); + this._removeSocketListeners(); + this._addSocketListeners(); + } + + protected _reconnect(): void { + if (this.isReconnecting) { + return; + } + this.isReconnecting = true; + + if (this._sentRequestsQueue.size > 0) { + this._sentRequestsQueue.forEach( + (request: SocketRequestItem, key: JsonRpcId) => { + request.deferredPromise.reject(new PendingRequestsOnReconnectingError()); + this._sentRequestsQueue.delete(key); + }, + ); + } + + if (this._reconnectAttempts < this._reconnectOptions.maxAttempts) { + this._reconnectAttempts += 1; + setTimeout(() => { + this._removeSocketListeners(); + this.connect(); + this.isReconnecting = false; + }, this._reconnectOptions.delay); + } else { + this.isReconnecting = false; + this._clearQueues(); + this._removeSocketListeners(); + this._eventEmitter.emit( + 'error', + new MaxAttemptsReachedOnReconnectingError(this._reconnectOptions.maxAttempts), + ); + } + } + + /** + * Creates a request object to be sent to the server + */ + public async request< + Method extends Web3APIMethod, + ResultType = Web3APIReturnType, + >(request: Web3APIPayload): Promise> { + if (isNullish(this._socketConnection)) { + throw new Error('Connection is undefined'); + } + // if socket disconnected - open connection + if (this.getStatus() === 'disconnected') { + this.connect(); + } + + const requestId = jsonRpc.isBatchRequest(request) + ? (request as unknown as JsonRpcBatchRequest)[0].id + : (request as unknown as JsonRpcRequest).id; + + if (!requestId) { + throw new Web3WSProviderError('Request Id not defined'); + } + + if (this._sentRequestsQueue.has(requestId)) { + throw new RequestAlreadySentError(requestId); + } + + const deferredPromise = new Web3DeferredPromise>(); + deferredPromise.catch(error => { + this._eventEmitter.emit('error', error); + }); + const reqItem: SocketRequestItem> = { + payload: request, + deferredPromise, + }; + + if (this.getStatus() === 'connecting') { + this._pendingRequestsQueue.set(requestId, reqItem); + + return reqItem.deferredPromise; + } + + this._sentRequestsQueue.set(requestId, reqItem); + + try { + this._sendToSocket(reqItem.payload); + } catch (error) { + this._sentRequestsQueue.delete(requestId); + + this._eventEmitter.emit('error', error); + } + + return deferredPromise; + } + + protected _onConnect() { + this._connectionStatus = 'connected'; + this._reconnectAttempts = 0; + super._onConnect(); + this._sendPendingRequests(); + } + + private _sendPendingRequests() { + for (const [id, value] of this._pendingRequestsQueue.entries()) { + this._sendToSocket(value.payload as Web3APIPayload); + this._pendingRequestsQueue.delete(id); + this._sentRequestsQueue.set(id, value); + } + } + + protected _onMessage(event: MessageEvent): void { + const responses = this._parseResponses(event); + if (isNullish(responses) || responses.length === 0) { + return; + } + + for (const response of responses) { + if ( + jsonRpc.isResponseWithNotification(response as JsonRpcNotification) && + (response as JsonRpcNotification).method.endsWith('_subscription') + ) { + this._eventEmitter.emit('message', response); + return; + } + + const requestId = jsonRpc.isBatchResponse(response) + ? (response as unknown as JsonRpcBatchResponse)[0].id + : (response as unknown as JsonRpcResponseWithResult).id; + + const requestItem = this._sentRequestsQueue.get(requestId); + + if (!requestItem) { + return; + } + + if ( + jsonRpc.isBatchResponse(response) || + jsonRpc.isResponseWithResult(response) || + jsonRpc.isResponseWithError(response) + ) { + this._eventEmitter.emit('message', response); + requestItem.deferredPromise.resolve(response); + } + + this._sentRequestsQueue.delete(requestId); + } + } + + public clearQueues(event?: ConnectionEvent) { + this._clearQueues(event); + } + + protected _clearQueues(event?: ConnectionEvent) { + if (this._pendingRequestsQueue.size > 0) { + this._pendingRequestsQueue.forEach( + (request: SocketRequestItem, key: JsonRpcId) => { + request.deferredPromise.reject(new ConnectionNotOpenError(event)); + this._pendingRequestsQueue.delete(key); + }, + ); + } + + if (this._sentRequestsQueue.size > 0) { + this._sentRequestsQueue.forEach( + (request: SocketRequestItem, key: JsonRpcId) => { + request.deferredPromise.reject(new ConnectionNotOpenError(event)); + this._sentRequestsQueue.delete(key); + }, + ); + } + + this._removeSocketListeners(); + } +} diff --git a/test/merkletreejs/node_modules/web3-utils/src/string_manipulation.ts b/test/merkletreejs/node_modules/web3-utils/src/string_manipulation.ts new file mode 100644 index 0000000..b7d0371 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/string_manipulation.ts @@ -0,0 +1,162 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Numbers } from 'web3-types'; +import { NibbleWidthError } from 'web3-errors'; +import { isHexStrict, validator, utils as validatorUtils, bigintPower } from 'web3-validator'; +import { numberToHex, toHex, toNumber } from './converters.js'; + +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * + * console.log(web3.utils.padLeft('0x123', 10)); + * >0x0000000123 + * ``` + */ +export const padLeft = (value: Numbers, characterAmount: number, sign = '0'): string => { + // To avoid duplicate code and circular dependency we will + // use `padLeft` implementation from `web3-validator` + + if (typeof value === 'string') { + if (!isHexStrict(value)) { + return value.padStart(characterAmount, sign); + } + return validatorUtils.padLeft(value, characterAmount, sign); + } + + validator.validate(['int'], [value]); + + return validatorUtils.padLeft(value, characterAmount, sign); +}; + +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. + * @param value - The value to be padded. + * @param characterAmount - The amount of characters the string should have. + * @param sign - The sign to be added (default is 0). + * @returns The padded string. + * + * @example + * ```ts + * console.log(web3.utils.padRight('0x123', 10)); + * > 0x1230000000 + * + * console.log(web3.utils.padRight('0x123', 10, '1')); + * > 0x1231111111 + * ``` + */ +export const padRight = (value: Numbers, characterAmount: number, sign = '0'): string => { + if (typeof value === 'string' && !isHexStrict(value)) { + return value.padEnd(characterAmount, sign); + } + + validator.validate(['int'], [value]); + + const hexString = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value); + + const prefixLength = hexString.startsWith('-') ? 3 : 2; + return hexString.padEnd(characterAmount + prefixLength, sign); +}; + +/** + * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight` + */ +export const rightPad = padRight; + +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft` + */ +export const leftPad = padLeft; + +/** + * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * + * @returns The hex string of the two’s complement. + * + * @example + * ```ts + * console.log(web3.utils.toTwosComplement(13, 32)); + * > 0x0000000000000000000000000000000d + * + * console.log(web3.utils.toTwosComplement('-0x1', 32)); + * > 0xffffffffffffffffffffffffffffffff + * + * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32)); + * > 0x00000000000000000020000000000000 + * ``` + */ +export const toTwosComplement = (value: Numbers, nibbleWidth = 64): string => { + validator.validate(['int'], [value]); + + const val = toNumber(value); + + if (val >= 0) return padLeft(toHex(val), nibbleWidth); + + const largestBit = bigintPower(BigInt(2), BigInt(nibbleWidth * 4)); + if (-val >= largestBit) { + throw new NibbleWidthError(`value: ${value}, nibbleWidth: ${nibbleWidth}`); + } + const updatedVal = BigInt(val); + + const complement = updatedVal + largestBit; + + return padLeft(numberToHex(complement), nibbleWidth); +}; + +/** + * Converts the twos complement into a decimal number or big int. + * @param value - The value to be converted. + * @param nibbleWidth - The nibble width of the hex string (default is 64). + * @returns The decimal number or big int. + * + * @example + * ```ts + * console.log(web3.utils.fromTwosComplement(''0x0000000000000000000000000000000d', 32')); + * > 13 + * + * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32)); + * > 9007199254740992n + * ``` + */ +export const fromTwosComplement = (value: Numbers, nibbleWidth = 64): number | bigint => { + validator.validate(['int'], [value]); + + const val = toNumber(value); + + if (val < 0) return val; + + const largestBit = Math.ceil(Math.log(Number(val)) / Math.log(2)); + + if (largestBit > nibbleWidth * 4) + throw new NibbleWidthError(`value: "${value}", nibbleWidth: "${nibbleWidth}"`); + + // check the largest bit to see if negative + if (nibbleWidth * 4 !== largestBit) return val; + + const complement = bigintPower(BigInt(2), BigInt(nibbleWidth) * BigInt(4)); + + return toNumber(BigInt(val) - complement); +}; diff --git a/test/merkletreejs/node_modules/web3-utils/src/uint8array.ts b/test/merkletreejs/node_modules/web3-utils/src/uint8array.ts new file mode 100644 index 0000000..0f1173b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/uint8array.ts @@ -0,0 +1,50 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export function uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array { + const length = parts.reduce((prev, part) => { + const agg = prev + part.length; + return agg; + }, 0); + const result = new Uint8Array(length); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.length; + } + return result; +} + +/** + * Returns true if the two passed Uint8Arrays have the same content + */ +export function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean { + if (a === b) { + return true; + } + + if (a.byteLength !== b.byteLength) { + return false; + } + + for (let i = 0; i < a.byteLength; i += 1) { + if (a[i] !== b[i]) { + return false; + } + } + + return true; +} diff --git a/test/merkletreejs/node_modules/web3-utils/src/uuid.ts b/test/merkletreejs/node_modules/web3-utils/src/uuid.ts new file mode 100644 index 0000000..369cdc8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/uuid.ts @@ -0,0 +1,55 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { bytesToHex } from './converters.js'; +import { randomBytes } from './random.js'; + +/** + * Generate a version 4 (random) uuid + * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5 + * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx + * @example + * ```ts + * console.log(web3.utils.uuidV4()); + * > "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed" + * ``` + */ +export const uuidV4 = (): string => { + const bytes = randomBytes(16); + + // https://github.com/ethers-io/ethers.js/blob/ce8f1e4015c0f27bf178238770b1325136e3351a/packages/json-wallets/src.ts/utils.ts#L54 + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + /* eslint-disable-next-line */ + bytes[6] = (bytes[6] & 0x0f) | 0x40; + + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + /* eslint-disable-next-line */ + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + const hexString = bytesToHex(bytes); + + return [ + hexString.substring(2, 10), + hexString.substring(10, 14), + hexString.substring(14, 18), + hexString.substring(18, 22), + hexString.substring(22, 34), + ].join('-'); +}; diff --git a/test/merkletreejs/node_modules/web3-utils/src/validation.ts b/test/merkletreejs/node_modules/web3-utils/src/validation.ts new file mode 100644 index 0000000..f0b25c3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/validation.ts @@ -0,0 +1,190 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { InvalidBlockError } from 'web3-errors'; +import { + checkAddressCheckSum as checkAddressCheckSumValidator, + isAddress as isAddressValidator, + isBlockTag, + isBloom as isBloomValidator, + isContractAddressInBloom as isContractAddressInBloomValidator, + isHex as isHexValidator, + isHexStrict as isHexStrictValidator, + isInBloom as isInBloomValidator, + isNullish as isNullishValidator, + isTopic as isTopicValidator, + isTopicInBloom as isTopicInBloomValidator, + isUserEthereumAddressInBloom as isUserEthereumAddressInBloomValidator, +} from 'web3-validator'; +import { BlockNumberOrTag, BlockTags, ContractInitOptions } from 'web3-types'; + +/** + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isHexStrict = isHexStrictValidator; + +/** + * returns true if input is a hexstring, number or bigint + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isHex = isHexValidator; + +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const checkAddressCheckSum = checkAddressCheckSumValidator; + +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isAddress = isAddressValidator; + +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isBloom = isBloomValidator; + +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isInBloom = isInBloomValidator; + +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isUserEthereumAddressInBloom = isUserEthereumAddressInBloomValidator; + +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isContractAddressInBloom = isContractAddressInBloomValidator; + +/** + * Checks if its a valid topic + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isTopic = isTopicValidator; + +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + * + * @deprecated Will be removed in next release. Please use `web3-validator` package instead. + */ +export const isTopicInBloom = isTopicInBloomValidator; + +/** + * Compares between block A and block B + * @param blockA - Block number or string + * @param blockB - Block number or string + * + * @returns - Returns -1 if a \< b, returns 1 if a \> b and returns 0 if a == b + * + * @example + * ```ts + * console.log(web3.utils.compareBlockNumbers('latest', 'pending')); + * > -1 + * + * console.log(web3.utils.compareBlockNumbers(12, 11)); + * > 1 + * ``` + */ +export const compareBlockNumbers = (blockA: BlockNumberOrTag, blockB: BlockNumberOrTag) => { + const isABlockTag = typeof blockA === 'string' && isBlockTag(blockA); + const isBBlockTag = typeof blockB === 'string' && isBlockTag(blockB); + + if ( + blockA === blockB || + ((blockA === 'earliest' || blockA === 0) && (blockB === 'earliest' || blockB === 0)) // only exception compare blocktag with number + ) { + return 0; + } + if (blockA === 'earliest' && blockB > 0) { + return -1; + } + if (blockB === 'earliest' && blockA > 0) { + return 1; + } + + if (isABlockTag && isBBlockTag) { + // Increasing order: earliest, finalized , safe, latest, pending + const tagsOrder = { + [BlockTags.EARLIEST as string]: 1, + [BlockTags.FINALIZED as string]: 2, + [BlockTags.SAFE as string]: 3, + [BlockTags.LATEST as string]: 4, + [BlockTags.PENDING as string]: 5, + }; + + if (tagsOrder[blockA] < tagsOrder[blockB]) { + return -1; + } + + return 1; + } + if ((isABlockTag && !isBBlockTag) || (!isABlockTag && isBBlockTag)) { + throw new InvalidBlockError('Cannot compare blocktag with provided non-blocktag input.'); + } + + const bigIntA = BigInt(blockA); + const bigIntB = BigInt(blockB); + + if (bigIntA < bigIntB) { + return -1; + } + if (bigIntA === bigIntB) { + return 0; + } + return 1; +}; + + +export const isContractInitOptions = (options: unknown): options is ContractInitOptions => + typeof options === 'object' && + !isNullishValidator(options) && + Object.keys(options).length !== 0 && + [ + 'input', + 'data', + 'from', + 'gas', + 'gasPrice', + 'gasLimit', + 'address', + 'jsonInterface', + 'syncWithContext', + 'dataInputFill', + ].some(key => key in options); + +export const isNullish = isNullishValidator; diff --git a/test/merkletreejs/node_modules/web3-utils/src/web3_deferred_promise.ts b/test/merkletreejs/node_modules/web3-utils/src/web3_deferred_promise.ts new file mode 100644 index 0000000..01805b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/web3_deferred_promise.ts @@ -0,0 +1,149 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { OperationTimeoutError } from 'web3-errors'; +import { Web3DeferredPromiseInterface } from 'web3-types'; +import { Timeout } from './promise_helpers.js'; + +/** + * The class is a simple implementation of a deferred promise with optional timeout functionality, + * which can be useful when dealing with asynchronous tasks. + * + */ +export class Web3DeferredPromise implements Promise, Web3DeferredPromiseInterface { + // public tag to treat object as promise by different libs + // eslint-disable-next-line @typescript-eslint/prefer-as-const + public [Symbol.toStringTag]: 'Promise' = 'Promise'; + + private readonly _promise: Promise; + private _resolve!: (value: T | PromiseLike) => void; + private _reject!: (reason?: unknown) => void; + private _state: 'pending' | 'fulfilled' | 'rejected' = 'pending'; + private _timeoutId?: Timeout; + private readonly _timeoutInterval?: number; + private readonly _timeoutMessage: string; + + /** + * + * @param timeout - (optional) The timeout in milliseconds. + * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created. + * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out. + */ + public constructor( + { + timeout, + eagerStart, + timeoutMessage, + }: { timeout: number; eagerStart: boolean; timeoutMessage: string } = { + timeout: 0, + eagerStart: false, + timeoutMessage: 'DeferredPromise timed out', + }, + ) { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + + this._timeoutMessage = timeoutMessage; + this._timeoutInterval = timeout; + + if (eagerStart) { + this.startTimer(); + } + } + /** + * Returns the current state of the promise. + * @returns 'pending' | 'fulfilled' | 'rejected' + */ + public get state(): 'pending' | 'fulfilled' | 'rejected' { + return this._state; + } + /** + * + * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled. + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + public async then( + onfulfilled?: (value: T) => TResult1 | PromiseLike, + onrejected?: (reason: unknown) => TResult2 | PromiseLike, + ): Promise { + return this._promise.then(onfulfilled, onrejected); + } + /** + * + * @param onrejected - (optional) The callback to execute when the promise is rejected. + * @returns + */ + public async catch( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onrejected?: (reason: any) => TResult | PromiseLike, + ): Promise { + return this._promise.catch(onrejected); + } + + /** + * + * @param onfinally - (optional) The callback to execute when the promise is settled (fulfilled or rejected). + * @returns + */ + public async finally(onfinally?: (() => void) | undefined): Promise { + return this._promise.finally(onfinally); + } + + /** + * Resolves the current promise. + * @param value - The value to resolve the promise with. + */ + public resolve(value: T | PromiseLike): void { + this._resolve(value); + this._state = 'fulfilled'; + this._clearTimeout(); + } + + /** + * Rejects the current promise. + * @param reason - The reason to reject the promise with. + */ + public reject(reason?: unknown): void { + this._reject(reason); + this._state = 'rejected'; + this._clearTimeout(); + } + + /** + * Starts the timeout timer for the promise. + */ + public startTimer() { + if (this._timeoutInterval && this._timeoutInterval > 0) { + this._timeoutId = setTimeout(this._checkTimeout.bind(this), this._timeoutInterval); + } + } + + private _checkTimeout() { + if (this._state === 'pending' && this._timeoutId) { + this.reject(new OperationTimeoutError(this._timeoutMessage)); + } + } + + private _clearTimeout() { + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + } +} diff --git a/test/merkletreejs/node_modules/web3-utils/src/web3_eip1193_provider.ts b/test/merkletreejs/node_modules/web3-utils/src/web3_eip1193_provider.ts new file mode 100644 index 0000000..15f132f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-utils/src/web3_eip1193_provider.ts @@ -0,0 +1,116 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { + EthExecutionAPI, + HexString, + ProviderConnectInfo, + Web3APIMethod, + Web3APIPayload, + Web3APISpec, + Web3BaseProvider, +} from 'web3-types'; +import { EventEmitter } from 'events'; +import { EIP1193ProviderRpcError } from 'web3-errors'; +import { toPayload } from './json_rpc.js'; + +/** + * This is an abstract class, which extends {@link Web3BaseProvider} class. This class is used to implement a provider that adheres to the EIP-1193 standard for Ethereum providers. + */ +export abstract class Eip1193Provider< + API extends Web3APISpec = EthExecutionAPI, +> extends Web3BaseProvider { + protected readonly _eventEmitter: EventEmitter = new EventEmitter(); + private _chainId: HexString = ''; + private _accounts: HexString[] = []; + + private async _getChainId(): Promise { + const data = await (this as Web3BaseProvider).request< + Web3APIMethod, + ResponseType + >( + toPayload({ + method: 'eth_chainId', + params: [], + }) as Web3APIPayload>, + ); + return data?.result ?? ''; + } + + private async _getAccounts(): Promise { + const data = await (this as Web3BaseProvider).request, HexString[]>( + toPayload({ + method: 'eth_accounts', + params: [], + }) as Web3APIPayload>, + ); + return data?.result ?? []; + } + + protected _onConnect() { + Promise.all([ + this._getChainId() + .then(chainId => { + if (chainId !== this._chainId) { + this._chainId = chainId; + this._eventEmitter.emit('chainChanged', this._chainId); + } + }) + .catch(err => { + // todo: add error handler + console.error(err); + }), + + this._getAccounts() + .then(accounts => { + if ( + !( + this._accounts.length === accounts.length && + accounts.every(v => accounts.includes(v)) + ) + ) { + this._accounts = accounts; + this._onAccountsChanged(); + } + }) + .catch(err => { + // todo: add error handler + // eslint-disable-next-line no-console + console.error(err); + }), + ]) + .then(() => + this._eventEmitter.emit('connect', { + chainId: this._chainId, + } as ProviderConnectInfo), + ) + .catch(err => { + // todo: add error handler + // eslint-disable-next-line no-console + console.error(err); + }); + } + + // todo this must be ProvideRpcError with a message too + protected _onDisconnect(code: number, data?: unknown) { + this._eventEmitter.emit('disconnect', new EIP1193ProviderRpcError(code, data)); + } + + private _onAccountsChanged() { + // get chainId and safe to local + this._eventEmitter.emit('accountsChanged', this._accounts); + } +} diff --git a/test/merkletreejs/node_modules/web3-validator/LICENSE b/test/merkletreejs/node_modules/web3-validator/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3-validator/README.md b/test/merkletreejs/node_modules/web3-validator/README.md new file mode 100644 index 0000000..8096002 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/README.md @@ -0,0 +1,98 @@ +

+ web3.js +

+ +# web3-validator + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is a sub-package of [web3.js][repo]. + +`web3-validator` contains functions for validating objects. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3-validator) or using [Yarn](https://yarnpkg.com/package/web3-validator) + +### Using NPM + +```bash +npm install web3-validator +``` + +### Using Yarn + +```bash +yarn add web3-validator +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +### Usage + +You can use the the validator by importing as and using to validate; + +```ts +import { validator } from 'web3-validator'; + +// To validate and throw +validator.validate(['uint8', 'string'], [val1, val2]); + +// To validate and return error +const errors = validator.validate(['uint8', 'string'], [val1, val2], { silent: true }); +``` + +To see more examples of schema you can use to validate check [following file](./test/fixtures/abi_to_json_schema.ts). + +Following eth types are supported to validate. + +| Type | Input As | Description | +| ----- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| uint | `number`, `string`, `HexString` | Unsigned integer, all ethereum compatible variants are also supported e.g. `uint8`, `uint256`. You can also use array specifiers as `uint[]` or `uint[2]` | +| int | `number`, `string`, `HexString` | Signed integer, all ethereum compatible variants are also supported e.g. `int8`, `int256`. You can also use array specifiers as `int[]` or `int[2]` | +| bytes | `HexString`, `Uint8Array` | Raw bytes. You can also use fixed length bytes as `bytes[2]` | + +| string | `string` | String values | +| address | `string`, `HexString` | Ethereum network compatible address | +| bloom | `string`, `HexString` | Check if a given string is a Eth bloom | +| tuple | `array` | You can specify any tuple as nested arrays. e.g. `['uint', 'string']`. For a custom tuple or array tuple you can use syntax e.g. `['tuple[3]', ['uint', 'string']]` | + +For the ethereum compatible data values should be passed as arrays e.g. for schema `['uint', 'string']` value should be passed as `[2, 'my-string']`. + +You can also pass full ABI schema for the validation. e.g. + +```json +[{ "name": "owner", "type": "address" }] +``` + +The implementation of the validator is extension of [JSON-Schema-Draft07](https://json-schema.org/draft-07/json-schema-release-notes.html) with a custom keyword `eth`. So you can use JSON-Schema compatible schema to validate any object based data as well. + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3-validator +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-validator%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3-validator +[downloads-image]: https://img.shields.io/npm/dm/web3-validator?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.d.ts new file mode 100644 index 0000000..49751e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.d.ts @@ -0,0 +1 @@ +export declare const VALID_ETH_BASE_TYPES: string[]; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.js new file mode 100644 index 0000000..4e023de --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.js @@ -0,0 +1,21 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VALID_ETH_BASE_TYPES = void 0; +exports.VALID_ETH_BASE_TYPES = ['bool', 'int', 'uint', 'bytes', 'string', 'address', 'tuple']; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.js.map new file mode 100644 index 0000000..1aa339b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEW,QAAA,oBAAoB,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.d.ts new file mode 100644 index 0000000..0058a07 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.d.ts @@ -0,0 +1,2 @@ +import { Web3Validator } from './web3_validator.js'; +export declare const validator: Web3Validator; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.js new file mode 100644 index 0000000..df0748e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.js @@ -0,0 +1,22 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validator = void 0; +const web3_validator_js_1 = require("./web3_validator.js"); +exports.validator = new web3_validator_js_1.Web3Validator(); +//# sourceMappingURL=default_validator.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.js.map new file mode 100644 index 0000000..70b41d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/default_validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default_validator.js","sourceRoot":"","sources":["../../src/default_validator.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2DAAoD;AAEvC,QAAA,SAAS,GAAG,IAAI,iCAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.d.ts new file mode 100644 index 0000000..962750f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.d.ts @@ -0,0 +1,8 @@ +import { BaseWeb3Error } from 'web3-errors'; +import { Web3ValidationErrorObject } from 'web3-types'; +export declare class Web3ValidatorError extends BaseWeb3Error { + code: number; + readonly errors: Web3ValidationErrorObject[]; + constructor(errors: Web3ValidationErrorObject[]); + private _compileErrors; +} diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.js new file mode 100644 index 0000000..99d5c33 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.js @@ -0,0 +1,39 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3ValidatorError = void 0; +const web3_errors_1 = require("web3-errors"); +const errorFormatter = (error) => { + if (error.message) { + return error.message; + } + return 'unspecified error'; +}; +class Web3ValidatorError extends web3_errors_1.BaseWeb3Error { + constructor(errors) { + super(); + this.code = web3_errors_1.ERR_VALIDATION; + this.errors = errors; + super.message = `Web3 validator found ${errors.length} error[s]:\n${this._compileErrors().join('\n')}`; + } + _compileErrors() { + return this.errors.map(errorFormatter); + } +} +exports.Web3ValidatorError = Web3ValidatorError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.js.map new file mode 100644 index 0000000..1f68cee --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAA4D;AAG5D,MAAM,cAAc,GAAG,CAAC,KAAgC,EAAU,EAAE;IACnE,IAAI,KAAK,CAAC,OAAO,EAAE;QAClB,OAAO,KAAK,CAAC,OAAO,CAAC;KACrB;IAED,OAAO,mBAAmB,CAAC;AAC5B,CAAC,CAAC;AAEF,MAAa,kBAAmB,SAAQ,2BAAa;IAIpD,YAAmB,MAAmC;QACrD,KAAK,EAAE,CAAC;QAJF,SAAI,GAAG,4BAAc,CAAC;QAM5B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,KAAK,CAAC,OAAO,GAAG,wBACf,MAAM,CAAC,MACR,eAAe,IAAI,CAAC,cAAc,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IACnD,CAAC;IAEO,cAAc;QACrB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IACxC,CAAC;CACD;AAjBD,gDAiBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.d.ts new file mode 100644 index 0000000..42239f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.d.ts @@ -0,0 +1,4 @@ +declare const formats: { + [key: string]: (data: unknown) => boolean; +}; +export default formats; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.js new file mode 100644 index 0000000..7d67d09 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const address_js_1 = require("./validation/address.js"); +const block_js_1 = require("./validation/block.js"); +const bloom_js_1 = require("./validation/bloom.js"); +const boolean_js_1 = require("./validation/boolean.js"); +const bytes_js_1 = require("./validation/bytes.js"); +const filter_js_1 = require("./validation/filter.js"); +const string_js_1 = require("./validation/string.js"); +const numbers_js_1 = require("./validation/numbers.js"); +const formats = { + address: (data) => (0, address_js_1.isAddress)(data), + bloom: (data) => (0, bloom_js_1.isBloom)(data), + blockNumber: (data) => (0, block_js_1.isBlockNumber)(data), + blockTag: (data) => (0, block_js_1.isBlockTag)(data), + blockNumberOrTag: (data) => (0, block_js_1.isBlockNumberOrTag)(data), + bool: (data) => (0, boolean_js_1.isBoolean)(data), + bytes: (data) => (0, bytes_js_1.isBytes)(data), + filter: (data) => (0, filter_js_1.isFilterObject)(data), + hex: (data) => (0, string_js_1.isHexStrict)(data), + uint: (data) => (0, numbers_js_1.isUInt)(data), + int: (data) => (0, numbers_js_1.isInt)(data), + number: (data) => (0, numbers_js_1.isNumber)(data), + string: (data) => (0, string_js_1.isString)(data), +}; +// generate formats for all numbers types +for (let bitSize = 8; bitSize <= 256; bitSize += 8) { + formats[`int${bitSize}`] = data => (0, numbers_js_1.isInt)(data, { bitSize }); + formats[`uint${bitSize}`] = data => (0, numbers_js_1.isUInt)(data, { bitSize }); +} +// generate bytes +for (let size = 1; size <= 32; size += 1) { + formats[`bytes${size}`] = data => (0, bytes_js_1.isBytes)(data, { size }); +} +formats.bytes256 = formats.bytes; +exports.default = formats; +//# sourceMappingURL=formats.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.js.map new file mode 100644 index 0000000..37df6e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/formats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formats.js","sourceRoot":"","sources":["../../src/formats.ts"],"names":[],"mappings":";;AAkBA,wDAAoD;AACpD,oDAAsF;AACtF,oDAAgD;AAChD,wDAAoD;AACpD,oDAAgD;AAChD,sDAAwD;AACxD,sDAA+D;AAC/D,wDAAkE;AAElE,MAAM,OAAO,GAAkD;IAC9D,OAAO,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,IAAA,sBAAS,EAAC,IAAuB,CAAC;IAC9D,KAAK,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,IAAuB,CAAC;IAC1D,WAAW,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,IAAA,wBAAa,EAAC,IAAgC,CAAC;IAC/E,QAAQ,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,IAAA,qBAAU,EAAC,IAAc,CAAC;IACvD,gBAAgB,EAAE,CAAC,IAAa,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AE,CAAC,GAAG,IAAI,CAAC,EAAE,CAChC,IAAA,kBAAO,EAAC,IAA+C,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;CACpE;AACD,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC;AAEjC,kBAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.d.ts new file mode 100644 index 0000000..a5cff9d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.d.ts @@ -0,0 +1,7 @@ +export * from './web3_validator.js'; +export * from './default_validator.js'; +export * from './types.js'; +export * as utils from './utils.js'; +export * from './errors.js'; +export * from './constants.js'; +export * from './validation/index.js'; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.js new file mode 100644 index 0000000..78ac6e4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.js @@ -0,0 +1,53 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.utils = void 0; +__exportStar(require("./web3_validator.js"), exports); +__exportStar(require("./default_validator.js"), exports); +__exportStar(require("./types.js"), exports); +exports.utils = __importStar(require("./utils.js")); +__exportStar(require("./errors.js"), exports); +__exportStar(require("./constants.js"), exports); +__exportStar(require("./validation/index.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.js.map new file mode 100644 index 0000000..54c660a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,sDAAoC;AACpC,yDAAuC;AACvC,6CAA2B;AAC3B,oDAAoC;AACpC,8CAA4B;AAC5B,iDAA+B;AAC/B,wDAAsC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.d.ts new file mode 100644 index 0000000..0f4c8d8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.d.ts @@ -0,0 +1,105 @@ +import { AbiParameter } from 'web3-types'; +import { ZodIssueBase } from 'zod'; +export declare type ValidInputTypes = Uint8Array | bigint | string | number | boolean; +export declare type EthBaseTypes = 'bool' | 'bytes' | 'string' | 'uint' | 'int' | 'address' | 'tuple'; +export declare type EthBaseTypesWithMeta = `string${string}` | `string${string}[${number}]` | `bytes${string}` | `bytes${string}[${number}]` | `address[${number}]` | `bool[${number}]` | `int${string}` | `int${string}[${number}]` | `uint${string}` | `uint${string}[${number}]` | `tuple[]` | `tuple[${number}]`; +export declare type EthExtendedTypes = 'hex' | 'number' | 'blockNumber' | 'blockNumberOrTag' | 'filter' | 'bloom'; +export declare type FullValidationSchema = ReadonlyArray; +export declare type ShortValidationSchema = ReadonlyArray; +export declare type ValidationSchemaInput = FullValidationSchema | ShortValidationSchema; +export declare type Web3ValidationOptions = { + readonly silent: boolean; +}; +export declare type Json = string | number | boolean | Array | { + [id: string]: Json; +}; +export declare type ValidationError = ZodIssueBase; +export interface Validate { + (value: Json): boolean; + errors?: ValidationError[]; +} +export declare type Schema = { + $schema?: string; + $vocabulary?: string; + id?: string; + $id?: string; + $anchor?: string; + $ref?: string; + definitions?: { + [id: string]: Schema; + }; + $defs?: { + [id: string]: Schema; + }; + $recursiveRef?: string; + $recursiveAnchor?: boolean; + type?: string | Array; + required?: Array | boolean; + default?: Json; + enum?: Array; + const?: Json; + not?: Schema; + allOf?: Array; + anyOf?: Array; + oneOf?: Array; + if?: Schema; + then?: Schema; + else?: Schema; + maximum?: number; + minimum?: number; + exclusiveMaximum?: number | boolean; + exclusiveMinimum?: number | boolean; + multipleOf?: number; + divisibleBy?: number; + maxItems?: number; + minItems?: number; + additionalItems?: Schema; + contains?: Schema; + minContains?: number; + maxContains?: number; + uniqueItems?: boolean; + maxLength?: number; + minLength?: number; + format?: string; + pattern?: string; + contentEncoding?: string; + contentMediaType?: string; + contentSchema?: Schema; + properties?: { + [id: string]: Schema; + }; + maxProperties?: number; + minProperties?: number; + additionalProperties?: Schema; + patternProperties?: { + [pattern: string]: Schema; + }; + propertyNames?: Schema; + dependencies?: { + [id: string]: Array | Schema; + }; + dependentRequired?: { + [id: string]: Array; + }; + dependentSchemas?: { + [id: string]: Schema; + }; + unevaluatedProperties?: Schema; + unevaluatedItems?: Schema; + title?: string; + description?: string; + deprecated?: boolean; + readOnly?: boolean; + writeOnly?: boolean; + examples?: Array; + $comment?: string; + discriminator?: { + propertyName: string; + mapping?: { + [value: string]: string; + }; + }; + readonly eth?: string; + items?: Schema | Schema[]; +}; +export declare type JsonSchema = Schema; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.d.ts new file mode 100644 index 0000000..c0761d5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.d.ts @@ -0,0 +1,29 @@ +import { FullValidationSchema, ShortValidationSchema, ValidationSchemaInput, ValidInputTypes } from './types.js'; +export declare const parseBaseType: (type: string) => { + baseType?: T | undefined; + baseTypeSize: number | undefined; + arraySizes: number[]; + isArray: boolean; +}; +export declare const abiSchemaToJsonSchema: (abis: ShortValidationSchema | FullValidationSchema, level?: string) => import("./types.js").Schema; +export declare const ethAbiToJsonSchema: (abis: ValidationSchemaInput) => import("./types.js").Schema; +export declare const fetchArrayElement: (data: Array, level: number) => unknown; +export declare const transformJsonDataToAbiFormat: (abis: FullValidationSchema, data: ReadonlyArray | Record, transformedData?: Array) => Array; +/** + * Code points to int + */ +export declare const codePointToInt: (codePoint: number) => number; +/** + * Converts value to it's number representation + */ +export declare const hexToNumber: (value: string) => bigint | number; +/** + * Converts value to it's hex representation + */ +export declare const numberToHex: (value: ValidInputTypes) => string; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + */ +export declare const padLeft: (value: ValidInputTypes, characterAmount: number, sign?: string) => string; +export declare function uint8ArrayToHexString(uint8Array: Uint8Array): string; +export declare function hexToUint8Array(hex: string): Uint8Array; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.js new file mode 100644 index 0000000..eafd2ba --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.js @@ -0,0 +1,389 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hexToUint8Array = exports.uint8ArrayToHexString = exports.padLeft = exports.numberToHex = exports.hexToNumber = exports.codePointToInt = exports.transformJsonDataToAbiFormat = exports.fetchArrayElement = exports.ethAbiToJsonSchema = exports.abiSchemaToJsonSchema = exports.parseBaseType = void 0; +const web3_errors_1 = require("web3-errors"); +const constants_js_1 = require("./constants.js"); +const abi_js_1 = require("./validation/abi.js"); +const string_js_1 = require("./validation/string.js"); +const errors_js_1 = require("./errors.js"); +const extraTypes = ['hex', 'number', 'blockNumber', 'blockNumberOrTag', 'filter', 'bloom']; +const parseBaseType = (type) => { + // Remove all empty spaces to avoid any parsing issue. + let strippedType = type.replace(/ /, ''); + let baseTypeSize; + let isArray = false; + let arraySizes = []; + if (type.includes('[')) { + // Extract the array type + strippedType = strippedType.slice(0, strippedType.indexOf('[')); + // Extract array indexes + arraySizes = [...type.matchAll(/(?:\[(\d*)\])/g)] + .map(match => parseInt(match[1], 10)) + .map(size => (Number.isNaN(size) ? -1 : size)); + isArray = arraySizes.length > 0; + } + if (constants_js_1.VALID_ETH_BASE_TYPES.includes(strippedType)) { + return { baseType: strippedType, isArray, baseTypeSize, arraySizes }; + } + if (strippedType.startsWith('int')) { + baseTypeSize = parseInt(strippedType.substring(3), 10); + strippedType = 'int'; + } + else if (strippedType.startsWith('uint')) { + baseTypeSize = parseInt(type.substring(4), 10); + strippedType = 'uint'; + } + else if (strippedType.startsWith('bytes')) { + baseTypeSize = parseInt(strippedType.substring(5), 10); + strippedType = 'bytes'; + } + else { + return { baseType: undefined, isArray: false, baseTypeSize: undefined, arraySizes }; + } + return { baseType: strippedType, isArray, baseTypeSize, arraySizes }; +}; +exports.parseBaseType = parseBaseType; +const convertEthType = (type, parentSchema = {}) => { + const typePropertyPresent = Object.keys(parentSchema).includes('type'); + if (typePropertyPresent) { + throw new errors_js_1.Web3ValidatorError([ + { + keyword: 'eth', + message: 'Either "eth" or "type" can be presented in schema', + params: { eth: type }, + instancePath: '', + schemaPath: '', + }, + ]); + } + const { baseType, baseTypeSize } = (0, exports.parseBaseType)(type); + if (!baseType && !extraTypes.includes(type)) { + throw new errors_js_1.Web3ValidatorError([ + { + keyword: 'eth', + message: `Eth data type "${type}" is not valid`, + params: { eth: type }, + instancePath: '', + schemaPath: '', + }, + ]); + } + if (baseType) { + if (baseType === 'tuple') { + throw new Error('"tuple" type is not implemented directly.'); + } + return { format: `${baseType}${baseTypeSize !== null && baseTypeSize !== void 0 ? baseTypeSize : ''}`, required: true }; + } + if (type) { + return { format: type, required: true }; + } + return {}; +}; +const abiSchemaToJsonSchema = (abis, level = '/0') => { + const schema = { + type: 'array', + items: [], + maxItems: abis.length, + minItems: abis.length, + }; + for (const [index, abi] of abis.entries()) { + // eslint-disable-next-line no-nested-ternary + let abiType; + let abiName; + let abiComponents = []; + // If it's a complete Abi Parameter + // e.g. {name: 'a', type: 'uint'} + if ((0, abi_js_1.isAbiParameterSchema)(abi)) { + abiType = abi.type; + abiName = abi.name; + abiComponents = abi.components; + // If its short form string value e.g. ['uint'] + } + else if (typeof abi === 'string') { + abiType = abi; + abiName = `${level}/${index}`; + // If it's provided in short form of tuple e.g. [['uint', 'string']] + } + else if (Array.isArray(abi)) { + // If its custom tuple e.g. ['tuple[2]', ['uint', 'string']] + if (abi[0] && + typeof abi[0] === 'string' && + abi[0].startsWith('tuple') && + !Array.isArray(abi[0]) && + abi[1] && + Array.isArray(abi[1])) { + // eslint-disable-next-line prefer-destructuring + abiType = abi[0]; + abiName = `${level}/${index}`; + abiComponents = abi[1]; + } + else { + abiType = 'tuple'; + abiName = `${level}/${index}`; + abiComponents = abi; + } + } + const { baseType, isArray, arraySizes } = (0, exports.parseBaseType)(abiType); + let childSchema; + let lastSchema = schema; + for (let i = arraySizes.length - 1; i > 0; i -= 1) { + childSchema = { + type: 'array', + items: [], + maxItems: arraySizes[i], + minItems: arraySizes[i], + }; + if (arraySizes[i] < 0) { + delete childSchema.maxItems; + delete childSchema.minItems; + } + // lastSchema.items is a Schema, concat with 'childSchema' + if (!Array.isArray(lastSchema.items)) { + lastSchema.items = [lastSchema.items, childSchema]; + } // lastSchema.items is an empty Scheme array, set it to 'childSchema' + else if (lastSchema.items.length === 0) { + lastSchema.items = childSchema; + } // lastSchema.items is a non-empty Scheme array, append 'childSchema' + else { + lastSchema.items.push(childSchema); + } + lastSchema = childSchema; + } + if (baseType === 'tuple' && !isArray) { + const nestedTuple = (0, exports.abiSchemaToJsonSchema)(abiComponents, abiName); + nestedTuple.$id = abiName; + lastSchema.items.push(nestedTuple); + } + else if (baseType === 'tuple' && isArray) { + const arraySize = arraySizes[0]; + const item = { + $id: abiName, + type: 'array', + items: (0, exports.abiSchemaToJsonSchema)(abiComponents, abiName), + maxItems: arraySize, + minItems: arraySize, + }; + if (arraySize < 0) { + delete item.maxItems; + delete item.minItems; + } + lastSchema.items.push(item); + } + else if (isArray) { + const arraySize = arraySizes[0]; + const item = { + type: 'array', + $id: abiName, + items: convertEthType(String(baseType)), + minItems: arraySize, + maxItems: arraySize, + }; + if (arraySize < 0) { + delete item.maxItems; + delete item.minItems; + } + lastSchema.items.push(item); + } + else if (Array.isArray(lastSchema.items)) { + // Array of non-tuple items + lastSchema.items.push(Object.assign({ $id: abiName }, convertEthType(abiType))); + } + else { + // Nested object + lastSchema.items.items.push(Object.assign({ $id: abiName }, convertEthType(abiType))); + } + lastSchema = schema; + } + return schema; +}; +exports.abiSchemaToJsonSchema = abiSchemaToJsonSchema; +const ethAbiToJsonSchema = (abis) => (0, exports.abiSchemaToJsonSchema)(abis); +exports.ethAbiToJsonSchema = ethAbiToJsonSchema; +const fetchArrayElement = (data, level) => { + if (level === 1) { + return data; + } + return (0, exports.fetchArrayElement)(data[0], level - 1); +}; +exports.fetchArrayElement = fetchArrayElement; +const transformJsonDataToAbiFormat = (abis, data, transformedData) => { + const newData = []; + for (const [index, abi] of abis.entries()) { + // eslint-disable-next-line no-nested-ternary + let abiType; + let abiName; + let abiComponents = []; + // If it's a complete Abi Parameter + // e.g. {name: 'a', type: 'uint'} + if ((0, abi_js_1.isAbiParameterSchema)(abi)) { + abiType = abi.type; + abiName = abi.name; + abiComponents = abi.components; + // If its short form string value e.g. ['uint'] + } + else if (typeof abi === 'string') { + abiType = abi; + // If it's provided in short form of tuple e.g. [['uint', 'string']] + } + else if (Array.isArray(abi)) { + // If its custom tuple e.g. ['tuple[2]', ['uint', 'string']] + if (abi[1] && Array.isArray(abi[1])) { + abiType = abi[0]; + abiComponents = abi[1]; + } + else { + abiType = 'tuple'; + abiComponents = abi; + } + } + const { baseType, isArray, arraySizes } = (0, exports.parseBaseType)(abiType); + const dataItem = Array.isArray(data) + ? data[index] + : data[abiName]; + if (baseType === 'tuple' && !isArray) { + newData.push((0, exports.transformJsonDataToAbiFormat)(abiComponents, dataItem, transformedData)); + } + else if (baseType === 'tuple' && isArray) { + const tupleData = []; + for (const tupleItem of dataItem) { + // Nested array + if (arraySizes.length > 1) { + const nestedItems = (0, exports.fetchArrayElement)(tupleItem, arraySizes.length - 1); + const nestedData = []; + for (const nestedItem of nestedItems) { + nestedData.push((0, exports.transformJsonDataToAbiFormat)(abiComponents, nestedItem, transformedData)); + } + tupleData.push(nestedData); + } + else { + tupleData.push((0, exports.transformJsonDataToAbiFormat)(abiComponents, tupleItem, transformedData)); + } + } + newData.push(tupleData); + } + else { + newData.push(dataItem); + } + } + // Have to reassign before pushing to transformedData + // eslint-disable-next-line no-param-reassign + transformedData = transformedData !== null && transformedData !== void 0 ? transformedData : []; + transformedData.push(...newData); + return transformedData; +}; +exports.transformJsonDataToAbiFormat = transformJsonDataToAbiFormat; +/** + * Code points to int + */ +const codePointToInt = (codePoint) => { + if (codePoint >= 48 && codePoint <= 57) { + /* ['0'..'9'] -> [0..9] */ + return codePoint - 48; + } + if (codePoint >= 65 && codePoint <= 70) { + /* ['A'..'F'] -> [10..15] */ + return codePoint - 55; + } + if (codePoint >= 97 && codePoint <= 102) { + /* ['a'..'f'] -> [10..15] */ + return codePoint - 87; + } + throw new Error(`Invalid code point: ${codePoint}`); +}; +exports.codePointToInt = codePointToInt; +/** + * Converts value to it's number representation + */ +const hexToNumber = (value) => { + if (!(0, string_js_1.isHexStrict)(value)) { + throw new Error('Invalid hex string'); + } + const [negative, hexValue] = value.startsWith('-') ? [true, value.slice(1)] : [false, value]; + const num = BigInt(hexValue); + if (num > Number.MAX_SAFE_INTEGER) { + return negative ? -num : num; + } + if (num < Number.MIN_SAFE_INTEGER) { + return num; + } + return negative ? -1 * Number(num) : Number(num); +}; +exports.hexToNumber = hexToNumber; +/** + * Converts value to it's hex representation + */ +const numberToHex = (value) => { + if ((typeof value === 'number' || typeof value === 'bigint') && value < 0) { + return `-0x${value.toString(16).slice(1)}`; + } + if ((typeof value === 'number' || typeof value === 'bigint') && value >= 0) { + return `0x${value.toString(16)}`; + } + if (typeof value === 'string' && (0, string_js_1.isHexStrict)(value)) { + const [negative, hex] = value.startsWith('-') ? [true, value.slice(1)] : [false, value]; + const hexValue = hex.split(/^(-)?0(x|X)/).slice(-1)[0]; + return `${negative ? '-' : ''}0x${hexValue.replace(/^0+/, '').toLowerCase()}`; + } + if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) { + return (0, exports.numberToHex)(BigInt(value)); + } + throw new web3_errors_1.InvalidNumberError(value); +}; +exports.numberToHex = numberToHex; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + */ +const padLeft = (value, characterAmount, sign = '0') => { + if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) { + return value.padStart(characterAmount, sign); + } + const hex = typeof value === 'string' && (0, string_js_1.isHexStrict)(value) ? value : (0, exports.numberToHex)(value); + const [prefix, hexValue] = hex.startsWith('-') ? ['-0x', hex.slice(3)] : ['0x', hex.slice(2)]; + return `${prefix}${hexValue.padStart(characterAmount, sign)}`; +}; +exports.padLeft = padLeft; +function uint8ArrayToHexString(uint8Array) { + let hexString = '0x'; + for (const e of uint8Array) { + const hex = e.toString(16); + hexString += hex.length === 1 ? `0${hex}` : hex; + } + return hexString; +} +exports.uint8ArrayToHexString = uint8ArrayToHexString; +function hexToUint8Array(hex) { + let value; + if (hex.toLowerCase().startsWith('0x')) { + value = hex.slice(2); + } + else { + value = hex; + } + if (value.length % 2 !== 0) { + throw new web3_errors_1.InvalidBytesError(`hex string has odd length: ${hex}`); + } + const bytes = new Uint8Array(Math.ceil(value.length / 2)); + for (let i = 0; i < bytes.length; i += 1) { + const byte = parseInt(value.substring(i * 2, i * 2 + 2), 16); + bytes[i] = byte; + } + return bytes; +} +exports.hexToUint8Array = hexToUint8Array; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.js.map new file mode 100644 index 0000000..119d7ce --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,6CAAoE;AACpE,iDAAsD;AAQtD,gDAA2D;AAC3D,sDAAqD;AACrD,2CAAiD;AAEjD,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,kBAAkB,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;AAEpF,MAAM,aAAa,GAAG,CAC5B,IAAY,EAMX,EAAE;IACH,sDAAsD;IACtD,IAAI,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACzC,IAAI,YAAg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,OAAO,SAAS,CAAC;AAClB,CAAC;AAPD,sDAOC;AAED,SAAgB,eAAe,CAAC,GAAW;IAC1C,IAAI,KAAK,CAAC;IACV,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QACvC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KACrB;SAAM;QACN,KAAK,GAAG,GAAG,CAAC;KACZ;IACD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE;QAC3B,MAAM,IAAI,+BAAiB,CAAC,8BAA8B,GAAG,EAAE,CAAC,CAAC;KACjE;IACD,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;IAC1D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QACzC,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC7D,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;KAChB;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAhBD,0CAgBC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.d.ts new file mode 100644 index 0000000..de4b4d0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.d.ts @@ -0,0 +1,3 @@ +import { AbiParameter } from 'web3-types'; +import { ShortValidationSchema } from '../types'; +export declare const isAbiParameterSchema: (schema: string | ShortValidationSchema | AbiParameter) => schema is AbiParameter; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.js new file mode 100644 index 0000000..5eaddd5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.js @@ -0,0 +1,22 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAbiParameterSchema = void 0; +const isAbiParameterSchema = (schema) => typeof schema === 'object' && 'type' in schema && 'name' in schema; +exports.isAbiParameterSchema = isAbiParameterSchema; +//# sourceMappingURL=abi.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.js.map new file mode 100644 index 0000000..7a279f7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/abi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abi.js","sourceRoot":"","sources":["../../../src/validation/abi.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAMK,MAAM,oBAAoB,GAAG,CACnC,MAAqD,EAC5B,EAAE,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,CAAC;AAFnF,QAAA,oBAAoB,wBAE+D"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.d.ts new file mode 100644 index 0000000..026156f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.d.ts @@ -0,0 +1,9 @@ +import { ValidInputTypes } from '../types.js'; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + */ +export declare const checkAddressCheckSum: (data: string) => boolean; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + */ +export declare const isAddress: (value: ValidInputTypes, checkChecksum?: boolean) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.js new file mode 100644 index 0000000..8e68288 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.js @@ -0,0 +1,73 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAddress = exports.checkAddressCheckSum = void 0; +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const utils_js_1 = require("ethereum-cryptography/utils.js"); +const utils_js_2 = require("../utils.js"); +const string_js_1 = require("./string.js"); +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + */ +const checkAddressCheckSum = (data) => { + if (!/^(0x)?[0-9a-f]{40}$/i.test(data)) + return false; + const address = data.slice(2); + const updatedData = (0, utils_js_1.utf8ToBytes)(address.toLowerCase()); + const addressHash = (0, utils_js_2.uint8ArrayToHexString)((0, keccak_js_1.keccak256)(updatedData)).slice(2); + for (let i = 0; i < 40; i += 1) { + // the nth letter should be uppercase if the nth digit of casemap is 1 + if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || + (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { + return false; + } + } + return true; +}; +exports.checkAddressCheckSum = checkAddressCheckSum; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + */ +const isAddress = (value, checkChecksum = true) => { + if (typeof value !== 'string' && !(value instanceof Uint8Array)) { + return false; + } + let valueToCheck; + if (value instanceof Uint8Array) { + valueToCheck = (0, utils_js_2.uint8ArrayToHexString)(value); + } + else if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) { + valueToCheck = value.toLowerCase().startsWith('0x') ? value : `0x${value}`; + } + else { + valueToCheck = value; + } + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(valueToCheck)) { + return false; + } + // If it's ALL lowercase or ALL upppercase + if (/^(0x|0X)?[0-9a-f]{40}$/.test(valueToCheck) || + /^(0x|0X)?[0-9A-F]{40}$/.test(valueToCheck)) { + return true; + // Otherwise check each case + } + return checkChecksum ? (0, exports.checkAddressCheckSum)(valueToCheck) : true; +}; +exports.isAddress = isAddress; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.js.map new file mode 100644 index 0000000..8924fe1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../src/validation/address.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,+DAA4D;AAC5D,6DAA6D;AAE7D,0CAAoD;AACpD,2CAA0C;AAE1C;;GAEG;AACI,MAAM,oBAAoB,GAAG,CAAC,IAAY,EAAW,EAAE;IAC7D,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IACrD,MAAM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AAG,KAAK,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC;KAC3E;SAAM;QACN,YAAY,GAAG,KAAK,CAAC;KACrB;IAED,uDAAuD;IACvD,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE;QAC/C,OAAO,KAAK,CAAC;KACb;IACD,0CAA0C;IAC1C,IACC,wBAAwB,CAAC,IAAI,CAAC,YAAY,CAAC;QAC3C,wBAAwB,CAAC,IAAI,CAAC,YAAY,CAAC,EAC1C;QACD,OAAO,IAAI,CAAC;QACZ,4BAA4B;KAC5B;IACD,OAAO,aAAa,CAAC,CAAC,CAAC,IAAA,4BAAoB,EAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAClE,CAAC,CAAC;AA5BW,QAAA,SAAS,aA4BpB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.d.ts new file mode 100644 index 0000000..92d12c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.d.ts @@ -0,0 +1,9 @@ +export declare const isBlockNumber: (value: string | number | bigint) => boolean; +/** + * Returns true if the given blockNumber is 'latest', 'pending', 'earliest, 'safe' or 'finalized' + */ +export declare const isBlockTag: (value: string) => boolean; +/** + * Returns true if given value is valid hex string and not negative, or is a valid BlockTag + */ +export declare const isBlockNumberOrTag: (value: string | number | bigint) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.js new file mode 100644 index 0000000..aaf4671 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.js @@ -0,0 +1,34 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBlockNumberOrTag = exports.isBlockTag = exports.isBlockNumber = void 0; +const web3_types_1 = require("web3-types"); +const numbers_js_1 = require("./numbers.js"); +const isBlockNumber = (value) => (0, numbers_js_1.isUInt)(value); +exports.isBlockNumber = isBlockNumber; +/** + * Returns true if the given blockNumber is 'latest', 'pending', 'earliest, 'safe' or 'finalized' + */ +const isBlockTag = (value) => Object.values(web3_types_1.BlockTags).includes(value); +exports.isBlockTag = isBlockTag; +/** + * Returns true if given value is valid hex string and not negative, or is a valid BlockTag + */ +const isBlockNumberOrTag = (value) => (0, exports.isBlockTag)(value) || (0, exports.isBlockNumber)(value); +exports.isBlockNumberOrTag = isBlockNumberOrTag; +//# sourceMappingURL=block.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.js.map new file mode 100644 index 0000000..57cdb97 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/block.js.map @@ -0,0 +1 @@ +{"version":3,"file":"block.js","sourceRoot":"","sources":["../../../src/validation/block.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAuC;AACvC,6CAAsC;AAE/B,MAAM,aAAa,GAAG,CAAC,KAA+B,EAAW,EAAE,CAAC,IAAA,mBAAM,EAAC,KAAK,CAAC,CAAC;AAA5E,QAAA,aAAa,iBAA+D;AAEzF;;GAEG;AACI,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,sBAAS,CAAC,CAAC,QAAQ,CAAC,KAAkB,CAAC,CAAC;AAAtF,QAAA,UAAU,cAA4E;AAEnG;;GAEG;AACI,MAAM,kBAAkB,GAAG,CAAC,KAA+B,EAAE,EAAE,CACrE,IAAA,kBAAU,EAAC,KAAe,CAAC,IAAI,IAAA,qBAAa,EAAC,KAAK,CAAC,CAAC;AADxC,QAAA,kBAAkB,sBACsB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.d.ts new file mode 100644 index 0000000..2a02a38 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.d.ts @@ -0,0 +1,20 @@ +import { ValidInputTypes } from '../types.js'; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + */ +export declare const isBloom: (bloom: ValidInputTypes) => boolean; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + */ +export declare const isInBloom: (bloom: string, value: string | Uint8Array) => boolean; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + */ +export declare const isUserEthereumAddressInBloom: (bloom: string, ethereumAddress: string) => boolean; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + */ +export declare const isContractAddressInBloom: (bloom: string, contractAddress: string) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.js new file mode 100644 index 0000000..6512ec2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.js @@ -0,0 +1,106 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isContractAddressInBloom = exports.isUserEthereumAddressInBloom = exports.isInBloom = exports.isBloom = void 0; +const keccak_js_1 = require("ethereum-cryptography/keccak.js"); +const utils_js_1 = require("../utils.js"); +const address_js_1 = require("./address.js"); +const string_js_1 = require("./string.js"); +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + */ +const isBloom = (bloom) => { + if (typeof bloom !== 'string') { + return false; + } + if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { + return false; + } + if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { + return true; + } + return false; +}; +exports.isBloom = isBloom; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + */ +const isInBloom = (bloom, value) => { + if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) { + return false; + } + if (!(0, exports.isBloom)(bloom)) { + return false; + } + const uint8Array = typeof value === 'string' ? (0, utils_js_1.hexToUint8Array)(value) : value; + const hash = (0, utils_js_1.uint8ArrayToHexString)((0, keccak_js_1.keccak256)(uint8Array)).slice(2); + for (let i = 0; i < 12; i += 4) { + // calculate bit position in bloom filter that must be active + const bitpos = + // eslint-disable-next-line no-bitwise + ((parseInt(hash.slice(i, i + 2), 16) << 8) + parseInt(hash.slice(i + 2, i + 4), 16)) & + 2047; + // test if bitpos in bloom is active + const code = (0, utils_js_1.codePointToInt)(bloom.charCodeAt(bloom.length - 1 - Math.floor(bitpos / 4))); + // eslint-disable-next-line no-bitwise + const offset = 1 << bitpos % 4; + // eslint-disable-next-line no-bitwise + if ((code & offset) !== offset) { + return false; + } + } + return true; +}; +exports.isInBloom = isInBloom; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + */ +const isUserEthereumAddressInBloom = (bloom, ethereumAddress) => { + if (!(0, exports.isBloom)(bloom)) { + return false; + } + if (!(0, address_js_1.isAddress)(ethereumAddress)) { + return false; + } + // you have to pad the ethereum address to 32 bytes + // else the bloom filter does not work + // this is only if your matching the USERS + // ethereum address. Contract address do not need this + // hence why we have 2 methods + // (0x is not in the 2nd parameter of padleft so 64 chars is fine) + const address = (0, utils_js_1.padLeft)(ethereumAddress, 64); + return (0, exports.isInBloom)(bloom, address); +}; +exports.isUserEthereumAddressInBloom = isUserEthereumAddressInBloom; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + */ +const isContractAddressInBloom = (bloom, contractAddress) => { + if (!(0, exports.isBloom)(bloom)) { + return false; + } + if (!(0, address_js_1.isAddress)(contractAddress)) { + return false; + } + return (0, exports.isInBloom)(bloom, contractAddress); +}; +exports.isContractAddressInBloom = isContractAddressInBloom; +//# sourceMappingURL=bloom.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.js.map new file mode 100644 index 0000000..5ded084 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bloom.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bloom.js","sourceRoot":"","sources":["../../../src/validation/bloom.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,+DAA4D;AAE5D,0CAA8F;AAC9F,6CAAyC;AACzC,2CAA0C;AAE1C;;;GAGG;AACI,MAAM,OAAO,GAAG,CAAC,KAAsB,EAAW,EAAE;IAC1D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,uBAAuB,CA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AA,wBAAwB,4BAUnC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.d.ts new file mode 100644 index 0000000..b28a3dc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.d.ts @@ -0,0 +1,2 @@ +import { ValidInputTypes } from '../types.js'; +export declare const isBoolean: (value: ValidInputTypes) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.js new file mode 100644 index 0000000..a607f04 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.js @@ -0,0 +1,38 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBoolean = void 0; +const string_js_1 = require("./string.js"); +const isBoolean = (value) => { + if (!['number', 'string', 'boolean'].includes(typeof value)) { + return false; + } + if (typeof value === 'boolean') { + return true; + } + if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) { + return value === '1' || value === '0'; + } + if (typeof value === 'string' && (0, string_js_1.isHexStrict)(value)) { + return value === '0x1' || value === '0x0'; + } + // type === number + return value === 1 || value === 0; +}; +exports.isBoolean = isBoolean; +//# sourceMappingURL=boolean.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.js.map new file mode 100644 index 0000000..155f545 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/boolean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.js","sourceRoot":"","sources":["../../../src/validation/boolean.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,2CAA0C;AAEnC,MAAM,SAAS,GAAG,CAAC,KAAsB,EAAE,EAAE;IACnD,IAAI,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC,EAAE;QAC5D,OAAO,KAAK,CAAC;KACb;IAED,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE;QAC/B,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,IAAA,uBAAW,EAAC,KAAK,CAAC,EAAE;QACrD,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC;KACtC;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,IAAA,uBAAW,EAAC,KAAK,CAAC,EAAE;QACpD,OAAO,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK,CAAC;KAC1C;IAED,kBAAkB;IAClB,OAAO,KAAK,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC;AACnC,CAAC,CAAC;AAnBW,QAAA,SAAS,aAmBpB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.d.ts new file mode 100644 index 0000000..5734492 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.d.ts @@ -0,0 +1,12 @@ +import { ValidInputTypes } from '../types.js'; +/** + * checks input if typeof data is valid Uint8Array input + */ +export declare const isUint8Array: (data: ValidInputTypes) => boolean; +export declare const isBytes: (value: ValidInputTypes | Uint8Array | number[], options?: { + abiType: string; + size?: never; +} | { + size: number; + abiType?: never; +}) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.js new file mode 100644 index 0000000..84d79fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.js @@ -0,0 +1,67 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBytes = exports.isUint8Array = void 0; +const utils_js_1 = require("../utils.js"); +const string_js_1 = require("./string.js"); +/** + * checks input if typeof data is valid Uint8Array input + */ +const isUint8Array = (data) => data instanceof Uint8Array; +exports.isUint8Array = isUint8Array; +const isBytes = (value, options = { + abiType: 'bytes', +}) => { + if (typeof value !== 'string' && !Array.isArray(value) && !(value instanceof Uint8Array)) { + return false; + } + // isHexStrict also accepts - prefix which can not exists in bytes + if (typeof value === 'string' && (0, string_js_1.isHexStrict)(value) && value.startsWith('-')) { + return false; + } + if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) { + return false; + } + let valueToCheck; + if (typeof value === 'string') { + if (value.length % 2 !== 0) { + // odd length hex + return false; + } + valueToCheck = (0, utils_js_1.hexToUint8Array)(value); + } + else if (Array.isArray(value)) { + if (value.some(d => d < 0 || d > 255 || !Number.isInteger(d))) { + return false; + } + valueToCheck = new Uint8Array(value); + } + else { + valueToCheck = value; + } + if (options === null || options === void 0 ? void 0 : options.abiType) { + const { baseTypeSize } = (0, utils_js_1.parseBaseType)(options.abiType); + return baseTypeSize ? valueToCheck.length === baseTypeSize : true; + } + if (options === null || options === void 0 ? void 0 : options.size) { + return valueToCheck.length === (options === null || options === void 0 ? void 0 : options.size); + } + return true; +}; +exports.isBytes = isBytes; +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.js.map new file mode 100644 index 0000000..07e2f9c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../src/validation/bytes.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,0CAA6D;AAC7D,2CAA0C;AAE1C;;GAEG;AACI,MAAM,YAAY,GAAG,CAAC,IAAqB,EAAE,EAAE,CAAC,IAAI,YAAY,UAAU,CAAC;AAArE,QAAA,YAAY,gBAAyD;AAE3E,MAAM,OAAO,GAAG,CACtB,KAA8C,EAC9C,UAAiF;IAChF,OAAO,EAAE,OAAO;CAChB,EACA,EAAE;IACH,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC,EAAE;QACzF,OAAO,KAAK,CAAC;KACb;IAED,kEAAkE;IAClE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,IAAA,uBAAW,EAAC,KAAK,CAAC,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QAC7E,OAAO,KAAK,CAAC;KACb;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,IAAA,uBAAW,EAAC,KAAK,CAAC,EAAE;QACrD,OAAO,KAAK,CAAC;KACb;IAED,IAAI,YAAwB,CAAC;IAE7B,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE;YAC3B,iBAAiB;YACjB,OAAO,KAAK,CAAC;SACb;QACD,YAAY,GAAG,IAAA,0BAAe,EAAC,KAAK,CAAC,CAAC;KACtC;SAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QAChC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE;YAC9D,OAAO,KAAK,CAAC;SACb;QACD,YAAY,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;KACrC;SAAM;QACN,YAAY,GAAG,KAAK,CAAC;KACrB;IAED,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,EAAE;QACrB,MAAM,EAAE,YAAY,EAAE,GAAG,IAAA,wBAAa,EAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAExD,OAAO,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,KAAK,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC;KAClE;IAED,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,EAAE;QAClB,OAAO,YAAY,CAAC,MAAM,MAAK,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,CAAA,CAAC;KAC7C;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA/CW,QAAA,OAAO,WA+ClB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.d.ts new file mode 100644 index 0000000..7a2a6f5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.d.ts @@ -0,0 +1 @@ +export declare const isValidEthBaseType: (type: string) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.js new file mode 100644 index 0000000..a3c2fb8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.js @@ -0,0 +1,42 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isValidEthBaseType = void 0; +const utils_js_1 = require("../utils.js"); +const isValidEthBaseType = (type) => { + const { baseType, baseTypeSize } = (0, utils_js_1.parseBaseType)(type); + if (!baseType) { + return false; + } + if (baseType === type) { + return true; + } + if ((baseType === 'int' || baseType === 'uint') && baseTypeSize) { + if (!(baseTypeSize <= 256 && baseTypeSize % 8 === 0)) { + return false; + } + } + if (baseType === 'bytes' && baseTypeSize) { + if (!(baseTypeSize >= 1 && baseTypeSize <= 32)) { + return false; + } + } + return true; +}; +exports.isValidEthBaseType = isValidEthBaseType; +//# sourceMappingURL=eth.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.js.map new file mode 100644 index 0000000..46ac156 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/eth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth.js","sourceRoot":"","sources":["../../../src/validation/eth.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,0CAA4C;AAErC,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAW,EAAE;IAC3D,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,IAAA,wBAAa,EAAC,IAAI,CAAC,CAAC;IAEvD,IAAI,CAAC,QAAQ,EAAE;QACd,OAAO,KAAK,CAAC;KACb;IAED,IAAI,QAAQ,KAAK,IAAI,EAAE;QACtB,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,CAAC,QAAQ,KAAK,KAAK,IAAI,QAAQ,KAAK,MAAM,CAAC,IAAI,YAAY,EAAE;QAChE,IAAI,CAAC,CAAC,YAAY,IAAI,GAAG,IAAI,YAAY,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;YACrD,OAAO,KAAK,CAAC;SACb;KACD;IAED,IAAI,QAAQ,KAAK,OAAO,IAAI,YAAY,EAAE;QACzC,IAAI,CAAC,CAAC,YAAY,IAAI,CAAC,IAAI,YAAY,IAAI,EAAE,CAAC,EAAE;YAC/C,OAAO,KAAK,CAAC;SACb;KACD;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AAxBW,QAAA,kBAAkB,sBAwB7B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.d.ts new file mode 100644 index 0000000..3b9e13a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.d.ts @@ -0,0 +1,8 @@ +import { Filter } from 'web3-types'; +/** + * First we check if all properties in the provided value are expected, + * then because all Filter properties are optional, we check if the expected properties + * are defined. If defined and they're not the expected type, we immediately return false, + * otherwise we return true after all checks pass. + */ +export declare const isFilterObject: (value: Filter) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.js new file mode 100644 index 0000000..f391a39 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.js @@ -0,0 +1,69 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isFilterObject = void 0; +const address_js_1 = require("./address.js"); +const block_js_1 = require("./block.js"); +const object_js_1 = require("./object.js"); +const topic_js_1 = require("./topic.js"); +/** + * First we check if all properties in the provided value are expected, + * then because all Filter properties are optional, we check if the expected properties + * are defined. If defined and they're not the expected type, we immediately return false, + * otherwise we return true after all checks pass. + */ +const isFilterObject = (value) => { + const expectedFilterProperties = [ + 'fromBlock', + 'toBlock', + 'address', + 'topics', + 'blockHash', + ]; + if ((0, object_js_1.isNullish)(value) || typeof value !== 'object') + return false; + if (!Object.keys(value).every(property => expectedFilterProperties.includes(property))) + return false; + if ((!(0, object_js_1.isNullish)(value.fromBlock) && !(0, block_js_1.isBlockNumberOrTag)(value.fromBlock)) || + (!(0, object_js_1.isNullish)(value.toBlock) && !(0, block_js_1.isBlockNumberOrTag)(value.toBlock))) + return false; + if (!(0, object_js_1.isNullish)(value.address)) { + if (Array.isArray(value.address)) { + if (!value.address.every(address => (0, address_js_1.isAddress)(address))) + return false; + } + else if (!(0, address_js_1.isAddress)(value.address)) + return false; + } + if (!(0, object_js_1.isNullish)(value.topics)) { + if (!value.topics.every(topic => { + if ((0, object_js_1.isNullish)(topic)) + return true; + if (Array.isArray(topic)) { + return topic.every(nestedTopic => (0, topic_js_1.isTopic)(nestedTopic)); + } + if ((0, topic_js_1.isTopic)(topic)) + return true; + return false; + })) + return false; + } + return true; +}; +exports.isFilterObject = isFilterObject; +//# sourceMappingURL=filter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.js.map new file mode 100644 index 0000000..710f524 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"filter.js","sourceRoot":"","sources":["../../../src/validation/filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,6CAAyC;AACzC,yCAAgD;AAChD,2CAAwC;AACxC,yCAAqC;AAErC;;;;;GAKG;AACI,MAAM,cAAc,GAAG,CAAC,KAAa,EAAE,EAAE;IAC/C,MAAM,wBAAwB,GAAqB;QAClD,WAAW;QACX,SAAS;QACT,SAAS;QACT,QAAQ;QACR,WAAW;KACX,CAAC;IACF,IAAI,IAAA,qBAAS,EAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAEhE,IACC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CACpC,wBAAwB,CAAC,QAAQ,CAAC,QAAwB,CAAC,CAC3D;QAED,OAAO,KAAK,CAAC;IAEd,IACC,CAAC,CAAC,IAAA,qBAAS,EAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,IAAA,6BAAkB,EAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACrE,CAAC,CAAC,IAAA,qBAAS,EAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAA,6BAAkB,EAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAEjE,OAAO,KAAK,CAAC;IAEd,IAAI,CAAC,IAAA,qBAAS,EAAC,KAAK,CAAC,OAAO,CAAC,EAAE;QAC9B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE;YACjC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAA,sBAAS,EAAC,OAAO,CAAC,CAAC;gBAAE,OAAO,KAAK,CAAC;SACtE;aAAM,IAAI,CAAC,IAAA,sBAAS,EAAC,KAAK,CAAC,OAAO,CAAC;YAAE,OAAO,KAAK,CAAC;KACnD;IAED,IAAI,CAAC,IAAA,qBAAS,EAAC,KAAK,CAAC,MAAM,CAAC,EAAE;QAC7B,IACC,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;YAC3B,IAAI,IAAA,qBAAS,EAAC,KAAK,CAAC;gBAAE,OAAO,IAAI,CAAC;YAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBACzB,OAAO,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAA,kBAAO,EAAC,WAAW,CAAC,CAAC,CAAC;aACxD;YAED,IAAI,IAAA,kBAAO,EAAC,KAAK,CAAC;gBAAE,OAAO,IAAI,CAAC;YAEhC,OAAO,KAAK,CAAC;QACd,CAAC,CAAC;YAEF,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA/CW,QAAA,cAAc,kBA+CzB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.d.ts new file mode 100644 index 0000000..e424d55 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.d.ts @@ -0,0 +1,11 @@ +export * from './address.js'; +export * from './block.js'; +export * from './bloom.js'; +export * from './boolean.js'; +export * from './bytes.js'; +export * from './eth.js'; +export * from './filter.js'; +export * from './numbers.js'; +export * from './string.js'; +export * from './topic.js'; +export * from './object.js'; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.js new file mode 100644 index 0000000..7e3b3ed --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.js @@ -0,0 +1,44 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./address.js"), exports); +__exportStar(require("./block.js"), exports); +__exportStar(require("./bloom.js"), exports); +__exportStar(require("./boolean.js"), exports); +__exportStar(require("./bytes.js"), exports); +__exportStar(require("./eth.js"), exports); +__exportStar(require("./filter.js"), exports); +__exportStar(require("./numbers.js"), exports); +__exportStar(require("./string.js"), exports); +__exportStar(require("./topic.js"), exports); +__exportStar(require("./object.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.js.map new file mode 100644 index 0000000..c9dbbbc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;AAEF,+CAA6B;AAC7B,6CAA2B;AAC3B,6CAA2B;AAC3B,+CAA6B;AAC7B,6CAA2B;AAC3B,2CAAyB;AACzB,8CAA4B;AAC5B,+CAA6B;AAC7B,8CAA4B;AAC5B,6CAA2B;AAC3B,8CAA4B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.d.ts new file mode 100644 index 0000000..a53ff7a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.d.ts @@ -0,0 +1,22 @@ +import { ValidInputTypes } from '../types.js'; +/** + * Checks if a given value is a valid big int + */ +export declare const isBigInt: (value: ValidInputTypes) => boolean; +/** @internal */ +export declare const bigintPower: (base: bigint, expo: bigint) => bigint; +export declare const isUInt: (value: ValidInputTypes, options?: { + abiType: string; + bitSize?: never; +} | { + bitSize: number; + abiType?: never; +}) => boolean; +export declare const isInt: (value: ValidInputTypes, options?: { + abiType: string; + bitSize?: never; +} | { + bitSize: number; + abiType?: never; +}) => boolean; +export declare const isNumber: (value: ValidInputTypes) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.js new file mode 100644 index 0000000..e6206ca --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.js @@ -0,0 +1,120 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNumber = exports.isInt = exports.isUInt = exports.bigintPower = exports.isBigInt = void 0; +const utils_js_1 = require("../utils.js"); +const string_js_1 = require("./string.js"); +/** + * Checks if a given value is a valid big int + */ +const isBigInt = (value) => typeof value === 'bigint'; +exports.isBigInt = isBigInt; +// Note: this could be simplified using ** operator, but babel does not handle it well +// you can find more at: https://github.com/babel/babel/issues/13109 and https://github.com/web3/web3.js/issues/6187 +/** @internal */ +const bigintPower = (base, expo) => { + let res = base; + for (let index = 1; index < expo; index += 1) { + res *= base; + } + return res; +}; +exports.bigintPower = bigintPower; +const isUInt = (value, options = { + abiType: 'uint', +}) => { + if (!['number', 'string', 'bigint'].includes(typeof value) || + (typeof value === 'string' && value.length === 0)) { + return false; + } + let size; + if (options === null || options === void 0 ? void 0 : options.abiType) { + const { baseTypeSize } = (0, utils_js_1.parseBaseType)(options.abiType); + if (baseTypeSize) { + size = baseTypeSize; + } + } + else if (options.bitSize) { + size = options.bitSize; + } + const maxSize = (0, exports.bigintPower)(BigInt(2), BigInt(size !== null && size !== void 0 ? size : 256)) - BigInt(1); + try { + const valueToCheck = typeof value === 'string' && (0, string_js_1.isHexStrict)(value) + ? BigInt((0, utils_js_1.hexToNumber)(value)) + : BigInt(value); + return valueToCheck >= 0 && valueToCheck <= maxSize; + } + catch (error) { + // Some invalid number value given which can not be converted via BigInt + return false; + } +}; +exports.isUInt = isUInt; +const isInt = (value, options = { + abiType: 'int', +}) => { + if (!['number', 'string', 'bigint'].includes(typeof value)) { + return false; + } + if (typeof value === 'number' && value > Number.MAX_SAFE_INTEGER) { + return false; + } + let size; + if (options === null || options === void 0 ? void 0 : options.abiType) { + const { baseTypeSize, baseType } = (0, utils_js_1.parseBaseType)(options.abiType); + if (baseType !== 'int') { + return false; + } + if (baseTypeSize) { + size = baseTypeSize; + } + } + else if (options.bitSize) { + size = options.bitSize; + } + const maxSize = (0, exports.bigintPower)(BigInt(2), BigInt((size !== null && size !== void 0 ? size : 256) - 1)); + const minSize = BigInt(-1) * (0, exports.bigintPower)(BigInt(2), BigInt((size !== null && size !== void 0 ? size : 256) - 1)); + try { + const valueToCheck = typeof value === 'string' && (0, string_js_1.isHexStrict)(value) + ? BigInt((0, utils_js_1.hexToNumber)(value)) + : BigInt(value); + return valueToCheck >= minSize && valueToCheck <= maxSize; + } + catch (error) { + // Some invalid number value given which can not be converted via BigInt + return false; + } +}; +exports.isInt = isInt; +const isNumber = (value) => { + if ((0, exports.isInt)(value)) { + return true; + } + // It would be a decimal number + if (typeof value === 'string' && + /[0-9.]/.test(value) && + value.indexOf('.') === value.lastIndexOf('.')) { + return true; + } + if (typeof value === 'number') { + return true; + } + return false; +}; +exports.isNumber = isNumber; +//# sourceMappingURL=numbers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.js.map new file mode 100644 index 0000000..8679ccb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/numbers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numbers.js","sourceRoot":"","sources":["../../../src/validation/numbers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAGF,0CAAyD;AACzD,2CAA0C;AAE1C;;GAEG;AACI,MAAM,QAAQ,GAAG,CAAC,KAAsB,EAAW,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;AAA1E,QAAA,QAAQ,YAAkE;AAEvF,sFAAsF;AACtF,qHAAqH;AACrH,gBAAgB;AACT,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,IAAY,EAAE,EAAE;IACzD,IAAI,GAAG,GAAG,IAAI,CAAC;IACf,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI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AAY,GACjB,OAAO,KAAK,KAAK,QAAQ,IAAI,IAAA,uBAAW,EAAC,KAAK,CAAC;YAC9C,CAAC,CAAC,MAAM,CAAC,IAAA,sBAAW,EAAC,KAAK,CAAC,CAAC;YAC5B,CAAC,CAAC,MAAM,CAAC,KAAe,CAAC,CAAC;QAE5B,OAAO,YAAY,IAAI,OAAO,IAAI,YAAY,IAAI,OAAO,CAAC;KAC1D;IAAC,OAAO,KAAK,EAAE;QACf,wEAAwE;QACxE,OAAO,KAAK,CAAC;KACb;AACF,CAAC,CAAC;AA5CW,QAAA,KAAK,SA4ChB;AAEK,MAAM,QAAQ,GAAG,CAAC,KAAsB,EAAE,EAAE;IAClD,IAAI,IAAA,aAAK,EAAC,KAAK,CAAC,EAAE;QACjB,OAAO,IAAI,CAAC;KACZ;IAED,+BAA+B;IAC/B,IACC,OAAO,KAAK,KAAK,QAAQ;QACzB,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;QACpB,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,EAC5C;QACD,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AAnBW,QAAA,QAAQ,YAmBnB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.d.ts new file mode 100644 index 0000000..fa63eca --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.d.ts @@ -0,0 +1,2 @@ +export declare const isNullish: (item: unknown) => item is null | undefined; +export declare const isObject: (item: unknown) => item is Record; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.js new file mode 100644 index 0000000..9ac52d3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.js @@ -0,0 +1,33 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isObject = exports.isNullish = void 0; +const web3_types_1 = require("web3-types"); +// Explicitly check for the +// eslint-disable-next-line @typescript-eslint/ban-types +const isNullish = (item) => +// Using "null" value intentionally for validation +// eslint-disable-next-line no-null/no-null +item === undefined || item === null; +exports.isNullish = isNullish; +const isObject = (item) => typeof item === 'object' && + !(0, exports.isNullish)(item) && + !Array.isArray(item) && + !(item instanceof web3_types_1.TypedArray); +exports.isObject = isObject; +//# sourceMappingURL=object.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.js.map new file mode 100644 index 0000000..7168fae --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/object.js.map @@ -0,0 +1 @@ +{"version":3,"file":"object.js","sourceRoot":"","sources":["../../../src/validation/object.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,2CAAwC;AAExC,2BAA2B;AAC3B,wDAAwD;AACjD,MAAM,SAAS,GAAG,CAAC,IAAa,EAA4B,EAAE;AACpE,kDAAkD;AAClD,2CAA2C;AAC3C,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,CAAC;AAHxB,QAAA,SAAS,aAGe;AAE9B,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAmC,EAAE,CAC1E,OAAO,IAAI,KAAK,QAAQ;IACxB,CAAC,IAAA,iBAAS,EAAC,IAAI,CAAC;IAChB,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;IACpB,CAAC,CAAC,IAAI,YAAY,uBAAU,CAAC,CAAC;AAJlB,QAAA,QAAQ,YAIU"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.d.ts new file mode 100644 index 0000000..a9de171 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.d.ts @@ -0,0 +1,40 @@ +import { ValidInputTypes } from '../types.js'; +/** + * checks input if typeof data is valid string input + */ +export declare const isString: (value: ValidInputTypes) => boolean; +export declare const isHexStrict: (hex: ValidInputTypes) => boolean; +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +export declare function isHexString(value: string, length?: number): boolean; +export declare const isHex: (hex: ValidInputTypes) => boolean; +export declare const isHexString8Bytes: (value: string, prefixed?: boolean) => boolean; +export declare const isHexString32Bytes: (value: string, prefixed?: boolean) => boolean; +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +export declare function isHexPrefixed(str: string): boolean; +/** + * Checks provided Uint8Array for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Uint8Array values + * @throws if any provided value is found to have leading zero bytes + */ +export declare const validateNoLeadingZeroes: (values: { + [key: string]: Uint8Array | undefined; +}) => void; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.js new file mode 100644 index 0000000..695047b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.js @@ -0,0 +1,84 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateNoLeadingZeroes = exports.isHexPrefixed = exports.isHexString32Bytes = exports.isHexString8Bytes = exports.isHex = exports.isHexString = exports.isHexStrict = exports.isString = void 0; +/** + * checks input if typeof data is valid string input + */ +const isString = (value) => typeof value === 'string'; +exports.isString = isString; +const isHexStrict = (hex) => typeof hex === 'string' && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex); +exports.isHexStrict = isHexStrict; +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +function isHexString(value, length) { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) + return false; + if (typeof length !== 'undefined' && length > 0 && value.length !== 2 + 2 * length) + return false; + return true; +} +exports.isHexString = isHexString; +const isHex = (hex) => typeof hex === 'number' || + typeof hex === 'bigint' || + (typeof hex === 'string' && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex)); +exports.isHex = isHex; +const isHexString8Bytes = (value, prefixed = true) => prefixed ? (0, exports.isHexStrict)(value) && value.length === 18 : (0, exports.isHex)(value) && value.length === 16; +exports.isHexString8Bytes = isHexString8Bytes; +const isHexString32Bytes = (value, prefixed = true) => prefixed ? (0, exports.isHexStrict)(value) && value.length === 66 : (0, exports.isHex)(value) && value.length === 64; +exports.isHexString32Bytes = isHexString32Bytes; +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +function isHexPrefixed(str) { + if (typeof str !== 'string') { + throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`); + } + return str.startsWith('0x'); +} +exports.isHexPrefixed = isHexPrefixed; +/** + * Checks provided Uint8Array for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Uint8Array values + * @throws if any provided value is found to have leading zero bytes + */ +const validateNoLeadingZeroes = function (values) { + for (const [k, v] of Object.entries(values)) { + if (v !== undefined && v.length > 0 && v[0] === 0) { + throw new Error(`${k} cannot have leading zeroes, received: ${v.toString()}`); + } + } +}; +exports.validateNoLeadingZeroes = validateNoLeadingZeroes; +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.js.map new file mode 100644 index 0000000..f295321 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src/validation/string.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAIF;;GAEG;AACI,MAAM,QAAQ,GAAG,CAAC,KAAsB,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;AAAjE,QAAA,QAAQ,YAAyD;AAEvE,MAAM,WAAW,GAAG,CAAC,GAAoB,EAAE,EAAE,CACnD,OAAO,GAAG,KAAK,QAAQ,IAAI,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AADrD,QAAA,WAAW,eAC0C;AAElE;;;;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IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,8DAA8D,OAAO,GAAG,EAAE,CAAC,CAAC;KAC5F;IAED,OAAO,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAND,sCAMC;AAED;;;;;;;;;;;;GAYG;AACI,MAAM,uBAAuB,GAAG,UAAU,MAEhD;IACA,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QAC5C,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE;YAClD,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;SAC9E;KACD;AACF,CAAC,CAAC;AARW,QAAA,uBAAuB,2BAQlC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.d.ts new file mode 100644 index 0000000..14a3aa5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.d.ts @@ -0,0 +1,9 @@ +/** + * Checks if its a valid topic + */ +export declare const isTopic: (topic: string) => boolean; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + */ +export declare const isTopicInBloom: (bloom: string, topic: string) => boolean; diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.js new file mode 100644 index 0000000..995d526 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.js @@ -0,0 +1,51 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTopicInBloom = exports.isTopic = void 0; +const bloom_js_1 = require("./bloom.js"); +/** + * Checks if its a valid topic + */ +const isTopic = (topic) => { + if (typeof topic !== 'string') { + return false; + } + if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { + return false; + } + if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { + return true; + } + return false; +}; +exports.isTopic = isTopic; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + */ +const isTopicInBloom = (bloom, topic) => { + if (!(0, bloom_js_1.isBloom)(bloom)) { + return false; + } + if (!(0, exports.isTopic)(topic)) { + return false; + } + return (0, bloom_js_1.isInBloom)(bloom, topic); +}; +exports.isTopicInBloom = isTopicInBloom; +//# sourceMappingURL=topic.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.js.map new file mode 100644 index 0000000..de68452 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validation/topic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topic.js","sourceRoot":"","sources":["../../../src/validation/topic.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAEF,yCAAgD;AAEhD;;GAEG;AACI,MAAM,OAAO,GAAG,CAAC,KAAa,EAAW,EAAE;IACjD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QACxC,OAAO,KAAK,CAAC;KACb;IAED,IAAI,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QAC3E,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AAdW,QAAA,OAAO,WAclB;AAEF;;;GAGG;AACI,MAAM,cAAc,GAAG,CAAC,KAAa,EAAE,KAAa,EAAW,EAAE;IACvE,IAAI,CAAC,IAAA,kBAAO,EAAC,KAAK,CAAC,EAAE;QACpB,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,IAAA,eAAO,EAAC,KAAK,CAAC,EAAE;QACpB,OAAO,KAAK,CAAC;KACb;IAED,OAAO,IAAA,oBAAS,EAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAChC,CAAC,CAAC;AAVW,QAAA,cAAc,kBAUzB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.d.ts new file mode 100644 index 0000000..e469ff2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.d.ts @@ -0,0 +1,10 @@ +import { Web3ValidationErrorObject } from 'web3-types'; +import { Json, JsonSchema } from './types.js'; +export declare class Validator { + private static validatorInstance?; + static factory(): Validator; + validate(schema: JsonSchema, data: Json, options?: { + silent?: boolean; + }): Web3ValidationErrorObject, unknown>[] | undefined; + private convertErrors; +} diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.js new file mode 100644 index 0000000..4775fcf --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.js @@ -0,0 +1,148 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Validator = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +const web3_errors_1 = require("web3-errors"); +const zod_1 = require("zod"); +const errors_js_1 = require("./errors.js"); +const formats_js_1 = __importDefault(require("./formats.js")); +const convertToZod = (schema) => { + if ((!(schema === null || schema === void 0 ? void 0 : schema.type) || (schema === null || schema === void 0 ? void 0 : schema.type) === 'object') && (schema === null || schema === void 0 ? void 0 : schema.properties)) { + const obj = {}; + for (const name of Object.keys(schema.properties)) { + const zItem = convertToZod(schema.properties[name]); + if (zItem) { + obj[name] = zItem; + } + } + if (Array.isArray(schema.required)) { + return zod_1.z + .object(obj) + .partial() + .required(schema.required.reduce((acc, v) => (Object.assign(Object.assign({}, acc), { [v]: true })), {})); + } + return zod_1.z.object(obj).partial(); + } + if ((schema === null || schema === void 0 ? void 0 : schema.type) === 'array' && (schema === null || schema === void 0 ? void 0 : schema.items)) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + const arr = []; + for (const item of schema.items) { + const zItem = convertToZod(item); + if (zItem) { + arr.push(zItem); + } + } + return zod_1.z.tuple(arr); + } + return zod_1.z.array(convertToZod(schema.items)); + } + if (schema.oneOf && Array.isArray(schema.oneOf)) { + return zod_1.z.union(schema.oneOf.map(oneOfSchema => convertToZod(oneOfSchema))); + } + if (schema === null || schema === void 0 ? void 0 : schema.format) { + if (!formats_js_1.default[schema.format]) { + throw new web3_errors_1.SchemaFormatError(schema.format); + } + return zod_1.z.any().refine(formats_js_1.default[schema.format], (value) => ({ + params: { value, format: schema.format }, + })); + } + if ((schema === null || schema === void 0 ? void 0 : schema.type) && + (schema === null || schema === void 0 ? void 0 : schema.type) !== 'object' && + typeof zod_1.z[String(schema.type)] === 'function') { + return zod_1.z[String(schema.type)](); + } + return zod_1.z.object({ data: zod_1.z.any() }).partial(); +}; +class Validator { + // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function + static factory() { + if (!Validator.validatorInstance) { + Validator.validatorInstance = new Validator(); + } + return Validator.validatorInstance; + } + validate(schema, data, options) { + var _a, _b; + const zod = convertToZod(schema); + const result = zod.safeParse(data); + if (!result.success) { + const errors = this.convertErrors((_b = (_a = result.error) === null || _a === void 0 ? void 0 : _a.issues) !== null && _b !== void 0 ? _b : []); + if (errors) { + if (options === null || options === void 0 ? void 0 : options.silent) { + return errors; + } + throw new errors_js_1.Web3ValidatorError(errors); + } + } + return undefined; + } + // eslint-disable-next-line class-methods-use-this + convertErrors(errors) { + if (errors && Array.isArray(errors) && errors.length > 0) { + return errors.map((error) => { + var _a; + let message; + let keyword; + let params; + let schemaPath; + schemaPath = error.path.join('/'); + const field = String(error.path[error.path.length - 1]); + const instancePath = error.path.join('/'); + if (error.code === zod_1.ZodIssueCode.too_big) { + keyword = 'maxItems'; + schemaPath = `${instancePath}/maxItems`; + params = { limit: error.maximum }; + message = `must NOT have more than ${error.maximum} items`; + } + else if (error.code === zod_1.ZodIssueCode.too_small) { + keyword = 'minItems'; + schemaPath = `${instancePath}/minItems`; + params = { limit: error.minimum }; + message = `must NOT have fewer than ${error.minimum} items`; + } + else if (error.code === zod_1.ZodIssueCode.custom) { + const { value, format } = ((_a = error.params) !== null && _a !== void 0 ? _a : {}); + if (typeof value === 'undefined') { + message = `value at "/${schemaPath}" is required`; + } + else { + message = `value "${ + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + typeof value === 'object' ? JSON.stringify(value) : value}" at "/${schemaPath}" must pass "${format}" validation`; + } + params = { value }; + } + return { + keyword: keyword !== null && keyword !== void 0 ? keyword : field, + instancePath: instancePath ? `/${instancePath}` : '', + schemaPath: schemaPath ? `#${schemaPath}` : '#', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params: params !== null && params !== void 0 ? params : { value: error.message }, + message: message !== null && message !== void 0 ? message : error.message, + }; + }); + } + return undefined; + } +} +exports.Validator = Validator; +//# sourceMappingURL=validator.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.js.map new file mode 100644 index 0000000..69177b3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/validator.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,6CAAgD;AAGhD,6BAAqE;AAGrE,2CAAiD;AAEjD,8DAAmC;AAEnC,MAAM,YAAY,GAAG,CAAC,MAAkB,EAAW,EAAE;IACpD,IAAI,CAAC,CAAC,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAA,IAAI,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,MAAK,QAAQ,CAAC,KAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,UAAU,CAAA,EAAE;QACvE,MAAM,GAAG,GAA+B,EAAE,CAAC;QAC3C,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE;YAClD,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;YACpD,IAAI,KAAK,EAAE;gBACV,GAAG,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;aAClB;SACD;QAED,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE;YACnC,OAAO,OAAC;iBACN,MAAM,CAAC,GAAG,CAAC;iBACX,OAAO,EAAE;iBACT,QAAQ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a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.d.ts new file mode 100644 index 0000000..3662edc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.d.ts @@ -0,0 +1,8 @@ +import { Web3ValidationErrorObject } from 'web3-types'; +import { ValidationSchemaInput, Web3ValidationOptions } from './types.js'; +export declare class Web3Validator { + private readonly _validator; + constructor(); + validateJSONSchema(schema: object, data: object, options?: Web3ValidationOptions): Web3ValidationErrorObject[] | undefined; + validate(schema: ValidationSchemaInput, data: ReadonlyArray, options?: Web3ValidationOptions): Web3ValidationErrorObject[] | undefined; +} diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.js b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.js new file mode 100644 index 0000000..69064ac --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3Validator = void 0; +const validator_js_1 = require("./validator.js"); +const utils_js_1 = require("./utils.js"); +const errors_js_1 = require("./errors.js"); +class Web3Validator { + constructor() { + this._validator = validator_js_1.Validator.factory(); + } + validateJSONSchema(schema, data, options) { + return this._validator.validate(schema, data, options); + } + validate(schema, data, options = { silent: false }) { + var _a, _b; + const jsonSchema = (0, utils_js_1.ethAbiToJsonSchema)(schema); + if (Array.isArray(jsonSchema.items) && + ((_a = jsonSchema.items) === null || _a === void 0 ? void 0 : _a.length) === 0 && + data.length === 0) { + return undefined; + } + if (Array.isArray(jsonSchema.items) && + ((_b = jsonSchema.items) === null || _b === void 0 ? void 0 : _b.length) === 0 && + data.length !== 0) { + throw new errors_js_1.Web3ValidatorError([ + { + instancePath: '/0', + schemaPath: '/', + keyword: 'required', + message: 'empty schema against data can not be validated', + params: data, + }, + ]); + } + return this._validator.validate(jsonSchema, data, options); + } +} +exports.Web3Validator = Web3Validator; +//# sourceMappingURL=web3_validator.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.js.map b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.js.map new file mode 100644 index 0000000..7059f99 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/commonjs/web3_validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_validator.js","sourceRoot":"","sources":["../../src/web3_validator.ts"],"names":[],"mappings":";;;AAkBA,iDAA2C;AAC3C,yCAAgD;AAEhD,2CAAiD;AAEjD,MAAa,aAAa;IAEzB;QACC,IAAI,CAAC,UAAU,GAAG,wBAAS,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;IACM,kBAAkB,CACxB,MAAc,EACd,IAAY,EACZ,OAA+B;QAE/B,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAY,EAAE,OAAO,CAAC,CAAC;IAChE,CAAC;IACM,QAAQ,CACd,MAA6B,EAC7B,IAA4B,EAC5B,UAAiC,EAAE,MAAM,EAAE,KAAK,EAAE;;QAElD,MAAM,UAAU,GAAG,IAAA,6BAAkB,EAAC,MAAM,CAAC,CAAC;QAC9C,IACC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;YAC/B,CAAA,MAAA,UAAU,CAAC,KAAK,0CAAE,MAAM,MAAK,CAAC;YAC9B,IAAI,CAAC,MAAM,KAAK,CAAC,EAChB;YACD,OAAO,SAAS,CAAC;SACjB;QAED,IACC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;YAC/B,CAAA,MAAA,UAAU,CAAC,KAAK,0CAAE,MAAM,MAAK,CAAC;YAC9B,IAAI,CAAC,MAAM,KAAK,CAAC,EAChB;YACD,MAAM,IAAI,8BAAkB,CAAC;gBAC5B;oBACC,YAAY,EAAE,IAAI;oBAClB,UAAU,EAAE,GAAG;oBACf,OAAO,EAAE,UAAU;oBACnB,OAAO,EAAE,gDAAgD;oBACzD,MAAM,EAAE,IAAI;iBACZ;aACD,CAAC,CAAC;SACH;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,UAAU,EAAE,IAAY,EAAE,OAAO,CAAC,CAAC;IACpE,CAAC;CACD;AA5CD,sCA4CC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/constants.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/constants.js new file mode 100644 index 0000000..7975660 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/constants.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export const VALID_ETH_BASE_TYPES = ['bool', 'int', 'uint', 'bytes', 'string', 'address', 'tuple']; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/constants.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/constants.js.map new file mode 100644 index 0000000..fae832b --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/default_validator.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/default_validator.js new file mode 100644 index 0000000..5352a1f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/default_validator.js @@ -0,0 +1,19 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3Validator } from './web3_validator.js'; +export const validator = new Web3Validator(); +//# sourceMappingURL=default_validator.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/default_validator.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/default_validator.js.map new file mode 100644 index 0000000..1209200 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/default_validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default_validator.js","sourceRoot":"","sources":["../../src/default_validator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/errors.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/errors.js new file mode 100644 index 0000000..182d49a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/errors.js @@ -0,0 +1,35 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { BaseWeb3Error, ERR_VALIDATION } from 'web3-errors'; +const errorFormatter = (error) => { + if (error.message) { + return error.message; + } + return 'unspecified error'; +}; +export class Web3ValidatorError extends BaseWeb3Error { + constructor(errors) { + super(); + this.code = ERR_VALIDATION; + this.errors = errors; + super.message = `Web3 validator found ${errors.length} error[s]:\n${this._compileErrors().join('\n')}`; + } + _compileErrors() { + return this.errors.map(errorFormatter); + } +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/errors.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/errors.js.map new file mode 100644 index 0000000..dda66bc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAG5D,MAAM,cAAc,GAAG,CAAC,KAAgC,EAAU,EAAE;IACnE,IAAI,KAAK,CAAC,OAAO,EAAE;QAClB,OAAO,KAAK,CAAC,OAAO,CAAC;KACrB;IAED,OAAO,mBAAmB,CAAC;AAC5B,CAAC,CAAC;AAEF,MAAM,OAAO,kBAAmB,SAAQ,aAAa;IAIpD,YAAmB,MAAmC;QACrD,KAAK,EAAE,CAAC;QAJF,SAAI,GAAG,cAAc,CAAC;QAM5B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,KAAK,CAAC,OAAO,GAAG,wBACf,MAAM,CAAC,MACR,eAAe,IAAI,CAAC,cAAc,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IACnD,CAAC;IAEO,cAAc;QACrB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IACxC,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/formats.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/formats.js new file mode 100644 index 0000000..5d56087 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/formats.js @@ -0,0 +1,35 @@ +import { isAddress } from './validation/address.js'; +import { isBlockNumber, isBlockNumberOrTag, isBlockTag } from './validation/block.js'; +import { isBloom } from './validation/bloom.js'; +import { isBoolean } from './validation/boolean.js'; +import { isBytes } from './validation/bytes.js'; +import { isFilterObject } from './validation/filter.js'; +import { isHexStrict, isString } from './validation/string.js'; +import { isNumber, isInt, isUInt } from './validation/numbers.js'; +const formats = { + address: (data) => isAddress(data), + bloom: (data) => isBloom(data), + blockNumber: (data) => isBlockNumber(data), + blockTag: (data) => isBlockTag(data), + blockNumberOrTag: (data) => isBlockNumberOrTag(data), + bool: (data) => isBoolean(data), + bytes: (data) => isBytes(data), + filter: (data) => isFilterObject(data), + hex: (data) => isHexStrict(data), + uint: (data) => isUInt(data), + int: (data) => isInt(data), + number: (data) => isNumber(data), + string: (data) => isString(data), +}; +// generate formats for all numbers types +for (let bitSize = 8; bitSize <= 256; bitSize += 8) { + formats[`int${bitSize}`] = data => isInt(data, { bitSize }); + formats[`uint${bitSize}`] = data => isUInt(data, { bitSize }); +} +// generate bytes +for (let size = 1; size <= 32; size += 1) { + formats[`bytes${size}`] = data => isBytes(data, { size }); +} +formats.bytes256 = formats.bytes; +export default formats; +//# sourceMappingURL=formats.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/formats.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/formats.js.map new file mode 100644 index 0000000..2f5f0cd --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/formats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formats.js","sourceRoot":"","s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E,EAAE,CAAC,MAAM,CAAC,IAAuB,CAAC;IACxD,GAAG,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,KAAK,CAAC,IAAuB,CAAC;IACtD,MAAM,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAuB,CAAC;IAC5D,MAAM,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAuB,CAAC;CAC5D,CAAC;AACF,yCAAyC;AACzC,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,GAAG,EAAE,OAAO,IAAI,CAAC,EAAE;IACnD,OAAO,CAAC,MAAM,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,IAAuB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/E,OAAO,CAAC,OAAO,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,IAAuB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;CACjF;AACD,iBAAiB;AACjB,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,IAAI,EAAE,EAAE,IAAI,IAAI,CAAC,EAAE;IACzC,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAChC,OAAO,CAAC,IAA+C,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;CACpE;AACD,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC;AAEjC,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/index.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/index.js new file mode 100644 index 0000000..bb6adf3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/index.js @@ -0,0 +1,24 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './web3_validator.js'; +export * from './default_validator.js'; +export * from './types.js'; +export * as utils from './utils.js'; +export * from './errors.js'; +export * from './constants.js'; +export * from './validation/index.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/index.js.map new file mode 100644 index 0000000..5dbe654 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,YAAY,CAAC;AAC3B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/package.json b/test/merkletreejs/node_modules/web3-validator/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/types.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/utils.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/utils.js new file mode 100644 index 0000000..5bf8f1c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/utils.js @@ -0,0 +1,375 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { InvalidBytesError, InvalidNumberError } from 'web3-errors'; +import { VALID_ETH_BASE_TYPES } from './constants.js'; +import { isAbiParameterSchema } from './validation/abi.js'; +import { isHexStrict } from './validation/string.js'; +import { Web3ValidatorError } from './errors.js'; +const extraTypes = ['hex', 'number', 'blockNumber', 'blockNumberOrTag', 'filter', 'bloom']; +export const parseBaseType = (type) => { + // Remove all empty spaces to avoid any parsing issue. + let strippedType = type.replace(/ /, ''); + let baseTypeSize; + let isArray = false; + let arraySizes = []; + if (type.includes('[')) { + // Extract the array type + strippedType = strippedType.slice(0, strippedType.indexOf('[')); + // Extract array indexes + arraySizes = [...type.matchAll(/(?:\[(\d*)\])/g)] + .map(match => parseInt(match[1], 10)) + .map(size => (Number.isNaN(size) ? -1 : size)); + isArray = arraySizes.length > 0; + } + if (VALID_ETH_BASE_TYPES.includes(strippedType)) { + return { baseType: strippedType, isArray, baseTypeSize, arraySizes }; + } + if (strippedType.startsWith('int')) { + baseTypeSize = parseInt(strippedType.substring(3), 10); + strippedType = 'int'; + } + else if (strippedType.startsWith('uint')) { + baseTypeSize = parseInt(type.substring(4), 10); + strippedType = 'uint'; + } + else if (strippedType.startsWith('bytes')) { + baseTypeSize = parseInt(strippedType.substring(5), 10); + strippedType = 'bytes'; + } + else { + return { baseType: undefined, isArray: false, baseTypeSize: undefined, arraySizes }; + } + return { baseType: strippedType, isArray, baseTypeSize, arraySizes }; +}; +const convertEthType = (type, parentSchema = {}) => { + const typePropertyPresent = Object.keys(parentSchema).includes('type'); + if (typePropertyPresent) { + throw new Web3ValidatorError([ + { + keyword: 'eth', + message: 'Either "eth" or "type" can be presented in schema', + params: { eth: type }, + instancePath: '', + schemaPath: '', + }, + ]); + } + const { baseType, baseTypeSize } = parseBaseType(type); + if (!baseType && !extraTypes.includes(type)) { + throw new Web3ValidatorError([ + { + keyword: 'eth', + message: `Eth data type "${type}" is not valid`, + params: { eth: type }, + instancePath: '', + schemaPath: '', + }, + ]); + } + if (baseType) { + if (baseType === 'tuple') { + throw new Error('"tuple" type is not implemented directly.'); + } + return { format: `${baseType}${baseTypeSize !== null && baseTypeSize !== void 0 ? baseTypeSize : ''}`, required: true }; + } + if (type) { + return { format: type, required: true }; + } + return {}; +}; +export const abiSchemaToJsonSchema = (abis, level = '/0') => { + const schema = { + type: 'array', + items: [], + maxItems: abis.length, + minItems: abis.length, + }; + for (const [index, abi] of abis.entries()) { + // eslint-disable-next-line no-nested-ternary + let abiType; + let abiName; + let abiComponents = []; + // If it's a complete Abi Parameter + // e.g. {name: 'a', type: 'uint'} + if (isAbiParameterSchema(abi)) { + abiType = abi.type; + abiName = abi.name; + abiComponents = abi.components; + // If its short form string value e.g. ['uint'] + } + else if (typeof abi === 'string') { + abiType = abi; + abiName = `${level}/${index}`; + // If it's provided in short form of tuple e.g. [['uint', 'string']] + } + else if (Array.isArray(abi)) { + // If its custom tuple e.g. ['tuple[2]', ['uint', 'string']] + if (abi[0] && + typeof abi[0] === 'string' && + abi[0].startsWith('tuple') && + !Array.isArray(abi[0]) && + abi[1] && + Array.isArray(abi[1])) { + // eslint-disable-next-line prefer-destructuring + abiType = abi[0]; + abiName = `${level}/${index}`; + abiComponents = abi[1]; + } + else { + abiType = 'tuple'; + abiName = `${level}/${index}`; + abiComponents = abi; + } + } + const { baseType, isArray, arraySizes } = parseBaseType(abiType); + let childSchema; + let lastSchema = schema; + for (let i = arraySizes.length - 1; i > 0; i -= 1) { + childSchema = { + type: 'array', + items: [], + maxItems: arraySizes[i], + minItems: arraySizes[i], + }; + if (arraySizes[i] < 0) { + delete childSchema.maxItems; + delete childSchema.minItems; + } + // lastSchema.items is a Schema, concat with 'childSchema' + if (!Array.isArray(lastSchema.items)) { + lastSchema.items = [lastSchema.items, childSchema]; + } // lastSchema.items is an empty Scheme array, set it to 'childSchema' + else if (lastSchema.items.length === 0) { + lastSchema.items = childSchema; + } // lastSchema.items is a non-empty Scheme array, append 'childSchema' + else { + lastSchema.items.push(childSchema); + } + lastSchema = childSchema; + } + if (baseType === 'tuple' && !isArray) { + const nestedTuple = abiSchemaToJsonSchema(abiComponents, abiName); + nestedTuple.$id = abiName; + lastSchema.items.push(nestedTuple); + } + else if (baseType === 'tuple' && isArray) { + const arraySize = arraySizes[0]; + const item = { + $id: abiName, + type: 'array', + items: abiSchemaToJsonSchema(abiComponents, abiName), + maxItems: arraySize, + minItems: arraySize, + }; + if (arraySize < 0) { + delete item.maxItems; + delete item.minItems; + } + lastSchema.items.push(item); + } + else if (isArray) { + const arraySize = arraySizes[0]; + const item = { + type: 'array', + $id: abiName, + items: convertEthType(String(baseType)), + minItems: arraySize, + maxItems: arraySize, + }; + if (arraySize < 0) { + delete item.maxItems; + delete item.minItems; + } + lastSchema.items.push(item); + } + else if (Array.isArray(lastSchema.items)) { + // Array of non-tuple items + lastSchema.items.push(Object.assign({ $id: abiName }, convertEthType(abiType))); + } + else { + // Nested object + lastSchema.items.items.push(Object.assign({ $id: abiName }, convertEthType(abiType))); + } + lastSchema = schema; + } + return schema; +}; +export const ethAbiToJsonSchema = (abis) => abiSchemaToJsonSchema(abis); +export const fetchArrayElement = (data, level) => { + if (level === 1) { + return data; + } + return fetchArrayElement(data[0], level - 1); +}; +export const transformJsonDataToAbiFormat = (abis, data, transformedData) => { + const newData = []; + for (const [index, abi] of abis.entries()) { + // eslint-disable-next-line no-nested-ternary + let abiType; + let abiName; + let abiComponents = []; + // If it's a complete Abi Parameter + // e.g. {name: 'a', type: 'uint'} + if (isAbiParameterSchema(abi)) { + abiType = abi.type; + abiName = abi.name; + abiComponents = abi.components; + // If its short form string value e.g. ['uint'] + } + else if (typeof abi === 'string') { + abiType = abi; + // If it's provided in short form of tuple e.g. [['uint', 'string']] + } + else if (Array.isArray(abi)) { + // If its custom tuple e.g. ['tuple[2]', ['uint', 'string']] + if (abi[1] && Array.isArray(abi[1])) { + abiType = abi[0]; + abiComponents = abi[1]; + } + else { + abiType = 'tuple'; + abiComponents = abi; + } + } + const { baseType, isArray, arraySizes } = parseBaseType(abiType); + const dataItem = Array.isArray(data) + ? data[index] + : data[abiName]; + if (baseType === 'tuple' && !isArray) { + newData.push(transformJsonDataToAbiFormat(abiComponents, dataItem, transformedData)); + } + else if (baseType === 'tuple' && isArray) { + const tupleData = []; + for (const tupleItem of dataItem) { + // Nested array + if (arraySizes.length > 1) { + const nestedItems = fetchArrayElement(tupleItem, arraySizes.length - 1); + const nestedData = []; + for (const nestedItem of nestedItems) { + nestedData.push(transformJsonDataToAbiFormat(abiComponents, nestedItem, transformedData)); + } + tupleData.push(nestedData); + } + else { + tupleData.push(transformJsonDataToAbiFormat(abiComponents, tupleItem, transformedData)); + } + } + newData.push(tupleData); + } + else { + newData.push(dataItem); + } + } + // Have to reassign before pushing to transformedData + // eslint-disable-next-line no-param-reassign + transformedData = transformedData !== null && transformedData !== void 0 ? transformedData : []; + transformedData.push(...newData); + return transformedData; +}; +/** + * Code points to int + */ +export const codePointToInt = (codePoint) => { + if (codePoint >= 48 && codePoint <= 57) { + /* ['0'..'9'] -> [0..9] */ + return codePoint - 48; + } + if (codePoint >= 65 && codePoint <= 70) { + /* ['A'..'F'] -> [10..15] */ + return codePoint - 55; + } + if (codePoint >= 97 && codePoint <= 102) { + /* ['a'..'f'] -> [10..15] */ + return codePoint - 87; + } + throw new Error(`Invalid code point: ${codePoint}`); +}; +/** + * Converts value to it's number representation + */ +export const hexToNumber = (value) => { + if (!isHexStrict(value)) { + throw new Error('Invalid hex string'); + } + const [negative, hexValue] = value.startsWith('-') ? [true, value.slice(1)] : [false, value]; + const num = BigInt(hexValue); + if (num > Number.MAX_SAFE_INTEGER) { + return negative ? -num : num; + } + if (num < Number.MIN_SAFE_INTEGER) { + return num; + } + return negative ? -1 * Number(num) : Number(num); +}; +/** + * Converts value to it's hex representation + */ +export const numberToHex = (value) => { + if ((typeof value === 'number' || typeof value === 'bigint') && value < 0) { + return `-0x${value.toString(16).slice(1)}`; + } + if ((typeof value === 'number' || typeof value === 'bigint') && value >= 0) { + return `0x${value.toString(16)}`; + } + if (typeof value === 'string' && isHexStrict(value)) { + const [negative, hex] = value.startsWith('-') ? [true, value.slice(1)] : [false, value]; + const hexValue = hex.split(/^(-)?0(x|X)/).slice(-1)[0]; + return `${negative ? '-' : ''}0x${hexValue.replace(/^0+/, '').toLowerCase()}`; + } + if (typeof value === 'string' && !isHexStrict(value)) { + return numberToHex(BigInt(value)); + } + throw new InvalidNumberError(value); +}; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + */ +export const padLeft = (value, characterAmount, sign = '0') => { + if (typeof value === 'string' && !isHexStrict(value)) { + return value.padStart(characterAmount, sign); + } + const hex = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value); + const [prefix, hexValue] = hex.startsWith('-') ? ['-0x', hex.slice(3)] : ['0x', hex.slice(2)]; + return `${prefix}${hexValue.padStart(characterAmount, sign)}`; +}; +export function uint8ArrayToHexString(uint8Array) { + let hexString = '0x'; + for (const e of uint8Array) { + const hex = e.toString(16); + hexString += hex.length === 1 ? `0${hex}` : hex; + } + return hexString; +} +export function hexToUint8Array(hex) { + let value; + if (hex.toLowerCase().startsWith('0x')) { + value = hex.slice(2); + } + else { + value = hex; + } + if (value.length % 2 !== 0) { + throw new InvalidBytesError(`hex string has odd length: ${hex}`); + } + const bytes = new Uint8Array(Math.ceil(value.length / 2)); + for (let i = 0; i < bytes.length; i += 1) { + const byte = parseInt(value.substring(i * 2, i * 2 + 2), 16); + bytes[i] = byte; + } + return bytes; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/utils.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/utils.js.map new file mode 100644 index 0000000..67d868f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAQtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,UAAU,GAAG,CAA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AAED,MAAM,UAAU,eAAe,CAAC,GAAW;IAC1C,IAAI,KAAK,CAAC;IACV,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QACvC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KACrB;SAAM;QACN,KAAK,GAAG,GAAG,CAAC;KACZ;IACD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE;QAC3B,MAAM,IAAI,iBAAiB,CAAC,8BAA8B,GAAG,EAAE,CAAC,CAAC;KACjE;IACD,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;IAC1D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QACzC,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC7D,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;KAChB;IACD,OAAO,KAAK,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/abi.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/abi.js new file mode 100644 index 0000000..d020123 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/abi.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export const isAbiParameterSchema = (schema) => typeof schema === 'object' && 'type' in schema && 'name' in schema; +//# sourceMappingURL=abi.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/abi.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/abi.js.map new file mode 100644 index 0000000..fb2b69f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/abi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abi.js","sourceRoot":"","sources":["../../../src/validation/abi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAMF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CACnC,MAAqD,EAC5B,EAAE,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/address.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/address.js new file mode 100644 index 0000000..fd9bfd4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/address.js @@ -0,0 +1,68 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { utf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { uint8ArrayToHexString } from '../utils.js'; +import { isHexStrict } from './string.js'; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + */ +export const checkAddressCheckSum = (data) => { + if (!/^(0x)?[0-9a-f]{40}$/i.test(data)) + return false; + const address = data.slice(2); + const updatedData = utf8ToBytes(address.toLowerCase()); + const addressHash = uint8ArrayToHexString(keccak256(updatedData)).slice(2); + for (let i = 0; i < 40; i += 1) { + // the nth letter should be uppercase if the nth digit of casemap is 1 + if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || + (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { + return false; + } + } + return true; +}; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + */ +export const isAddress = (value, checkChecksum = true) => { + if (typeof value !== 'string' && !(value instanceof Uint8Array)) { + return false; + } + let valueToCheck; + if (value instanceof Uint8Array) { + valueToCheck = uint8ArrayToHexString(value); + } + else if (typeof value === 'string' && !isHexStrict(value)) { + valueToCheck = value.toLowerCase().startsWith('0x') ? value : `0x${value}`; + } + else { + valueToCheck = value; + } + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(valueToCheck)) { + return false; + } + // If it's ALL lowercase or ALL upppercase + if (/^(0x|0X)?[0-9a-f]{40}$/.test(valueToCheck) || + /^(0x|0X)?[0-9A-F]{40}$/.test(valueToCheck)) { + return true; + // Otherwise check each case + } + return checkChecksum ? checkAddressCheckSum(valueToCheck) : true; +}; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/address.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/address.js.map new file mode 100644 index 0000000..4dc7ff6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../src/validation/address.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,WAAW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;QAChE,OAAO,KAAK,CAAC;KACb;IAED,IAAI,YAAoB,CAAC;IAEzB,IAAI,KAAK,YAAY,UAAU,EAAE;QAChC,YAAY,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;KAC5C;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE;QAC5D,YAAY,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC;KAC3E;SAAM;QACN,YAAY,GAAG,KAAK,CAAC;KACrB;IAED,uDAAuD;IACvD,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE;QAC/C,OAAO,KAAK,CAAC;KACb;IACD,0CAA0C;IAC1C,IACC,wBAAwB,CAAC,IAAI,CAAC,YAAY,CAAC;QAC3C,wBAAwB,CAAC,IAAI,CAAC,YAAY,CAAC,EAC1C;QACD,OAAO,IAAI,CAAC;QACZ,4BAA4B;KAC5B;IACD,OAAO,aAAa,CAAC,CAAC,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAClE,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/block.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/block.js new file mode 100644 index 0000000..f27e300 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/block.js @@ -0,0 +1,28 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { BlockTags } from 'web3-types'; +import { isUInt } from './numbers.js'; +export const isBlockNumber = (value) => isUInt(value); +/** + * Returns true if the given blockNumber is 'latest', 'pending', 'earliest, 'safe' or 'finalized' + */ +export const isBlockTag = (value) => Object.values(BlockTags).includes(value); +/** + * Returns true if given value is valid hex string and not negative, or is a valid BlockTag + */ +export const isBlockNumberOrTag = (value) => isBlockTag(value) || isBlockNumber(value); +//# sourceMappingURL=block.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/block.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/block.js.map new file mode 100644 index 0000000..517c3db --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/block.js.map @@ -0,0 +1 @@ +{"version":3,"file":"block.js","sourceRoot":"","sources":["../../../src/validation/block.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAA+B,EAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAEzF;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,KAAkB,CAAC,CAAC;AAEnG;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,KAA+B,EAAE,EAAE,CACrE,UAAU,CAAC,KAAe,CAAC,IAAI,aAAa,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bloom.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bloom.js new file mode 100644 index 0000000..d7e3bb6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bloom.js @@ -0,0 +1,99 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { codePointToInt, hexToUint8Array, padLeft, uint8ArrayToHexString } from '../utils.js'; +import { isAddress } from './address.js'; +import { isHexStrict } from './string.js'; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + */ +export const isBloom = (bloom) => { + if (typeof bloom !== 'string') { + return false; + } + if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { + return false; + } + if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { + return true; + } + return false; +}; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + */ +export const isInBloom = (bloom, value) => { + if (typeof value === 'string' && !isHexStrict(value)) { + return false; + } + if (!isBloom(bloom)) { + return false; + } + const uint8Array = typeof value === 'string' ? hexToUint8Array(value) : value; + const hash = uint8ArrayToHexString(keccak256(uint8Array)).slice(2); + for (let i = 0; i < 12; i += 4) { + // calculate bit position in bloom filter that must be active + const bitpos = + // eslint-disable-next-line no-bitwise + ((parseInt(hash.slice(i, i + 2), 16) << 8) + parseInt(hash.slice(i + 2, i + 4), 16)) & + 2047; + // test if bitpos in bloom is active + const code = codePointToInt(bloom.charCodeAt(bloom.length - 1 - Math.floor(bitpos / 4))); + // eslint-disable-next-line no-bitwise + const offset = 1 << bitpos % 4; + // eslint-disable-next-line no-bitwise + if ((code & offset) !== offset) { + return false; + } + } + return true; +}; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + */ +export const isUserEthereumAddressInBloom = (bloom, ethereumAddress) => { + if (!isBloom(bloom)) { + return false; + } + if (!isAddress(ethereumAddress)) { + return false; + } + // you have to pad the ethereum address to 32 bytes + // else the bloom filter does not work + // this is only if your matching the USERS + // ethereum address. Contract address do not need this + // hence why we have 2 methods + // (0x is not in the 2nd parameter of padleft so 64 chars is fine) + const address = padLeft(ethereumAddress, 64); + return isInBloom(bloom, address); +}; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + */ +export const isContractAddressInBloom = (bloom, contractAddress) => { + if (!isBloom(bloom)) { + return false; + } + if (!isAddress(contractAddress)) { + return false; + } + return isInBloom(bloom, contractAddress); +}; +//# sourceMappingURL=bloom.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bloom.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bloom.js.map new file mode 100644 index 0000000..3ef44bb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bloom.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bloom.js","sourceRoot":"","sources":["../../../src/validation/bloom.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC9F,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C;;;GAGG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,KAAsB,EAAW,EAAE;IAC1D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,OAAO,KAAK,CAAC;KACb;IAED,IAAI,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AC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAEzF,sCAAsC;QACtC,MAAM,MAAM,GAAG,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;QAE/B,sCAAsC;QACtC,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,MAAM,EAAE;YAC/B,OAAO,KAAK,CAAC;SACb;KACD;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,KAAa,EAAE,eAAuB,EAAW,EAAE;IAC/F,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACpB,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,EAAE;QAChC,OAAO,KAAK,CAAC;KACb;IAED,mDAAmD;IACnD,sCAAsC;IACtC,0CAA0C;IAC1C,sDAAsD;IACtD,8BAA8B;IAC9B,kEAAkE;IAElE,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;IAE7C,OAAO,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAClC,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAa,EAAE,eAAuB,EAAW,EAAE;IAC3F,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACpB,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,EAAE;QAChC,OAAO,KAAK,CAAC;KACb;IAED,OAAO,SAAS,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;AAC1C,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/boolean.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/boolean.js new file mode 100644 index 0000000..71ca0d2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/boolean.js @@ -0,0 +1,34 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isHexStrict } from './string.js'; +export const isBoolean = (value) => { + if (!['number', 'string', 'boolean'].includes(typeof value)) { + return false; + } + if (typeof value === 'boolean') { + return true; + } + if (typeof value === 'string' && !isHexStrict(value)) { + return value === '1' || value === '0'; + } + if (typeof value === 'string' && isHexStrict(value)) { + return value === '0x1' || value === '0x0'; + } + // type === number + return value === 1 || value === 0; +}; +//# sourceMappingURL=boolean.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/boolean.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/boolean.js.map new file mode 100644 index 0000000..522b8e3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/boolean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.js","sourceRoot":"","sources":["../../../src/validation/boolean.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAsB,EAAE,EAAE;IACnD,IAAI,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC,EAAE;QAC5D,OAAO,KAAK,CAAC;KACb;IAED,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE;QAC/B,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE;QACrD,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC;KACtC;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;QACpD,OAAO,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK,CAAC;KAC1C;IAED,kBAAkB;IAClB,OAAO,KAAK,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC;AACnC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bytes.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bytes.js new file mode 100644 index 0000000..4ff5df7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bytes.js @@ -0,0 +1,62 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { hexToUint8Array, parseBaseType } from '../utils.js'; +import { isHexStrict } from './string.js'; +/** + * checks input if typeof data is valid Uint8Array input + */ +export const isUint8Array = (data) => data instanceof Uint8Array; +export const isBytes = (value, options = { + abiType: 'bytes', +}) => { + if (typeof value !== 'string' && !Array.isArray(value) && !(value instanceof Uint8Array)) { + return false; + } + // isHexStrict also accepts - prefix which can not exists in bytes + if (typeof value === 'string' && isHexStrict(value) && value.startsWith('-')) { + return false; + } + if (typeof value === 'string' && !isHexStrict(value)) { + return false; + } + let valueToCheck; + if (typeof value === 'string') { + if (value.length % 2 !== 0) { + // odd length hex + return false; + } + valueToCheck = hexToUint8Array(value); + } + else if (Array.isArray(value)) { + if (value.some(d => d < 0 || d > 255 || !Number.isInteger(d))) { + return false; + } + valueToCheck = new Uint8Array(value); + } + else { + valueToCheck = value; + } + if (options === null || options === void 0 ? void 0 : options.abiType) { + const { baseTypeSize } = parseBaseType(options.abiType); + return baseTypeSize ? valueToCheck.length === baseTypeSize : true; + } + if (options === null || options === void 0 ? void 0 : options.size) { + return valueToCheck.length === (options === null || options === void 0 ? void 0 : options.size); + } + return true; +}; +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bytes.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bytes.js.map new file mode 100644 index 0000000..a8463f8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../src/validation/bytes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAqB,EAAE,EAAE,CAAC,IAAI,YAAY,UAAU,CAAC;AAElF,MAAM,CAAC,MAAM,OAAO,GAAG,CACtB,KAA8C,EAC9C,UAAiF;IAChF,OAAO,EAAE,OAAO;CAChB,EACA,EAAE;IACH,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC,EAAE;QACzF,OAAO,KAAK,CAAC;KACb;IAED,kEAAkE;IAClE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,UAAU,CA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/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/eth.js new file mode 100644 index 0000000..d21e37a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/eth.js @@ -0,0 +1,38 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { parseBaseType } from '../utils.js'; +export const isValidEthBaseType = (type) => { + const { baseType, baseTypeSize } = parseBaseType(type); + if (!baseType) { + return false; + } + if (baseType === type) { + return true; + } + if ((baseType === 'int' || baseType === 'uint') && baseTypeSize) { + if (!(baseTypeSize <= 256 && baseTypeSize % 8 === 0)) { + return false; + } + } + if (baseType === 'bytes' && baseTypeSize) { + if (!(baseTypeSize >= 1 && baseTypeSize <= 32)) { + return false; + } + } + return true; +}; +//# sourceMappingURL=eth.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/eth.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/eth.js.map new file mode 100644 index 0000000..f08a849 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/eth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth.js","sourceRoot":"","sources":["../../../src/validation/eth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAW,EAAE;IAC3D,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IAEvD,IAAI,CAAC,QAAQ,EAAE;QACd,OAAO,KAAK,CAAC;KACb;IAED,IAAI,QAAQ,KAAK,IAAI,EAAE;QACtB,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,CAAC,QAAQ,KAAK,KAAK,IAAI,QAAQ,KAAK,MAAM,CAAC,IAAI,YAAY,EAAE;QAChE,IAAI,CAAC,CAAC,YAAY,IAAI,GAAG,IAAI,YAAY,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;YACrD,OAAO,KAAK,CAAC;SACb;KACD;IAED,IAAI,QAAQ,KAAK,OAAO,IAAI,YAAY,EAAE;QACzC,IAAI,CAAC,CAAC,YAAY,IAAI,CAAC,IAAI,YAAY,IAAI,EAAE,CAAC,EAAE;YAC/C,OAAO,KAAK,CAAC;SACb;KACD;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/filter.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/filter.js new file mode 100644 index 0000000..ae4cea7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/filter.js @@ -0,0 +1,65 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isAddress } from './address.js'; +import { isBlockNumberOrTag } from './block.js'; +import { isNullish } from './object.js'; +import { isTopic } from './topic.js'; +/** + * First we check if all properties in the provided value are expected, + * then because all Filter properties are optional, we check if the expected properties + * are defined. If defined and they're not the expected type, we immediately return false, + * otherwise we return true after all checks pass. + */ +export const isFilterObject = (value) => { + const expectedFilterProperties = [ + 'fromBlock', + 'toBlock', + 'address', + 'topics', + 'blockHash', + ]; + if (isNullish(value) || typeof value !== 'object') + return false; + if (!Object.keys(value).every(property => expectedFilterProperties.includes(property))) + return false; + if ((!isNullish(value.fromBlock) && !isBlockNumberOrTag(value.fromBlock)) || + (!isNullish(value.toBlock) && !isBlockNumberOrTag(value.toBlock))) + return false; + if (!isNullish(value.address)) { + if (Array.isArray(value.address)) { + if (!value.address.every(address => isAddress(address))) + return false; + } + else if (!isAddress(value.address)) + return false; + } + if (!isNullish(value.topics)) { + if (!value.topics.every(topic => { + if (isNullish(topic)) + return true; + if (Array.isArray(topic)) { + return topic.every(nestedTopic => isTopic(nestedTopic)); + } + if (isTopic(topic)) + return true; + return false; + })) + return false; + } + return true; +}; +//# sourceMappingURL=filter.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/filter.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/filter.js.map new file mode 100644 index 0000000..7ee8e15 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"filter.js","sourceRoot":"","sources":["../../../src/validation/filter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAa,EAAE,EAAE;IAC/C,MAAM,wBAAwB,GAAqB;QAClD,WAAW;QACX,SAAS;QACT,SAAS;QACT,QAAQ;QACR,WAAW;KACX,CAAC;IACF,IAAI,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAEhE,I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K,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/index.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/index.js new file mode 100644 index 0000000..6a2c2f9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/index.js @@ -0,0 +1,28 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from './address.js'; +export * from './block.js'; +export * from './bloom.js'; +export * from './boolean.js'; +export * from './bytes.js'; +export * from './eth.js'; +export * from './filter.js'; +export * from './numbers.js'; +export * from './string.js'; +export * from './topic.js'; +export * from './object.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/index.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/index.js.map new file mode 100644 index 0000000..725edd0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/numbers.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/numbers.js new file mode 100644 index 0000000..ab2b791 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/numbers.js @@ -0,0 +1,112 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { parseBaseType, hexToNumber } from '../utils.js'; +import { isHexStrict } from './string.js'; +/** + * Checks if a given value is a valid big int + */ +export const isBigInt = (value) => typeof value === 'bigint'; +// Note: this could be simplified using ** operator, but babel does not handle it well +// you can find more at: https://github.com/babel/babel/issues/13109 and https://github.com/web3/web3.js/issues/6187 +/** @internal */ +export const bigintPower = (base, expo) => { + let res = base; + for (let index = 1; index < expo; index += 1) { + res *= base; + } + return res; +}; +export const isUInt = (value, options = { + abiType: 'uint', +}) => { + if (!['number', 'string', 'bigint'].includes(typeof value) || + (typeof value === 'string' && value.length === 0)) { + return false; + } + let size; + if (options === null || options === void 0 ? void 0 : options.abiType) { + const { baseTypeSize } = parseBaseType(options.abiType); + if (baseTypeSize) { + size = baseTypeSize; + } + } + else if (options.bitSize) { + size = options.bitSize; + } + const maxSize = bigintPower(BigInt(2), BigInt(size !== null && size !== void 0 ? size : 256)) - BigInt(1); + try { + const valueToCheck = typeof value === 'string' && isHexStrict(value) + ? BigInt(hexToNumber(value)) + : BigInt(value); + return valueToCheck >= 0 && valueToCheck <= maxSize; + } + catch (error) { + // Some invalid number value given which can not be converted via BigInt + return false; + } +}; +export const isInt = (value, options = { + abiType: 'int', +}) => { + if (!['number', 'string', 'bigint'].includes(typeof value)) { + return false; + } + if (typeof value === 'number' && value > Number.MAX_SAFE_INTEGER) { + return false; + } + let size; + if (options === null || options === void 0 ? void 0 : options.abiType) { + const { baseTypeSize, baseType } = parseBaseType(options.abiType); + if (baseType !== 'int') { + return false; + } + if (baseTypeSize) { + size = baseTypeSize; + } + } + else if (options.bitSize) { + size = options.bitSize; + } + const maxSize = bigintPower(BigInt(2), BigInt((size !== null && size !== void 0 ? size : 256) - 1)); + const minSize = BigInt(-1) * bigintPower(BigInt(2), BigInt((size !== null && size !== void 0 ? size : 256) - 1)); + try { + const valueToCheck = typeof value === 'string' && isHexStrict(value) + ? BigInt(hexToNumber(value)) + : BigInt(value); + return valueToCheck >= minSize && valueToCheck <= maxSize; + } + catch (error) { + // Some invalid number value given which can not be converted via BigInt + return false; + } +}; +export const isNumber = (value) => { + if (isInt(value)) { + return true; + } + // It would be a decimal number + if (typeof value === 'string' && + /[0-9.]/.test(value) && + value.indexOf('.') === value.lastIndexOf('.')) { + return true; + } + if (typeof value === 'number') { + return true; + } + return false; +}; +//# sourceMappingURL=numbers.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/numbers.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/numbers.js.map new file mode 100644 index 0000000..1c390e7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/numbers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numbers.js","sourceRoot":"","sources":["../../../src/validation/numbers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAGF,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C;;GAEG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAsB,EAAW,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ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AC,CAAC,EAAE,MAAM,CAAC,CAAC,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAE/E,IAAI;QACH,MAAM,YAAY,GACjB,OAAO,KAAK,KAAK,QAAQ,IAAI,WAAW,CAAC,KAAK,CAAC;YAC9C,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YAC5B,CAAC,CAAC,MAAM,CAAC,KAAe,CAAC,CAAC;QAE5B,OAAO,YAAY,IAAI,OAAO,IAAI,YAAY,IAAI,OAAO,CAAC;KAC1D;IAAC,OAAO,KAAK,EAAE;QACf,wEAAwE;QACxE,OAAO,KAAK,CAAC;KACb;AACF,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAsB,EAAE,EAAE;IAClD,IAAI,KAAK,CAAC,KAAK,CAAC,EAAE;QACjB,OAAO,IAAI,CAAC;KACZ;IAED,+BAA+B;IAC/B,IACC,OAAO,KAAK,KAAK,QAAQ;QACzB,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;QACpB,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,EAC5C;QACD,OAAO,IAAI,CAAC;KACZ;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/object.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/object.js new file mode 100644 index 0000000..546e0d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/object.js @@ -0,0 +1,28 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { TypedArray } from 'web3-types'; +// Explicitly check for the +// eslint-disable-next-line @typescript-eslint/ban-types +export const isNullish = (item) => +// Using "null" value intentionally for validation +// eslint-disable-next-line no-null/no-null +item === undefined || item === null; +export const isObject = (item) => typeof item === 'object' && + !isNullish(item) && + !Array.isArray(item) && + !(item instanceof TypedArray); +//# sourceMappingURL=object.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/object.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/object.js.map new file mode 100644 index 0000000..bffc199 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/object.js.map @@ -0,0 +1 @@ +{"version":3,"file":"object.js","sourceRoot":"","sources":["../../../src/validation/object.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,2BAA2B;AAC3B,wDAAwD;AACxD,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,IAAa,EAA4B,EAAE;AACpE,kDAAkD;AAClD,2CAA2C;AAC3C,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,CAAC;AAErC,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAmC,EAAE,CAC1E,OAAO,IAAI,KAAK,QAAQ;IACxB,CAAC,SAAS,CAAC,IAAI,CAAC;IAChB,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;IACpB,CAAC,CAAC,IAAI,YAAY,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/string.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/string.js new file mode 100644 index 0000000..e82dfd1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/string.js @@ -0,0 +1,73 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * checks input if typeof data is valid string input + */ +export const isString = (value) => typeof value === 'string'; +export const isHexStrict = (hex) => typeof hex === 'string' && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex); +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +export function isHexString(value, length) { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) + return false; + if (typeof length !== 'undefined' && length > 0 && value.length !== 2 + 2 * length) + return false; + return true; +} +export const isHex = (hex) => typeof hex === 'number' || + typeof hex === 'bigint' || + (typeof hex === 'string' && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex)); +export const isHexString8Bytes = (value, prefixed = true) => prefixed ? isHexStrict(value) && value.length === 18 : isHex(value) && value.length === 16; +export const isHexString32Bytes = (value, prefixed = true) => prefixed ? isHexStrict(value) && value.length === 66 : isHex(value) && value.length === 64; +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +export function isHexPrefixed(str) { + if (typeof str !== 'string') { + throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`); + } + return str.startsWith('0x'); +} +/** + * Checks provided Uint8Array for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Uint8Array values + * @throws if any provided value is found to have leading zero bytes + */ +export const validateNoLeadingZeroes = function (values) { + for (const [k, v] of Object.entries(values)) { + if (v !== undefined && v.length > 0 && v[0] === 0) { + throw new Error(`${k} cannot have leading zeroes, received: ${v.toString()}`); + } + } +}; +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/string.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/string.js.map new file mode 100644 index 0000000..3018a34 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src/validation/string.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAIF;;GAEG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAsB,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;AAE9E,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAoB,EAAE,EAAE,CACnD,OAAO,GAAG,KAAK,QAAQ,IAAI,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAElE;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa,EAAE,MAAe;IACzD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAAC;QAAE,OAAO,KAAK,CAAC;IAEhF,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM;QACjF,OAAO,KAAK,CAAC;IAEd,OAAO,IAAI,CAAC;AACb,CAAC;AAED,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,GAAoB,EAAW,E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,KAAK,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;SAC9E;KACD;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/topic.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/topic.js new file mode 100644 index 0000000..7838a82 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/topic.js @@ -0,0 +1,46 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { isBloom, isInBloom } from './bloom.js'; +/** + * Checks if its a valid topic + */ +export const isTopic = (topic) => { + if (typeof topic !== 'string') { + return false; + } + if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { + return false; + } + if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { + return true; + } + return false; +}; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + */ +export const isTopicInBloom = (bloom, topic) => { + if (!isBloom(bloom)) { + return false; + } + if (!isTopic(topic)) { + return false; + } + return isInBloom(bloom, topic); +}; +//# sourceMappingURL=topic.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/topic.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/topic.js.map new file mode 100644 index 0000000..f452f06 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validation/topic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topic.js","sourceRoot":"","sources":["../../../src/validation/topic.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEhD;;GAEG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,KAAa,EAAW,EAAE;IACjD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QACxC,OAAO,KAAK,CAAC;KACb;IAED,IAAI,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QAC3E,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAa,EAAE,KAAa,EAAW,EAAE;IACvE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACpB,OAAO,KAAK,CAAC;KACb;IAED,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACpB,OAAO,KAAK,CAAC;KACb;IAED,OAAO,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAChC,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validator.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/validator.js new file mode 100644 index 0000000..969ac83 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validator.js @@ -0,0 +1,141 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { SchemaFormatError } from 'web3-errors'; +import { z, ZodIssueCode } from 'zod'; +import { Web3ValidatorError } from './errors.js'; +import formats from './formats.js'; +const convertToZod = (schema) => { + if ((!(schema === null || schema === void 0 ? void 0 : schema.type) || (schema === null || schema === void 0 ? void 0 : schema.type) === 'object') && (schema === null || schema === void 0 ? void 0 : schema.properties)) { + const obj = {}; + for (const name of Object.keys(schema.properties)) { + const zItem = convertToZod(schema.properties[name]); + if (zItem) { + obj[name] = zItem; + } + } + if (Array.isArray(schema.required)) { + return z + .object(obj) + .partial() + .required(schema.required.reduce((acc, v) => (Object.assign(Object.assign({}, acc), { [v]: true })), {})); + } + return z.object(obj).partial(); + } + if ((schema === null || schema === void 0 ? void 0 : schema.type) === 'array' && (schema === null || schema === void 0 ? void 0 : schema.items)) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + const arr = []; + for (const item of schema.items) { + const zItem = convertToZod(item); + if (zItem) { + arr.push(zItem); + } + } + return z.tuple(arr); + } + return z.array(convertToZod(schema.items)); + } + if (schema.oneOf && Array.isArray(schema.oneOf)) { + return z.union(schema.oneOf.map(oneOfSchema => convertToZod(oneOfSchema))); + } + if (schema === null || schema === void 0 ? void 0 : schema.format) { + if (!formats[schema.format]) { + throw new SchemaFormatError(schema.format); + } + return z.any().refine(formats[schema.format], (value) => ({ + params: { value, format: schema.format }, + })); + } + if ((schema === null || schema === void 0 ? void 0 : schema.type) && + (schema === null || schema === void 0 ? void 0 : schema.type) !== 'object' && + typeof z[String(schema.type)] === 'function') { + return z[String(schema.type)](); + } + return z.object({ data: z.any() }).partial(); +}; +export class Validator { + // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function + static factory() { + if (!Validator.validatorInstance) { + Validator.validatorInstance = new Validator(); + } + return Validator.validatorInstance; + } + validate(schema, data, options) { + var _a, _b; + const zod = convertToZod(schema); + const result = zod.safeParse(data); + if (!result.success) { + const errors = this.convertErrors((_b = (_a = result.error) === null || _a === void 0 ? void 0 : _a.issues) !== null && _b !== void 0 ? _b : []); + if (errors) { + if (options === null || options === void 0 ? void 0 : options.silent) { + return errors; + } + throw new Web3ValidatorError(errors); + } + } + return undefined; + } + // eslint-disable-next-line class-methods-use-this + convertErrors(errors) { + if (errors && Array.isArray(errors) && errors.length > 0) { + return errors.map((error) => { + var _a; + let message; + let keyword; + let params; + let schemaPath; + schemaPath = error.path.join('/'); + const field = String(error.path[error.path.length - 1]); + const instancePath = error.path.join('/'); + if (error.code === ZodIssueCode.too_big) { + keyword = 'maxItems'; + schemaPath = `${instancePath}/maxItems`; + params = { limit: error.maximum }; + message = `must NOT have more than ${error.maximum} items`; + } + else if (error.code === ZodIssueCode.too_small) { + keyword = 'minItems'; + schemaPath = `${instancePath}/minItems`; + params = { limit: error.minimum }; + message = `must NOT have fewer than ${error.minimum} items`; + } + else if (error.code === ZodIssueCode.custom) { + const { value, format } = ((_a = error.params) !== null && _a !== void 0 ? _a : {}); + if (typeof value === 'undefined') { + message = `value at "/${schemaPath}" is required`; + } + else { + message = `value "${ + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + typeof value === 'object' ? JSON.stringify(value) : value}" at "/${schemaPath}" must pass "${format}" validation`; + } + params = { value }; + } + return { + keyword: keyword !== null && keyword !== void 0 ? keyword : field, + instancePath: instancePath ? `/${instancePath}` : '', + schemaPath: schemaPath ? `#${schemaPath}` : '#', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params: params !== null && params !== void 0 ? params : { value: error.message }, + message: message !== null && message !== void 0 ? message : error.message, + }; + }); + } + return undefined; + } +} +//# sourceMappingURL=validator.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/validator.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/validator.js.map new file mode 100644 index 0000000..0135b42 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validator.js","source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AAM,EAAE,GAAG,CAAC,MAAA,KAAK,CAAC,MAAM,mCAAI,EAAE,CAG5C,CAAC;oBAEF,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;wBACjC,OAAO,GAAG,cAAc,UAAU,eAAe,CAAC;qBAClD;yBAAM;wBACN,OAAO,GAAG,UAAU;wBACnB,4EAA4E;wBAC5E,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KACrD,UAAU,UAAU,gBAAgB,MAAM,cAAc,CAAC;qBACzD;oBAED,MAAM,GAAG,EAAE,KAAK,EAAE,CAAC;iBACnB;gBAED,OAAO;oBACN,OAAO,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,KAAK;oBACzB,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,IAAI,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE;oBACpD,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC,CAAC,GAAG;oBAC/C,mEAAmE;oBACnE,MAAM,EAAE,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE;oBAC1C,OAAO,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,KAAK,CAAC,OAAO;iBACJ,CAAC;YAChC,CAAC,CAAC,CAAC;SACH;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/web3_validator.js b/test/merkletreejs/node_modules/web3-validator/lib/esm/web3_validator.js new file mode 100644 index 0000000..c5f28c0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/web3_validator.js @@ -0,0 +1,35 @@ +import { Validator } from './validator.js'; +import { ethAbiToJsonSchema } from './utils.js'; +import { Web3ValidatorError } from './errors.js'; +export class Web3Validator { + constructor() { + this._validator = Validator.factory(); + } + validateJSONSchema(schema, data, options) { + return this._validator.validate(schema, data, options); + } + validate(schema, data, options = { silent: false }) { + var _a, _b; + const jsonSchema = ethAbiToJsonSchema(schema); + if (Array.isArray(jsonSchema.items) && + ((_a = jsonSchema.items) === null || _a === void 0 ? void 0 : _a.length) === 0 && + data.length === 0) { + return undefined; + } + if (Array.isArray(jsonSchema.items) && + ((_b = jsonSchema.items) === null || _b === void 0 ? void 0 : _b.length) === 0 && + data.length !== 0) { + throw new Web3ValidatorError([ + { + instancePath: '/0', + schemaPath: '/', + keyword: 'required', + message: 'empty schema against data can not be validated', + params: data, + }, + ]); + } + return this._validator.validate(jsonSchema, data, options); + } +} +//# sourceMappingURL=web3_validator.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/esm/web3_validator.js.map b/test/merkletreejs/node_modules/web3-validator/lib/esm/web3_validator.js.map new file mode 100644 index 0000000..be24797 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/esm/web3_validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_validator.js","sourceRoot":"","sources":["../../src/web3_validator.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEhD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,OAAO,aAAa;IAEzB;QACC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;IACM,kBAAkB,CACxB,MAAc,EACd,IAAY,EACZ,OAA+B;QAE/B,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAY,EAAE,OAAO,CAAC,CAAC;IAChE,CAAC;IACM,QAAQ,CACd,MAA6B,EAC7B,IAA4B,EAC5B,UAAiC,EAAE,MAAM,EAAE,KAAK,EAAE;;QAElD,MAAM,UAAU,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAC9C,IACC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;YAC/B,CAAA,MAAA,UAAU,CAAC,KAAK,0CAAE,MAAM,MAAK,CAAC;YAC9B,IAAI,CAAC,MAAM,KAAK,CAAC,EAChB;YACD,OAAO,SAAS,CAAC;SACjB;QAED,IACC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;YAC/B,CAAA,MAAA,UAAU,CAAC,KAAK,0CAAE,MAAM,MAAK,CAAC;YAC9B,IAAI,CAAC,MAAM,KAAK,CAAC,EAChB;YACD,MAAM,IAAI,kBAAkB,CAAC;gBAC5B;oBACC,YAAY,EAAE,IAAI;oBAClB,UAAU,EAAE,GAAG;oBACf,OAAO,EAAE,UAAU;oBACnB,OAAO,EAAE,gDAAgD;oBACzD,MAAM,EAAE,IAAI;iBACZ;aACD,CAAC,CAAC;SACH;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,UAAU,EAAE,IAAY,EAAE,OAAO,CAAC,CAAC;IACpE,CAAC;CACD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/constants.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/constants.d.ts new file mode 100644 index 0000000..f4c9ee8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/constants.d.ts @@ -0,0 +1,2 @@ +export declare const VALID_ETH_BASE_TYPES: string[]; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/constants.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/constants.d.ts.map new file mode 100644 index 0000000..d1abb6a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,oBAAoB,UAAiE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/default_validator.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/default_validator.d.ts new file mode 100644 index 0000000..5835ec8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/default_validator.d.ts @@ -0,0 +1,3 @@ +import { Web3Validator } from './web3_validator.js'; +export declare const validator: Web3Validator; +//# sourceMappingURL=default_validator.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/default_validator.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/default_validator.d.ts.map new file mode 100644 index 0000000..37b99fc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/default_validator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default_validator.d.ts","sourceRoot":"","sources":["../../src/default_validator.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,eAAO,MAAM,SAAS,eAAsB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/errors.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/errors.d.ts new file mode 100644 index 0000000..6cfbe42 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/errors.d.ts @@ -0,0 +1,9 @@ +import { BaseWeb3Error } from 'web3-errors'; +import { Web3ValidationErrorObject } from 'web3-types'; +export declare class Web3ValidatorError extends BaseWeb3Error { + code: number; + readonly errors: Web3ValidationErrorObject[]; + constructor(errors: Web3ValidationErrorObject[]); + private _compileErrors; +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/errors.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/errors.d.ts.map new file mode 100644 index 0000000..b9ed386 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,aAAa,EAAkB,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAUvD,qBAAa,kBAAmB,SAAQ,aAAa;IAC7C,IAAI,SAAkB;IAC7B,SAAgB,MAAM,EAAE,yBAAyB,EAAE,CAAC;gBAEjC,MAAM,EAAE,yBAAyB,EAAE;IAUtD,OAAO,CAAC,cAAc;CAGtB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/formats.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/formats.d.ts new file mode 100644 index 0000000..8dc1278 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/formats.d.ts @@ -0,0 +1,5 @@ +declare const formats: { + [key: string]: (data: unknown) => boolean; +}; +export default formats; +//# sourceMappingURL=formats.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/formats.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/formats.d.ts.map new file mode 100644 index 0000000..7756bea --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/formats.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"formats.d.ts","sourceRoot":"","sources":["../../src/formats.ts"],"names":[],"mappings":"AA2BA,QAAA,MAAM,OAAO,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,CAAA;CAczD,CAAC;AAaF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/index.d.ts new file mode 100644 index 0000000..ae1d6d9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/index.d.ts @@ -0,0 +1,8 @@ +export * from './web3_validator.js'; +export * from './default_validator.js'; +export * from './types.js'; +export * as utils from './utils.js'; +export * from './errors.js'; +export * from './constants.js'; +export * from './validation/index.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/index.d.ts.map new file mode 100644 index 0000000..5e0b774 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,YAAY,CAAC;AAC3B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/types.d.ts new file mode 100644 index 0000000..629bbff --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/types.d.ts @@ -0,0 +1,106 @@ +import { AbiParameter } from 'web3-types'; +import { ZodIssueBase } from 'zod'; +export declare type ValidInputTypes = Uint8Array | bigint | string | number | boolean; +export declare type EthBaseTypes = 'bool' | 'bytes' | 'string' | 'uint' | 'int' | 'address' | 'tuple'; +export declare type EthBaseTypesWithMeta = `string${string}` | `string${string}[${number}]` | `bytes${string}` | `bytes${string}[${number}]` | `address[${number}]` | `bool[${number}]` | `int${string}` | `int${string}[${number}]` | `uint${string}` | `uint${string}[${number}]` | `tuple[]` | `tuple[${number}]`; +export declare type EthExtendedTypes = 'hex' | 'number' | 'blockNumber' | 'blockNumberOrTag' | 'filter' | 'bloom'; +export declare type FullValidationSchema = ReadonlyArray; +export declare type ShortValidationSchema = ReadonlyArray; +export declare type ValidationSchemaInput = FullValidationSchema | ShortValidationSchema; +export declare type Web3ValidationOptions = { + readonly silent: boolean; +}; +export declare type Json = string | number | boolean | Array | { + [id: string]: Json; +}; +export declare type ValidationError = ZodIssueBase; +export interface Validate { + (value: Json): boolean; + errors?: ValidationError[]; +} +export declare type Schema = { + $schema?: string; + $vocabulary?: string; + id?: string; + $id?: string; + $anchor?: string; + $ref?: string; + definitions?: { + [id: string]: Schema; + }; + $defs?: { + [id: string]: Schema; + }; + $recursiveRef?: string; + $recursiveAnchor?: boolean; + type?: string | Array; + required?: Array | boolean; + default?: Json; + enum?: Array; + const?: Json; + not?: Schema; + allOf?: Array; + anyOf?: Array; + oneOf?: Array; + if?: Schema; + then?: Schema; + else?: Schema; + maximum?: number; + minimum?: number; + exclusiveMaximum?: number | boolean; + exclusiveMinimum?: number | boolean; + multipleOf?: number; + divisibleBy?: number; + maxItems?: number; + minItems?: number; + additionalItems?: Schema; + contains?: Schema; + minContains?: number; + maxContains?: number; + uniqueItems?: boolean; + maxLength?: number; + minLength?: number; + format?: string; + pattern?: string; + contentEncoding?: string; + contentMediaType?: string; + contentSchema?: Schema; + properties?: { + [id: string]: Schema; + }; + maxProperties?: number; + minProperties?: number; + additionalProperties?: Schema; + patternProperties?: { + [pattern: string]: Schema; + }; + propertyNames?: Schema; + dependencies?: { + [id: string]: Array | Schema; + }; + dependentRequired?: { + [id: string]: Array; + }; + dependentSchemas?: { + [id: string]: Schema; + }; + unevaluatedProperties?: Schema; + unevaluatedItems?: Schema; + title?: string; + description?: string; + deprecated?: boolean; + readOnly?: boolean; + writeOnly?: boolean; + examples?: Array; + $comment?: string; + discriminator?: { + propertyName: string; + mapping?: { + [value: string]: string; + }; + }; + readonly eth?: string; + items?: Schema | Schema[]; +}; +export declare type JsonSchema = Schema; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/types.d.ts.map new file mode 100644 index 0000000..dad2556 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,KAAK,CAAC;AAEnC,oBAAY,eAAe,GAAG,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAC9E,oBAAY,YAAY,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,GAAG,SAAS,GAAG,OAAO,CAAC;AAC9F,oBAAY,oBAAoB,GAC7B,SAAS,MAAM,EAAE,GACjB,SAAS,MAAM,IAAI,MAAM,GAAG,GAC5B,QAAQ,MAAM,EAAE,GAChB,QAAQ,MAAM,IAAI,MAAM,GAAG,GAC3B,WAAW,MAAM,GAAG,GACpB,QAAQ,MAAM,GAAG,GACjB,MAAM,MAAM,EAAE,GACd,MAAM,MAAM,IAAI,MAAM,GAAG,GACzB,OAAO,MAAM,EAAE,GACf,OAAO,MAAM,IAAI,MAAM,GAAG,GAC1B,SAAS,GACT,SAAS,MAAM,GAAG,CAAC;AAEtB,oBAAY,gBAAgB,GACzB,KAAK,GACL,QAAQ,GACR,aAAa,GACb,kBAAkB,GAClB,QAAQ,GACR,OAAO,CAAC;AAEX,oBAAY,oBAAoB,GAAG,aAAa,CAAC,YAAY,CAAC,CAAC;AAC/D,oBAAY,qBAAqB,GAAG,aAAa,CAChD,MAAM,GAAG,YAAY,GAAG,gBAAgB,GAAG,oBAAoB,GAAG,qBAAqB,CACvF,CAAC;AACF,oBAAY,qBAAqB,GAAG,oBAAoB,GAAG,qBAAqB,CAAC;AAEjF,oBAAY,qBAAqB,GAAG;IACnC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,oBAAY,IAAI,GAAG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AAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAA;KAAE,CAAC;IACxD,iBAAiB,CAAC,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAA;KAAE,CAAC;IACpD,gBAAgB,CAAC,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;IAE5C,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAI1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,aAAa,CAAC,EAAE;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE;YAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IAChF,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CAC1B,CAAC;AAEF,oBAAY,UAAU,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/utils.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/utils.d.ts new file mode 100644 index 0000000..4c41b02 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/utils.d.ts @@ -0,0 +1,30 @@ +import { FullValidationSchema, ShortValidationSchema, ValidationSchemaInput, ValidInputTypes } from './types.js'; +export declare const parseBaseType: (type: string) => { + baseType?: T | undefined; + baseTypeSize: number | undefined; + arraySizes: number[]; + isArray: boolean; +}; +export declare const abiSchemaToJsonSchema: (abis: ShortValidationSchema | FullValidationSchema, level?: string) => import("./types.js").Schema; +export declare const ethAbiToJsonSchema: (abis: ValidationSchemaInput) => import("./types.js").Schema; +export declare const fetchArrayElement: (data: Array, level: number) => unknown; +export declare const transformJsonDataToAbiFormat: (abis: FullValidationSchema, data: ReadonlyArray | Record, transformedData?: Array) => Array; +/** + * Code points to int + */ +export declare const codePointToInt: (codePoint: number) => number; +/** + * Converts value to it's number representation + */ +export declare const hexToNumber: (value: string) => bigint | number; +/** + * Converts value to it's hex representation + */ +export declare const numberToHex: (value: ValidInputTypes) => string; +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + */ +export declare const padLeft: (value: ValidInputTypes, characterAmount: number, sign?: string) => string; +export declare function uint8ArrayToHexString(uint8Array: Uint8Array): string; +export declare function hexToUint8Array(hex: string): Uint8Array; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/utils.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/utils.d.ts.map new file mode 100644 index 0000000..96ae072 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAmBA,OAAO,EACN,oBAAoB,EAEpB,qBAAqB,EACrB,qBAAqB,EACrB,eAAe,EACf,MAAM,YAAY,CAAC;AAOpB,eAAO,MAAM,aAAa,qBACnB,MAAM;;kBAGE,MAAM,GAAG,SAAS;gBACpB,MAAM,EAAE;aACX,OAAO;CAqChB,CAAC;AA+CF,eAAO,MAAM,qBAAqB,SAC3B,qBAAqB,GAAG,oBAAoB,gDAiIlD,CAAC;AAEF,eAAO,MAAM,kBAAkB,SAAU,qBAAqB,gCAAgC,CAAC;AAE/F,eAAO,MAAM,iBAAiB,SAAU,MAAM,OAAO,CAAC,SAAS,MAAM,KAAG,OAMvE,CAAC;AAEF,eAAO,MAAM,4BAA4B,qCAElC,cAAc,OAAO,CAAC,GAAG,OAAO,MAAM,EAAE,OAAO,CAAC,oBACpC,MAAM,OAAO,CAAC,KAC9B,MAAM,OAAO,CAuFf,CAAC;AAEF;;GAEG;AAEH,eAAO,MAAM,cAAc,cAAe,MAAM,KAAG,MAiBlD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,UAAW,MAAM,KAAG,MAAM,GAAG,MAiBpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,UAAW,eAAe,KAAG,MAoBpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,OAAO,UAAW,eAAe,mBAAmB,MAAM,oBAAe,MAUrF,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAOpE;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAgBvD"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/abi.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/abi.d.ts new file mode 100644 index 0000000..16a7041 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/abi.d.ts @@ -0,0 +1,4 @@ +import { AbiParameter } from 'web3-types'; +import { ShortValidationSchema } from '../types'; +export declare const isAbiParameterSchema: (schema: string | ShortValidationSchema | AbiParameter) => schema is AbiParameter; +//# sourceMappingURL=abi.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/abi.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/abi.d.ts.map new file mode 100644 index 0000000..bdbd318 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/abi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abi.d.ts","sourceRoot":"","sources":["../../../src/validation/abi.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD,eAAO,MAAM,oBAAoB,WACxB,MAAM,GAAG,qBAAqB,GAAG,YAAY,2BACyC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/address.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/address.d.ts new file mode 100644 index 0000000..fe0c9de --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/address.d.ts @@ -0,0 +1,10 @@ +import { ValidInputTypes } from '../types.js'; +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + */ +export declare const checkAddressCheckSum: (data: string) => boolean; +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + */ +export declare const isAddress: (value: ValidInputTypes, checkChecksum?: boolean) => boolean; +//# sourceMappingURL=address.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/address.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/address.d.ts.map new file mode 100644 index 0000000..6ac1411 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../../src/validation/address.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAI9C;;GAEG;AACH,eAAO,MAAM,oBAAoB,SAAU,MAAM,KAAG,OAiBnD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,UAAW,eAAe,qCA4B/C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/block.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/block.d.ts new file mode 100644 index 0000000..4712612 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/block.d.ts @@ -0,0 +1,10 @@ +export declare const isBlockNumber: (value: string | number | bigint) => boolean; +/** + * Returns true if the given blockNumber is 'latest', 'pending', 'earliest, 'safe' or 'finalized' + */ +export declare const isBlockTag: (value: string) => boolean; +/** + * Returns true if given value is valid hex string and not negative, or is a valid BlockTag + */ +export declare const isBlockNumberOrTag: (value: string | number | bigint) => boolean; +//# sourceMappingURL=block.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/block.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/block.d.ts.map new file mode 100644 index 0000000..0e8dae1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/block.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"block.d.ts","sourceRoot":"","sources":["../../../src/validation/block.ts"],"names":[],"mappings":"AAoBA,eAAO,MAAM,aAAa,UAAW,MAAM,GAAG,MAAM,GAAG,MAAM,KAAG,OAAwB,CAAC;AAEzF;;GAEG;AACH,eAAO,MAAM,UAAU,UAAW,MAAM,YAA0D,CAAC;AAEnG;;GAEG;AACH,eAAO,MAAM,kBAAkB,UAAW,MAAM,GAAG,MAAM,GAAG,MAAM,YACd,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bloom.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bloom.d.ts new file mode 100644 index 0000000..6ab6866 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bloom.d.ts @@ -0,0 +1,21 @@ +import { ValidInputTypes } from '../types.js'; +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + */ +export declare const isBloom: (bloom: ValidInputTypes) => boolean; +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + */ +export declare const isInBloom: (bloom: string, value: string | Uint8Array) => boolean; +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + */ +export declare const isUserEthereumAddressInBloom: (bloom: string, ethereumAddress: string) => boolean; +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + */ +export declare const isContractAddressInBloom: (bloom: string, contractAddress: string) => boolean; +//# sourceMappingURL=bloom.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bloom.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bloom.d.ts.map new file mode 100644 index 0000000..0a3f040 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bloom.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bloom.d.ts","sourceRoot":"","sources":["../../../src/validation/bloom.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAK9C;;;GAGG;AACH,eAAO,MAAM,OAAO,UAAW,eAAe,KAAG,OAchD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,SAAS,UAAW,MAAM,SAAS,MAAM,GAAG,UAAU,KAAG,OAiCrE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,UAAW,MAAM,mBAAmB,MAAM,KAAG,OAmBrF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wBAAwB,UAAW,MAAM,mBAAmB,MAAM,KAAG,OAUjF,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/boolean.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/boolean.d.ts new file mode 100644 index 0000000..d1d3aa7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/boolean.d.ts @@ -0,0 +1,3 @@ +import { ValidInputTypes } from '../types.js'; +export declare const isBoolean: (value: ValidInputTypes) => boolean; +//# sourceMappingURL=boolean.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/boolean.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/boolean.d.ts.map new file mode 100644 index 0000000..02f4056 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/boolean.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.d.ts","sourceRoot":"","sources":["../../../src/validation/boolean.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,eAAO,MAAM,SAAS,UAAW,eAAe,YAmB/C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bytes.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bytes.d.ts new file mode 100644 index 0000000..6fb7c59 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bytes.d.ts @@ -0,0 +1,13 @@ +import { ValidInputTypes } from '../types.js'; +/** + * checks input if typeof data is valid Uint8Array input + */ +export declare const isUint8Array: (data: ValidInputTypes) => boolean; +export declare const isBytes: (value: ValidInputTypes | Uint8Array | number[], options?: { + abiType: string; + size?: never; +} | { + size: number; + abiType?: never; +}) => boolean; +//# sourceMappingURL=bytes.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bytes.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bytes.d.ts.map new file mode 100644 index 0000000..9b86038 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/bytes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.d.ts","sourceRoot":"","sources":["../../../src/validation/bytes.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAI9C;;GAEG;AACH,eAAO,MAAM,YAAY,SAAU,eAAe,YAA+B,CAAC;AAElF,eAAO,MAAM,OAAO,UACZ,eAAe,GAAG,UAAU,GAAG,MAAM,EAAE,YACrC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,YA6C9E,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/eth.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/eth.d.ts new file mode 100644 index 0000000..42bc388 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/eth.d.ts @@ -0,0 +1,2 @@ +export declare const isValidEthBaseType: (type: string) => boolean; +//# sourceMappingURL=eth.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/eth.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/eth.d.ts.map new file mode 100644 index 0000000..f274103 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/eth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth.d.ts","sourceRoot":"","sources":["../../../src/validation/eth.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,kBAAkB,SAAU,MAAM,KAAG,OAwBjD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/filter.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/filter.d.ts new file mode 100644 index 0000000..1e9074e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/filter.d.ts @@ -0,0 +1,9 @@ +import { Filter } from 'web3-types'; +/** + * First we check if all properties in the provided value are expected, + * then because all Filter properties are optional, we check if the expected properties + * are defined. If defined and they're not the expected type, we immediately return false, + * otherwise we return true after all checks pass. + */ +export declare const isFilterObject: (value: Filter) => boolean; +//# sourceMappingURL=filter.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/filter.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/filter.d.ts.map new file mode 100644 index 0000000..9862901 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/filter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"filter.d.ts","sourceRoot":"","sources":["../../../src/validation/filter.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAMpC;;;;;GAKG;AACH,eAAO,MAAM,cAAc,UAAW,MAAM,YA+C3C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/index.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/index.d.ts new file mode 100644 index 0000000..ac1a1a4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/index.d.ts @@ -0,0 +1,12 @@ +export * from './address.js'; +export * from './block.js'; +export * from './bloom.js'; +export * from './boolean.js'; +export * from './bytes.js'; +export * from './eth.js'; +export * from './filter.js'; +export * from './numbers.js'; +export * from './string.js'; +export * from './topic.js'; +export * from './object.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/index.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/index.d.ts.map new file mode 100644 index 0000000..023268d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAiBA,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/numbers.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/numbers.d.ts new file mode 100644 index 0000000..307e803 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/numbers.d.ts @@ -0,0 +1,23 @@ +import { ValidInputTypes } from '../types.js'; +/** + * Checks if a given value is a valid big int + */ +export declare const isBigInt: (value: ValidInputTypes) => boolean; +/** @internal */ +export declare const bigintPower: (base: bigint, expo: bigint) => bigint; +export declare const isUInt: (value: ValidInputTypes, options?: { + abiType: string; + bitSize?: never; +} | { + bitSize: number; + abiType?: never; +}) => boolean; +export declare const isInt: (value: ValidInputTypes, options?: { + abiType: string; + bitSize?: never; +} | { + bitSize: number; + abiType?: never; +}) => boolean; +export declare const isNumber: (value: ValidInputTypes) => boolean; +//# sourceMappingURL=numbers.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/numbers.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/numbers.d.ts.map new file mode 100644 index 0000000..9773a14 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/numbers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../../../src/validation/numbers.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAI9C;;GAEG;AACH,eAAO,MAAM,QAAQ,UAAW,eAAe,KAAG,OAAoC,CAAC;AAIvF,gBAAgB;AAChB,eAAO,MAAM,WAAW,SAAU,MAAM,QAAQ,MAAM,WAMrD,CAAC;AAEF,eAAO,MAAM,MAAM,UACX,eAAe,YACb;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,YAoCpF,CAAC;AAEF,eAAO,MAAM,KAAK,UACV,eAAe,YACb;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,YA0CpF,CAAC;AAEF,eAAO,MAAM,QAAQ,UAAW,eAAe,YAmB9C,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/object.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/object.d.ts new file mode 100644 index 0000000..d1fab54 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/object.d.ts @@ -0,0 +1,3 @@ +export declare const isNullish: (item: unknown) => item is null | undefined; +export declare const isObject: (item: unknown) => item is Record; +//# sourceMappingURL=object.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/object.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/object.d.ts.map new file mode 100644 index 0000000..a6ea72d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../../../src/validation/object.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,SAAS,SAAU,OAAO,6BAGH,CAAC;AAErC,eAAO,MAAM,QAAQ,SAAU,OAAO,oCAIR,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/string.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/string.d.ts new file mode 100644 index 0000000..c5fb29f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/string.d.ts @@ -0,0 +1,41 @@ +import { ValidInputTypes } from '../types.js'; +/** + * checks input if typeof data is valid string input + */ +export declare const isString: (value: ValidInputTypes) => boolean; +export declare const isHexStrict: (hex: ValidInputTypes) => boolean; +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +export declare function isHexString(value: string, length?: number): boolean; +export declare const isHex: (hex: ValidInputTypes) => boolean; +export declare const isHexString8Bytes: (value: string, prefixed?: boolean) => boolean; +export declare const isHexString32Bytes: (value: string, prefixed?: boolean) => boolean; +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +export declare function isHexPrefixed(str: string): boolean; +/** + * Checks provided Uint8Array for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Uint8Array values + * @throws if any provided value is found to have leading zero bytes + */ +export declare const validateNoLeadingZeroes: (values: { + [key: string]: Uint8Array | undefined; +}) => void; +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/string.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/string.d.ts.map new file mode 100644 index 0000000..8e08e3d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../../../src/validation/string.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C;;GAEG;AACH,eAAO,MAAM,QAAQ,UAAW,eAAe,YAA8B,CAAC;AAE9E,eAAO,MAAM,WAAW,QAAS,eAAe,YACiB,CAAC;AAElE;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAOnE;AAED,eAAO,MAAM,KAAK,QAAS,eAAe,KAAG,OAG2B,CAAC;AAEzE,eAAO,MAAM,iBAAiB,UAAW,MAAM,gCAC4C,CAAC;AAE5F,eAAO,MAAM,kBAAkB,UAAW,MAAM,gCAC2C,CAAC;AAE5F;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAMlD;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB;;UAQnC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/topic.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/topic.d.ts new file mode 100644 index 0000000..5c66282 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/topic.d.ts @@ -0,0 +1,10 @@ +/** + * Checks if its a valid topic + */ +export declare const isTopic: (topic: string) => boolean; +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + */ +export declare const isTopicInBloom: (bloom: string, topic: string) => boolean; +//# sourceMappingURL=topic.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validation/topic.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/topic.d.ts.map new file mode 100644 index 0000000..f9afbfc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validation/topic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"topic.d.ts","sourceRoot":"","sources":["../../../src/validation/topic.ts"],"names":[],"mappings":"AAmBA;;GAEG;AACH,eAAO,MAAM,OAAO,UAAW,MAAM,KAAG,OAcvC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,UAAW,MAAM,SAAS,MAAM,KAAG,OAU7D,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validator.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/validator.d.ts new file mode 100644 index 0000000..6a75b19 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validator.d.ts @@ -0,0 +1,11 @@ +import { Web3ValidationErrorObject } from 'web3-types'; +import { Json, JsonSchema } from './types.js'; +export declare class Validator { + private static validatorInstance?; + static factory(): Validator; + validate(schema: JsonSchema, data: Json, options?: { + silent?: boolean; + }): Web3ValidationErrorObject, unknown>[] | undefined; + private convertErrors; +} +//# sourceMappingURL=validator.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/validator.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/validator.d.ts.map new file mode 100644 index 0000000..e671c2c --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/validator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../src/validator.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAMvD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAsE9C,qBAAa,SAAS;IAErB,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAY;WAG/B,OAAO,IAAI,SAAS;IAO3B,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE;IAe9E,OAAO,CAAC,aAAa;CAoDrB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/web3_validator.d.ts b/test/merkletreejs/node_modules/web3-validator/lib/types/web3_validator.d.ts new file mode 100644 index 0000000..4f3ef8a --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/web3_validator.d.ts @@ -0,0 +1,9 @@ +import { Web3ValidationErrorObject } from 'web3-types'; +import { ValidationSchemaInput, Web3ValidationOptions } from './types.js'; +export declare class Web3Validator { + private readonly _validator; + constructor(); + validateJSONSchema(schema: object, data: object, options?: Web3ValidationOptions): Web3ValidationErrorObject[] | undefined; + validate(schema: ValidationSchemaInput, data: ReadonlyArray, options?: Web3ValidationOptions): Web3ValidationErrorObject[] | undefined; +} +//# sourceMappingURL=web3_validator.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/lib/types/web3_validator.d.ts.map b/test/merkletreejs/node_modules/web3-validator/lib/types/web3_validator.d.ts.map new file mode 100644 index 0000000..2c5ce5e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/lib/types/web3_validator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3_validator.d.ts","sourceRoot":"","sources":["../../src/web3_validator.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAIvD,OAAO,EAAQ,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAGhF,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAY;;IAIhC,kBAAkB,CACxB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,qBAAqB,GAC7B,yBAAyB,EAAE,GAAG,SAAS;IAGnC,QAAQ,CACd,MAAM,EAAE,qBAAqB,EAC7B,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,EAC5B,OAAO,GAAE,qBAAyC,GAChD,yBAAyB,EAAE,GAAG,SAAS;CA4B1C"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3-validator/package.json b/test/merkletreejs/node_modules/web3-validator/package.json new file mode 100644 index 0000000..8ea1b5f --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/package.json @@ -0,0 +1,69 @@ +{ + "name": "web3-validator", + "version": "2.0.3", + "description": "JSON-Schema compatible validator for web3", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "browser": "./dist/web3-validator.min.js", + "repository": "https://github.com/ChainSafe/web3.js", + "author": "ChainSafe Systems", + "license": "LGPL-3.0", + "engines": { + "node": ">=14", + "npm": ">=6.12.0" + }, + "files": [ + "lib/**/*", + "src/**/*", + "dist/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "build": "concurrently --kill-others-on-fail \"yarn:build:*(!check|web)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:web": "npx webpack", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests --coverage=true --coverage-reporters=text", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --passWithNoTests" + }, + "dependencies": { + "ethereum-cryptography": "^2.0.0", + "util": "^0.12.5", + "web3-errors": "^1.1.3", + "web3-types": "^1.3.0", + "zod": "^3.21.4" + }, + "devDependencies": { + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4" + }, + "gitHead": "c8799b074e7abf86b4b03a163aa9183250ad7228" +} diff --git a/test/merkletreejs/node_modules/web3-validator/src/constants.ts b/test/merkletreejs/node_modules/web3-validator/src/constants.ts new file mode 100644 index 0000000..f4fd05d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/constants.ts @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export const VALID_ETH_BASE_TYPES = ['bool', 'int', 'uint', 'bytes', 'string', 'address', 'tuple']; diff --git a/test/merkletreejs/node_modules/web3-validator/src/default_validator.ts b/test/merkletreejs/node_modules/web3-validator/src/default_validator.ts new file mode 100644 index 0000000..ef42bfb --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/default_validator.ts @@ -0,0 +1,20 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Web3Validator } from './web3_validator.js'; + +export const validator = new Web3Validator(); diff --git a/test/merkletreejs/node_modules/web3-validator/src/errors.ts b/test/merkletreejs/node_modules/web3-validator/src/errors.ts new file mode 100644 index 0000000..8faf361 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/errors.ts @@ -0,0 +1,46 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { BaseWeb3Error, ERR_VALIDATION } from 'web3-errors'; +import { Web3ValidationErrorObject } from 'web3-types'; + +const errorFormatter = (error: Web3ValidationErrorObject): string => { + if (error.message) { + return error.message; + } + + return 'unspecified error'; +}; + +export class Web3ValidatorError extends BaseWeb3Error { + public code = ERR_VALIDATION; + public readonly errors: Web3ValidationErrorObject[]; + + public constructor(errors: Web3ValidationErrorObject[]) { + super(); + + this.errors = errors; + + super.message = `Web3 validator found ${ + errors.length + } error[s]:\n${this._compileErrors().join('\n')}`; + } + + private _compileErrors(): string[] { + return this.errors.map(errorFormatter); + } +} diff --git a/test/merkletreejs/node_modules/web3-validator/src/formats.ts b/test/merkletreejs/node_modules/web3-validator/src/formats.ts new file mode 100644 index 0000000..69d6fa9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/formats.ts @@ -0,0 +1,55 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Filter } from 'web3-types'; +import { ValidInputTypes } from './types.js'; +import { isAddress } from './validation/address.js'; +import { isBlockNumber, isBlockNumberOrTag, isBlockTag } from './validation/block.js'; +import { isBloom } from './validation/bloom.js'; +import { isBoolean } from './validation/boolean.js'; +import { isBytes } from './validation/bytes.js'; +import { isFilterObject } from './validation/filter.js'; +import { isHexStrict, isString } from './validation/string.js'; +import { isNumber, isInt, isUInt } from './validation/numbers.js'; + +const formats: { [key: string]: (data: unknown) => boolean } = { + address: (data: unknown) => isAddress(data as ValidInputTypes), + bloom: (data: unknown) => isBloom(data as ValidInputTypes), + blockNumber: (data: unknown) => isBlockNumber(data as string | number | bigint), + blockTag: (data: unknown) => isBlockTag(data as string), + blockNumberOrTag: (data: unknown) => isBlockNumberOrTag(data as string | number | bigint), + bool: (data: unknown) => isBoolean(data as ValidInputTypes), + bytes: (data: unknown) => isBytes(data as ValidInputTypes | Uint8Array | number[]), + filter: (data: unknown) => isFilterObject(data as Filter), + hex: (data: unknown) => isHexStrict(data as ValidInputTypes), + uint: (data: unknown) => isUInt(data as ValidInputTypes), + int: (data: unknown) => isInt(data as ValidInputTypes), + number: (data: unknown) => isNumber(data as ValidInputTypes), + string: (data: unknown) => isString(data as ValidInputTypes), +}; +// generate formats for all numbers types +for (let bitSize = 8; bitSize <= 256; bitSize += 8) { + formats[`int${bitSize}`] = data => isInt(data as ValidInputTypes, { bitSize }); + formats[`uint${bitSize}`] = data => isUInt(data as ValidInputTypes, { bitSize }); +} +// generate bytes +for (let size = 1; size <= 32; size += 1) { + formats[`bytes${size}`] = data => + isBytes(data as ValidInputTypes | Uint8Array | number[], { size }); +} +formats.bytes256 = formats.bytes; + +export default formats; diff --git a/test/merkletreejs/node_modules/web3-validator/src/index.ts b/test/merkletreejs/node_modules/web3-validator/src/index.ts new file mode 100644 index 0000000..4b816bc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/index.ts @@ -0,0 +1,24 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './web3_validator.js'; +export * from './default_validator.js'; +export * from './types.js'; +export * as utils from './utils.js'; +export * from './errors.js'; +export * from './constants.js'; +export * from './validation/index.js'; diff --git a/test/merkletreejs/node_modules/web3-validator/src/types.ts b/test/merkletreejs/node_modules/web3-validator/src/types.ts new file mode 100644 index 0000000..1a179e8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/types.ts @@ -0,0 +1,146 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiParameter } from 'web3-types'; +import { ZodIssueBase } from 'zod'; + +export type ValidInputTypes = Uint8Array | bigint | string | number | boolean; +export type EthBaseTypes = 'bool' | 'bytes' | 'string' | 'uint' | 'int' | 'address' | 'tuple'; +export type EthBaseTypesWithMeta = + | `string${string}` + | `string${string}[${number}]` + | `bytes${string}` + | `bytes${string}[${number}]` + | `address[${number}]` + | `bool[${number}]` + | `int${string}` + | `int${string}[${number}]` + | `uint${string}` + | `uint${string}[${number}]` + | `tuple[]` + | `tuple[${number}]`; + +export type EthExtendedTypes = + | 'hex' + | 'number' + | 'blockNumber' + | 'blockNumberOrTag' + | 'filter' + | 'bloom'; + +export type FullValidationSchema = ReadonlyArray; +export type ShortValidationSchema = ReadonlyArray< + string | EthBaseTypes | EthExtendedTypes | EthBaseTypesWithMeta | ShortValidationSchema +>; +export type ValidationSchemaInput = FullValidationSchema | ShortValidationSchema; + +export type Web3ValidationOptions = { + readonly silent: boolean; +}; + +export type Json = string | number | boolean | Array | { [id: string]: Json }; + +export type ValidationError = ZodIssueBase; + +export interface Validate { + (value: Json): boolean; + errors?: ValidationError[]; +} + +export type Schema = { + // version + $schema?: string; + $vocabulary?: string; + // pointers + id?: string; + $id?: string; + $anchor?: string; + $ref?: string; + definitions?: { [id: string]: Schema }; + $defs?: { [id: string]: Schema }; + $recursiveRef?: string; + $recursiveAnchor?: boolean; + // generic + type?: string | Array; + required?: Array | boolean; + default?: Json; + // constant values + enum?: Array; + const?: Json; + // logical checks + not?: Schema; + allOf?: Array; + anyOf?: Array; + oneOf?: Array; + if?: Schema; + then?: Schema; + else?: Schema; + // numbers + maximum?: number; + minimum?: number; + exclusiveMaximum?: number | boolean; + exclusiveMinimum?: number | boolean; + multipleOf?: number; + divisibleBy?: number; + // arrays, basic + maxItems?: number; + minItems?: number; + additionalItems?: Schema; + // arrays, complex + contains?: Schema; + minContains?: number; + maxContains?: number; + uniqueItems?: boolean; + // strings + maxLength?: number; + minLength?: number; + format?: string; + pattern?: string; + // strings content + contentEncoding?: string; + contentMediaType?: string; + contentSchema?: Schema; + // objects + properties?: { [id: string]: Schema }; + maxProperties?: number; + minProperties?: number; + additionalProperties?: Schema; + patternProperties?: { [pattern: string]: Schema }; + propertyNames?: Schema; + dependencies?: { [id: string]: Array | Schema }; + dependentRequired?: { [id: string]: Array }; + dependentSchemas?: { [id: string]: Schema }; + // see-through + unevaluatedProperties?: Schema; + unevaluatedItems?: Schema; + // Unused meta keywords not affecting validation (annotations and comments) + // https://json-schema.org/understanding-json-schema/reference/generic.html + // https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9 + title?: string; + description?: string; + deprecated?: boolean; + readOnly?: boolean; + writeOnly?: boolean; + examples?: Array; + $comment?: string; + // optimization hint and error filtering only, does not affect validation result + discriminator?: { propertyName: string; mapping?: { [value: string]: string } }; + readonly eth?: string; + items?: Schema | Schema[]; +}; + +export type JsonSchema = Schema; diff --git a/test/merkletreejs/node_modules/web3-validator/src/utils.ts b/test/merkletreejs/node_modules/web3-validator/src/utils.ts new file mode 100644 index 0000000..28270c9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/utils.ts @@ -0,0 +1,468 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { InvalidBytesError, InvalidNumberError } from 'web3-errors'; +import { VALID_ETH_BASE_TYPES } from './constants.js'; +import { + FullValidationSchema, + JsonSchema, + ShortValidationSchema, + ValidationSchemaInput, + ValidInputTypes, +} from './types.js'; +import { isAbiParameterSchema } from './validation/abi.js'; +import { isHexStrict } from './validation/string.js'; +import { Web3ValidatorError } from './errors.js'; + +const extraTypes = ['hex', 'number', 'blockNumber', 'blockNumberOrTag', 'filter', 'bloom']; + +export const parseBaseType = ( + type: string, +): { + baseType?: T; + baseTypeSize: number | undefined; + arraySizes: number[]; + isArray: boolean; +} => { + // Remove all empty spaces to avoid any parsing issue. + let strippedType = type.replace(/ /, ''); + let baseTypeSize: number | undefined; + let isArray = false; + let arraySizes: number[] = []; + + if (type.includes('[')) { + // Extract the array type + strippedType = strippedType.slice(0, strippedType.indexOf('[')); + // Extract array indexes + arraySizes = [...type.matchAll(/(?:\[(\d*)\])/g)] + .map(match => parseInt(match[1], 10)) + .map(size => (Number.isNaN(size) ? -1 : size)); + + isArray = arraySizes.length > 0; + } + + if (VALID_ETH_BASE_TYPES.includes(strippedType)) { + return { baseType: strippedType as unknown as T, isArray, baseTypeSize, arraySizes }; + } + + if (strippedType.startsWith('int')) { + baseTypeSize = parseInt(strippedType.substring(3), 10); + strippedType = 'int'; + } else if (strippedType.startsWith('uint')) { + baseTypeSize = parseInt(type.substring(4), 10); + strippedType = 'uint'; + } else if (strippedType.startsWith('bytes')) { + baseTypeSize = parseInt(strippedType.substring(5), 10); + strippedType = 'bytes'; + } else { + return { baseType: undefined, isArray: false, baseTypeSize: undefined, arraySizes }; + } + + return { baseType: strippedType as unknown as T, isArray, baseTypeSize, arraySizes }; +}; + +const convertEthType = ( + type: string, + parentSchema: JsonSchema = {}, +): { format?: string; required?: boolean } => { + const typePropertyPresent = Object.keys(parentSchema).includes('type'); + + if (typePropertyPresent) { + throw new Web3ValidatorError([ + { + keyword: 'eth', + message: 'Either "eth" or "type" can be presented in schema', + params: { eth: type }, + instancePath: '', + schemaPath: '', + }, + ]); + } + + const { baseType, baseTypeSize } = parseBaseType(type); + + if (!baseType && !extraTypes.includes(type)) { + throw new Web3ValidatorError([ + { + keyword: 'eth', + message: `Eth data type "${type}" is not valid`, + params: { eth: type }, + instancePath: '', + schemaPath: '', + }, + ]); + } + + if (baseType) { + if (baseType === 'tuple') { + throw new Error('"tuple" type is not implemented directly.'); + } + return { format: `${baseType}${baseTypeSize ?? ''}`, required: true }; + } + if (type) { + return { format: type, required: true }; + } + + return {}; +}; + +export const abiSchemaToJsonSchema = ( + abis: ShortValidationSchema | FullValidationSchema, + level = '/0', +) => { + const schema: JsonSchema = { + type: 'array', + items: [], + maxItems: abis.length, + minItems: abis.length, + }; + + for (const [index, abi] of abis.entries()) { + // eslint-disable-next-line no-nested-ternary + let abiType!: string; + let abiName!: string; + let abiComponents: ShortValidationSchema | FullValidationSchema | undefined = []; + + // If it's a complete Abi Parameter + // e.g. {name: 'a', type: 'uint'} + if (isAbiParameterSchema(abi)) { + abiType = abi.type; + abiName = abi.name; + abiComponents = abi.components as FullValidationSchema; + // If its short form string value e.g. ['uint'] + } else if (typeof abi === 'string') { + abiType = abi; + abiName = `${level}/${index}`; + + // If it's provided in short form of tuple e.g. [['uint', 'string']] + } else if (Array.isArray(abi)) { + // If its custom tuple e.g. ['tuple[2]', ['uint', 'string']] + if ( + abi[0] && + typeof abi[0] === 'string' && + abi[0].startsWith('tuple') && + !Array.isArray(abi[0]) && + abi[1] && + Array.isArray(abi[1]) + ) { + // eslint-disable-next-line prefer-destructuring + abiType = abi[0]; + abiName = `${level}/${index}`; + abiComponents = abi[1] as ReadonlyArray; + } else { + abiType = 'tuple'; + abiName = `${level}/${index}`; + abiComponents = abi; + } + } + + const { baseType, isArray, arraySizes } = parseBaseType(abiType); + + let childSchema: JsonSchema; + let lastSchema = schema; + for (let i = arraySizes.length - 1; i > 0; i -= 1) { + childSchema = { + type: 'array', + items: [], + maxItems: arraySizes[i], + minItems: arraySizes[i], + }; + + if (arraySizes[i] < 0) { + delete childSchema.maxItems; + delete childSchema.minItems; + } + + // lastSchema.items is a Schema, concat with 'childSchema' + if (!Array.isArray(lastSchema.items)) { + lastSchema.items = [lastSchema.items as JsonSchema, childSchema]; + } // lastSchema.items is an empty Scheme array, set it to 'childSchema' + else if (lastSchema.items.length === 0) { + lastSchema.items = childSchema; + } // lastSchema.items is a non-empty Scheme array, append 'childSchema' + else { + lastSchema.items.push(childSchema); + } + lastSchema = childSchema; + } + + if (baseType === 'tuple' && !isArray) { + const nestedTuple = abiSchemaToJsonSchema(abiComponents, abiName); + nestedTuple.$id = abiName; + (lastSchema.items as JsonSchema[]).push(nestedTuple); + } else if (baseType === 'tuple' && isArray) { + const arraySize = arraySizes[0]; + const item: JsonSchema = { + $id: abiName, + type: 'array', + items: abiSchemaToJsonSchema(abiComponents, abiName), + maxItems: arraySize, + minItems: arraySize, + }; + + if (arraySize < 0) { + delete item.maxItems; + delete item.minItems; + } + + (lastSchema.items as JsonSchema[]).push(item); + } else if (isArray) { + const arraySize = arraySizes[0]; + const item: JsonSchema = { + type: 'array', + $id: abiName, + items: convertEthType(String(baseType)), + minItems: arraySize, + maxItems: arraySize, + }; + + if (arraySize < 0) { + delete item.maxItems; + delete item.minItems; + } + + (lastSchema.items as JsonSchema[]).push(item); + } else if (Array.isArray(lastSchema.items)) { + // Array of non-tuple items + lastSchema.items.push({ $id: abiName, ...convertEthType(abiType) }); + } else { + // Nested object + ((lastSchema.items as JsonSchema).items as JsonSchema[]).push({ + $id: abiName, + ...convertEthType(abiType), + }); + } + lastSchema = schema; + } + + return schema; +}; + +export const ethAbiToJsonSchema = (abis: ValidationSchemaInput) => abiSchemaToJsonSchema(abis); + +export const fetchArrayElement = (data: Array, level: number): unknown => { + if (level === 1) { + return data; + } + + return fetchArrayElement(data[0] as Array, level - 1); +}; + +export const transformJsonDataToAbiFormat = ( + abis: FullValidationSchema, + data: ReadonlyArray | Record, + transformedData?: Array, +): Array => { + const newData: Array = []; + + for (const [index, abi] of abis.entries()) { + // eslint-disable-next-line no-nested-ternary + let abiType!: string; + let abiName!: string; + let abiComponents: ShortValidationSchema | FullValidationSchema | undefined = []; + + // If it's a complete Abi Parameter + // e.g. {name: 'a', type: 'uint'} + if (isAbiParameterSchema(abi)) { + abiType = abi.type; + abiName = abi.name; + abiComponents = abi.components as FullValidationSchema; + // If its short form string value e.g. ['uint'] + } else if (typeof abi === 'string') { + abiType = abi; + + // If it's provided in short form of tuple e.g. [['uint', 'string']] + } else if (Array.isArray(abi)) { + // If its custom tuple e.g. ['tuple[2]', ['uint', 'string']] + if (abi[1] && Array.isArray(abi[1])) { + abiType = abi[0] as string; + abiComponents = abi[1] as ReadonlyArray; + } else { + abiType = 'tuple'; + abiComponents = abi; + } + } + + const { baseType, isArray, arraySizes } = parseBaseType(abiType); + const dataItem = Array.isArray(data) + ? (data as Array)[index] + : (data as Record)[abiName]; + + if (baseType === 'tuple' && !isArray) { + newData.push( + transformJsonDataToAbiFormat( + abiComponents as FullValidationSchema, + dataItem as Array, + transformedData, + ), + ); + } else if (baseType === 'tuple' && isArray) { + const tupleData = []; + for (const tupleItem of dataItem as Array) { + // Nested array + if (arraySizes.length > 1) { + const nestedItems = fetchArrayElement( + tupleItem as Array, + arraySizes.length - 1, + ); + const nestedData = []; + + for (const nestedItem of nestedItems as Array) { + nestedData.push( + transformJsonDataToAbiFormat( + abiComponents as FullValidationSchema, + nestedItem as Array, + transformedData, + ), + ); + } + tupleData.push(nestedData); + } else { + tupleData.push( + transformJsonDataToAbiFormat( + abiComponents as FullValidationSchema, + tupleItem as Array, + transformedData, + ), + ); + } + } + newData.push(tupleData); + } else { + newData.push(dataItem); + } + } + + // Have to reassign before pushing to transformedData + // eslint-disable-next-line no-param-reassign + transformedData = transformedData ?? []; + transformedData.push(...newData); + + return transformedData; +}; + +/** + * Code points to int + */ + +export const codePointToInt = (codePoint: number): number => { + if (codePoint >= 48 && codePoint <= 57) { + /* ['0'..'9'] -> [0..9] */ + return codePoint - 48; + } + + if (codePoint >= 65 && codePoint <= 70) { + /* ['A'..'F'] -> [10..15] */ + return codePoint - 55; + } + + if (codePoint >= 97 && codePoint <= 102) { + /* ['a'..'f'] -> [10..15] */ + return codePoint - 87; + } + + throw new Error(`Invalid code point: ${codePoint}`); +}; + +/** + * Converts value to it's number representation + */ +export const hexToNumber = (value: string): bigint | number => { + if (!isHexStrict(value)) { + throw new Error('Invalid hex string'); + } + + const [negative, hexValue] = value.startsWith('-') ? [true, value.slice(1)] : [false, value]; + const num = BigInt(hexValue); + + if (num > Number.MAX_SAFE_INTEGER) { + return negative ? -num : num; + } + + if (num < Number.MIN_SAFE_INTEGER) { + return num; + } + + return negative ? -1 * Number(num) : Number(num); +}; + +/** + * Converts value to it's hex representation + */ +export const numberToHex = (value: ValidInputTypes): string => { + if ((typeof value === 'number' || typeof value === 'bigint') && value < 0) { + return `-0x${value.toString(16).slice(1)}`; + } + + if ((typeof value === 'number' || typeof value === 'bigint') && value >= 0) { + return `0x${value.toString(16)}`; + } + + if (typeof value === 'string' && isHexStrict(value)) { + const [negative, hex] = value.startsWith('-') ? [true, value.slice(1)] : [false, value]; + const hexValue = hex.split(/^(-)?0(x|X)/).slice(-1)[0]; + return `${negative ? '-' : ''}0x${hexValue.replace(/^0+/, '').toLowerCase()}`; + } + + if (typeof value === 'string' && !isHexStrict(value)) { + return numberToHex(BigInt(value)); + } + + throw new InvalidNumberError(value); +}; + +/** + * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. + */ +export const padLeft = (value: ValidInputTypes, characterAmount: number, sign = '0'): string => { + if (typeof value === 'string' && !isHexStrict(value)) { + return value.padStart(characterAmount, sign); + } + + const hex = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value); + + const [prefix, hexValue] = hex.startsWith('-') ? ['-0x', hex.slice(3)] : ['0x', hex.slice(2)]; + + return `${prefix}${hexValue.padStart(characterAmount, sign)}`; +}; + +export function uint8ArrayToHexString(uint8Array: Uint8Array): string { + let hexString = '0x'; + for (const e of uint8Array) { + const hex = e.toString(16); + hexString += hex.length === 1 ? `0${hex}` : hex; + } + return hexString; +} + +export function hexToUint8Array(hex: string): Uint8Array { + let value; + if (hex.toLowerCase().startsWith('0x')) { + value = hex.slice(2); + } else { + value = hex; + } + if (value.length % 2 !== 0) { + throw new InvalidBytesError(`hex string has odd length: ${hex}`); + } + const bytes = new Uint8Array(Math.ceil(value.length / 2)); + for (let i = 0; i < bytes.length; i += 1) { + const byte = parseInt(value.substring(i * 2, i * 2 + 2), 16); + bytes[i] = byte; + } + return bytes; +} diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/abi.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/abi.ts new file mode 100644 index 0000000..52e835d --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/abi.ts @@ -0,0 +1,24 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { AbiParameter } from 'web3-types'; +// eslint-disable-next-line require-extensions/require-extensions +import { ShortValidationSchema } from '../types'; + +export const isAbiParameterSchema = ( + schema: string | ShortValidationSchema | AbiParameter, +): schema is AbiParameter => typeof schema === 'object' && 'type' in schema && 'name' in schema; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/address.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/address.ts new file mode 100644 index 0000000..f1c5b82 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/address.ts @@ -0,0 +1,77 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { utf8ToBytes } from 'ethereum-cryptography/utils.js'; +import { ValidInputTypes } from '../types.js'; +import { uint8ArrayToHexString } from '../utils.js'; +import { isHexStrict } from './string.js'; + +/** + * Checks the checksum of a given address. Will also return false on non-checksum addresses. + */ +export const checkAddressCheckSum = (data: string): boolean => { + if (!/^(0x)?[0-9a-f]{40}$/i.test(data)) return false; + const address = data.slice(2); + const updatedData = utf8ToBytes(address.toLowerCase()); + + const addressHash = uint8ArrayToHexString(keccak256(updatedData)).slice(2); + + for (let i = 0; i < 40; i += 1) { + // the nth letter should be uppercase if the nth digit of casemap is 1 + if ( + (parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || + (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i]) + ) { + return false; + } + } + return true; +}; + +/** + * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters. + */ +export const isAddress = (value: ValidInputTypes, checkChecksum = true) => { + if (typeof value !== 'string' && !(value instanceof Uint8Array)) { + return false; + } + + let valueToCheck: string; + + if (value instanceof Uint8Array) { + valueToCheck = uint8ArrayToHexString(value); + } else if (typeof value === 'string' && !isHexStrict(value)) { + valueToCheck = value.toLowerCase().startsWith('0x') ? value : `0x${value}`; + } else { + valueToCheck = value; + } + + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(valueToCheck)) { + return false; + } + // If it's ALL lowercase or ALL upppercase + if ( + /^(0x|0X)?[0-9a-f]{40}$/.test(valueToCheck) || + /^(0x|0X)?[0-9A-F]{40}$/.test(valueToCheck) + ) { + return true; + // Otherwise check each case + } + return checkChecksum ? checkAddressCheckSum(valueToCheck) : true; +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/block.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/block.ts new file mode 100644 index 0000000..695ac3e --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/block.ts @@ -0,0 +1,32 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { BlockTags } from 'web3-types'; +import { isUInt } from './numbers.js'; + +export const isBlockNumber = (value: string | number | bigint): boolean => isUInt(value); + +/** + * Returns true if the given blockNumber is 'latest', 'pending', 'earliest, 'safe' or 'finalized' + */ +export const isBlockTag = (value: string) => Object.values(BlockTags).includes(value as BlockTags); + +/** + * Returns true if given value is valid hex string and not negative, or is a valid BlockTag + */ +export const isBlockNumberOrTag = (value: string | number | bigint) => + isBlockTag(value as string) || isBlockNumber(value); diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/bloom.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/bloom.ts new file mode 100644 index 0000000..e9cde96 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/bloom.ts @@ -0,0 +1,121 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { keccak256 } from 'ethereum-cryptography/keccak.js'; +import { ValidInputTypes } from '../types.js'; +import { codePointToInt, hexToUint8Array, padLeft, uint8ArrayToHexString } from '../utils.js'; +import { isAddress } from './address.js'; +import { isHexStrict } from './string.js'; + +/** + * Returns true if the bloom is a valid bloom + * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7 + */ +export const isBloom = (bloom: ValidInputTypes): boolean => { + if (typeof bloom !== 'string') { + return false; + } + + if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { + return false; + } + + if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { + return true; + } + + return false; +}; + +/** + * Returns true if the value is part of the given bloom + * note: false positives are possible. + */ +export const isInBloom = (bloom: string, value: string | Uint8Array): boolean => { + if (typeof value === 'string' && !isHexStrict(value)) { + return false; + } + + if (!isBloom(bloom)) { + return false; + } + + const uint8Array = typeof value === 'string' ? hexToUint8Array(value) : value; + + const hash = uint8ArrayToHexString(keccak256(uint8Array)).slice(2); + + for (let i = 0; i < 12; i += 4) { + // calculate bit position in bloom filter that must be active + const bitpos = + // eslint-disable-next-line no-bitwise + ((parseInt(hash.slice(i, i + 2), 16) << 8) + parseInt(hash.slice(i + 2, i + 4), 16)) & + 2047; + + // test if bitpos in bloom is active + const code = codePointToInt(bloom.charCodeAt(bloom.length - 1 - Math.floor(bitpos / 4))); + + // eslint-disable-next-line no-bitwise + const offset = 1 << bitpos % 4; + + // eslint-disable-next-line no-bitwise + if ((code & offset) !== offset) { + return false; + } + } + + return true; +}; + +/** + * Returns true if the ethereum users address is part of the given bloom note: false positives are possible. + */ +export const isUserEthereumAddressInBloom = (bloom: string, ethereumAddress: string): boolean => { + if (!isBloom(bloom)) { + return false; + } + + if (!isAddress(ethereumAddress)) { + return false; + } + + // you have to pad the ethereum address to 32 bytes + // else the bloom filter does not work + // this is only if your matching the USERS + // ethereum address. Contract address do not need this + // hence why we have 2 methods + // (0x is not in the 2nd parameter of padleft so 64 chars is fine) + + const address = padLeft(ethereumAddress, 64); + + return isInBloom(bloom, address); +}; + +/** + * Returns true if the contract address is part of the given bloom. + * note: false positives are possible. + */ +export const isContractAddressInBloom = (bloom: string, contractAddress: string): boolean => { + if (!isBloom(bloom)) { + return false; + } + + if (!isAddress(contractAddress)) { + return false; + } + + return isInBloom(bloom, contractAddress); +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/boolean.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/boolean.ts new file mode 100644 index 0000000..17593c8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/boolean.ts @@ -0,0 +1,40 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ValidInputTypes } from '../types.js'; +import { isHexStrict } from './string.js'; + +export const isBoolean = (value: ValidInputTypes) => { + if (!['number', 'string', 'boolean'].includes(typeof value)) { + return false; + } + + if (typeof value === 'boolean') { + return true; + } + + if (typeof value === 'string' && !isHexStrict(value)) { + return value === '1' || value === '0'; + } + + if (typeof value === 'string' && isHexStrict(value)) { + return value === '0x1' || value === '0x0'; + } + + // type === number + return value === 1 || value === 0; +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/bytes.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/bytes.ts new file mode 100644 index 0000000..ef15fbc --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/bytes.ts @@ -0,0 +1,74 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ValidInputTypes } from '../types.js'; +import { hexToUint8Array, parseBaseType } from '../utils.js'; +import { isHexStrict } from './string.js'; + +/** + * checks input if typeof data is valid Uint8Array input + */ +export const isUint8Array = (data: ValidInputTypes) => data instanceof Uint8Array; + +export const isBytes = ( + value: ValidInputTypes | Uint8Array | number[], + options: { abiType: string; size?: never } | { size: number; abiType?: never } = { + abiType: 'bytes', + }, +) => { + if (typeof value !== 'string' && !Array.isArray(value) && !(value instanceof Uint8Array)) { + return false; + } + + // isHexStrict also accepts - prefix which can not exists in bytes + if (typeof value === 'string' && isHexStrict(value) && value.startsWith('-')) { + return false; + } + + if (typeof value === 'string' && !isHexStrict(value)) { + return false; + } + + let valueToCheck: Uint8Array; + + if (typeof value === 'string') { + if (value.length % 2 !== 0) { + // odd length hex + return false; + } + valueToCheck = hexToUint8Array(value); + } else if (Array.isArray(value)) { + if (value.some(d => d < 0 || d > 255 || !Number.isInteger(d))) { + return false; + } + valueToCheck = new Uint8Array(value); + } else { + valueToCheck = value; + } + + if (options?.abiType) { + const { baseTypeSize } = parseBaseType(options.abiType); + + return baseTypeSize ? valueToCheck.length === baseTypeSize : true; + } + + if (options?.size) { + return valueToCheck.length === options?.size; + } + + return true; +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/eth.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/eth.ts new file mode 100644 index 0000000..774bba1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/eth.ts @@ -0,0 +1,44 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { parseBaseType } from '../utils.js'; + +export const isValidEthBaseType = (type: string): boolean => { + const { baseType, baseTypeSize } = parseBaseType(type); + + if (!baseType) { + return false; + } + + if (baseType === type) { + return true; + } + + if ((baseType === 'int' || baseType === 'uint') && baseTypeSize) { + if (!(baseTypeSize <= 256 && baseTypeSize % 8 === 0)) { + return false; + } + } + + if (baseType === 'bytes' && baseTypeSize) { + if (!(baseTypeSize >= 1 && baseTypeSize <= 32)) { + return false; + } + } + + return true; +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/filter.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/filter.ts new file mode 100644 index 0000000..2f13f08 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/filter.ts @@ -0,0 +1,77 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Filter } from 'web3-types'; +import { isAddress } from './address.js'; +import { isBlockNumberOrTag } from './block.js'; +import { isNullish } from './object.js'; +import { isTopic } from './topic.js'; + +/** + * First we check if all properties in the provided value are expected, + * then because all Filter properties are optional, we check if the expected properties + * are defined. If defined and they're not the expected type, we immediately return false, + * otherwise we return true after all checks pass. + */ +export const isFilterObject = (value: Filter) => { + const expectedFilterProperties: (keyof Filter)[] = [ + 'fromBlock', + 'toBlock', + 'address', + 'topics', + 'blockHash', + ]; + if (isNullish(value) || typeof value !== 'object') return false; + + if ( + !Object.keys(value).every(property => + expectedFilterProperties.includes(property as keyof Filter), + ) + ) + return false; + + if ( + (!isNullish(value.fromBlock) && !isBlockNumberOrTag(value.fromBlock)) || + (!isNullish(value.toBlock) && !isBlockNumberOrTag(value.toBlock)) + ) + return false; + + if (!isNullish(value.address)) { + if (Array.isArray(value.address)) { + if (!value.address.every(address => isAddress(address))) return false; + } else if (!isAddress(value.address)) return false; + } + + if (!isNullish(value.topics)) { + if ( + !value.topics.every(topic => { + if (isNullish(topic)) return true; + + if (Array.isArray(topic)) { + return topic.every(nestedTopic => isTopic(nestedTopic)); + } + + if (isTopic(topic)) return true; + + return false; + }) + ) + return false; + } + + return true; +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/index.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/index.ts new file mode 100644 index 0000000..1791289 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/index.ts @@ -0,0 +1,28 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from './address.js'; +export * from './block.js'; +export * from './bloom.js'; +export * from './boolean.js'; +export * from './bytes.js'; +export * from './eth.js'; +export * from './filter.js'; +export * from './numbers.js'; +export * from './string.js'; +export * from './topic.js'; +export * from './object.js'; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/numbers.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/numbers.ts new file mode 100644 index 0000000..276fb84 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/numbers.ts @@ -0,0 +1,143 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ValidInputTypes } from '../types.js'; +import { parseBaseType, hexToNumber } from '../utils.js'; +import { isHexStrict } from './string.js'; + +/** + * Checks if a given value is a valid big int + */ +export const isBigInt = (value: ValidInputTypes): boolean => typeof value === 'bigint'; + +// Note: this could be simplified using ** operator, but babel does not handle it well +// you can find more at: https://github.com/babel/babel/issues/13109 and https://github.com/web3/web3.js/issues/6187 +/** @internal */ +export const bigintPower = (base: bigint, expo: bigint) => { + let res = base; + for (let index = 1; index < expo; index += 1) { + res *= base; + } + return res; +}; + +export const isUInt = ( + value: ValidInputTypes, + options: { abiType: string; bitSize?: never } | { bitSize: number; abiType?: never } = { + abiType: 'uint', + }, +) => { + if ( + !['number', 'string', 'bigint'].includes(typeof value) || + (typeof value === 'string' && value.length === 0) + ) { + return false; + } + + let size!: number; + + if (options?.abiType) { + const { baseTypeSize } = parseBaseType(options.abiType); + + if (baseTypeSize) { + size = baseTypeSize; + } + } else if (options.bitSize) { + size = options.bitSize; + } + + const maxSize = bigintPower(BigInt(2), BigInt(size ?? 256)) - BigInt(1); + + try { + const valueToCheck = + typeof value === 'string' && isHexStrict(value) + ? BigInt(hexToNumber(value)) + : BigInt(value as number); + + return valueToCheck >= 0 && valueToCheck <= maxSize; + } catch (error) { + // Some invalid number value given which can not be converted via BigInt + return false; + } +}; + +export const isInt = ( + value: ValidInputTypes, + options: { abiType: string; bitSize?: never } | { bitSize: number; abiType?: never } = { + abiType: 'int', + }, +) => { + if (!['number', 'string', 'bigint'].includes(typeof value)) { + return false; + } + + if (typeof value === 'number' && value > Number.MAX_SAFE_INTEGER) { + return false; + } + + let size!: number; + + if (options?.abiType) { + const { baseTypeSize, baseType } = parseBaseType(options.abiType); + + if (baseType !== 'int') { + return false; + } + + if (baseTypeSize) { + size = baseTypeSize; + } + } else if (options.bitSize) { + size = options.bitSize; + } + + const maxSize = bigintPower(BigInt(2), BigInt((size ?? 256) - 1)); + const minSize = BigInt(-1) * bigintPower(BigInt(2), BigInt((size ?? 256) - 1)); + + try { + const valueToCheck = + typeof value === 'string' && isHexStrict(value) + ? BigInt(hexToNumber(value)) + : BigInt(value as number); + + return valueToCheck >= minSize && valueToCheck <= maxSize; + } catch (error) { + // Some invalid number value given which can not be converted via BigInt + return false; + } +}; + +export const isNumber = (value: ValidInputTypes) => { + if (isInt(value)) { + return true; + } + + // It would be a decimal number + if ( + typeof value === 'string' && + /[0-9.]/.test(value) && + value.indexOf('.') === value.lastIndexOf('.') + ) { + return true; + } + + if (typeof value === 'number') { + return true; + } + + return false; +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/object.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/object.ts new file mode 100644 index 0000000..1d1aba0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/object.ts @@ -0,0 +1,31 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { TypedArray } from 'web3-types'; + +// Explicitly check for the +// eslint-disable-next-line @typescript-eslint/ban-types +export const isNullish = (item: unknown): item is undefined | null => + // Using "null" value intentionally for validation + // eslint-disable-next-line no-null/no-null + item === undefined || item === null; + +export const isObject = (item: unknown): item is Record => + typeof item === 'object' && + !isNullish(item) && + !Array.isArray(item) && + !(item instanceof TypedArray); diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/string.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/string.ts new file mode 100644 index 0000000..d586af7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/string.ts @@ -0,0 +1,90 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { ValidInputTypes } from '../types.js'; + +/** + * checks input if typeof data is valid string input + */ +export const isString = (value: ValidInputTypes) => typeof value === 'string'; + +export const isHexStrict = (hex: ValidInputTypes) => + typeof hex === 'string' && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex); + +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +export function isHexString(value: string, length?: number): boolean { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) return false; + + if (typeof length !== 'undefined' && length > 0 && value.length !== 2 + 2 * length) + return false; + + return true; +} + +export const isHex = (hex: ValidInputTypes): boolean => + typeof hex === 'number' || + typeof hex === 'bigint' || + (typeof hex === 'string' && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex)); + +export const isHexString8Bytes = (value: string, prefixed = true) => + prefixed ? isHexStrict(value) && value.length === 18 : isHex(value) && value.length === 16; + +export const isHexString32Bytes = (value: string, prefixed = true) => + prefixed ? isHexStrict(value) && value.length === 66 : isHex(value) && value.length === 64; + +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +export function isHexPrefixed(str: string): boolean { + if (typeof str !== 'string') { + throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`); + } + + return str.startsWith('0x'); +} + +/** + * Checks provided Uint8Array for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Uint8Array values + * @throws if any provided value is found to have leading zero bytes + */ +export const validateNoLeadingZeroes = function (values: { + [key: string]: Uint8Array | undefined; +}) { + for (const [k, v] of Object.entries(values)) { + if (v !== undefined && v.length > 0 && v[0] === 0) { + throw new Error(`${k} cannot have leading zeroes, received: ${v.toString()}`); + } + } +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validation/topic.ts b/test/merkletreejs/node_modules/web3-validator/src/validation/topic.ts new file mode 100644 index 0000000..4f5ed44 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validation/topic.ts @@ -0,0 +1,53 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { isBloom, isInBloom } from './bloom.js'; + +/** + * Checks if its a valid topic + */ +export const isTopic = (topic: string): boolean => { + if (typeof topic !== 'string') { + return false; + } + + if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { + return false; + } + + if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { + return true; + } + + return false; +}; + +/** + * Returns true if the topic is part of the given bloom. + * note: false positives are possible. + */ +export const isTopicInBloom = (bloom: string, topic: string): boolean => { + if (!isBloom(bloom)) { + return false; + } + + if (!isTopic(topic)) { + return false; + } + + return isInBloom(bloom, topic); +}; diff --git a/test/merkletreejs/node_modules/web3-validator/src/validator.ts b/test/merkletreejs/node_modules/web3-validator/src/validator.ts new file mode 100644 index 0000000..d477a06 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/validator.ts @@ -0,0 +1,173 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { SchemaFormatError } from 'web3-errors'; +import { Web3ValidationErrorObject } from 'web3-types'; + +import { z, ZodType, ZodIssue, ZodIssueCode, ZodTypeAny } from 'zod'; + +import { RawCreateParams } from 'zod/lib/types'; +import { Web3ValidatorError } from './errors.js'; +import { Json, JsonSchema } from './types.js'; +import formats from './formats.js'; + +const convertToZod = (schema: JsonSchema): ZodType => { + if ((!schema?.type || schema?.type === 'object') && schema?.properties) { + const obj: { [key: string]: ZodType } = {}; + for (const name of Object.keys(schema.properties)) { + const zItem = convertToZod(schema.properties[name]); + if (zItem) { + obj[name] = zItem; + } + } + + if (Array.isArray(schema.required)) { + return z + .object(obj) + .partial() + .required(schema.required.reduce((acc, v: string) => ({ ...acc, [v]: true }), {})); + } + return z.object(obj).partial(); + } + + if (schema?.type === 'array' && schema?.items) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + const arr: Partial<[ZodTypeAny, ...ZodTypeAny[]]> = []; + for (const item of schema.items) { + const zItem = convertToZod(item); + if (zItem) { + arr.push(zItem); + } + } + return z.tuple(arr as [ZodTypeAny, ...ZodTypeAny[]]); + } + return z.array(convertToZod(schema.items as JsonSchema)); + } + + if (schema.oneOf && Array.isArray(schema.oneOf)) { + return z.union( + schema.oneOf.map(oneOfSchema => convertToZod(oneOfSchema)) as [ + ZodTypeAny, + ZodTypeAny, + ...ZodTypeAny[], + ], + ); + } + + if (schema?.format) { + if (!formats[schema.format]) { + throw new SchemaFormatError(schema.format); + } + + return z.any().refine(formats[schema.format], (value: unknown) => ({ + params: { value, format: schema.format }, + })); + } + + if ( + schema?.type && + schema?.type !== 'object' && + typeof (z as unknown as { [key: string]: (params?: RawCreateParams) => ZodType })[ + String(schema.type) + ] === 'function' + ) { + return (z as unknown as { [key: string]: (params?: RawCreateParams) => ZodType })[ + String(schema.type) + ](); + } + return z.object({ data: z.any() }).partial(); +}; + +export class Validator { + // eslint-disable-next-line no-use-before-define + private static validatorInstance?: Validator; + + // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function + public static factory(): Validator { + if (!Validator.validatorInstance) { + Validator.validatorInstance = new Validator(); + } + return Validator.validatorInstance; + } + + public validate(schema: JsonSchema, data: Json, options?: { silent?: boolean }) { + const zod = convertToZod(schema); + const result = zod.safeParse(data); + if (!result.success) { + const errors = this.convertErrors(result.error?.issues ?? []); + if (errors) { + if (options?.silent) { + return errors; + } + throw new Web3ValidatorError(errors); + } + } + return undefined; + } + // eslint-disable-next-line class-methods-use-this + private convertErrors(errors: ZodIssue[] | undefined): Web3ValidationErrorObject[] | undefined { + if (errors && Array.isArray(errors) && errors.length > 0) { + return errors.map((error: ZodIssue) => { + let message; + let keyword; + let params; + let schemaPath; + + schemaPath = error.path.join('/'); + + const field = String(error.path[error.path.length - 1]); + const instancePath = error.path.join('/'); + if (error.code === ZodIssueCode.too_big) { + keyword = 'maxItems'; + schemaPath = `${instancePath}/maxItems`; + params = { limit: error.maximum }; + message = `must NOT have more than ${error.maximum} items`; + } else if (error.code === ZodIssueCode.too_small) { + keyword = 'minItems'; + schemaPath = `${instancePath}/minItems`; + params = { limit: error.minimum }; + message = `must NOT have fewer than ${error.minimum} items`; + } else if (error.code === ZodIssueCode.custom) { + const { value, format } = (error.params ?? {}) as { + value: unknown; + format: string; + }; + + if (typeof value === 'undefined') { + message = `value at "/${schemaPath}" is required`; + } else { + message = `value "${ + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + typeof value === 'object' ? JSON.stringify(value) : value + }" at "/${schemaPath}" must pass "${format}" validation`; + } + + params = { value }; + } + + return { + keyword: keyword ?? field, + instancePath: instancePath ? `/${instancePath}` : '', + schemaPath: schemaPath ? `#${schemaPath}` : '#', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params: params ?? { value: error.message }, + message: message ?? error.message, + } as Web3ValidationErrorObject; + }); + } + return undefined; + } +} diff --git a/test/merkletreejs/node_modules/web3-validator/src/web3_validator.ts b/test/merkletreejs/node_modules/web3-validator/src/web3_validator.ts new file mode 100644 index 0000000..a165a36 --- /dev/null +++ b/test/merkletreejs/node_modules/web3-validator/src/web3_validator.ts @@ -0,0 +1,68 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { Web3ValidationErrorObject } from 'web3-types'; + +import { Validator } from './validator.js'; +import { ethAbiToJsonSchema } from './utils.js'; +import { Json, ValidationSchemaInput, Web3ValidationOptions } from './types.js'; +import { Web3ValidatorError } from './errors.js'; + +export class Web3Validator { + private readonly _validator: Validator; + public constructor() { + this._validator = Validator.factory(); + } + public validateJSONSchema( + schema: object, + data: object, + options?: Web3ValidationOptions, + ): Web3ValidationErrorObject[] | undefined { + return this._validator.validate(schema, data as Json, options); + } + public validate( + schema: ValidationSchemaInput, + data: ReadonlyArray, + options: Web3ValidationOptions = { silent: false }, + ): Web3ValidationErrorObject[] | undefined { + const jsonSchema = ethAbiToJsonSchema(schema); + if ( + Array.isArray(jsonSchema.items) && + jsonSchema.items?.length === 0 && + data.length === 0 + ) { + return undefined; + } + + if ( + Array.isArray(jsonSchema.items) && + jsonSchema.items?.length === 0 && + data.length !== 0 + ) { + throw new Web3ValidatorError([ + { + instancePath: '/0', + schemaPath: '/', + keyword: 'required', + message: 'empty schema against data can not be validated', + params: data, + }, + ]); + } + + return this._validator.validate(jsonSchema, data as Json, options); + } +} diff --git a/test/merkletreejs/node_modules/web3/LICENSE b/test/merkletreejs/node_modules/web3/LICENSE new file mode 100644 index 0000000..29a99ab --- /dev/null +++ b/test/merkletreejs/node_modules/web3/LICENSE @@ -0,0 +1,14 @@ +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . diff --git a/test/merkletreejs/node_modules/web3/README.md b/test/merkletreejs/node_modules/web3/README.md new file mode 100644 index 0000000..bec916e --- /dev/null +++ b/test/merkletreejs/node_modules/web3/README.md @@ -0,0 +1,89 @@ +

+ web3.js +

+ +# web3.js + +![ES Version](https://img.shields.io/badge/ES-2020-yellow) +![Node Version](https://img.shields.io/badge/node-14.x-green) +[![NPM Package][npm-image]][npm-url] +[![Downloads][downloads-image]][npm-url] + +This is the main package of [web3.js](repo). + +`web3` contains the ideal setup for a Web3.js package. + +## Installation + +You can install the package either using [NPM](https://www.npmjs.com/package/web3) or using [Yarn](https://yarnpkg.com/package/web3) + +### Using NPM + +```bash +npm install web3 +``` + +### Using Yarn + +```bash +yarn add web3 +``` + +## Getting Started + +- :writing_hand: If you have questions [submit an issue](https://github.com/ChainSafe/web3.js/issues/new) or join us on [Discord](https://discord.gg/yjyvFRP) + ![Discord](https://img.shields.io/discord/593655374469660673.svg?label=Discord&logo=discord) + +## Prerequisites + +- :gear: [NodeJS](https://nodejs.org/) (LTS/Fermium) +- :toolbox: [Yarn](https://yarnpkg.com/)/[Lerna](https://lerna.js.org/) + +## Migration Guide + +- [Migration Guide from Web3.js 1.x to 4.x](https://docs.web3js.org/docs/guides/web3_migration_guide) + Breaking changes are listed in migration guide and its first step for migrating from Web3.js 1.x to 4.x. If there is any question or discussion feel free to ask in discord, and in case of any bug or new feature request [open issue](https://github.com/web3/web3.js/issues/new) or create a pull request for [contributions](https://github.com/web3/web3.js/blob/4.x/CONTRIBUTIONS.md). + +## Package.json Scripts + +| Script | Description | +| ---------------- | -------------------------------------------------- | +| clean | Uses `rimraf` to remove `dist/` | +| build | Uses `tsc` to build package and dependent packages | +| lint | Uses `eslint` to lint package | +| lint:fix | Uses `eslint` to check and fix any warnings | +| format | Uses `prettier` to format the code | +| test | Uses `jest` to run unit tests | +| test:integration | Uses `jest` to run tests under `/test/integration` | +| test:unit | Uses `jest` to run tests under `/test/unit` | + +## Web3.js Packages + +We encourage users to use only required individual packages listed in following table, for making lightweight application instead of importing main web3 package, and if you don't need functions from most of the packages that are implicitly included with main web3 package. + +| Package | Version | License | Docs | Description | +| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| [web3](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3%2Fpackage.json)](https://www.npmjs.com/package/web3) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3) | :rotating_light: Entire Web3.js offering (includes all packages) | +| [web3-core](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-core) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-core%2Fpackage.json)](https://www.npmjs.com/package/web3-core) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-core) | Core functions for web3.js packages | +| [web3-errors](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-errors) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-errors%2Fpackage.json)](https://www.npmjs.com/package/web3-core) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-errors) | Errors Objects | +| [web3-eth](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth%2Fpackage.json)](https://www.npmjs.com/package/web3-eth) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth) | Modules to interact with the Ethereum blockchain and smart contracts | +| [web3-eth-abi](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth-abi) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-abi%2Fpackage.json)](https://www.npmjs.com/package/web3-eth-abi) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth-abi) | Functions for encoding and decoding EVM in/output | +| [web3-eth-accounts](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth-accounts) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-accounts%2Fpackage.json)](https://www.npmjs.com/package/web3-eth-accounts) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth-accounts) | Functions for managing Ethereum accounts and signing | +| [web3-eth-contract](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth-contract) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-contract%2Fpackage.json)](https://www.npmjs.com/package/web3-eth-contract) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth-contract) | The contract package contained in [web3-eth](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth) | +| [web3-eth-ens](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth-ens) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-ens%2Fpackage.json)](https://www.npmjs.com/package/web3-eth-ens) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth-ens) | Functions for interacting with the Ethereum Name Service | +| [web3-eth-iban](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth-iban) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-iban%2Fpackage.json)](https://www.npmjs.com/package/web3-eth-iban) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth-iban) | Functionality for converting Ethereum addressed to IBAN addressed and vice versa | +| [web3-eth-personal](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-eth-personal) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-eth-personal%2Fpackage.json)](https://www.npmjs.com/package/web3-eth-personal) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-eth-personal) | Module to interact with the Ethereum blockchain accounts stored in the node | +| [web3-net](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-net) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-net%2Fpackage.json)](https://www.npmjs.com/package/web3-net) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-net) | Functions to interact with an Ethereum node's network properties | +| [web3-providers-http](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-providers-http) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-providers-http%2Fpackage.json)](https://www.npmjs.com/package/web3-providers-http) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-providers-http) | Web3.js provider for the HTTP protocol | +| [web3-providers-ipc](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-providers-ipc) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-providers-ipc%2Fpackage.json)](https://www.npmjs.com/package/web3-providers-ipc) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-providers-ipc) | Web3.js provider for IPC | +| [web3-providers-ws](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-providers-ws) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-providers-ws%2Fpackage.json)](https://www.npmjs.com/package/web3-providers-ws) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-providers-ws) | Web3.js provider for the Websocket protocol | +| [web3-rpc-methods](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-rpc-methods) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-rpc-methods%2Fpackage.json)](https://www.npmjs.com/package/web3-types) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/) | RPC Methods | +| [web3-types](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-types) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-types%2Fpackage.json)](https://www.npmjs.com/package/web3-types) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-types) | Shared useable types | +| [web3-utils](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-utils) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-utils%2Fpackage.json)](https://www.npmjs.com/package/web3-utils) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-utils) | Useful utility functions for Dapp developers | +| [web3-validator](https://github.com/ChainSafe/web3.js/tree/4.x/packages/web3-validator) | [![npm](https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3-validator%2Fpackage.json)](https://www.npmjs.com/package/web3-validator) | [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) | [![documentation](https://img.shields.io/badge/typedoc-blue)](https://docs.web3js.org/api/web3-validator) | Utilities for validating objects | + +[docs]: https://docs.web3js.org/ +[repo]: https://github.com/web3/web3.js/tree/4.x/packages/web3 +[npm-image]: https://img.shields.io/github/package-json/v/web3/web3.js/4.x?filename=packages%2Fweb3%2Fpackage.json +[npm-url]: https://npmjs.org/package/web3 +[downloads-image]: https://img.shields.io/npm/dm/web3?label=npm%20downloads diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/abi.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/abi.d.ts new file mode 100644 index 0000000..3f475c5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/abi.d.ts @@ -0,0 +1,17 @@ +/** + * The object for `web3.abi` + */ +declare const _default: { + encodeEventSignature: (functionName: string | import("web3-types").AbiEventFragment) => string; + encodeFunctionCall: (jsonInterface: import("web3-types").AbiFunctionFragment, params: unknown[]) => string; + encodeFunctionSignature: (functionName: string | import("web3-types").AbiFunctionFragment) => string; + encodeParameter: (abi: import("web3-types").AbiInput, param: unknown) => string; + encodeParameters: (abi: readonly import("web3-types").AbiInput[], params: unknown[]) => string; + decodeParameter: (abi: import("web3-types").AbiInput, bytes: string) => unknown; + decodeParameters: (abi: import("web3-types").AbiInput[], bytes: string) => { + [key: string]: unknown; + __length__: number; + }; + decodeLog: (inputs: import("web3-types").AbiParameter[], data: string, topics: string | string[]) => ReturnType_1; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/abi.js b/test/merkletreejs/node_modules/web3/lib/commonjs/abi.js new file mode 100644 index 0000000..8c1384d --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/abi.js @@ -0,0 +1,33 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +const web3_eth_abi_1 = require("web3-eth-abi"); +/** + * The object for `web3.abi` + */ +exports.default = { + encodeEventSignature: web3_eth_abi_1.encodeEventSignature, + encodeFunctionCall: web3_eth_abi_1.encodeFunctionCall, + encodeFunctionSignature: web3_eth_abi_1.encodeFunctionSignature, + encodeParameter: web3_eth_abi_1.encodeParameter, + encodeParameters: web3_eth_abi_1.encodeParameters, + decodeParameter: web3_eth_abi_1.decodeParameter, + decodeParameters: web3_eth_abi_1.decodeParameters, + decodeLog: web3_eth_abi_1.decodeLog, +}; +//# sourceMappingURL=abi.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/abi.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/abi.js.map new file mode 100644 index 0000000..ebb4469 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/abi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abi.js","sourceRoot":"","sources":["../../src/abi.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;AAEF,+CASsB;AAEtB;;GAEG;AACH,kBAAe;IACd,oBAAoB,EAApB,mCAAoB;IACpB,kBAAkB,EAAlB,iCAAkB;IAClB,uBAAuB,EAAvB,sCAAuB;IACvB,eAAe,EAAf,8BAAe;IACf,gBAAgB,EAAhB,+BAAgB;IAChB,eAAe,EAAf,8BAAe;IACf,gBAAgB,EAAhB,+BAAgB;IAChB,SAAS,EAAT,wBAAS;CACT,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.d.ts new file mode 100644 index 0000000..295ab15 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.d.ts @@ -0,0 +1,77 @@ +import { EthExecutionAPI, Bytes, Transaction, KeyStore } from 'web3-types'; +import { Web3Context } from 'web3-core'; +import { Wallet } from 'web3-eth-accounts'; +/** + * Initialize the accounts module for the given context. + * + * To avoid multiple package dependencies for `web3-eth-accounts` we are creating + * this function in `web3` package. In future the actual `web3-eth-accounts` package + * should be converted to context aware. + */ +export declare const initAccountsForContext: (context: Web3Context) => { + signTransaction: (transaction: Transaction, privateKey: Bytes) => Promise; + create: () => { + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }; + privateKeyToAccount: (privateKey: Uint8Array | string) => { + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }; + decrypt: (keystore: KeyStore | string, password: string, options?: Record) => Promise<{ + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }>; + recoverTransaction: (rawTransaction: string) => string; + hashMessage: (message: string) => string; + sign: (data: string, privateKey: Bytes) => import("web3-eth-accounts").SignResult; + recover: (data: string | import("web3-eth-accounts").SignatureObject, signatureOrV?: string | undefined, prefixedOrR?: string | boolean | undefined, s?: string | undefined, prefixed?: boolean | undefined) => string; + encrypt: (privateKey: Bytes, password: string | Uint8Array, options?: import("web3-types").CipherOptions | undefined) => Promise; + wallet: Wallet<{ + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }>; + privateKeyToAddress: (privateKey: Bytes) => string; + parseAndValidatePrivateKey: (data: Bytes, ignoreLength?: boolean | undefined) => Uint8Array; + privateKeyToPublicKey: (privateKey: Bytes, isCompressed: boolean) => string; +}; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.js b/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.js new file mode 100644 index 0000000..5899a84 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.js @@ -0,0 +1,81 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.initAccountsForContext = void 0; +const web3_types_1 = require("web3-types"); +const web3_utils_1 = require("web3-utils"); +const web3_eth_1 = require("web3-eth"); +const web3_eth_accounts_1 = require("web3-eth-accounts"); +/** + * Initialize the accounts module for the given context. + * + * To avoid multiple package dependencies for `web3-eth-accounts` we are creating + * this function in `web3` package. In future the actual `web3-eth-accounts` package + * should be converted to context aware. + */ +const initAccountsForContext = (context) => { + const signTransactionWithContext = (transaction, privateKey) => __awaiter(void 0, void 0, void 0, function* () { + const tx = yield (0, web3_eth_1.prepareTransactionForSigning)(transaction, context); + const privateKeyBytes = (0, web3_utils_1.format)({ format: 'bytes' }, privateKey, web3_types_1.ETH_DATA_FORMAT); + return (0, web3_eth_accounts_1.signTransaction)(tx, privateKeyBytes); + }); + const privateKeyToAccountWithContext = (privateKey) => { + const account = (0, web3_eth_accounts_1.privateKeyToAccount)(privateKey); + return Object.assign(Object.assign({}, account), { signTransaction: (transaction) => __awaiter(void 0, void 0, void 0, function* () { return signTransactionWithContext(transaction, account.privateKey); }) }); + }; + const decryptWithContext = (keystore, password, options) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const account = yield (0, web3_eth_accounts_1.decrypt)(keystore, password, (_a = options === null || options === void 0 ? void 0 : options.nonStrict) !== null && _a !== void 0 ? _a : true); + return Object.assign(Object.assign({}, account), { signTransaction: (transaction) => __awaiter(void 0, void 0, void 0, function* () { return signTransactionWithContext(transaction, account.privateKey); }) }); + }); + const createWithContext = () => { + const account = (0, web3_eth_accounts_1.create)(); + return Object.assign(Object.assign({}, account), { signTransaction: (transaction) => __awaiter(void 0, void 0, void 0, function* () { return signTransactionWithContext(transaction, account.privateKey); }) }); + }; + const wallet = new web3_eth_accounts_1.Wallet({ + create: createWithContext, + privateKeyToAccount: privateKeyToAccountWithContext, + decrypt: decryptWithContext, + }); + return { + signTransaction: signTransactionWithContext, + create: createWithContext, + privateKeyToAccount: privateKeyToAccountWithContext, + decrypt: decryptWithContext, + recoverTransaction: web3_eth_accounts_1.recoverTransaction, + hashMessage: web3_eth_accounts_1.hashMessage, + sign: web3_eth_accounts_1.sign, + recover: web3_eth_accounts_1.recover, + encrypt: web3_eth_accounts_1.encrypt, + wallet, + privateKeyToAddress: web3_eth_accounts_1.privateKeyToAddress, + parseAndValidatePrivateKey: web3_eth_accounts_1.parseAndValidatePrivateKey, + privateKeyToPublicKey: web3_eth_accounts_1.privateKeyToPublicKey, + }; +}; +exports.initAccountsForContext = initAccountsForContext; +//# sourceMappingURL=accounts.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.js.map new file mode 100644 index 0000000..cca3259 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/accounts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/accounts.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAA4F;AAC5F,2CAAoC;AAEpC,uCAAwD;AACxD,yDAc2B;AAE3B;;;;;;GAMG;AACI,MAAM,sBAAsB,GAAG,CAAC,OAAqC,EAAE,EAAE;IAC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,CAAA,GAAA,IAC3D;IACH,CAAC,CAAC;IAEF,MAAM,MAAM,GAAG,IAAI,0BAAM,CAAC;QACzB,MAAM,EAAE,iBAAiB;QACzB,mBAAmB,EAAE,8BAA8B;QACnD,OAAO,EAAE,kBAAkB;KAC3B,CAAC,CAAC;IAEH,OAAO;QACN,eAAe,EAAE,0BAA0B;QAC3C,MAAM,EAAE,iBAAiB;QACzB,mBAAmB,EAAE,8BAA8B;QACnD,OAAO,EAAE,kBAAkB;QAC3B,kBAAkB,EAAlB,sCAAkB;QAClB,WAAW,EAAX,+BAAW;QACX,IAAI,EAAJ,wBAAI;QACJ,OAAO,EAAP,2BAAO;QACP,OAAO,EAAP,2BAAO;QACP,MAAM;QACN,mBAAmB,EAAnB,uCAAmB;QACnB,0BAA0B,EAA1B,8CAA0B;QAC1B,qBAAqB,EAArB,yCAAqB;KACrB,CAAA;AACF,CAAC,CAAC;AAhEW,QAAA,sBAAsB,0BAgEjC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.d.ts new file mode 100644 index 0000000..72ffc02 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.d.ts @@ -0,0 +1,7 @@ +export * from 'web3-eth'; +export * as abi from 'web3-eth-abi'; +export * as accounts from 'web3-eth-accounts'; +export * as contract from 'web3-eth-contract'; +export * as ens from 'web3-eth-ens'; +export * as personal from 'web3-eth-personal'; +export * as iban from 'web3-eth-iban'; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.js b/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.js new file mode 100644 index 0000000..a8768fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.js @@ -0,0 +1,53 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.iban = exports.personal = exports.ens = exports.contract = exports.accounts = exports.abi = void 0; +__exportStar(require("web3-eth"), exports); +exports.abi = __importStar(require("web3-eth-abi")); +exports.accounts = __importStar(require("web3-eth-accounts")); +exports.contract = __importStar(require("web3-eth-contract")); +exports.ens = __importStar(require("web3-eth-ens")); +exports.personal = __importStar(require("web3-eth-personal")); +exports.iban = __importStar(require("web3-eth-iban")); +//# sourceMappingURL=eth.exports.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.js.map new file mode 100644 index 0000000..729add5 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/eth.exports.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth.exports.js","sourceRoot":"","sources":["../../src/eth.exports.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,2CAAyB;AAEzB,oDAAoC;AACpC,8DAA8C;AAC9C,8DAA8C;AAC9C,oDAAoC;AACpC,8DAA8C;AAC9C,sDAAsC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/index.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/index.d.ts new file mode 100644 index 0000000..495e72b --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/index.d.ts @@ -0,0 +1,343 @@ +/** + * This is the main (or 'umbrella') class of the web3.js library. + * + * ```ts + * import Web3 from 'web3'; + * + * > Web3.utils + * > Web3.version + * > Web3.givenProvider + * > Web3.providers + * > Web3.modules + * ``` + * + * # Web3.modules + * + * ```ts + * Web3.modules + * ``` + * + * Will return an object with the classes of all major sub modules, to be able to instantiate them manually. + * + * #### Returns + * + * `Object` A list of module constructors: + * + * + * + `Eth` - `Constructor`: The Eth module for interacting with the Ethereum network + * + * + * + `Net` - `Constructor`: The Net module for interacting with network properties. + * + * + * + `Personal` - `constructor`: The Personal module for interacting with the Ethereum accounts (web3.eth.personal). + * + * #### Example + * + * ```ts + * Web3.modules + * > { + * Eth: Eth(provider), + * Net: Net(provider), + * Personal: Personal(provider), + * } + * ``` + * + * See details: {@link Web3.modules} + * + * # Web3 Instance + * + * The Web3 class is an umbrella package to house all Ethereum related modules. + * + * ```ts + * import Web3 from 'web3'; + * + * // "Web3.givenProvider" will be set if in an Ethereum supported browser. + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * > web3.eth + * > web3.utils + * > web3.version + * ``` + * + * ### version + * + * Contains the current package version of the web3.js library. + * + * #### Returns + * //todo enable when functionality added + * // @see Web3.version + * + * ### utils + * + * Static accessible property of the Web3 class and property of the instance as well. + * + * ```ts + * Web3.utils + * web3.utils + * ``` + * + * Utility functions are also exposed on the `Web3` class object diretly. + * + * //todo enable when implemented + * //See details: {@link Web3.utils} + * + * ### setProvider + * + * ```ts + * web3.setProvider(myProvider) + * web3.eth.setProvider(myProvider) + * ... + * ``` + * + * Will change the provider for its module. + * + * **_NOTE:_** When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth etc. + * + * #### Parameters + * `Object` - `myProvider`: a valid provider. + * + * #### Returns + * `Boolean` + * + * See details: {@link Web3.setProvider} + * + * #### Example: Local Geth Node + * ```ts + * import Web3 from "web3"; + * let web3: Web3 = new Web3('http://localhost:8545'); + * // or + * let web3: Web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); + * + * // change provider + * web3.setProvider('ws://localhost:8546'); + * // or + * web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546')); + * + * //todo add IPC provider + * ``` + * + * #### Example: Remote Geth Node + * + * ```ts + * // Using a remote node provider, like Alchemy (https://www.alchemyapi.io/supernode), is simple. + * import Web3 from "web3"; + * let web3: Web3 = new Web3("https://eth-mainnet.alchemyapi.io/v2/your-api-key"); + * ``` + * + * ### providers + * + * ```ts + * web3.providers + * web3.eth.providers + * ``` + * Contains the current available providers. + * + * #### Returns + * `Object` with the following providers: + * + * + * + `Object` - `HttpProvider`: HTTP provider, does not support subscriptions. + * + * + * + `Object` - `WebSocketProvider`: The WebSocket provider is the standard for usage in legacy browsers. + * + * + * + `Object` - `IpcProvider`: The IPC provider is used in node.js dapps when running a local node. Gives the most secure connection. + * + * + * #### Example + * ```ts + * import { Web3 } from 'web3'; + * // use the given Provider or instantiate a new websocket provider + * let web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546'); + * // or + * let web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546')); + * + * // Using the IPC provider in node.js + * import { Web3 } from 'web3'; + * import { IpcProvider } from 'web3-providers-ipc'; + * var web3 = new Web3(new IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc')); // mac os path + * // on windows the path is: "\\\\.\\pipe\\geth.ipc" + * // on linux the path is: "/users/myuser/.ethereum/geth.ipc" + * ``` + * #### Configuration + * + * ```ts + * + * //=== + * //Http + * //=== + * + * import Web3HttpProvider, { HttpProviderOptions } from "web3-providers-http"; + * + * let options: HttpProviderOptions = { + * providerOptions: { + * keepalive: true, + * credentials: "omit", + * headers: { + * "Access-Control-Allow-Origin": "*", + * }, + * }, + * }; + * + * + * var provider = new Web3HttpProvider("http://localhost:8545", options); + * web3.setProvider(provider); + * + * //=== + * //WebSockets + * //=== + * import Web3WsProvider, { + * ClientOptions, + * ClientRequestArgs, + * ReconnectOptions, + * } from "web3-providers-ws"; + * + * + * let clientOptions: ClientOptions = { + * // Useful for credentialed urls, e.g: ws://username:password@localhost:8546 + * headers: { + * authorization: "Basic username:password", + * }, + * maxPayload: 100000000, + * }; + * + * // Enable auto reconnection + * let reconnectOptions: ReconnectOptions = { + * autoReconnect: true, + * delay: 5000, // ms + * maxAttempts: 5, + * }; + * + * //clientOptions and reconnectOptions are optional + * //clientOptions: ClientOptions | ClientRequestArgs + * let ws = new Web3WsProvider( + * "ws://localhost:8546", + * clientOptions, + * reconnectOptions + * ); + * web3.setProvider(ws); + * + * ``` + * More information for the Http and Websocket provider modules can be found here: + * + * + * - {@link HttpProvider} + * + * + * - {@link WebSocketProvider} + * + * See details: {@link Web3.providers} + * + * + * ### givenProvider + * + * ```ts + * web3.givenProvider + * web3.eth.givenProvider + * ... + * ``` + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. + * Will return the given provider by the (browser) environment, otherwise `undefined`. + * + * #### Returns + * `Object` - The given provider set or `undefined`. + * + * See details: {@link Web3.givenProvider} + * + * ### currentProvider + * + * ```ts + * web3.currentProvider + * web3.eth.currentProvider + * ... + * ``` + * Will return the current provider, otherwise `undefined`. + * + * #### Returns + * `Object`: The current provider, otherwise `undefined`. + * + * See details: {@link Web3.currentProvider} + * + * ### BatchRequest + * + * ```ts + * new web3.BatchRequest() + * new web3.BatchRequest() + * ... + * ``` + * Class to create and execute batch requests. + * + * #### Parameters + * none + * + * #### Returns + * `Object`: With the following methods: + * + * + `add(request)`: To add a request object to the batch call. + * + * + `execute()` : To execute the batch request. + * + * #### Example + * ```ts + * let request1: JsonRpcOptionalRequest = { + * id: 10, + * method: 'eth_getBalance', + * params: ["0xdc6bad79dab7ea733098f66f6c6f9dd008da3258", 'latest'], + * }; + * let request2: JsonRpcOptionalRequest = { + * id: 11, + * method: 'eth_getBalance', + * params: ["0x962f9a9c2a6c092474d24def35eccb3d9363265e", 'latest'], + * }; + * + * const batch = new web3.BatchRequest(); + * + * batch.add(request1); + * batch.add(request2); + * // add returns a deferred promise which can be used to run specific code after completion of each respective request. + * //const request2Promise = batch.add(request2); + * + * const response = await batch.execute(); + * ``` + * See details: {@link Web3.BatchRequest} + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import Web3 from './web3.js'; +export * from './types.js'; +export default Web3; +/** + * Named exports for all objects which are the default-exported-object in their packages + */ +export { Web3 }; +export { Web3Context, Web3PluginBase, Web3EthPluginBase } from 'web3-core'; +export { Web3Eth } from 'web3-eth'; +export { Contract } from 'web3-eth-contract'; +export { Iban } from 'web3-eth-iban'; +export { Personal } from 'web3-eth-personal'; +export { Net } from 'web3-net'; +export { HttpProvider } from 'web3-providers-http'; +export { WebSocketProvider } from 'web3-providers-ws'; +export { Web3Validator } from 'web3-validator'; +/** + * Export all packages grouped by name spaces + */ +export * as core from 'web3-core'; +export * as errors from 'web3-errors'; +export * as eth from './eth.exports.js'; +export * as net from 'web3-net'; +export * as providers from './providers.exports.js'; +export * as rpcMethods from 'web3-rpc-methods'; +export * as types from 'web3-types'; +export * as utils from 'web3-utils'; +export * as validator from 'web3-validator'; +/** + * Export all types from `web3-types` without a namespace (in addition to being available at `types` namespace). + * To enable the user to write: `function something(): Web3Api` without the need for `types.Web3Api`. + * And the same for `web3-errors`. Because this package contains error classes and constants. + */ +export * from 'web3-errors'; +export * from 'web3-types'; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/index.js b/test/merkletreejs/node_modules/web3/lib/commonjs/index.js new file mode 100644 index 0000000..3c51b5b --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/index.js @@ -0,0 +1,400 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validator = exports.utils = exports.types = exports.rpcMethods = exports.providers = exports.net = exports.eth = exports.errors = exports.core = exports.Web3Validator = exports.WebSocketProvider = exports.HttpProvider = exports.Net = exports.Personal = exports.Iban = exports.Contract = exports.Web3Eth = exports.Web3EthPluginBase = exports.Web3PluginBase = exports.Web3Context = exports.Web3 = void 0; +/** + * This is the main (or 'umbrella') class of the web3.js library. + * + * ```ts + * import Web3 from 'web3'; + * + * > Web3.utils + * > Web3.version + * > Web3.givenProvider + * > Web3.providers + * > Web3.modules + * ``` + * + * # Web3.modules + * + * ```ts + * Web3.modules + * ``` + * + * Will return an object with the classes of all major sub modules, to be able to instantiate them manually. + * + * #### Returns + * + * `Object` A list of module constructors: + * + * + * + `Eth` - `Constructor`: The Eth module for interacting with the Ethereum network + * + * + * + `Net` - `Constructor`: The Net module for interacting with network properties. + * + * + * + `Personal` - `constructor`: The Personal module for interacting with the Ethereum accounts (web3.eth.personal). + * + * #### Example + * + * ```ts + * Web3.modules + * > { + * Eth: Eth(provider), + * Net: Net(provider), + * Personal: Personal(provider), + * } + * ``` + * + * See details: {@link Web3.modules} + * + * # Web3 Instance + * + * The Web3 class is an umbrella package to house all Ethereum related modules. + * + * ```ts + * import Web3 from 'web3'; + * + * // "Web3.givenProvider" will be set if in an Ethereum supported browser. + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * > web3.eth + * > web3.utils + * > web3.version + * ``` + * + * ### version + * + * Contains the current package version of the web3.js library. + * + * #### Returns + * //todo enable when functionality added + * // @see Web3.version + * + * ### utils + * + * Static accessible property of the Web3 class and property of the instance as well. + * + * ```ts + * Web3.utils + * web3.utils + * ``` + * + * Utility functions are also exposed on the `Web3` class object diretly. + * + * //todo enable when implemented + * //See details: {@link Web3.utils} + * + * ### setProvider + * + * ```ts + * web3.setProvider(myProvider) + * web3.eth.setProvider(myProvider) + * ... + * ``` + * + * Will change the provider for its module. + * + * **_NOTE:_** When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth etc. + * + * #### Parameters + * `Object` - `myProvider`: a valid provider. + * + * #### Returns + * `Boolean` + * + * See details: {@link Web3.setProvider} + * + * #### Example: Local Geth Node + * ```ts + * import Web3 from "web3"; + * let web3: Web3 = new Web3('http://localhost:8545'); + * // or + * let web3: Web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); + * + * // change provider + * web3.setProvider('ws://localhost:8546'); + * // or + * web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546')); + * + * //todo add IPC provider + * ``` + * + * #### Example: Remote Geth Node + * + * ```ts + * // Using a remote node provider, like Alchemy (https://www.alchemyapi.io/supernode), is simple. + * import Web3 from "web3"; + * let web3: Web3 = new Web3("https://eth-mainnet.alchemyapi.io/v2/your-api-key"); + * ``` + * + * ### providers + * + * ```ts + * web3.providers + * web3.eth.providers + * ``` + * Contains the current available providers. + * + * #### Returns + * `Object` with the following providers: + * + * + * + `Object` - `HttpProvider`: HTTP provider, does not support subscriptions. + * + * + * + `Object` - `WebSocketProvider`: The WebSocket provider is the standard for usage in legacy browsers. + * + * + * + `Object` - `IpcProvider`: The IPC provider is used in node.js dapps when running a local node. Gives the most secure connection. + * + * + * #### Example + * ```ts + * import { Web3 } from 'web3'; + * // use the given Provider or instantiate a new websocket provider + * let web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546'); + * // or + * let web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546')); + * + * // Using the IPC provider in node.js + * import { Web3 } from 'web3'; + * import { IpcProvider } from 'web3-providers-ipc'; + * var web3 = new Web3(new IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc')); // mac os path + * // on windows the path is: "\\\\.\\pipe\\geth.ipc" + * // on linux the path is: "/users/myuser/.ethereum/geth.ipc" + * ``` + * #### Configuration + * + * ```ts + * + * //=== + * //Http + * //=== + * + * import Web3HttpProvider, { HttpProviderOptions } from "web3-providers-http"; + * + * let options: HttpProviderOptions = { + * providerOptions: { + * keepalive: true, + * credentials: "omit", + * headers: { + * "Access-Control-Allow-Origin": "*", + * }, + * }, + * }; + * + * + * var provider = new Web3HttpProvider("http://localhost:8545", options); + * web3.setProvider(provider); + * + * //=== + * //WebSockets + * //=== + * import Web3WsProvider, { + * ClientOptions, + * ClientRequestArgs, + * ReconnectOptions, + * } from "web3-providers-ws"; + * + * + * let clientOptions: ClientOptions = { + * // Useful for credentialed urls, e.g: ws://username:password@localhost:8546 + * headers: { + * authorization: "Basic username:password", + * }, + * maxPayload: 100000000, + * }; + * + * // Enable auto reconnection + * let reconnectOptions: ReconnectOptions = { + * autoReconnect: true, + * delay: 5000, // ms + * maxAttempts: 5, + * }; + * + * //clientOptions and reconnectOptions are optional + * //clientOptions: ClientOptions | ClientRequestArgs + * let ws = new Web3WsProvider( + * "ws://localhost:8546", + * clientOptions, + * reconnectOptions + * ); + * web3.setProvider(ws); + * + * ``` + * More information for the Http and Websocket provider modules can be found here: + * + * + * - {@link HttpProvider} + * + * + * - {@link WebSocketProvider} + * + * See details: {@link Web3.providers} + * + * + * ### givenProvider + * + * ```ts + * web3.givenProvider + * web3.eth.givenProvider + * ... + * ``` + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. + * Will return the given provider by the (browser) environment, otherwise `undefined`. + * + * #### Returns + * `Object` - The given provider set or `undefined`. + * + * See details: {@link Web3.givenProvider} + * + * ### currentProvider + * + * ```ts + * web3.currentProvider + * web3.eth.currentProvider + * ... + * ``` + * Will return the current provider, otherwise `undefined`. + * + * #### Returns + * `Object`: The current provider, otherwise `undefined`. + * + * See details: {@link Web3.currentProvider} + * + * ### BatchRequest + * + * ```ts + * new web3.BatchRequest() + * new web3.BatchRequest() + * ... + * ``` + * Class to create and execute batch requests. + * + * #### Parameters + * none + * + * #### Returns + * `Object`: With the following methods: + * + * + `add(request)`: To add a request object to the batch call. + * + * + `execute()` : To execute the batch request. + * + * #### Example + * ```ts + * let request1: JsonRpcOptionalRequest = { + * id: 10, + * method: 'eth_getBalance', + * params: ["0xdc6bad79dab7ea733098f66f6c6f9dd008da3258", 'latest'], + * }; + * let request2: JsonRpcOptionalRequest = { + * id: 11, + * method: 'eth_getBalance', + * params: ["0x962f9a9c2a6c092474d24def35eccb3d9363265e", 'latest'], + * }; + * + * const batch = new web3.BatchRequest(); + * + * batch.add(request1); + * batch.add(request2); + * // add returns a deferred promise which can be used to run specific code after completion of each respective request. + * //const request2Promise = batch.add(request2); + * + * const response = await batch.execute(); + * ``` + * See details: {@link Web3.BatchRequest} + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +const web3_js_1 = __importDefault(require("./web3.js")); +exports.Web3 = web3_js_1.default; +__exportStar(require("./types.js"), exports); +exports.default = web3_js_1.default; +var web3_core_1 = require("web3-core"); +Object.defineProperty(exports, "Web3Context", { enumerable: true, get: function () { return web3_core_1.Web3Context; } }); +Object.defineProperty(exports, "Web3PluginBase", { enumerable: true, get: function () { return web3_core_1.Web3PluginBase; } }); +Object.defineProperty(exports, "Web3EthPluginBase", { enumerable: true, get: function () { return web3_core_1.Web3EthPluginBase; } }); +var web3_eth_1 = require("web3-eth"); +Object.defineProperty(exports, "Web3Eth", { enumerable: true, get: function () { return web3_eth_1.Web3Eth; } }); +var web3_eth_contract_1 = require("web3-eth-contract"); +Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return web3_eth_contract_1.Contract; } }); +var web3_eth_iban_1 = require("web3-eth-iban"); +Object.defineProperty(exports, "Iban", { enumerable: true, get: function () { return web3_eth_iban_1.Iban; } }); +var web3_eth_personal_1 = require("web3-eth-personal"); +Object.defineProperty(exports, "Personal", { enumerable: true, get: function () { return web3_eth_personal_1.Personal; } }); +var web3_net_1 = require("web3-net"); +Object.defineProperty(exports, "Net", { enumerable: true, get: function () { return web3_net_1.Net; } }); +var web3_providers_http_1 = require("web3-providers-http"); +Object.defineProperty(exports, "HttpProvider", { enumerable: true, get: function () { return web3_providers_http_1.HttpProvider; } }); +var web3_providers_ws_1 = require("web3-providers-ws"); +Object.defineProperty(exports, "WebSocketProvider", { enumerable: true, get: function () { return web3_providers_ws_1.WebSocketProvider; } }); +var web3_validator_1 = require("web3-validator"); +Object.defineProperty(exports, "Web3Validator", { enumerable: true, get: function () { return web3_validator_1.Web3Validator; } }); +/** + * Export all packages grouped by name spaces + */ +exports.core = __importStar(require("web3-core")); +exports.errors = __importStar(require("web3-errors")); +exports.eth = __importStar(require("./eth.exports.js")); +exports.net = __importStar(require("web3-net")); +exports.providers = __importStar(require("./providers.exports.js")); +exports.rpcMethods = __importStar(require("web3-rpc-methods")); +exports.types = __importStar(require("web3-types")); +exports.utils = __importStar(require("web3-utils")); +exports.validator = __importStar(require("web3-validator")); +/** + * Export all types from `web3-types` without a namespace (in addition to being available at `types` namespace). + * To enable the user to write: `function something(): Web3Api` without the need for `types.Web3Api`. + * And the same for `web3-errors`. Because this package contains error classes and constants. + */ +__exportStar(require("web3-errors"), exports); +__exportStar(require("web3-types"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/index.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/index.js.map new file mode 100644 index 0000000..e7523d8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgTG;AACH;;GAEG;AAEH,wDAA6B;AAQpB,eARF,iBAAI,CAQE;AANb,6CAA2B;AAC3B,kBAAe,iBAAI,CAAC;AAMpB,uCAA2E;AAAlE,wGAAA,WAAW,OAAA;AAAE,2GAAA,cAAc,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AACvD,qCAAmC;AAA1B,mGAAA,OAAO,OAAA;AAChB,uDAA6C;AAApC,6GAAA,QAAQ,OAAA;AACjB,+CAAqC;AAA5B,qGAAA,IAAI,OAAA;AACb,uDAA6C;AAApC,6GAAA,QAAQ,OAAA;AACjB,qCAA+B;AAAtB,+FAAA,GAAG,OAAA;AACZ,2DAAmD;AAA1C,mHAAA,YAAY,OAAA;AACrB,uDAAsD;AAA7C,sHAAA,iBAAiB,OAAA;AAC1B,iDAA+C;AAAtC,+GAAA,aAAa,OAAA;AAEtB;;GAEG;AACH,kDAAkC;AAClC,sDAAsC;AACtC,wDAAwC;AACxC,gDAAgC;AAChC,oEAAoD;AACpD,+DAA+C;AAC/C,oDAAoC;AACpC,oDAAoC;AACpC,4DAA4C;AAE5C;;;;GAIG;AACH,8CAA4B;AAC5B,6CAA2B"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/package.json b/test/merkletreejs/node_modules/web3/lib/commonjs/package.json new file mode 100644 index 0000000..b731bd6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.d.ts new file mode 100644 index 0000000..a86a6b0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.d.ts @@ -0,0 +1,3 @@ +export { Eip1193Provider, SocketProvider } from 'web3-utils'; +export * as http from 'web3-providers-http'; +export * as ws from 'web3-providers-ws'; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.js b/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.js new file mode 100644 index 0000000..33057b7 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.js @@ -0,0 +1,48 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ws = exports.http = exports.SocketProvider = exports.Eip1193Provider = void 0; +var web3_utils_1 = require("web3-utils"); +Object.defineProperty(exports, "Eip1193Provider", { enumerable: true, get: function () { return web3_utils_1.Eip1193Provider; } }); +Object.defineProperty(exports, "SocketProvider", { enumerable: true, get: function () { return web3_utils_1.SocketProvider; } }); +exports.http = __importStar(require("web3-providers-http")); +exports.ws = __importStar(require("web3-providers-ws")); +//# sourceMappingURL=providers.exports.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.js.map new file mode 100644 index 0000000..99c0f72 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/providers.exports.js.map @@ -0,0 +1 @@ +{"version":3,"file":"providers.exports.js","sourceRoot":"","sources":["../../src/providers.exports.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;;;;;;;;;;;;AAEF,yCAA6D;AAApD,6GAAA,eAAe,OAAA;AAAE,4GAAA,cAAc,OAAA;AAExC,4DAA4C;AAC5C,wDAAwC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/types.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/types.d.ts new file mode 100644 index 0000000..ae91381 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/types.d.ts @@ -0,0 +1,53 @@ +import { Bytes, Transaction } from 'web3-types'; +import Eth from 'web3-eth'; +import { decodeLog, decodeParameter, decodeParameters, encodeFunctionCall, encodeFunctionSignature, encodeParameter, encodeParameters } from 'web3-eth-abi'; +import { encrypt, hashMessage, recover, recoverTransaction, sign, signTransaction, Wallet, Web3Account } from 'web3-eth-accounts'; +import { Contract } from 'web3-eth-contract'; +import { ENS } from 'web3-eth-ens'; +import { Net } from 'web3-net'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; +/** + * The Ethereum interface for main web3 object. It provides extra methods in addition to `web3-eth` interface. + * + * {@link web3_eth.Web3Eth} for details about the `Eth` interface. + */ +export interface Web3EthInterface extends Eth { + /** + * Extended [Contract](/api/web3-eth-contract/class/Contract) constructor for main `web3` object. See [Contract](/api/web3-eth-contract/class/Contract) for further details. + * + * You can use `.setProvider` on this constructor to set provider for **all the instances** of the contracts which were created by `web3.eth.Contract`. + * Please check the {@doclink guides/web3_upgrade_guide/x/providers_migration_guide | following guide} to understand more about setting provider. + * + * ```ts + * web3.eth.Contract.setProvider(myProvider) + * ``` + */ + Contract: typeof Contract; + Iban: typeof Iban; + net: Net; + ens: ENS; + abi: { + encodeEventSignature: typeof encodeFunctionSignature; + encodeFunctionCall: typeof encodeFunctionCall; + encodeFunctionSignature: typeof encodeFunctionSignature; + encodeParameter: typeof encodeParameter; + encodeParameters: typeof encodeParameters; + decodeParameter: typeof decodeParameter; + decodeParameters: typeof decodeParameters; + decodeLog: typeof decodeLog; + }; + accounts: { + create: () => Web3Account; + privateKeyToAccount: (privateKey: Uint8Array | string) => Web3Account; + signTransaction: (transaction: Transaction, privateKey: Bytes) => ReturnType; + recoverTransaction: typeof recoverTransaction; + hashMessage: typeof hashMessage; + sign: typeof sign; + recover: typeof recover; + encrypt: typeof encrypt; + decrypt: (keystore: string, password: string, options?: Record) => Promise; + wallet: Wallet; + }; + personal: Personal; +} diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/types.js b/test/merkletreejs/node_modules/web3/lib/commonjs/types.js new file mode 100644 index 0000000..852a8e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/types.js @@ -0,0 +1,19 @@ +"use strict"; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/types.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/types.js.map new file mode 100644 index 0000000..92512b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/version.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/version.d.ts new file mode 100644 index 0000000..dfe02db --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/version.d.ts @@ -0,0 +1,3 @@ +export declare const Web3PkgInfo: { + version: string; +}; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/version.js b/test/merkletreejs/node_modules/web3/lib/commonjs/version.js new file mode 100644 index 0000000..5b69903 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3PkgInfo = void 0; +/* eslint-disable header/header */ exports.Web3PkgInfo = { version: '4.3.0' }; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/version.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/version.js.map new file mode 100644 index 0000000..2b1153e --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAA,kCAAkC,CAAc,QAAA,WAAW,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/web3.d.ts b/test/merkletreejs/node_modules/web3/lib/commonjs/web3.d.ts new file mode 100644 index 0000000..f5067f6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/web3.d.ts @@ -0,0 +1,26 @@ +import { Web3Context, Web3ContextInitOptions, Web3SubscriptionConstructor } from 'web3-core'; +import { Web3Eth, RegisteredSubscription } from 'web3-eth'; +import { ENS } from 'web3-eth-ens'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; +import { Net } from 'web3-net'; +import * as utils from 'web3-utils'; +import { EthExecutionAPI, SupportedProviders } from 'web3-types'; +import { Web3EthInterface } from './types.js'; +export declare class Web3; +} = RegisteredSubscription> extends Web3Context { + static version: string; + static utils: typeof utils; + static modules: { + Web3Eth: typeof Web3Eth; + Iban: typeof Iban; + Net: typeof Net; + ENS: typeof ENS; + Personal: typeof Personal; + }; + utils: typeof utils; + eth: Web3EthInterface; + constructor(providerOrContext?: string | SupportedProviders | Web3ContextInitOptions); +} +export default Web3; diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/web3.js b/test/merkletreejs/node_modules/web3/lib/commonjs/web3.js new file mode 100644 index 0000000..2b4bfb3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/web3.js @@ -0,0 +1,172 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Web3 = void 0; +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line max-classes-per-file +const web3_core_1 = require("web3-core"); +const web3_eth_1 = require("web3-eth"); +const web3_eth_contract_1 = __importDefault(require("web3-eth-contract")); +const web3_eth_ens_1 = require("web3-eth-ens"); +const web3_eth_iban_1 = require("web3-eth-iban"); +const web3_eth_personal_1 = require("web3-eth-personal"); +const web3_net_1 = require("web3-net"); +const utils = __importStar(require("web3-utils")); +const web3_utils_1 = require("web3-utils"); +const web3_types_1 = require("web3-types"); +const web3_errors_1 = require("web3-errors"); +const abi_js_1 = __importDefault(require("./abi.js")); +const accounts_js_1 = require("./accounts.js"); +const version_js_1 = require("./version.js"); +class Web3 extends web3_core_1.Web3Context { + constructor(providerOrContext) { + var _a; + if ((0, web3_utils_1.isNullish)(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() === '') || + (typeof providerOrContext !== 'string' && + !(0, web3_core_1.isSupportedProvider)(providerOrContext) && + !providerOrContext.provider)) { + console.warn('NOTE: web3.js is running without provider. You need to pass a provider in order to interact with the network!'); + } + let contextInitOptions = {}; + if (typeof providerOrContext === 'string' || + (0, web3_core_1.isSupportedProvider)(providerOrContext)) { + contextInitOptions.provider = providerOrContext; + } + else if (providerOrContext) { + contextInitOptions = providerOrContext; + } + else { + contextInitOptions = {}; + } + contextInitOptions.registeredSubscriptions = Object.assign(Object.assign({}, web3_eth_1.registeredSubscriptions), ((_a = contextInitOptions.registeredSubscriptions) !== null && _a !== void 0 ? _a : {})); + super(contextInitOptions); + const accounts = (0, accounts_js_1.initAccountsForContext)(this); + // Init protected properties + this._wallet = accounts.wallet; + this._accountProvider = accounts; + this.utils = utils; + // Have to use local alias to initiate contract context + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + class ContractBuilder extends web3_eth_contract_1.default { + constructor(jsonInterface, addressOrOptionsOrContext, optionsOrContextOrReturnFormat, contextOrReturnFormat, returnFormat) { + if ((0, web3_utils_1.isContractInitOptions)(addressOrOptionsOrContext) && (0, web3_utils_1.isContractInitOptions)(optionsOrContextOrReturnFormat)) { + throw new web3_errors_1.InvalidMethodParamsError('Should not provide options at both 2nd and 3rd parameters'); + } + let address; + let options = {}; + let context; + let dataFormat = web3_types_1.DEFAULT_RETURN_FORMAT; + // add validation so its not a breaking change + if (!(0, web3_utils_1.isNullish)(addressOrOptionsOrContext) && typeof addressOrOptionsOrContext !== 'object' && typeof addressOrOptionsOrContext !== 'string') { + throw new web3_errors_1.InvalidMethodParamsError(); + } + if (typeof addressOrOptionsOrContext === 'string') { + address = addressOrOptionsOrContext; + } + if ((0, web3_utils_1.isContractInitOptions)(addressOrOptionsOrContext)) { + options = addressOrOptionsOrContext; + } + else if ((0, web3_utils_1.isContractInitOptions)(optionsOrContextOrReturnFormat)) { + options = optionsOrContextOrReturnFormat; + } + else { + options = {}; + } + if (addressOrOptionsOrContext instanceof web3_core_1.Web3Context) { + context = addressOrOptionsOrContext; + } + else if (optionsOrContextOrReturnFormat instanceof web3_core_1.Web3Context) { + context = optionsOrContextOrReturnFormat; + } + else if (contextOrReturnFormat instanceof web3_core_1.Web3Context) { + context = contextOrReturnFormat; + } + else { + context = self.getContextObject(); + } + if (returnFormat) { + dataFormat = returnFormat; + } + else if ((0, web3_utils_1.isDataFormat)(optionsOrContextOrReturnFormat)) { + dataFormat = optionsOrContextOrReturnFormat; + } + else if ((0, web3_utils_1.isDataFormat)(contextOrReturnFormat)) { + dataFormat = contextOrReturnFormat; + } + super(jsonInterface, address, options, context, dataFormat); + super.subscribeToContextEvents(self); + } + } + const eth = self.use(web3_eth_1.Web3Eth); + // Eth Module + this.eth = Object.assign(eth, { + // ENS module + ens: self.use(web3_eth_ens_1.ENS, web3_eth_ens_1.registryAddresses.main), + // Iban helpers + Iban: // registry address defaults to main network + web3_eth_iban_1.Iban, + net: self.use(web3_net_1.Net), + personal: self.use(web3_eth_personal_1.Personal), + // Contract helper and module + Contract: ContractBuilder, + // ABI Helpers + abi: abi_js_1.default, + // Accounts helper + accounts, + }); + } +} +exports.Web3 = Web3; +Web3.version = version_js_1.Web3PkgInfo.version; +Web3.utils = utils; +Web3.modules = { + Web3Eth: web3_eth_1.Web3Eth, + Iban: web3_eth_iban_1.Iban, + Net: web3_net_1.Net, + ENS: web3_eth_ens_1.ENS, + Personal: web3_eth_personal_1.Personal, +}; +exports.default = Web3; +//# sourceMappingURL=web3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/commonjs/web3.js.map b/test/merkletreejs/node_modules/web3/lib/commonjs/web3.js.map new file mode 100644 index 0000000..fa52fa1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/commonjs/web3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3.js","sourceRoot":"","sources":["../../src/web3.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,gDAAgD;AAChD,yCAMmB;AACnB,uCAAoF;AACpF,0EAAyC;AACzC,+CAAsD;AACtD,iDAAqC;AACrC,yDAA6C;AAC7C,uCAA+B;AAC/B,kDAAoC;AACpC,2CAA4E;AAC5E,2CAQoB;AACpB,6CAAuD;AACvD,sDAA2B;AAC3B,+CAAuD;AAEvD,6CAA2C;AAE3C,MAAa,IAIX,SAAQ,uBAAmF;IAe5F,YACC,iBAGwE;;QAExE,IACC,IAAA,sBAAS,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C,qBAAqB,CAAC,EAAE;oBAC/C,UAAU,GAAG,qBAAqB,CAAC;iBACnC;gBAED,KAAK,CAAC,aAAa,EAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,CAAC,CAAA;gBAC1D,KAAK,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC;YACtC,CAAC;SACD;QAED,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,kBAAO,CAAC,CAAC;QAE9B,aAAa;QACb,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE;YAC7B,aAAa;YACb,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,kBAAG,EAAE,gCAAiB,CAAC,IAAI,CAAC;YAE1C,eAAe;YACf,IAAI,EAHwC,4CAA4C;YAGxF,oBAAI;YAEJ,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,cAAG,CAAC;YAClB,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,4BAAQ,CAAC;YAE5B,6BAA6B;YAC7B,QAAQ,EAAE,eAAe;YAEzB,cAAc;YACd,GAAG,EAAH,gBAAG;YAEH,kBAAkB;YAClB,QAAQ;SACR,CAAC,CAAC;IACJ,CAAC;;AA1KF,oBA2KC;AAtKc,YAAO,GAAG,wBAAW,CAAC,OAAO,CAAC;AAC9B,UAAK,GAAG,KAAK,CAAC;AACd,YAAO,GAAG;IACvB,OAAO,EAAP,kBAAO;IACP,IAAI,EAAJ,oBAAI;IACJ,GAAG,EAAH,cAAG;IACH,GAAG,EAAH,kBAAG;IACH,QAAQ,EAAR,4BAAQ;CACR,CAAC;AA+JH,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/abi.js b/test/merkletreejs/node_modules/web3/lib/esm/abi.js new file mode 100644 index 0000000..66780a9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/abi.js @@ -0,0 +1,31 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +import { decodeLog, decodeParameter, decodeParameters, encodeEventSignature, encodeFunctionCall, encodeFunctionSignature, encodeParameter, encodeParameters, } from 'web3-eth-abi'; +/** + * The object for `web3.abi` + */ +export default { + encodeEventSignature, + encodeFunctionCall, + encodeFunctionSignature, + encodeParameter, + encodeParameters, + decodeParameter, + decodeParameters, + decodeLog, +}; +//# sourceMappingURL=abi.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/abi.js.map b/test/merkletreejs/node_modules/web3/lib/esm/abi.js.map new file mode 100644 index 0000000..36af5ff --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/abi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abi.js","sourceRoot":"","sources":["../../src/abi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EACN,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,oBAAoB,EACpB,kBAAkB,EAClB,uBAAuB,EACvB,eAAe,EACf,gBAAgB,GAChB,MAAM,cAAc,CAAC;AAEtB;;GAEG;AACH,eAAe;IACd,oBAAoB;IACpB,kBAAkB;IAClB,uBAAuB;IACvB,eAAe;IACf,gBAAgB;IAChB,eAAe;IACf,gBAAgB;IAChB,SAAS;CACT,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/accounts.js b/test/merkletreejs/node_modules/web3/lib/esm/accounts.js new file mode 100644 index 0000000..a6c98c1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/accounts.js @@ -0,0 +1,77 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { ETH_DATA_FORMAT } from 'web3-types'; +import { format } from 'web3-utils'; +import { prepareTransactionForSigning } from 'web3-eth'; +import { create, decrypt, encrypt, hashMessage, privateKeyToAccount, recover, recoverTransaction, signTransaction, sign, Wallet, privateKeyToAddress, parseAndValidatePrivateKey, privateKeyToPublicKey, } from 'web3-eth-accounts'; +/** + * Initialize the accounts module for the given context. + * + * To avoid multiple package dependencies for `web3-eth-accounts` we are creating + * this function in `web3` package. In future the actual `web3-eth-accounts` package + * should be converted to context aware. + */ +export const initAccountsForContext = (context) => { + const signTransactionWithContext = (transaction, privateKey) => __awaiter(void 0, void 0, void 0, function* () { + const tx = yield prepareTransactionForSigning(transaction, context); + const privateKeyBytes = format({ format: 'bytes' }, privateKey, ETH_DATA_FORMAT); + return signTransaction(tx, privateKeyBytes); + }); + const privateKeyToAccountWithContext = (privateKey) => { + const account = privateKeyToAccount(privateKey); + return Object.assign(Object.assign({}, account), { signTransaction: (transaction) => __awaiter(void 0, void 0, void 0, function* () { return signTransactionWithContext(transaction, account.privateKey); }) }); + }; + const decryptWithContext = (keystore, password, options) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const account = yield decrypt(keystore, password, (_a = options === null || options === void 0 ? void 0 : options.nonStrict) !== null && _a !== void 0 ? _a : true); + return Object.assign(Object.assign({}, account), { signTransaction: (transaction) => __awaiter(void 0, void 0, void 0, function* () { return signTransactionWithContext(transaction, account.privateKey); }) }); + }); + const createWithContext = () => { + const account = create(); + return Object.assign(Object.assign({}, account), { signTransaction: (transaction) => __awaiter(void 0, void 0, void 0, function* () { return signTransactionWithContext(transaction, account.privateKey); }) }); + }; + const wallet = new Wallet({ + create: createWithContext, + privateKeyToAccount: privateKeyToAccountWithContext, + decrypt: decryptWithContext, + }); + return { + signTransaction: signTransactionWithContext, + create: createWithContext, + privateKeyToAccount: privateKeyToAccountWithContext, + decrypt: decryptWithContext, + recoverTransaction, + hashMessage, + sign, + recover, + encrypt, + wallet, + privateKeyToAddress, + parseAndValidatePrivateKey, + privateKeyToPublicKey, + }; +}; +//# sourceMappingURL=accounts.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/accounts.js.map b/test/merkletreejs/node_modules/web3/lib/esm/accounts.js.map new file mode 100644 index 0000000..a1b17e2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/accounts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/accounts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;AAEF,OAAO,EAAiD,eAAe,EAAE,MAAM,YAAY,CAAC;AAC5F,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEpC,OAAO,EAAE,4BAA4B,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EACN,MAAM,EACN,OAAO,EACP,OAAO,EACP,WAAW,EACX,mBAAmB,EACnB,OAAO,EACP,kBAAkB,EAClB,eAAe,EACf,IAAI,EACJ,MAAM,EACN,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,GAC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AAE,kDACnD,OAAA,0BAA0B,CAAC,WAAW,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA,GAAA,IAC3D;IACH,CAAC,CAAC;IAEF,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC;QACzB,MAAM,EAAE,iBAAiB;QACzB,mBAAmB,EAAE,8BAA8B;QACnD,OAAO,EAAE,kBAAkB;KAC3B,CAAC,CAAC;IAEH,OAAO;QACN,eAAe,EAAE,0BAA0B;QAC3C,MAAM,EAAE,iBAAiB;QACzB,mBAAmB,EAAE,8BAA8B;QACnD,OAAO,EAAE,kBAAkB;QAC3B,kBAAkB;QAClB,WAAW;QACX,IAAI;QACJ,OAAO;QACP,OAAO;QACP,MAAM;QACN,mBAAmB;QACnB,0BAA0B;QAC1B,qBAAqB;KACrB,CAAA;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/eth.exports.js b/test/merkletreejs/node_modules/web3/lib/esm/eth.exports.js new file mode 100644 index 0000000..1053f06 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/eth.exports.js @@ -0,0 +1,24 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export * from 'web3-eth'; +export * as abi from 'web3-eth-abi'; +export * as accounts from 'web3-eth-accounts'; +export * as contract from 'web3-eth-contract'; +export * as ens from 'web3-eth-ens'; +export * as personal from 'web3-eth-personal'; +export * as iban from 'web3-eth-iban'; +//# sourceMappingURL=eth.exports.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/eth.exports.js.map b/test/merkletreejs/node_modules/web3/lib/esm/eth.exports.js.map new file mode 100644 index 0000000..7d372c9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/eth.exports.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eth.exports.js","sourceRoot":"","sources":["../../src/eth.exports.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,cAAc,UAAU,CAAC;AAEzB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,IAAI,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/index.js b/test/merkletreejs/node_modules/web3/lib/esm/index.js new file mode 100644 index 0000000..3972f4b --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/index.js @@ -0,0 +1,360 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +/** + * This is the main (or 'umbrella') class of the web3.js library. + * + * ```ts + * import Web3 from 'web3'; + * + * > Web3.utils + * > Web3.version + * > Web3.givenProvider + * > Web3.providers + * > Web3.modules + * ``` + * + * # Web3.modules + * + * ```ts + * Web3.modules + * ``` + * + * Will return an object with the classes of all major sub modules, to be able to instantiate them manually. + * + * #### Returns + * + * `Object` A list of module constructors: + * + * + * + `Eth` - `Constructor`: The Eth module for interacting with the Ethereum network + * + * + * + `Net` - `Constructor`: The Net module for interacting with network properties. + * + * + * + `Personal` - `constructor`: The Personal module for interacting with the Ethereum accounts (web3.eth.personal). + * + * #### Example + * + * ```ts + * Web3.modules + * > { + * Eth: Eth(provider), + * Net: Net(provider), + * Personal: Personal(provider), + * } + * ``` + * + * See details: {@link Web3.modules} + * + * # Web3 Instance + * + * The Web3 class is an umbrella package to house all Ethereum related modules. + * + * ```ts + * import Web3 from 'web3'; + * + * // "Web3.givenProvider" will be set if in an Ethereum supported browser. + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * > web3.eth + * > web3.utils + * > web3.version + * ``` + * + * ### version + * + * Contains the current package version of the web3.js library. + * + * #### Returns + * //todo enable when functionality added + * // @see Web3.version + * + * ### utils + * + * Static accessible property of the Web3 class and property of the instance as well. + * + * ```ts + * Web3.utils + * web3.utils + * ``` + * + * Utility functions are also exposed on the `Web3` class object diretly. + * + * //todo enable when implemented + * //See details: {@link Web3.utils} + * + * ### setProvider + * + * ```ts + * web3.setProvider(myProvider) + * web3.eth.setProvider(myProvider) + * ... + * ``` + * + * Will change the provider for its module. + * + * **_NOTE:_** When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth etc. + * + * #### Parameters + * `Object` - `myProvider`: a valid provider. + * + * #### Returns + * `Boolean` + * + * See details: {@link Web3.setProvider} + * + * #### Example: Local Geth Node + * ```ts + * import Web3 from "web3"; + * let web3: Web3 = new Web3('http://localhost:8545'); + * // or + * let web3: Web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); + * + * // change provider + * web3.setProvider('ws://localhost:8546'); + * // or + * web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546')); + * + * //todo add IPC provider + * ``` + * + * #### Example: Remote Geth Node + * + * ```ts + * // Using a remote node provider, like Alchemy (https://www.alchemyapi.io/supernode), is simple. + * import Web3 from "web3"; + * let web3: Web3 = new Web3("https://eth-mainnet.alchemyapi.io/v2/your-api-key"); + * ``` + * + * ### providers + * + * ```ts + * web3.providers + * web3.eth.providers + * ``` + * Contains the current available providers. + * + * #### Returns + * `Object` with the following providers: + * + * + * + `Object` - `HttpProvider`: HTTP provider, does not support subscriptions. + * + * + * + `Object` - `WebSocketProvider`: The WebSocket provider is the standard for usage in legacy browsers. + * + * + * + `Object` - `IpcProvider`: The IPC provider is used in node.js dapps when running a local node. Gives the most secure connection. + * + * + * #### Example + * ```ts + * import { Web3 } from 'web3'; + * // use the given Provider or instantiate a new websocket provider + * let web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546'); + * // or + * let web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546')); + * + * // Using the IPC provider in node.js + * import { Web3 } from 'web3'; + * import { IpcProvider } from 'web3-providers-ipc'; + * var web3 = new Web3(new IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc')); // mac os path + * // on windows the path is: "\\\\.\\pipe\\geth.ipc" + * // on linux the path is: "/users/myuser/.ethereum/geth.ipc" + * ``` + * #### Configuration + * + * ```ts + * + * //=== + * //Http + * //=== + * + * import Web3HttpProvider, { HttpProviderOptions } from "web3-providers-http"; + * + * let options: HttpProviderOptions = { + * providerOptions: { + * keepalive: true, + * credentials: "omit", + * headers: { + * "Access-Control-Allow-Origin": "*", + * }, + * }, + * }; + * + * + * var provider = new Web3HttpProvider("http://localhost:8545", options); + * web3.setProvider(provider); + * + * //=== + * //WebSockets + * //=== + * import Web3WsProvider, { + * ClientOptions, + * ClientRequestArgs, + * ReconnectOptions, + * } from "web3-providers-ws"; + * + * + * let clientOptions: ClientOptions = { + * // Useful for credentialed urls, e.g: ws://username:password@localhost:8546 + * headers: { + * authorization: "Basic username:password", + * }, + * maxPayload: 100000000, + * }; + * + * // Enable auto reconnection + * let reconnectOptions: ReconnectOptions = { + * autoReconnect: true, + * delay: 5000, // ms + * maxAttempts: 5, + * }; + * + * //clientOptions and reconnectOptions are optional + * //clientOptions: ClientOptions | ClientRequestArgs + * let ws = new Web3WsProvider( + * "ws://localhost:8546", + * clientOptions, + * reconnectOptions + * ); + * web3.setProvider(ws); + * + * ``` + * More information for the Http and Websocket provider modules can be found here: + * + * + * - {@link HttpProvider} + * + * + * - {@link WebSocketProvider} + * + * See details: {@link Web3.providers} + * + * + * ### givenProvider + * + * ```ts + * web3.givenProvider + * web3.eth.givenProvider + * ... + * ``` + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. + * Will return the given provider by the (browser) environment, otherwise `undefined`. + * + * #### Returns + * `Object` - The given provider set or `undefined`. + * + * See details: {@link Web3.givenProvider} + * + * ### currentProvider + * + * ```ts + * web3.currentProvider + * web3.eth.currentProvider + * ... + * ``` + * Will return the current provider, otherwise `undefined`. + * + * #### Returns + * `Object`: The current provider, otherwise `undefined`. + * + * See details: {@link Web3.currentProvider} + * + * ### BatchRequest + * + * ```ts + * new web3.BatchRequest() + * new web3.BatchRequest() + * ... + * ``` + * Class to create and execute batch requests. + * + * #### Parameters + * none + * + * #### Returns + * `Object`: With the following methods: + * + * + `add(request)`: To add a request object to the batch call. + * + * + `execute()` : To execute the batch request. + * + * #### Example + * ```ts + * let request1: JsonRpcOptionalRequest = { + * id: 10, + * method: 'eth_getBalance', + * params: ["0xdc6bad79dab7ea733098f66f6c6f9dd008da3258", 'latest'], + * }; + * let request2: JsonRpcOptionalRequest = { + * id: 11, + * method: 'eth_getBalance', + * params: ["0x962f9a9c2a6c092474d24def35eccb3d9363265e", 'latest'], + * }; + * + * const batch = new web3.BatchRequest(); + * + * batch.add(request1); + * batch.add(request2); + * // add returns a deferred promise which can be used to run specific code after completion of each respective request. + * //const request2Promise = batch.add(request2); + * + * const response = await batch.execute(); + * ``` + * See details: {@link Web3.BatchRequest} + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import Web3 from './web3.js'; +export * from './types.js'; +export default Web3; +/** + * Named exports for all objects which are the default-exported-object in their packages + */ +export { Web3 }; +export { Web3Context, Web3PluginBase, Web3EthPluginBase } from 'web3-core'; +export { Web3Eth } from 'web3-eth'; +export { Contract } from 'web3-eth-contract'; +export { Iban } from 'web3-eth-iban'; +export { Personal } from 'web3-eth-personal'; +export { Net } from 'web3-net'; +export { HttpProvider } from 'web3-providers-http'; +export { WebSocketProvider } from 'web3-providers-ws'; +export { Web3Validator } from 'web3-validator'; +/** + * Export all packages grouped by name spaces + */ +export * as core from 'web3-core'; +export * as errors from 'web3-errors'; +export * as eth from './eth.exports.js'; +export * as net from 'web3-net'; +export * as providers from './providers.exports.js'; +export * as rpcMethods from 'web3-rpc-methods'; +export * as types from 'web3-types'; +export * as utils from 'web3-utils'; +export * as validator from 'web3-validator'; +/** + * Export all types from `web3-types` without a namespace (in addition to being available at `types` namespace). + * To enable the user to write: `function something(): Web3Api` without the need for `types.Web3Api`. + * And the same for `web3-errors`. Because this package contains error classes and constants. + */ +export * from 'web3-errors'; +export * from 'web3-types'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/index.js.map b/test/merkletreejs/node_modules/web3/lib/esm/index.js.map new file mode 100644 index 0000000..5474a6f --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgTG;AACH;;GAEG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,cAAc,YAAY,CAAC;AAC3B,eAAe,IAAI,CAAC;AAEpB;;GAEG;AACH,OAAO,EAAE,IAAI,EAAE,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;GAEG;AACH,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,GAAG,MAAM,kBAAkB,CAAC;AACxC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,UAAU,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAC;AAE5C;;;;GAIG;AACH,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/package.json b/test/merkletreejs/node_modules/web3/lib/esm/package.json new file mode 100644 index 0000000..6990891 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/test/merkletreejs/node_modules/web3/lib/esm/providers.exports.js b/test/merkletreejs/node_modules/web3/lib/esm/providers.exports.js new file mode 100644 index 0000000..15643fa --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/providers.exports.js @@ -0,0 +1,20 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export { Eip1193Provider, SocketProvider } from 'web3-utils'; +export * as http from 'web3-providers-http'; +export * as ws from 'web3-providers-ws'; +//# sourceMappingURL=providers.exports.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/providers.exports.js.map b/test/merkletreejs/node_modules/web3/lib/esm/providers.exports.js.map new file mode 100644 index 0000000..ed9a80e --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/providers.exports.js.map @@ -0,0 +1 @@ +{"version":3,"file":"providers.exports.js","sourceRoot":"","sources":["../../src/providers.exports.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AAEF,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE7D,OAAO,KAAK,IAAI,MAAM,qBAAqB,CAAC;AAC5C,OAAO,KAAK,EAAE,MAAM,mBAAmB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/types.js b/test/merkletreejs/node_modules/web3/lib/esm/types.js new file mode 100644 index 0000000..43982a8 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/types.js @@ -0,0 +1,18 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/types.js.map b/test/merkletreejs/node_modules/web3/lib/esm/types.js.map new file mode 100644 index 0000000..1114514 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/version.js b/test/merkletreejs/node_modules/web3/lib/esm/version.js new file mode 100644 index 0000000..27c7e87 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/version.js @@ -0,0 +1,2 @@ +/* eslint-disable header/header */ export const Web3PkgInfo = { version: '4.3.0' }; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/version.js.map b/test/merkletreejs/node_modules/web3/lib/esm/version.js.map new file mode 100644 index 0000000..4f3e0b6 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,kCAAkC,CAAC,MAAM,CAAC,MAAM,WAAW,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/web3.js b/test/merkletreejs/node_modules/web3/lib/esm/web3.js new file mode 100644 index 0000000..c76af5c --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/web3.js @@ -0,0 +1,141 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line max-classes-per-file +import { Web3Context, isSupportedProvider } from 'web3-core'; +import { Web3Eth, registeredSubscriptions } from 'web3-eth'; +import Contract from 'web3-eth-contract'; +import { ENS, registryAddresses } from 'web3-eth-ens'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; +import { Net } from 'web3-net'; +import * as utils from 'web3-utils'; +import { isNullish, isDataFormat, isContractInitOptions } from 'web3-utils'; +import { DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { InvalidMethodParamsError } from 'web3-errors'; +import abi from './abi.js'; +import { initAccountsForContext } from './accounts.js'; +import { Web3PkgInfo } from './version.js'; +export class Web3 extends Web3Context { + constructor(providerOrContext) { + var _a; + if (isNullish(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() === '') || + (typeof providerOrContext !== 'string' && + !isSupportedProvider(providerOrContext) && + !providerOrContext.provider)) { + console.warn('NOTE: web3.js is running without provider. You need to pass a provider in order to interact with the network!'); + } + let contextInitOptions = {}; + if (typeof providerOrContext === 'string' || + isSupportedProvider(providerOrContext)) { + contextInitOptions.provider = providerOrContext; + } + else if (providerOrContext) { + contextInitOptions = providerOrContext; + } + else { + contextInitOptions = {}; + } + contextInitOptions.registeredSubscriptions = Object.assign(Object.assign({}, registeredSubscriptions), ((_a = contextInitOptions.registeredSubscriptions) !== null && _a !== void 0 ? _a : {})); + super(contextInitOptions); + const accounts = initAccountsForContext(this); + // Init protected properties + this._wallet = accounts.wallet; + this._accountProvider = accounts; + this.utils = utils; + // Have to use local alias to initiate contract context + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + class ContractBuilder extends Contract { + constructor(jsonInterface, addressOrOptionsOrContext, optionsOrContextOrReturnFormat, contextOrReturnFormat, returnFormat) { + if (isContractInitOptions(addressOrOptionsOrContext) && isContractInitOptions(optionsOrContextOrReturnFormat)) { + throw new InvalidMethodParamsError('Should not provide options at both 2nd and 3rd parameters'); + } + let address; + let options = {}; + let context; + let dataFormat = DEFAULT_RETURN_FORMAT; + // add validation so its not a breaking change + if (!isNullish(addressOrOptionsOrContext) && typeof addressOrOptionsOrContext !== 'object' && typeof addressOrOptionsOrContext !== 'string') { + throw new InvalidMethodParamsError(); + } + if (typeof addressOrOptionsOrContext === 'string') { + address = addressOrOptionsOrContext; + } + if (isContractInitOptions(addressOrOptionsOrContext)) { + options = addressOrOptionsOrContext; + } + else if (isContractInitOptions(optionsOrContextOrReturnFormat)) { + options = optionsOrContextOrReturnFormat; + } + else { + options = {}; + } + if (addressOrOptionsOrContext instanceof Web3Context) { + context = addressOrOptionsOrContext; + } + else if (optionsOrContextOrReturnFormat instanceof Web3Context) { + context = optionsOrContextOrReturnFormat; + } + else if (contextOrReturnFormat instanceof Web3Context) { + context = contextOrReturnFormat; + } + else { + context = self.getContextObject(); + } + if (returnFormat) { + dataFormat = returnFormat; + } + else if (isDataFormat(optionsOrContextOrReturnFormat)) { + dataFormat = optionsOrContextOrReturnFormat; + } + else if (isDataFormat(contextOrReturnFormat)) { + dataFormat = contextOrReturnFormat; + } + super(jsonInterface, address, options, context, dataFormat); + super.subscribeToContextEvents(self); + } + } + const eth = self.use(Web3Eth); + // Eth Module + this.eth = Object.assign(eth, { + // ENS module + ens: self.use(ENS, registryAddresses.main), + // Iban helpers + Iban, + net: self.use(Net), + personal: self.use(Personal), + // Contract helper and module + Contract: ContractBuilder, + // ABI Helpers + abi, + // Accounts helper + accounts, + }); + } +} +Web3.version = Web3PkgInfo.version; +Web3.utils = utils; +Web3.modules = { + Web3Eth, + Iban, + Net, + ENS, + Personal, +}; +export default Web3; +//# sourceMappingURL=web3.js.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/esm/web3.js.map b/test/merkletreejs/node_modules/web3/lib/esm/web3.js.map new file mode 100644 index 0000000..94e0bdc --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/esm/web3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web3.js","sourceRoot":"","sources":["../../src/web3.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;EAeE;AACF,gDAAgD;AAChD,OAAO,EACN,WAAW,EAIX,mBAAmB,EACnB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,OAAO,EAA0B,uBAAuB,EAAE,MAAM,UAAU,CAAC;AACpF,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,GAAG,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAC5E,OAAO,EAON,qBAAqB,EACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,MAAM,OAAO,IAIX,SAAQ,WAAmF;IAe5F,YACC,iBAGwE;;QAExE,IACC,SAAS,CAAC,iBAAiB,CAAC;YAC5B,CAAC,OAAO,iBAAiB,KAAK,QA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EAAE,UAAU,CAAC,CAAA;gBAC1D,KAAK,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC;YACtC,CAAC;SACD;QAED,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAE9B,aAAa;QACb,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE;YAC7B,aAAa;YACb,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,iBAAiB,CAAC,IAAI,CAAC;YAE1C,eAAe;YACf,IAAI;YAEJ,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAClB,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;YAE5B,6BAA6B;YAC7B,QAAQ,EAAE,eAAe;YAEzB,cAAc;YACd,GAAG;YAEH,kBAAkB;YAClB,QAAQ;SACR,CAAC,CAAC;IACJ,CAAC;;AArKa,YAAO,GAAG,WAAW,CAAC,OAAO,CAAC;AAC9B,UAAK,GAAG,KAAK,CAAC;AACd,YAAO,GAAG;IACvB,OAAO;IACP,IAAI;IACJ,GAAG;IACH,GAAG;IACH,QAAQ;CACR,CAAC;AA+JH,eAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/abi.d.ts b/test/merkletreejs/node_modules/web3/lib/types/abi.d.ts new file mode 100644 index 0000000..fa7d361 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/abi.d.ts @@ -0,0 +1,18 @@ +/** + * The object for `web3.abi` + */ +declare const _default: { + encodeEventSignature: (functionName: string | import("web3-types").AbiEventFragment) => string; + encodeFunctionCall: (jsonInterface: import("web3-types").AbiFunctionFragment, params: unknown[]) => string; + encodeFunctionSignature: (functionName: string | import("web3-types").AbiFunctionFragment) => string; + encodeParameter: (abi: import("web3-types").AbiInput, param: unknown) => string; + encodeParameters: (abi: readonly import("web3-types").AbiInput[], params: unknown[]) => string; + decodeParameter: (abi: import("web3-types").AbiInput, bytes: string) => unknown; + decodeParameters: (abi: import("web3-types").AbiInput[], bytes: string) => { + [key: string]: unknown; + __length__: number; + }; + decodeLog: (inputs: import("web3-types").AbiParameter[], data: string, topics: string | string[]) => ReturnType_1; +}; +export default _default; +//# sourceMappingURL=abi.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/abi.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/abi.d.ts.map new file mode 100644 index 0000000..96566d4 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/abi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abi.d.ts","sourceRoot":"","sources":["../../src/abi.ts"],"names":[],"mappings":"AA4BA;;GAEG;;;;;;;;;;;;;;AACH,wBASE"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/accounts.d.ts b/test/merkletreejs/node_modules/web3/lib/types/accounts.d.ts new file mode 100644 index 0000000..36092b9 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/accounts.d.ts @@ -0,0 +1,78 @@ +import { EthExecutionAPI, Bytes, Transaction, KeyStore } from 'web3-types'; +import { Web3Context } from 'web3-core'; +import { Wallet } from 'web3-eth-accounts'; +/** + * Initialize the accounts module for the given context. + * + * To avoid multiple package dependencies for `web3-eth-accounts` we are creating + * this function in `web3` package. In future the actual `web3-eth-accounts` package + * should be converted to context aware. + */ +export declare const initAccountsForContext: (context: Web3Context) => { + signTransaction: (transaction: Transaction, privateKey: Bytes) => Promise; + create: () => { + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }; + privateKeyToAccount: (privateKey: Uint8Array | string) => { + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }; + decrypt: (keystore: KeyStore | string, password: string, options?: Record) => Promise<{ + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }>; + recoverTransaction: (rawTransaction: string) => string; + hashMessage: (message: string) => string; + sign: (data: string, privateKey: Bytes) => import("web3-eth-accounts").SignResult; + recover: (data: string | import("web3-eth-accounts").SignatureObject, signatureOrV?: string | undefined, prefixedOrR?: string | boolean | undefined, s?: string | undefined, prefixed?: boolean | undefined) => string; + encrypt: (privateKey: Bytes, password: string | Uint8Array, options?: import("web3-types").CipherOptions | undefined) => Promise; + wallet: Wallet<{ + signTransaction: (transaction: Transaction) => Promise; + address: string; + privateKey: string; + sign: (data: string | Record) => { + readonly messageHash: string; + readonly r: string; + readonly s: string; + readonly v: string; + readonly message?: string | undefined; + readonly signature: string; + }; + encrypt: (password: string, options?: Record | undefined) => Promise; + }>; + privateKeyToAddress: (privateKey: Bytes) => string; + parseAndValidatePrivateKey: (data: Bytes, ignoreLength?: boolean | undefined) => Uint8Array; + privateKeyToPublicKey: (privateKey: Bytes, isCompressed: boolean) => string; +}; +//# sourceMappingURL=accounts.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/accounts.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/accounts.d.ts.map new file mode 100644 index 0000000..de5a840 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/accounts.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"accounts.d.ts","sourceRoot":"","sources":["../../src/accounts.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAmB,MAAM,YAAY,CAAC;AAE5F,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,OAAO,EAUN,MAAM,EAIN,MAAM,mBAAmB,CAAC;AAE3B;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,YAAa,YAAY,eAAe,CAAC;mCACpB,WAAW,cAAc,KAAK;;uCAqC9C,WAAW;;;;;;;;;;;;;sCA7BE,UAAU,GAAG,MAAM;uCAKhC,WAAW;;;;;;;;;;;;;wBAMvC,QAAQ,GAAG,MAAM,YACjB,MAAM,YACN,OAAO,MAAM,EAAE,OAAO,CAAC;uCAMK,WAAW;;;;;;;;;;;;;;;;;;;uCAAX,WAAW;;;;;;;;;;;;;;;;CAoClD,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/eth.exports.d.ts b/test/merkletreejs/node_modules/web3/lib/types/eth.exports.d.ts new file mode 100644 index 0000000..483d294 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/eth.exports.d.ts @@ -0,0 +1,8 @@ +export * from 'web3-eth'; +export * as abi from 'web3-eth-abi'; +export * as accounts from 'web3-eth-accounts'; +export * as contract from 'web3-eth-contract'; +export * as ens from 'web3-eth-ens'; +export * as personal from 'web3-eth-personal'; +export * as iban from 'web3-eth-iban'; +//# sourceMappingURL=eth.exports.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/eth.exports.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/eth.exports.d.ts.map new file mode 100644 index 0000000..d639a89 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/eth.exports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eth.exports.d.ts","sourceRoot":"","sources":["../../src/eth.exports.ts"],"names":[],"mappings":"AAiBA,cAAc,UAAU,CAAC;AAEzB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,IAAI,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/index.d.ts b/test/merkletreejs/node_modules/web3/lib/types/index.d.ts new file mode 100644 index 0000000..aac5f67 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/index.d.ts @@ -0,0 +1,344 @@ +/** + * This is the main (or 'umbrella') class of the web3.js library. + * + * ```ts + * import Web3 from 'web3'; + * + * > Web3.utils + * > Web3.version + * > Web3.givenProvider + * > Web3.providers + * > Web3.modules + * ``` + * + * # Web3.modules + * + * ```ts + * Web3.modules + * ``` + * + * Will return an object with the classes of all major sub modules, to be able to instantiate them manually. + * + * #### Returns + * + * `Object` A list of module constructors: + * + * + * + `Eth` - `Constructor`: The Eth module for interacting with the Ethereum network + * + * + * + `Net` - `Constructor`: The Net module for interacting with network properties. + * + * + * + `Personal` - `constructor`: The Personal module for interacting with the Ethereum accounts (web3.eth.personal). + * + * #### Example + * + * ```ts + * Web3.modules + * > { + * Eth: Eth(provider), + * Net: Net(provider), + * Personal: Personal(provider), + * } + * ``` + * + * See details: {@link Web3.modules} + * + * # Web3 Instance + * + * The Web3 class is an umbrella package to house all Ethereum related modules. + * + * ```ts + * import Web3 from 'web3'; + * + * // "Web3.givenProvider" will be set if in an Ethereum supported browser. + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * > web3.eth + * > web3.utils + * > web3.version + * ``` + * + * ### version + * + * Contains the current package version of the web3.js library. + * + * #### Returns + * //todo enable when functionality added + * // @see Web3.version + * + * ### utils + * + * Static accessible property of the Web3 class and property of the instance as well. + * + * ```ts + * Web3.utils + * web3.utils + * ``` + * + * Utility functions are also exposed on the `Web3` class object diretly. + * + * //todo enable when implemented + * //See details: {@link Web3.utils} + * + * ### setProvider + * + * ```ts + * web3.setProvider(myProvider) + * web3.eth.setProvider(myProvider) + * ... + * ``` + * + * Will change the provider for its module. + * + * **_NOTE:_** When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth etc. + * + * #### Parameters + * `Object` - `myProvider`: a valid provider. + * + * #### Returns + * `Boolean` + * + * See details: {@link Web3.setProvider} + * + * #### Example: Local Geth Node + * ```ts + * import Web3 from "web3"; + * let web3: Web3 = new Web3('http://localhost:8545'); + * // or + * let web3: Web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); + * + * // change provider + * web3.setProvider('ws://localhost:8546'); + * // or + * web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546')); + * + * //todo add IPC provider + * ``` + * + * #### Example: Remote Geth Node + * + * ```ts + * // Using a remote node provider, like Alchemy (https://www.alchemyapi.io/supernode), is simple. + * import Web3 from "web3"; + * let web3: Web3 = new Web3("https://eth-mainnet.alchemyapi.io/v2/your-api-key"); + * ``` + * + * ### providers + * + * ```ts + * web3.providers + * web3.eth.providers + * ``` + * Contains the current available providers. + * + * #### Returns + * `Object` with the following providers: + * + * + * + `Object` - `HttpProvider`: HTTP provider, does not support subscriptions. + * + * + * + `Object` - `WebSocketProvider`: The WebSocket provider is the standard for usage in legacy browsers. + * + * + * + `Object` - `IpcProvider`: The IPC provider is used in node.js dapps when running a local node. Gives the most secure connection. + * + * + * #### Example + * ```ts + * import { Web3 } from 'web3'; + * // use the given Provider or instantiate a new websocket provider + * let web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546'); + * // or + * let web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546')); + * + * // Using the IPC provider in node.js + * import { Web3 } from 'web3'; + * import { IpcProvider } from 'web3-providers-ipc'; + * var web3 = new Web3(new IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc')); // mac os path + * // on windows the path is: "\\\\.\\pipe\\geth.ipc" + * // on linux the path is: "/users/myuser/.ethereum/geth.ipc" + * ``` + * #### Configuration + * + * ```ts + * + * //=== + * //Http + * //=== + * + * import Web3HttpProvider, { HttpProviderOptions } from "web3-providers-http"; + * + * let options: HttpProviderOptions = { + * providerOptions: { + * keepalive: true, + * credentials: "omit", + * headers: { + * "Access-Control-Allow-Origin": "*", + * }, + * }, + * }; + * + * + * var provider = new Web3HttpProvider("http://localhost:8545", options); + * web3.setProvider(provider); + * + * //=== + * //WebSockets + * //=== + * import Web3WsProvider, { + * ClientOptions, + * ClientRequestArgs, + * ReconnectOptions, + * } from "web3-providers-ws"; + * + * + * let clientOptions: ClientOptions = { + * // Useful for credentialed urls, e.g: ws://username:password@localhost:8546 + * headers: { + * authorization: "Basic username:password", + * }, + * maxPayload: 100000000, + * }; + * + * // Enable auto reconnection + * let reconnectOptions: ReconnectOptions = { + * autoReconnect: true, + * delay: 5000, // ms + * maxAttempts: 5, + * }; + * + * //clientOptions and reconnectOptions are optional + * //clientOptions: ClientOptions | ClientRequestArgs + * let ws = new Web3WsProvider( + * "ws://localhost:8546", + * clientOptions, + * reconnectOptions + * ); + * web3.setProvider(ws); + * + * ``` + * More information for the Http and Websocket provider modules can be found here: + * + * + * - {@link HttpProvider} + * + * + * - {@link WebSocketProvider} + * + * See details: {@link Web3.providers} + * + * + * ### givenProvider + * + * ```ts + * web3.givenProvider + * web3.eth.givenProvider + * ... + * ``` + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. + * Will return the given provider by the (browser) environment, otherwise `undefined`. + * + * #### Returns + * `Object` - The given provider set or `undefined`. + * + * See details: {@link Web3.givenProvider} + * + * ### currentProvider + * + * ```ts + * web3.currentProvider + * web3.eth.currentProvider + * ... + * ``` + * Will return the current provider, otherwise `undefined`. + * + * #### Returns + * `Object`: The current provider, otherwise `undefined`. + * + * See details: {@link Web3.currentProvider} + * + * ### BatchRequest + * + * ```ts + * new web3.BatchRequest() + * new web3.BatchRequest() + * ... + * ``` + * Class to create and execute batch requests. + * + * #### Parameters + * none + * + * #### Returns + * `Object`: With the following methods: + * + * + `add(request)`: To add a request object to the batch call. + * + * + `execute()` : To execute the batch request. + * + * #### Example + * ```ts + * let request1: JsonRpcOptionalRequest = { + * id: 10, + * method: 'eth_getBalance', + * params: ["0xdc6bad79dab7ea733098f66f6c6f9dd008da3258", 'latest'], + * }; + * let request2: JsonRpcOptionalRequest = { + * id: 11, + * method: 'eth_getBalance', + * params: ["0x962f9a9c2a6c092474d24def35eccb3d9363265e", 'latest'], + * }; + * + * const batch = new web3.BatchRequest(); + * + * batch.add(request1); + * batch.add(request2); + * // add returns a deferred promise which can be used to run specific code after completion of each respective request. + * //const request2Promise = batch.add(request2); + * + * const response = await batch.execute(); + * ``` + * See details: {@link Web3.BatchRequest} + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ +import Web3 from './web3.js'; +export * from './types.js'; +export default Web3; +/** + * Named exports for all objects which are the default-exported-object in their packages + */ +export { Web3 }; +export { Web3Context, Web3PluginBase, Web3EthPluginBase } from 'web3-core'; +export { Web3Eth } from 'web3-eth'; +export { Contract } from 'web3-eth-contract'; +export { Iban } from 'web3-eth-iban'; +export { Personal } from 'web3-eth-personal'; +export { Net } from 'web3-net'; +export { HttpProvider } from 'web3-providers-http'; +export { WebSocketProvider } from 'web3-providers-ws'; +export { Web3Validator } from 'web3-validator'; +/** + * Export all packages grouped by name spaces + */ +export * as core from 'web3-core'; +export * as errors from 'web3-errors'; +export * as eth from './eth.exports.js'; +export * as net from 'web3-net'; +export * as providers from './providers.exports.js'; +export * as rpcMethods from 'web3-rpc-methods'; +export * as types from 'web3-types'; +export * as utils from 'web3-utils'; +export * as validator from 'web3-validator'; +/** + * Export all types from `web3-types` without a namespace (in addition to being available at `types` namespace). + * To enable the user to write: `function something(): Web3Api` without the need for `types.Web3Api`. + * And the same for `web3-errors`. Because this package contains error classes and constants. + */ +export * from 'web3-errors'; +export * from 'web3-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/index.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/index.d.ts.map new file mode 100644 index 0000000..104f4a3 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgTG;AACH;;GAEG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,cAAc,YAAY,CAAC;AAC3B,eAAe,IAAI,CAAC;AAEpB;;GAEG;AACH,OAAO,EAAE,IAAI,EAAE,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;GAEG;AACH,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,GAAG,MAAM,kBAAkB,CAAC;AACxC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,UAAU,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAC;AAE5C;;;;GAIG;AACH,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/providers.exports.d.ts b/test/merkletreejs/node_modules/web3/lib/types/providers.exports.d.ts new file mode 100644 index 0000000..032fad2 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/providers.exports.d.ts @@ -0,0 +1,4 @@ +export { Eip1193Provider, SocketProvider } from 'web3-utils'; +export * as http from 'web3-providers-http'; +export * as ws from 'web3-providers-ws'; +//# sourceMappingURL=providers.exports.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/providers.exports.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/providers.exports.d.ts.map new file mode 100644 index 0000000..01d0d2f --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/providers.exports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"providers.exports.d.ts","sourceRoot":"","sources":["../../src/providers.exports.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE7D,OAAO,KAAK,IAAI,MAAM,qBAAqB,CAAC;AAC5C,OAAO,KAAK,EAAE,MAAM,mBAAmB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/types.d.ts b/test/merkletreejs/node_modules/web3/lib/types/types.d.ts new file mode 100644 index 0000000..fa40171 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/types.d.ts @@ -0,0 +1,54 @@ +import { Bytes, Transaction } from 'web3-types'; +import Eth from 'web3-eth'; +import { decodeLog, decodeParameter, decodeParameters, encodeFunctionCall, encodeFunctionSignature, encodeParameter, encodeParameters } from 'web3-eth-abi'; +import { encrypt, hashMessage, recover, recoverTransaction, sign, signTransaction, Wallet, Web3Account } from 'web3-eth-accounts'; +import { Contract } from 'web3-eth-contract'; +import { ENS } from 'web3-eth-ens'; +import { Net } from 'web3-net'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; +/** + * The Ethereum interface for main web3 object. It provides extra methods in addition to `web3-eth` interface. + * + * {@link web3_eth.Web3Eth} for details about the `Eth` interface. + */ +export interface Web3EthInterface extends Eth { + /** + * Extended [Contract](/api/web3-eth-contract/class/Contract) constructor for main `web3` object. See [Contract](/api/web3-eth-contract/class/Contract) for further details. + * + * You can use `.setProvider` on this constructor to set provider for **all the instances** of the contracts which were created by `web3.eth.Contract`. + * Please check the {@doclink guides/web3_upgrade_guide/x/providers_migration_guide | following guide} to understand more about setting provider. + * + * ```ts + * web3.eth.Contract.setProvider(myProvider) + * ``` + */ + Contract: typeof Contract; + Iban: typeof Iban; + net: Net; + ens: ENS; + abi: { + encodeEventSignature: typeof encodeFunctionSignature; + encodeFunctionCall: typeof encodeFunctionCall; + encodeFunctionSignature: typeof encodeFunctionSignature; + encodeParameter: typeof encodeParameter; + encodeParameters: typeof encodeParameters; + decodeParameter: typeof decodeParameter; + decodeParameters: typeof decodeParameters; + decodeLog: typeof decodeLog; + }; + accounts: { + create: () => Web3Account; + privateKeyToAccount: (privateKey: Uint8Array | string) => Web3Account; + signTransaction: (transaction: Transaction, privateKey: Bytes) => ReturnType; + recoverTransaction: typeof recoverTransaction; + hashMessage: typeof hashMessage; + sign: typeof sign; + recover: typeof recover; + encrypt: typeof encrypt; + decrypt: (keystore: string, password: string, options?: Record) => Promise; + wallet: Wallet; + }; + personal: Personal; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/types.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/types.d.ts.map new file mode 100644 index 0000000..16698c0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,EACN,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,uBAAuB,EACvB,eAAe,EACf,gBAAgB,EAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EACN,OAAO,EACP,WAAW,EACX,OAAO,EACP,kBAAkB,EAClB,IAAI,EACJ,eAAe,EACf,MAAM,EACN,WAAW,EACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAE7C;;;;GAIG;AACH,MAAM,WAAW,gBAAiB,SAAQ,GAAG;IAC5C;;;;;;;;;OASG;IACH,QAAQ,EAAE,OAAO,QAAQ,CAAC;IAC1B,IAAI,EAAE,OAAO,IAAI,CAAC;IAClB,GAAG,EAAE,GAAG,CAAC;IACT,GAAG,EAAE,GAAG,CAAC;IACT,GAAG,EAAE;QACJ,oBAAoB,EAAE,OAAO,uBAAuB,CAAC;QACrD,kBAAkB,EAAE,OAAO,kBAAkB,CAAC;QAC9C,uBAAuB,EAAE,OAAO,uBAAuB,CAAC;QACxD,eAAe,EAAE,OAAO,eAAe,CAAC;QACxC,gBAAgB,EAAE,OAAO,gBAAgB,CAAC;QAC1C,eAAe,EAAE,OAAO,eAAe,CAAC;QACxC,gBAAgB,EAAE,OAAO,gBAAgB,CAAC;QAC1C,SAAS,EAAE,OAAO,SAAS,CAAC;KAC5B,CAAC;IACF,QAAQ,EAAE;QACT,MAAM,EAAE,MAAM,WAAW,CAAC;QAC1B,mBAAmB,EAAE,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,KAAK,WAAW,CAAC;QACtE,eAAe,EAAE,CAChB,WAAW,EAAE,WAAW,EACxB,UAAU,EAAE,KAAK,KACb,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;QACxC,kBAAkB,EAAE,OAAO,kBAAkB,CAAC;QAC9C,WAAW,EAAE,OAAO,WAAW,CAAC;QAChC,IAAI,EAAE,OAAO,IAAI,CAAC;QAClB,OAAO,EAAE,OAAO,OAAO,CAAC;QACxB,OAAO,EAAE,OAAO,OAAO,CAAC;QACxB,OAAO,EAAE,CACR,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,OAAO,CAAC,WAAW,CAAC,CAAC;QAC1B,MAAM,EAAE,MAAM,CAAC;KACf,CAAC;IACF,QAAQ,EAAE,QAAQ,CAAC;CACnB"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/version.d.ts b/test/merkletreejs/node_modules/web3/lib/types/version.d.ts new file mode 100644 index 0000000..7b26d4b --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/version.d.ts @@ -0,0 +1,4 @@ +export declare const Web3PkgInfo: { + version: string; +}; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/version.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/version.d.ts.map new file mode 100644 index 0000000..96473ee --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAmC,eAAO,MAAM,WAAW;;CAAuB,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/web3.d.ts b/test/merkletreejs/node_modules/web3/lib/types/web3.d.ts new file mode 100644 index 0000000..580e40e --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/web3.d.ts @@ -0,0 +1,27 @@ +import { Web3Context, Web3ContextInitOptions, Web3SubscriptionConstructor } from 'web3-core'; +import { Web3Eth, RegisteredSubscription } from 'web3-eth'; +import { ENS } from 'web3-eth-ens'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; +import { Net } from 'web3-net'; +import * as utils from 'web3-utils'; +import { EthExecutionAPI, SupportedProviders } from 'web3-types'; +import { Web3EthInterface } from './types.js'; +export declare class Web3; +} = RegisteredSubscription> extends Web3Context { + static version: string; + static utils: typeof utils; + static modules: { + Web3Eth: typeof Web3Eth; + Iban: typeof Iban; + Net: typeof Net; + ENS: typeof ENS; + Personal: typeof Personal; + }; + utils: typeof utils; + eth: Web3EthInterface; + constructor(providerOrContext?: string | SupportedProviders | Web3ContextInitOptions); +} +export default Web3; +//# sourceMappingURL=web3.d.ts.map \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/lib/types/web3.d.ts.map b/test/merkletreejs/node_modules/web3/lib/types/web3.d.ts.map new file mode 100644 index 0000000..debc9a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/lib/types/web3.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web3.d.ts","sourceRoot":"","sources":["../../src/web3.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,WAAW,EACX,sBAAsB,EAEtB,2BAA2B,EAE3B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,OAAO,EAAE,sBAAsB,EAA2B,MAAM,UAAU,CAAC;AAEpF,OAAO,EAAE,GAAG,EAAqB,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AAEpC,OAAO,EAIN,eAAe,EACf,kBAAkB,EAGlB,MAAM,YAAY,CAAC;AAIpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAG9C,qBAAa,IAAI,CAChB,4BAA4B,SAAS;IACpC,CAAC,GAAG,EAAE,MAAM,GAAG,2BAA2B,CAAC,eAAe,CAAC,CAAC;CAC5D,GAAG,sBAAsB,CACzB,SAAQ,WAAW,CAAC,eAAe,EAAE,4BAA4B,GAAG,sBAAsB,CAAC;IAC5F,OAAc,OAAO,SAAuB;IAC5C,OAAc,KAAK,eAAS;IAC5B,OAAc,OAAO;;;;;;MAMnB;IAEK,KAAK,EAAE,OAAO,KAAK,CAAC;IAEpB,GAAG,EAAE,gBAAgB,CAAC;gBAG5B,iBAAiB,CAAC,EACf,MAAM,GACN,kBAAkB,CAAC,eAAe,CAAC,GACnC,sBAAsB,CAAC,eAAe,EAAE,4BAA4B,CAAC;CAoJzE;AACD,eAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/test/merkletreejs/node_modules/web3/package.json b/test/merkletreejs/node_modules/web3/package.json new file mode 100644 index 0000000..1c59841 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/package.json @@ -0,0 +1,104 @@ +{ + "name": "web3", + "version": "4.3.0", + "description": "Ethereum JavaScript API", + "main": "./lib/commonjs/index.js", + "module": "./lib/esm/index.js", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/commonjs/index.js" + } + }, + "repository": "https://github.com/ChainSafe/web3.js", + "engines": { + "node": ">=14.0.0", + "npm": ">=6.12.0" + }, + "author": "ChainSafe Systems", + "browser": "./dist/web3.min.js", + "license": "LGPL-3.0", + "keywords": [ + "Ethereum", + "JavaScript", + "API" + ], + "files": [ + "lib/**/*", + "src/**/*", + "dist/**/*" + ], + "scripts": { + "clean": "rimraf dist && rimraf lib", + "prebuild": "yarn clean", + "version:output": "[ -z $npm_package_version ] && rm ./src/version.ts || echo \"/* eslint-disable header/header */ export const Web3PkgInfo = { version: '$npm_package_version' };\" > ./src/version.ts", + "build": "yarn version:output && concurrently --kill-others-on-fail \"yarn:build:*(!web|check)\"", + "build:cjs": "tsc --build tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > ./lib/commonjs/package.json", + "build:esm": "tsc --build tsconfig.esm.json && echo '{\"type\": \"module\"}' > ./lib/esm/package.json", + "build:types": "tsc --build tsconfig.types.json", + "build:web": "npx webpack", + "build:web:analyze": "npx webpack --config ./webpack.analyze.js", + "build:check": "node -e \"require('./lib')\"", + "lint": "eslint --ext .js,.ts .", + "lint:fix": "eslint --fix --ext .js,.ts .", + "format": "prettier --write '**/*'", + "test": "jest --config=./test/unit/jest.config.js", + "test:coverage:unit": "jest --config=./test/unit/jest.config.js --coverage=true --coverage-reporters=text", + "test:coverage:integration": "jest --config=./test/integration/jest.config.js --forceExit --coverage=true --coverage-reporters=text", + "test:e2e:mainnet": "jest --config=./test/e2e/jest.config.js --forceExit", + "test:e2e:sepolia": "jest --config=./test/e2e/jest.config.js --forceExit", + "test:sync:integration": "jest --config=./test/integration/jest.config.js ./test/integration/sync.test.ts", + "test:ci": "jest --coverage=true --coverage-reporters=json --verbose", + "test:watch": "npm test -- --watch", + "test:unit": "jest --config=./test/unit/jest.config.js", + "test:integration": "jest --config=./test/integration/jest.config.js --forceExit", + "test:integration:stress": "jest --config=./test/stress/jest.config.js --forceExit", + "test:blackbox:ganache:http": "./scripts/black_box_test.sh ganache http", + "test:blackbox:ganache:ws": "./scripts/black_box_test.sh ganache ws", + "test:blackbox:geth:http": "./scripts/black_box_test.sh geth http", + "test:blackbox:geth:ws": "./scripts/black_box_test.sh geth ws", + "test:blackbox:infura:http": "./scripts/black_box_test.sh infura http", + "test:blackbox:infura:ws": "./scripts/black_box_test.sh infura ws", + "test:e2e:chrome:stress": "npx cypress run --headless --browser chrome" + }, + "devDependencies": { + "@truffle/hdwallet-provider": "^2.0.12", + "@types/jest": "^28.1.6", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-base-web3": "0.1.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "ethereum-cryptography": "^2.1.2", + "ganache": "^7.5.0", + "hardhat": "^2.12.2", + "in3": "^3.3.3", + "jest": "^28.1.3", + "jest-extended": "^3.0.1", + "prettier": "^2.7.1", + "ts-jest": "^28.0.7", + "typescript": "^4.7.4", + "web3-providers-ipc": "^4.0.7" + }, + "dependencies": { + "web3-core": "^4.3.2", + "web3-errors": "^1.1.4", + "web3-eth": "^4.3.1", + "web3-eth-abi": "^4.1.4", + "web3-eth-accounts": "^4.1.0", + "web3-eth-contract": "^4.1.4", + "web3-eth-ens": "^4.0.8", + "web3-eth-iban": "^4.0.7", + "web3-eth-personal": "^4.0.8", + "web3-net": "^4.0.7", + "web3-providers-http": "^4.1.0", + "web3-providers-ws": "^4.0.7", + "web3-rpc-methods": "^1.1.4", + "web3-types": "^1.3.1", + "web3-utils": "^4.1.0", + "web3-validator": "^2.0.3" + }, + "gitHead": "b9b5fe0210da1a4ebf62e2b54f37a9c747bfa136" +} diff --git a/test/merkletreejs/node_modules/web3/src/abi.ts b/test/merkletreejs/node_modules/web3/src/abi.ts new file mode 100644 index 0000000..5abe753 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/abi.ts @@ -0,0 +1,41 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { + decodeLog, + decodeParameter, + decodeParameters, + encodeEventSignature, + encodeFunctionCall, + encodeFunctionSignature, + encodeParameter, + encodeParameters, +} from 'web3-eth-abi'; + +/** + * The object for `web3.abi` + */ +export default { + encodeEventSignature, + encodeFunctionCall, + encodeFunctionSignature, + encodeParameter, + encodeParameters, + decodeParameter, + decodeParameters, + decodeLog, +}; diff --git a/test/merkletreejs/node_modules/web3/src/accounts.ts b/test/merkletreejs/node_modules/web3/src/accounts.ts new file mode 100644 index 0000000..b0c2765 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/accounts.ts @@ -0,0 +1,109 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { EthExecutionAPI, Bytes, Transaction, KeyStore, ETH_DATA_FORMAT } from 'web3-types'; +import { format } from 'web3-utils'; +import { Web3Context } from 'web3-core'; +import { prepareTransactionForSigning } from 'web3-eth'; +import { + create, + decrypt, + encrypt, + hashMessage, + privateKeyToAccount, + recover, + recoverTransaction, + signTransaction, + sign, + Wallet, + privateKeyToAddress, + parseAndValidatePrivateKey, + privateKeyToPublicKey, +} from 'web3-eth-accounts'; + +/** + * Initialize the accounts module for the given context. + * + * To avoid multiple package dependencies for `web3-eth-accounts` we are creating + * this function in `web3` package. In future the actual `web3-eth-accounts` package + * should be converted to context aware. + */ +export const initAccountsForContext = (context: Web3Context) => { + const signTransactionWithContext = async (transaction: Transaction, privateKey: Bytes) => { + const tx = await prepareTransactionForSigning(transaction, context); + + const privateKeyBytes = format({ format: 'bytes' }, privateKey, ETH_DATA_FORMAT); + + return signTransaction(tx, privateKeyBytes); + }; + + const privateKeyToAccountWithContext = (privateKey: Uint8Array | string) => { + const account = privateKeyToAccount(privateKey); + + return { + ...account, + signTransaction: async (transaction: Transaction) => + signTransactionWithContext(transaction, account.privateKey), + }; + }; + + const decryptWithContext = async ( + keystore: KeyStore | string, + password: string, + options?: Record, + ) => { + const account = await decrypt(keystore, password, (options?.nonStrict as boolean) ?? true); + + return { + ...account, + signTransaction: async (transaction: Transaction) => + signTransactionWithContext(transaction, account.privateKey), + }; + }; + + const createWithContext = () => { + const account = create(); + + return { + ...account, + signTransaction: async (transaction: Transaction) => + signTransactionWithContext(transaction, account.privateKey), + }; + }; + + const wallet = new Wallet({ + create: createWithContext, + privateKeyToAccount: privateKeyToAccountWithContext, + decrypt: decryptWithContext, + }); + + return { + signTransaction: signTransactionWithContext, + create: createWithContext, + privateKeyToAccount: privateKeyToAccountWithContext, + decrypt: decryptWithContext, + recoverTransaction, + hashMessage, + sign, + recover, + encrypt, + wallet, + privateKeyToAddress, + parseAndValidatePrivateKey, + privateKeyToPublicKey, + } +}; diff --git a/test/merkletreejs/node_modules/web3/src/eth.exports.ts b/test/merkletreejs/node_modules/web3/src/eth.exports.ts new file mode 100644 index 0000000..8b37f03 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/eth.exports.ts @@ -0,0 +1,25 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export * from 'web3-eth'; + +export * as abi from 'web3-eth-abi'; +export * as accounts from 'web3-eth-accounts'; +export * as contract from 'web3-eth-contract'; +export * as ens from 'web3-eth-ens'; +export * as personal from 'web3-eth-personal'; +export * as iban from 'web3-eth-iban'; diff --git a/test/merkletreejs/node_modules/web3/src/index.ts b/test/merkletreejs/node_modules/web3/src/index.ts new file mode 100644 index 0000000..0fcc8a1 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/index.ts @@ -0,0 +1,365 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +/** + * This is the main (or 'umbrella') class of the web3.js library. + * + * ```ts + * import Web3 from 'web3'; + * + * > Web3.utils + * > Web3.version + * > Web3.givenProvider + * > Web3.providers + * > Web3.modules + * ``` + * + * # Web3.modules + * + * ```ts + * Web3.modules + * ``` + * + * Will return an object with the classes of all major sub modules, to be able to instantiate them manually. + * + * #### Returns + * + * `Object` A list of module constructors: + * + * + * + `Eth` - `Constructor`: The Eth module for interacting with the Ethereum network + * + * + * + `Net` - `Constructor`: The Net module for interacting with network properties. + * + * + * + `Personal` - `constructor`: The Personal module for interacting with the Ethereum accounts (web3.eth.personal). + * + * #### Example + * + * ```ts + * Web3.modules + * > { + * Eth: Eth(provider), + * Net: Net(provider), + * Personal: Personal(provider), + * } + * ``` + * + * See details: {@link Web3.modules} + * + * # Web3 Instance + * + * The Web3 class is an umbrella package to house all Ethereum related modules. + * + * ```ts + * import Web3 from 'web3'; + * + * // "Web3.givenProvider" will be set if in an Ethereum supported browser. + * const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546'); + * + * > web3.eth + * > web3.utils + * > web3.version + * ``` + * + * ### version + * + * Contains the current package version of the web3.js library. + * + * #### Returns + * //todo enable when functionality added + * // @see Web3.version + * + * ### utils + * + * Static accessible property of the Web3 class and property of the instance as well. + * + * ```ts + * Web3.utils + * web3.utils + * ``` + * + * Utility functions are also exposed on the `Web3` class object diretly. + * + * //todo enable when implemented + * //See details: {@link Web3.utils} + * + * ### setProvider + * + * ```ts + * web3.setProvider(myProvider) + * web3.eth.setProvider(myProvider) + * ... + * ``` + * + * Will change the provider for its module. + * + * **_NOTE:_** When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth etc. + * + * #### Parameters + * `Object` - `myProvider`: a valid provider. + * + * #### Returns + * `Boolean` + * + * See details: {@link Web3.setProvider} + * + * #### Example: Local Geth Node + * ```ts + * import Web3 from "web3"; + * let web3: Web3 = new Web3('http://localhost:8545'); + * // or + * let web3: Web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); + * + * // change provider + * web3.setProvider('ws://localhost:8546'); + * // or + * web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546')); + * + * //todo add IPC provider + * ``` + * + * #### Example: Remote Geth Node + * + * ```ts + * // Using a remote node provider, like Alchemy (https://www.alchemyapi.io/supernode), is simple. + * import Web3 from "web3"; + * let web3: Web3 = new Web3("https://eth-mainnet.alchemyapi.io/v2/your-api-key"); + * ``` + * + * ### providers + * + * ```ts + * web3.providers + * web3.eth.providers + * ``` + * Contains the current available providers. + * + * #### Returns + * `Object` with the following providers: + * + * + * + `Object` - `HttpProvider`: HTTP provider, does not support subscriptions. + * + * + * + `Object` - `WebSocketProvider`: The WebSocket provider is the standard for usage in legacy browsers. + * + * + * + `Object` - `IpcProvider`: The IPC provider is used in node.js dapps when running a local node. Gives the most secure connection. + * + * + * #### Example + * ```ts + * import { Web3 } from 'web3'; + * // use the given Provider or instantiate a new websocket provider + * let web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546'); + * // or + * let web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546')); + * + * // Using the IPC provider in node.js + * import { Web3 } from 'web3'; + * import { IpcProvider } from 'web3-providers-ipc'; + * var web3 = new Web3(new IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc')); // mac os path + * // on windows the path is: "\\\\.\\pipe\\geth.ipc" + * // on linux the path is: "/users/myuser/.ethereum/geth.ipc" + * ``` + * #### Configuration + * + * ```ts + * + * //=== + * //Http + * //=== + * + * import Web3HttpProvider, { HttpProviderOptions } from "web3-providers-http"; + * + * let options: HttpProviderOptions = { + * providerOptions: { + * keepalive: true, + * credentials: "omit", + * headers: { + * "Access-Control-Allow-Origin": "*", + * }, + * }, + * }; + * + * + * var provider = new Web3HttpProvider("http://localhost:8545", options); + * web3.setProvider(provider); + * + * //=== + * //WebSockets + * //=== + * import Web3WsProvider, { + * ClientOptions, + * ClientRequestArgs, + * ReconnectOptions, + * } from "web3-providers-ws"; + * + * + * let clientOptions: ClientOptions = { + * // Useful for credentialed urls, e.g: ws://username:password@localhost:8546 + * headers: { + * authorization: "Basic username:password", + * }, + * maxPayload: 100000000, + * }; + * + * // Enable auto reconnection + * let reconnectOptions: ReconnectOptions = { + * autoReconnect: true, + * delay: 5000, // ms + * maxAttempts: 5, + * }; + * + * //clientOptions and reconnectOptions are optional + * //clientOptions: ClientOptions | ClientRequestArgs + * let ws = new Web3WsProvider( + * "ws://localhost:8546", + * clientOptions, + * reconnectOptions + * ); + * web3.setProvider(ws); + * + * ``` + * More information for the Http and Websocket provider modules can be found here: + * + * + * - {@link HttpProvider} + * + * + * - {@link WebSocketProvider} + * + * See details: {@link Web3.providers} + * + * + * ### givenProvider + * + * ```ts + * web3.givenProvider + * web3.eth.givenProvider + * ... + * ``` + * When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. + * Will return the given provider by the (browser) environment, otherwise `undefined`. + * + * #### Returns + * `Object` - The given provider set or `undefined`. + * + * See details: {@link Web3.givenProvider} + * + * ### currentProvider + * + * ```ts + * web3.currentProvider + * web3.eth.currentProvider + * ... + * ``` + * Will return the current provider, otherwise `undefined`. + * + * #### Returns + * `Object`: The current provider, otherwise `undefined`. + * + * See details: {@link Web3.currentProvider} + * + * ### BatchRequest + * + * ```ts + * new web3.BatchRequest() + * new web3.BatchRequest() + * ... + * ``` + * Class to create and execute batch requests. + * + * #### Parameters + * none + * + * #### Returns + * `Object`: With the following methods: + * + * + `add(request)`: To add a request object to the batch call. + * + * + `execute()` : To execute the batch request. + * + * #### Example + * ```ts + * let request1: JsonRpcOptionalRequest = { + * id: 10, + * method: 'eth_getBalance', + * params: ["0xdc6bad79dab7ea733098f66f6c6f9dd008da3258", 'latest'], + * }; + * let request2: JsonRpcOptionalRequest = { + * id: 11, + * method: 'eth_getBalance', + * params: ["0x962f9a9c2a6c092474d24def35eccb3d9363265e", 'latest'], + * }; + * + * const batch = new web3.BatchRequest(); + * + * batch.add(request1); + * batch.add(request2); + * // add returns a deferred promise which can be used to run specific code after completion of each respective request. + * //const request2Promise = batch.add(request2); + * + * const response = await batch.execute(); + * ``` + * See details: {@link Web3.BatchRequest} + */ +/** + * This comment _supports3_ [Markdown](https://marked.js.org/) + */ + +import Web3 from './web3.js'; + +export * from './types.js'; +export default Web3; + +/** + * Named exports for all objects which are the default-exported-object in their packages + */ +export { Web3 }; +export { Web3Context, Web3PluginBase, Web3EthPluginBase } from 'web3-core'; +export { Web3Eth } from 'web3-eth'; +export { Contract } from 'web3-eth-contract'; +export { Iban } from 'web3-eth-iban'; +export { Personal } from 'web3-eth-personal'; +export { Net } from 'web3-net'; +export { HttpProvider } from 'web3-providers-http'; +export { WebSocketProvider } from 'web3-providers-ws'; +export { Web3Validator } from 'web3-validator'; + +/** + * Export all packages grouped by name spaces + */ +export * as core from 'web3-core'; +export * as errors from 'web3-errors'; +export * as eth from './eth.exports.js'; +export * as net from 'web3-net'; +export * as providers from './providers.exports.js'; +export * as rpcMethods from 'web3-rpc-methods'; +export * as types from 'web3-types'; +export * as utils from 'web3-utils'; +export * as validator from 'web3-validator'; + +/** + * Export all types from `web3-types` without a namespace (in addition to being available at `types` namespace). + * To enable the user to write: `function something(): Web3Api` without the need for `types.Web3Api`. + * And the same for `web3-errors`. Because this package contains error classes and constants. + */ +export * from 'web3-errors'; +export * from 'web3-types'; diff --git a/test/merkletreejs/node_modules/web3/src/providers.exports.ts b/test/merkletreejs/node_modules/web3/src/providers.exports.ts new file mode 100644 index 0000000..c0bbadc --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/providers.exports.ts @@ -0,0 +1,21 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +export { Eip1193Provider, SocketProvider } from 'web3-utils'; + +export * as http from 'web3-providers-http'; +export * as ws from 'web3-providers-ws'; diff --git a/test/merkletreejs/node_modules/web3/src/types.ts b/test/merkletreejs/node_modules/web3/src/types.ts new file mode 100644 index 0000000..fb14e6b --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/types.ts @@ -0,0 +1,95 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ + +import { Bytes, Transaction } from 'web3-types'; +import Eth from 'web3-eth'; +import { + decodeLog, + decodeParameter, + decodeParameters, + encodeFunctionCall, + encodeFunctionSignature, + encodeParameter, + encodeParameters, +} from 'web3-eth-abi'; +import { + encrypt, + hashMessage, + recover, + recoverTransaction, + sign, + signTransaction, + Wallet, + Web3Account, +} from 'web3-eth-accounts'; +import { Contract } from 'web3-eth-contract'; +import { ENS } from 'web3-eth-ens'; +import { Net } from 'web3-net'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; + +/** + * The Ethereum interface for main web3 object. It provides extra methods in addition to `web3-eth` interface. + * + * {@link web3_eth.Web3Eth} for details about the `Eth` interface. + */ +export interface Web3EthInterface extends Eth { + /** + * Extended [Contract](/api/web3-eth-contract/class/Contract) constructor for main `web3` object. See [Contract](/api/web3-eth-contract/class/Contract) for further details. + * + * You can use `.setProvider` on this constructor to set provider for **all the instances** of the contracts which were created by `web3.eth.Contract`. + * Please check the {@doclink guides/web3_upgrade_guide/x/providers_migration_guide | following guide} to understand more about setting provider. + * + * ```ts + * web3.eth.Contract.setProvider(myProvider) + * ``` + */ + Contract: typeof Contract; + Iban: typeof Iban; + net: Net; + ens: ENS; + abi: { + encodeEventSignature: typeof encodeFunctionSignature; + encodeFunctionCall: typeof encodeFunctionCall; + encodeFunctionSignature: typeof encodeFunctionSignature; + encodeParameter: typeof encodeParameter; + encodeParameters: typeof encodeParameters; + decodeParameter: typeof decodeParameter; + decodeParameters: typeof decodeParameters; + decodeLog: typeof decodeLog; + }; + accounts: { + create: () => Web3Account; + privateKeyToAccount: (privateKey: Uint8Array | string) => Web3Account; + signTransaction: ( + transaction: Transaction, + privateKey: Bytes, + ) => ReturnType; + recoverTransaction: typeof recoverTransaction; + hashMessage: typeof hashMessage; + sign: typeof sign; + recover: typeof recover; + encrypt: typeof encrypt; + decrypt: ( + keystore: string, + password: string, + options?: Record, + ) => Promise; + wallet: Wallet; + }; + personal: Personal; +} diff --git a/test/merkletreejs/node_modules/web3/src/version.ts b/test/merkletreejs/node_modules/web3/src/version.ts new file mode 100644 index 0000000..b90de90 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/version.ts @@ -0,0 +1 @@ +/* eslint-disable header/header */ export const Web3PkgInfo = { version: '4.3.0' }; diff --git a/test/merkletreejs/node_modules/web3/src/web3.ts b/test/merkletreejs/node_modules/web3/src/web3.ts new file mode 100644 index 0000000..e6d52e0 --- /dev/null +++ b/test/merkletreejs/node_modules/web3/src/web3.ts @@ -0,0 +1,220 @@ +/* +This file is part of web3.js. + +web3.js is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +web3.js is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with web3.js. If not, see . +*/ +// eslint-disable-next-line max-classes-per-file +import { + Web3Context, + Web3ContextInitOptions, + Web3ContextObject, + Web3SubscriptionConstructor, + isSupportedProvider +} from 'web3-core'; +import { Web3Eth, RegisteredSubscription, registeredSubscriptions } from 'web3-eth'; +import Contract from 'web3-eth-contract'; +import { ENS, registryAddresses } from 'web3-eth-ens'; +import { Iban } from 'web3-eth-iban'; +import { Personal } from 'web3-eth-personal'; +import { Net } from 'web3-net'; +import * as utils from 'web3-utils'; +import { isNullish, isDataFormat, isContractInitOptions } from 'web3-utils'; +import { + Address, + ContractAbi, + ContractInitOptions, + EthExecutionAPI, + SupportedProviders, + DataFormat, + DEFAULT_RETURN_FORMAT +} from 'web3-types'; +import { InvalidMethodParamsError } from 'web3-errors'; +import abi from './abi.js'; +import { initAccountsForContext } from './accounts.js'; +import { Web3EthInterface } from './types.js'; +import { Web3PkgInfo } from './version.js'; + +export class Web3< + CustomRegisteredSubscription extends { + [key: string]: Web3SubscriptionConstructor; + } = RegisteredSubscription, +> extends Web3Context { + public static version = Web3PkgInfo.version; + public static utils = utils; + public static modules = { + Web3Eth, + Iban, + Net, + ENS, + Personal, + }; + + public utils: typeof utils; + + public eth: Web3EthInterface; + + public constructor( + providerOrContext?: + | string + | SupportedProviders + | Web3ContextInitOptions, + ) { + if ( + isNullish(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() === '') || + (typeof providerOrContext !== 'string' && + !isSupportedProvider(providerOrContext as SupportedProviders) && + !(providerOrContext as Web3ContextInitOptions).provider) + ) { + console.warn( + 'NOTE: web3.js is running without provider. You need to pass a provider in order to interact with the network!', + ); + } + + let contextInitOptions: Web3ContextInitOptions = {}; + if ( + typeof providerOrContext === 'string' || + isSupportedProvider(providerOrContext as SupportedProviders) + ) { + contextInitOptions.provider = providerOrContext as + | undefined + | string + | SupportedProviders; + } else if (providerOrContext) { + contextInitOptions = providerOrContext as Web3ContextInitOptions; + } else { + contextInitOptions = {}; + } + + contextInitOptions.registeredSubscriptions = { + // all the Eth standard subscriptions + ...registeredSubscriptions, + // overridden and combined with any custom subscriptions + ...(contextInitOptions.registeredSubscriptions ?? {}), + } as CustomRegisteredSubscription; + + super(contextInitOptions); + const accounts = initAccountsForContext(this); + + // Init protected properties + this._wallet = accounts.wallet; + this._accountProvider = accounts; + + this.utils = utils; + + // Have to use local alias to initiate contract context + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + + class ContractBuilder extends Contract { + public constructor(jsonInterface: Abi); + public constructor(jsonInterface: Abi, + addressOrOptionsOrContext?: Address | ContractInitOptions | Web3Context, + ); + public constructor( + jsonInterface: Abi, + addressOrOptionsOrContext?: Address | ContractInitOptions | Web3Context, + optionsOrContextOrReturnFormat?: ContractInitOptions | Web3Context | DataFormat, + ); + public constructor(jsonInterface: Abi, + addressOrOptionsOrContext?: Address | ContractInitOptions, + optionsOrContextOrReturnFormat?: ContractInitOptions, + contextOrReturnFormat?: Web3Context | DataFormat, + ); + public constructor(jsonInterface: Abi, + addressOrOptionsOrContext?: Address | ContractInitOptions, + optionsOrContextOrReturnFormat?: ContractInitOptions, + contextOrReturnFormat?: Web3Context | DataFormat, + ); + public constructor(jsonInterface: Abi, + addressOrOptionsOrContext?: Address | ContractInitOptions, + optionsOrContextOrReturnFormat?: ContractInitOptions, + contextOrReturnFormat?: Web3Context | DataFormat, + returnFormat?: DataFormat + ) + { + if (isContractInitOptions(addressOrOptionsOrContext) && isContractInitOptions(optionsOrContextOrReturnFormat)) { + throw new InvalidMethodParamsError( + 'Should not provide options at both 2nd and 3rd parameters', + ); + } + let address: string | undefined; + let options: object = {}; + let context: Web3ContextObject; + let dataFormat: DataFormat = DEFAULT_RETURN_FORMAT; + + // add validation so its not a breaking change + if (!isNullish(addressOrOptionsOrContext) && typeof addressOrOptionsOrContext !== 'object' && typeof addressOrOptionsOrContext !== 'string') { + throw new InvalidMethodParamsError(); + } + + if (typeof addressOrOptionsOrContext === 'string') { + address = addressOrOptionsOrContext; + } + if (isContractInitOptions(addressOrOptionsOrContext)){ + options = addressOrOptionsOrContext as object; + } else if (isContractInitOptions(optionsOrContextOrReturnFormat)) { + options = optionsOrContextOrReturnFormat as object; + } else { + options = {} + } + + if (addressOrOptionsOrContext instanceof Web3Context) { + context = addressOrOptionsOrContext; + } else if (optionsOrContextOrReturnFormat instanceof Web3Context) { + context = optionsOrContextOrReturnFormat; + } else if (contextOrReturnFormat instanceof Web3Context) { + context = contextOrReturnFormat; + } else { + context = self.getContextObject() as Web3ContextObject; + } + + if (returnFormat){ + dataFormat = returnFormat; + } else if (isDataFormat(optionsOrContextOrReturnFormat)) { + dataFormat = optionsOrContextOrReturnFormat as DataFormat; + } else if (isDataFormat(contextOrReturnFormat)) { + dataFormat = contextOrReturnFormat; + } + + super(jsonInterface,address, options, context, dataFormat) + super.subscribeToContextEvents(self); + } + } + + const eth = self.use(Web3Eth); + + // Eth Module + this.eth = Object.assign(eth, { + // ENS module + ens: self.use(ENS, registryAddresses.main), // registry address defaults to main network + + // Iban helpers + Iban, + + net: self.use(Net), + personal: self.use(Personal), + + // Contract helper and module + Contract: ContractBuilder, + + // ABI Helpers + abi, + + // Accounts helper + accounts, + }); + } +} +export default Web3; diff --git a/test/merkletreejs/node_modules/webidl-conversions/LICENSE.md b/test/merkletreejs/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000..d4a994f --- /dev/null +++ b/test/merkletreejs/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/test/merkletreejs/node_modules/webidl-conversions/README.md b/test/merkletreejs/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000..3657890 --- /dev/null +++ b/test/merkletreejs/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/test/merkletreejs/node_modules/webidl-conversions/lib/index.js b/test/merkletreejs/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000..c5153a3 --- /dev/null +++ b/test/merkletreejs/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/test/merkletreejs/node_modules/webidl-conversions/package.json b/test/merkletreejs/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000..c31bc07 --- /dev/null +++ b/test/merkletreejs/node_modules/webidl-conversions/package.json @@ -0,0 +1,23 @@ +{ + "name": "webidl-conversions", + "version": "3.0.1", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "test": "mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "mocha": "^1.21.4" + } +} diff --git a/test/merkletreejs/node_modules/whatwg-url/LICENSE.txt b/test/merkletreejs/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000..54dfac3 --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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. diff --git a/test/merkletreejs/node_modules/whatwg-url/README.md b/test/merkletreejs/node_modules/whatwg-url/README.md new file mode 100644 index 0000000..4347a7f --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/README.md @@ -0,0 +1,67 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). + +## Current Status + +whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). + +## API + +### The `URL` Constructor + +The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. diff --git a/test/merkletreejs/node_modules/whatwg-url/lib/URL-impl.js b/test/merkletreejs/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 0000000..dc7452c --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,200 @@ +"use strict"; +const usm = require("./url-state-machine"); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/test/merkletreejs/node_modules/whatwg-url/lib/URL.js b/test/merkletreejs/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 0000000..78c7207 --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,196 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); +const Impl = require(".//URL-impl.js"); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + diff --git a/test/merkletreejs/node_modules/whatwg-url/lib/public-api.js b/test/merkletreejs/node_modules/whatwg-url/lib/public-api.js new file mode 100644 index 0000000..932dcad --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/lib/public-api.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.URL = require("./URL").interface; +exports.serializeURL = require("./url-state-machine").serializeURL; +exports.serializeURLOrigin = require("./url-state-machine").serializeURLOrigin; +exports.basicURLParse = require("./url-state-machine").basicURLParse; +exports.setTheUsername = require("./url-state-machine").setTheUsername; +exports.setThePassword = require("./url-state-machine").setThePassword; +exports.serializeHost = require("./url-state-machine").serializeHost; +exports.serializeInteger = require("./url-state-machine").serializeInteger; +exports.parseURL = require("./url-state-machine").parseURL; diff --git a/test/merkletreejs/node_modules/whatwg-url/lib/url-state-machine.js b/test/merkletreejs/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 0000000..c25dbc2 --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1297 @@ +"use strict"; +const punycode = require("punycode"); +const tr46 = require("tr46"); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/test/merkletreejs/node_modules/whatwg-url/lib/utils.js b/test/merkletreejs/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 0000000..a562009 --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/test/merkletreejs/node_modules/whatwg-url/package.json b/test/merkletreejs/node_modules/whatwg-url/package.json new file mode 100644 index 0000000..fce35ae --- /dev/null +++ b/test/merkletreejs/node_modules/whatwg-url/package.json @@ -0,0 +1,32 @@ +{ + "name": "whatwg-url", + "version": "5.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "lib/public-api.js", + "files": [ + "lib/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + } +} diff --git a/test/merkletreejs/node_modules/which-typed-array/.editorconfig b/test/merkletreejs/node_modules/which-typed-array/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/test/merkletreejs/node_modules/which-typed-array/.eslintrc b/test/merkletreejs/node_modules/which-typed-array/.eslintrc new file mode 100644 index 0000000..8b2ada0 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + }, +} diff --git a/test/merkletreejs/node_modules/which-typed-array/.github/FUNDING.yml b/test/merkletreejs/node_modules/which-typed-array/.github/FUNDING.yml new file mode 100644 index 0000000..d6aa180 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/which-typed-array +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/test/merkletreejs/node_modules/which-typed-array/.nycrc b/test/merkletreejs/node_modules/which-typed-array/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/test/merkletreejs/node_modules/which-typed-array/CHANGELOG.md b/test/merkletreejs/node_modules/which-typed-array/CHANGELOG.md new file mode 100644 index 0000000..0e5fda7 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/CHANGELOG.md @@ -0,0 +1,204 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.13](https://github.com/inspect-js/which-typed-array/compare/v1.1.12...v1.1.13) - 2023-10-19 + +### Commits + +- [Refactor] avoid call-binding entirely when there is no method to bind [`9ff452b`](https://github.com/inspect-js/which-typed-array/commit/9ff452b88fbd8e4419bd768d86d0ea9a87d7e310) + +## [v1.1.12](https://github.com/inspect-js/which-typed-array/compare/v1.1.11...v1.1.12) - 2023-10-19 + +### Commits + +- [Fix] somehow node 0.12 - 3 can hit here, and they lack slice but have set [`c28e9b8`](https://github.com/inspect-js/which-typed-array/commit/c28e9b84d6d68ad5f52236ba59c26b06cde6300b) +- [Deps] update `call-bind` [`a648554`](https://github.com/inspect-js/which-typed-array/commit/a64855495106235352ebb3550a860d3bfd4a1ce1) +- [Dev Deps] update `tape` [`7a094d6`](https://github.com/inspect-js/which-typed-array/commit/7a094d6f9219b903c9a9e13c559e68f0e9672b59) + +## [v1.1.11](https://github.com/inspect-js/which-typed-array/compare/v1.1.10...v1.1.11) - 2023-07-17 + +### Commits + +- [Fix] `node < v0.6` lacks proper Object toString behavior [`b8fd654`](https://github.com/inspect-js/which-typed-array/commit/b8fd65479c0bd18385378cfae79750ebf7cb6ee7) +- [Dev Deps] update `tape` [`e1734c9`](https://github.com/inspect-js/which-typed-array/commit/e1734c99d79880ab11efa55220498a7a1e887834) + +## [v1.1.10](https://github.com/inspect-js/which-typed-array/compare/v1.1.9...v1.1.10) - 2023-07-10 + +### Commits + +- [actions] update rebase action to use reusable workflow [`2c10582`](https://github.com/inspect-js/which-typed-array/commit/2c105820d77274c079cb6d040cb348396e516ef5) +- [Robustness] use `call-bind` [`b2335fd`](https://github.com/inspect-js/which-typed-array/commit/b2335fdfca80840995eea5e6fcfffc6d712279a1) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`ad5e41b`](https://github.com/inspect-js/which-typed-array/commit/ad5e41ba18e7d23af1f9b211215c43a64bf75d70) + +## [v1.1.9](https://github.com/inspect-js/which-typed-array/compare/v1.1.8...v1.1.9) - 2022-11-02 + +### Commits + +- [Dev Deps] update `aud`, `is-callable`, `tape` [`9a20b3c`](https://github.com/inspect-js/which-typed-array/commit/9a20b3cb8f5d087789a8160395517bffe27b4339) +- [Refactor] use `gopd` instead of `es-abstract` helper [`00157af`](https://github.com/inspect-js/which-typed-array/commit/00157af909842b8b5affa5485d3574ec92d94065) +- [Deps] update `is-typed-array` [`6714240`](https://github.com/inspect-js/which-typed-array/commit/6714240e748cbbb634cb1e405ad762bc52acde66) +- [meta] add `sideEffects` flag [`89b96cc`](https://github.com/inspect-js/which-typed-array/commit/89b96cc3decc78d9621598e94fa1c2bb87eabf2e) + +## [v1.1.8](https://github.com/inspect-js/which-typed-array/compare/v1.1.7...v1.1.8) - 2022-05-14 + +### Commits + +- [actions] reuse common workflows [`95ea6c0`](https://github.com/inspect-js/which-typed-array/commit/95ea6c02dc5ec4ed0ee1b9c4692bb060108c8637) +- [meta] use `npmignore` to autogenerate an npmignore file [`d08436a`](https://github.com/inspect-js/which-typed-array/commit/d08436a19cdd76219732f5040a01cdb92ef2820e) +- [readme] add github actions/codecov badges [`35ae3af`](https://github.com/inspect-js/which-typed-array/commit/35ae3af6a0bb328c9d9b9bbb53e47122f269d81a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`86e6e3a`](https://github.com/inspect-js/which-typed-array/commit/86e6e3af60b2436f0ff34968d9d6240a23f40528) +- [actions] update codecov uploader [`0aa6e30`](https://github.com/inspect-js/which-typed-array/commit/0aa6e3026ab4198c4364737ed4f0315a2ecc432a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`a881a78`](https://github.com/inspect-js/which-typed-array/commit/a881a785f094e823e1cefe2ae9e4ebe31a8e996e) +- [Refactor] use `for-each` instead of `foreach` [`9dafa03`](https://github.com/inspect-js/which-typed-array/commit/9dafa0377fc5c690059a9d454f1dd4d365c5c902) +- [Deps] update `es-abstract`, `is-typed-array` [`0684022`](https://github.com/inspect-js/which-typed-array/commit/068402297608f321a4ec99ebce741b3eb38fcfdd) +- [Deps] update `es-abstract`, `is-typed-array` [`633a529`](https://github.com/inspect-js/which-typed-array/commit/633a529081b5c48d9675abb8aea425e6e33d528e) + +## [v1.1.7](https://github.com/inspect-js/which-typed-array/compare/v1.1.6...v1.1.7) - 2021-08-30 + +### Commits + +- [Refactor] use `globalThis` if available [`2a16d1f`](https://github.com/inspect-js/which-typed-array/commit/2a16d1fd520871ce6b23c60f0bd2113cf33b2533) +- [meta] changelog cleanup [`ba99f56`](https://github.com/inspect-js/which-typed-array/commit/ba99f56b45e6acde7aef4a1f34bb00e44088ccee) +- [Dev Deps] update `@ljharb/eslint-config` [`19a6e04`](https://github.com/inspect-js/which-typed-array/commit/19a6e04ce0094fb3fd6d0d2cbc58d320556ddf50) +- [Deps] update `available-typed-arrays` [`50dbc58`](https://github.com/inspect-js/which-typed-array/commit/50dbc5810a24c468b49409e1f0a79d03501e3dd6) +- [Deps] update `is-typed-array` [`c1b83ea`](https://github.com/inspect-js/which-typed-array/commit/c1b83eae65f042e46b6ae941ac4e814b7965a0f7) + +## [v1.1.6](https://github.com/inspect-js/which-typed-array/compare/v1.1.5...v1.1.6) - 2021-08-06 + +### Fixed + +- [Fix] if Symbol.toStringTag exists but is not present, use Object.prototype.toString [`#51`](https://github.com/inspect-js/which-typed-array/issues/51) [`#49`](https://github.com/inspect-js/which-typed-array/issues/49) + +### Commits + +- [Dev Deps] update `is-callable`, `tape` [`63eb1e3`](https://github.com/inspect-js/which-typed-array/commit/63eb1e3faede3f328bbbb4a5fcffc2e4769cf4ec) +- [Deps] update `is-typed-array` [`c5056f0`](https://github.com/inspect-js/which-typed-array/commit/c5056f0007d4c9434f1fa69eff183109468b4769) + +## [v1.1.5](https://github.com/inspect-js/which-typed-array/compare/v1.1.4...v1.1.5) - 2021-08-05 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`63fa8dd`](https://github.com/inspect-js/which-typed-array/commit/63fa8dd1dc9c0f0dbbaa16d1de0eb89797324c5d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `is-callable`, `tape` [`1107c74`](https://github.com/inspect-js/which-typed-array/commit/1107c74c52ed6eb4a719faec88e16c4343976d73) +- [Deps] update `available-typed-arrays`, `call-bind`, `es-abstract`, `is-typed-array` [`f953454`](https://github.com/inspect-js/which-typed-array/commit/f953454b2c6f589f09573ddc961431f970c2e1b6) +- [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams [`8aee720`](https://github.com/inspect-js/which-typed-array/commit/8aee7207abcd72c799ac324b214fbb6ca7ae4a28) +- [meta] use `prepublishOnly` script for npm 7+ [`6c5167b`](https://github.com/inspect-js/which-typed-array/commit/6c5167b4cd06cb62a5487a2e797d8e41cc2970b1) + +## [v1.1.4](https://github.com/inspect-js/which-typed-array/compare/v1.1.3...v1.1.4) - 2020-12-05 + +### Commits + +- [meta] npmignore github action workflows [`aa427e7`](https://github.com/inspect-js/which-typed-array/commit/aa427e79a230a985953695a8129ceb6bb7d42527) + +## [v1.1.3](https://github.com/inspect-js/which-typed-array/compare/v1.1.2...v1.1.3) - 2020-12-05 + +### Commits + +- [Tests] migrate tests to Github Actions [`803d4dd`](https://github.com/inspect-js/which-typed-array/commit/803d4ddb601ff03e587be792bd452de0e2783d03) +- [Tests] run `nyc` on all tests [`205a13f`](https://github.com/inspect-js/which-typed-array/commit/205a13f7aa172e014ddc2079c84af6ba575581c8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `is-callable`, `tape` [`97ceb07`](https://github.com/inspect-js/which-typed-array/commit/97ceb070d5aea1c3a696c6f695800ae468bafc0b) +- [actions] add "Allow Edits" workflow [`b140492`](https://github.com/inspect-js/which-typed-array/commit/b14049211eff32bd4149767def4f939483810051) +- [Deps] update `es-abstract`; use `call-bind` where applicable [`2abdb87`](https://github.com/inspect-js/which-typed-array/commit/2abdb871961b4e1b58925115a7d56a9cc5966a02) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`256d34b`](https://github.com/inspect-js/which-typed-array/commit/256d34b8bdb67b8af0e9f83c9a318e54f3340e3b) +- [Dev Deps] update `auto-changelog`; add `aud` [`ddea96f`](https://github.com/inspect-js/which-typed-array/commit/ddea96fe320dbdd0c7d7569812399a7f64d43e04) +- [meta] gitignore nyc output [`8a812bd`](https://github.com/inspect-js/which-typed-array/commit/8a812bd1ce7c5609988fb4fe2e9af2089eccd07d) + +## [v1.1.2](https://github.com/inspect-js/which-typed-array/compare/v1.1.1...v1.1.2) - 2020-04-07 + +### Commits + +- [Dev Deps] update `make-arrow-function`, `make-generator-function` [`28c61ef`](https://github.com/inspect-js/which-typed-array/commit/28c61eff4903ff6509f65c2f500858b9cb4636f1) +- [Dev Deps] update `@ljharb/eslint-config` [`a233879`](https://github.com/inspect-js/which-typed-array/commit/a2338798d3a4a3169cda54e322b2f2eb0e976ad0) +- [Dev Deps] update `auto-changelog` [`df0134c`](https://github.com/inspect-js/which-typed-array/commit/df0134c0e20ec6d94993988ad670e1b3cf350bea) +- [Fix] move `foreach` to dependencies [`6ef29c0`](https://github.com/inspect-js/which-typed-array/commit/6ef29c0dbb91a7ec21df7ce8736f99f41efea39e) +- [Tests] only audit prod deps [`eb21044`](https://github.com/inspect-js/which-typed-array/commit/eb210446bd7a433657204d2314ef56fe264c21ad) +- [Deps] update `es-abstract` [`5ef0236`](https://github.com/inspect-js/which-typed-array/commit/5ef02368d9876a1074123aa7725d6759b4f3e358) +- [Dev Deps] update `tape` [`7456037`](https://github.com/inspect-js/which-typed-array/commit/745603728c6c3da8bdddee321e8a9196f4827aa3) +- [Deps] update `available-typed-arrays` [`8a856c9`](https://github.com/inspect-js/which-typed-array/commit/8a856c9aa707c1e6f7a52e834485356b31395ea6) + +## [v1.1.1](https://github.com/inspect-js/which-typed-array/compare/v1.1.0...v1.1.1) - 2020-01-24 + +### Commits + +- [Tests] use shared travis-ci configs [`0a627d9`](https://github.com/inspect-js/which-typed-array/commit/0a627d9694d0eabdaee63b19e605584166995a79) +- [meta] add `auto-changelog` [`2a14c58`](https://github.com/inspect-js/which-typed-array/commit/2a14c58b79f72e32ef2078efb40d31a4bf8c197a) +- [meta] remove unused Makefile and associated utilities [`75f7f22`](https://github.com/inspect-js/which-typed-array/commit/75f7f222199f42618c290de363c542b11f5a5632) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`4162327`](https://github.com/inspect-js/which-typed-array/commit/416232725e7d127cbd886af0f8988dae612a342f) +- [Refactor] use `es-abstract`’s `callBound`, `available-typed-arrays`, `has-symbols` [`9b04a2a`](https://github.com/inspect-js/which-typed-array/commit/9b04a2a14c758600cffcf59485b7b3c85839c266) +- [readme] fix repo URLs, remove testling [`03ed52f`](https://github.com/inspect-js/which-typed-array/commit/03ed52f3ae4fcd35614bcda7e947b14e62009c71) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape` [`bfbcf3e`](https://github.com/inspect-js/which-typed-array/commit/bfbcf3ec9c449bd0089ed805c01a32ba4e7e5938) +- [actions] add automatic rebasing / merge commit blocking [`cc88ac5`](https://github.com/inspect-js/which-typed-array/commit/cc88ac56bcfb71cb26c656ebde4c560a22fadd85) +- [meta] create FUNDING.yml [`acbc723`](https://github.com/inspect-js/which-typed-array/commit/acbc7230929b1256c83df28be4a456eed3e147e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `tape` [`f1ab63e`](https://github.com/inspect-js/which-typed-array/commit/f1ab63e9366027eae2e29398c035181dac164132) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` [`ac9f50b`](https://github.com/inspect-js/which-typed-array/commit/ac9f50b59558933292dff993df2e68eaa44b07e2) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`aaaa15d`](https://github.com/inspect-js/which-typed-array/commit/aaaa15dfb5bd8228c0cfb8f2aba267efb405b0a1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`602fc9a`](https://github.com/inspect-js/which-typed-array/commit/602fc9a0a7d708236f90c76f592e6a980ecde940) +- [Deps] update `available-typed-arrays`, `is-typed-array` [`b2d69b6`](https://github.com/inspect-js/which-typed-array/commit/b2d69b639bf14344d09f8512dbc060cd4f533161) +- [meta] add `funding` field [`156f613`](https://github.com/inspect-js/which-typed-array/commit/156f613d0ce547c4b15e1ae279198b66e3cef55e) + +## [v1.1.0](https://github.com/inspect-js/which-typed-array/compare/v1.0.1...v1.1.0) - 2019-02-16 + +### Commits + +- [Tests] remove `jscs` [`381c9b4`](https://github.com/inspect-js/which-typed-array/commit/381c9b4bd858da1adedf23d8555af3a3ed901a83) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`, `v5.8`; improve matrix; newer npm breaks on older node [`7015c19`](https://github.com/inspect-js/which-typed-array/commit/7015c196ba86540b04d18d9b1d2c368909492023) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9`; use `nvm install-latest-npm` [`ad67885`](https://github.com/inspect-js/which-typed-array/commit/ad678853e245986720d7650be1c974a9ff3ac814) +- [Tests] up to `node` `v11.6`, `v10.15`, `v8.15`, `v6.16` [`dd94bfb`](https://github.com/inspect-js/which-typed-array/commit/dd94bfb6309a92d1537352f2d1100f9e913ebc01) +- [Refactor] use an array instead of an object for storing Typed Array names [`de98bc1`](https://github.com/inspect-js/which-typed-array/commit/de98bc1d44af92909a34212e276deb5d79ac428a) +- [meta] ignore `test.html` [`06cfb1b`](https://github.com/inspect-js/which-typed-array/commit/06cfb1bc0ca7881d1bd1621fa946a16366cd6afc) +- [Tests] up to `node` `v7.0`, `v6.9`, `v4.6`; improve test matrix [`df76eaa`](https://github.com/inspect-js/which-typed-array/commit/df76eaa39b94b28147e81a89bb587e8aa3e3dba3) +- [New] add `BigInt64Array` and `BigUint64Array` [`d6bca3a`](https://github.com/inspect-js/which-typed-array/commit/d6bca3a68ccfe33f6659a24b770068e89dab1592) +- [Dev Deps] update `jscs`, `nsp`, `eslint` [`f23b45b`](https://github.com/inspect-js/which-typed-array/commit/f23b45b2796bd1f63ddddf28b4b80b9709478cb3) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint`, `semver`, `tape` [`ddb4484`](https://github.com/inspect-js/which-typed-array/commit/ddb4484adc3b45c4396632611556055f3b2f5990) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `is-callable`, `replace`, `semver`, `tape` [`4524e59`](https://github.com/inspect-js/which-typed-array/commit/4524e593e9387c185d5632696c62c1600c0b380f) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`1ec7056`](https://github.com/inspect-js/which-typed-array/commit/1ec70568565c479a6168b03e0a5aec6ec9ac5a21) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`799487d`](https://github.com/inspect-js/which-typed-array/commit/799487d666b32d1ae0d27cfededf2f5480c5faea) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`8092598`](https://github.com/inspect-js/which-typed-array/commit/8092598998a1f9f8005b4e3d299eb09c96fa2e21) +- [Tests] up to `node` `v11.10` [`a5aabb1`](https://github.com/inspect-js/which-typed-array/commit/a5aabb1910e8408f857a791253487824c7c758d3) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint`, `nsp`, `semver`, `tape` [`277be33`](https://github.com/inspect-js/which-typed-array/commit/277be331d9f05ff95644d6bcd896547ca620cd8e) +- [Tests] use `npm audit` instead of `nsp` [`ee97dc7`](https://github.com/inspect-js/which-typed-array/commit/ee97dc7c5d384d68f60ce6cb5a85d9509e75f72b) +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` [`262ffb0`](https://github.com/inspect-js/which-typed-array/commit/262ffb025facb0795b33fbd5131183bdbc0a40f6) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`d6bbcfc`](https://github.com/inspect-js/which-typed-array/commit/d6bbcfc3eea427f0156fbdcf9ae11dbf3745a755) +- [Tests] up to `node` `v6.2` [`2ff89eb`](https://github.com/inspect-js/which-typed-array/commit/2ff89eb91754146c0bc1ae689f37458d84f6e690) +- Only apps should have lockfiles [`e2bc271`](https://github.com/inspect-js/which-typed-array/commit/e2bc271e1e9a6481a2836f892177825a808c331c) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`b79e93b`](https://github.com/inspect-js/which-typed-array/commit/b79e93bf15c871ce0ff24fa3ad61001707eea463) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`016dbff`](https://github.com/inspect-js/which-typed-array/commit/016dbff8c49c32cda7ec80d86006c8a7c43bc40c) +- [Dev Deps] update `eslint`, `tape` [`6ce4bbc`](https://github.com/inspect-js/which-typed-array/commit/6ce4bbc5f6caf632cbcf9ababbfe36e1bf4093d7) +- [Tests] on `node` `v10.1` [`f0683a0`](https://github.com/inspect-js/which-typed-array/commit/f0683a0c17e039e926ecaad4c4c341cd8e5878f1) +- [Tests] up to `node` `v7.2` [`2f29cef`](https://github.com/inspect-js/which-typed-array/commit/2f29cef42d30f87259cd6687c25a79ae4651d0c9) +- [Dev Deps] update `replace` [`73b5ba6`](https://github.com/inspect-js/which-typed-array/commit/73b5ba6e87638d13553985977cab9d1bad33e242) +- [Deps] update `function-bind` [`c8a18c2`](https://github.com/inspect-js/which-typed-array/commit/c8a18c2982e6b126ecc1d4655ec2e53b05535b20) +- [Tests] on `node` `v5.12` [`812102b`](https://github.com/inspect-js/which-typed-array/commit/812102bf223422da8f7a89e5a1308214dd158571) +- [Tests] on `node` `v5.10` [`271584f`](https://github.com/inspect-js/which-typed-array/commit/271584f3a8b10ef68a7d419ac0062b444e63d07c) + +## [v1.0.1](https://github.com/inspect-js/which-typed-array/compare/v1.0.0...v1.0.1) - 2016-03-19 + +### Commits + +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `is-callable` [`4a628c5`](https://github.com/inspect-js/which-typed-array/commit/4a628c520d8e080a9fa7e8218947d3b2ceedca72) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `is-callable` [`8e09372`](https://github.com/inspect-js/which-typed-array/commit/8e09372ded877a191cbf777060483227d5071e84) +- [Tests] up to `node` `v5.6`, `v4.3` [`3a35bf9`](https://github.com/inspect-js/which-typed-array/commit/3a35bf9fb9c7f8e6ac1b579ed2754087351ad1a5) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`9410d5e`](https://github.com/inspect-js/which-typed-array/commit/9410d5e35db4b834827b31ea1723bbeebbcde5ba) +- [Fix] `Symbol.toStringTag` is on the super-[[Prototype]] of Float32Array, not the [[Prototype]]. [`7c40a3a`](https://github.com/inspect-js/which-typed-array/commit/7c40a3a05046bbbd188340fb19471ad913e4af05) +- [Tests] up to `node` `v5.9`, `v4.4` [`07878e7`](https://github.com/inspect-js/which-typed-array/commit/07878e7cd23d586ddb9e85a03f675e0a574db246) +- Use the object form of "author" in package.json [`65caa56`](https://github.com/inspect-js/which-typed-array/commit/65caa560d1c0c15c1080b25a9df55c7373c73f08) +- [Tests] use pretest/posttest for linting/security [`c170f7e`](https://github.com/inspect-js/which-typed-array/commit/c170f7ebcf07475d6420f2d2d2d08b1646280cd4) +- [Deps] update `is-typed-array` [`9ab324e`](https://github.com/inspect-js/which-typed-array/commit/9ab324e746a7552b2d9363777fc5c9f5c2e31ce7) +- [Deps] update `function-bind` [`a723142`](https://github.com/inspect-js/which-typed-array/commit/a723142c70a5b6a4f8f5feecc9705619590f4eeb) +- [Deps] update `is-typed-array` [`ed82ce4`](https://github.com/inspect-js/which-typed-array/commit/ed82ce4e8ecc657fc6e839d23ef6347497bc93be) +- [Tests] on `node` `v4.2` [`f581c20`](https://github.com/inspect-js/which-typed-array/commit/f581c2031990668894a8e5a08eaf01a2548e822c) + +## v1.0.0 - 2015-10-05 + +### Commits + +- Dotfiles / Makefile [`667f89a`](https://github.com/inspect-js/which-typed-array/commit/667f89a9046502594e2559dbf5568e062af3b770) +- Tests. [`a14d05e`](https://github.com/inspect-js/which-typed-array/commit/a14d05ef443d2ac678cb0567befc0abf8cf21709) +- package.json [`560b1aa`](https://github.com/inspect-js/which-typed-array/commit/560b1aa4f8bbc5d41d9cee96c93faf08c25be0e5) +- Read me [`a22096e`](https://github.com/inspect-js/which-typed-array/commit/a22096e05773f93b34e672d3f743ec6f1963bc24) +- Implementation [`0b1ae28`](https://github.com/inspect-js/which-typed-array/commit/0b1ae2848372f6256cf075d687e3722878e67aca) +- Initial commit [`4b32f0a`](https://github.com/inspect-js/which-typed-array/commit/4b32f0a9d32165d6ab91797d6971ea83cf4ce9da) diff --git a/test/merkletreejs/node_modules/which-typed-array/LICENSE b/test/merkletreejs/node_modules/which-typed-array/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +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. + diff --git a/test/merkletreejs/node_modules/which-typed-array/README.md b/test/merkletreejs/node_modules/which-typed-array/README.md new file mode 100644 index 0000000..1b922cd --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/README.md @@ -0,0 +1,70 @@ +# which-typed-array [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag. + +## Example + +```js +var whichTypedArray = require('which-typed-array'); +var assert = require('assert'); + +assert.equal(false, whichTypedArray(undefined)); +assert.equal(false, whichTypedArray(null)); +assert.equal(false, whichTypedArray(false)); +assert.equal(false, whichTypedArray(true)); +assert.equal(false, whichTypedArray([])); +assert.equal(false, whichTypedArray({})); +assert.equal(false, whichTypedArray(/a/g)); +assert.equal(false, whichTypedArray(new RegExp('a', 'g'))); +assert.equal(false, whichTypedArray(new Date())); +assert.equal(false, whichTypedArray(42)); +assert.equal(false, whichTypedArray(NaN)); +assert.equal(false, whichTypedArray(Infinity)); +assert.equal(false, whichTypedArray(new Number(42))); +assert.equal(false, whichTypedArray('foo')); +assert.equal(false, whichTypedArray(Object('foo'))); +assert.equal(false, whichTypedArray(function () {})); +assert.equal(false, whichTypedArray(function* () {})); +assert.equal(false, whichTypedArray(x => x * x)); +assert.equal(false, whichTypedArray([])); + +assert.equal('Int8Array', whichTypedArray(new Int8Array())); +assert.equal('Uint8Array', whichTypedArray(new Uint8Array())); +assert.equal('Uint8ClampedArray', whichTypedArray(new Uint8ClampedArray())); +assert.equal('Int16Array', whichTypedArray(new Int16Array())); +assert.equal('Uint16Array', whichTypedArray(new Uint16Array())); +assert.equal('Int32Array', whichTypedArray(new Int32Array())); +assert.equal('Uint32Array', whichTypedArray(new Uint32Array())); +assert.equal('Float32Array', whichTypedArray(new Float32Array())); +assert.equal('Float64Array', whichTypedArray(new Float64Array())); +assert.equal('BigInt64Array', whichTypedArray(new BigInt64Array())); +assert.equal('BigUint64Array', whichTypedArray(new BigUint64Array())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/which-typed-array +[npm-version-svg]: https://versionbadg.es/inspect-js/which-typed-array.svg +[deps-svg]: https://david-dm.org/inspect-js/which-typed-array.svg +[deps-url]: https://david-dm.org/inspect-js/which-typed-array +[dev-deps-svg]: https://david-dm.org/inspect-js/which-typed-array/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/which-typed-array#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/which-typed-array.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/which-typed-array.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/which-typed-array.svg +[downloads-url]: https://npm-stat.com/charts.html?package=which-typed-array +[codecov-image]: https://codecov.io/gh/inspect-js/which-typed-array/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/which-typed-array/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/which-typed-array +[actions-url]: https://github.com/inspect-js/which-typed-array/actions diff --git a/test/merkletreejs/node_modules/which-typed-array/index.js b/test/merkletreejs/node_modules/which-typed-array/index.js new file mode 100644 index 0000000..300eb3f --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/index.js @@ -0,0 +1,92 @@ +'use strict'; + +var forEach = require('for-each'); +var availableTypedArrays = require('available-typed-arrays'); +var callBind = require('call-bind'); +var callBound = require('call-bind/callBound'); +var gOPD = require('gopd'); + +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var g = typeof globalThis === 'undefined' ? global : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); + +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD(superProto, Symbol.toStringTag); + } + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + cache['$' + typedArray] = callBind(fn); + } + }); +} + +var tryTypedArrays = function tryAllTypedArrays(value) { + var found = false; + forEach(cache, function (getter, typedArray) { + if (!found) { + try { + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + }); + return found; +}; + +var trySlices = function tryAllSlices(value) { + var found = false; + forEach(cache, function (getter, name) { + if (!found) { + try { + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + }); + return found; +}; + +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); +}; diff --git a/test/merkletreejs/node_modules/which-typed-array/package.json b/test/merkletreejs/node_modules/which-typed-array/package.json new file mode 100644 index 0000000..d0558cd --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/package.json @@ -0,0 +1,115 @@ +{ + "name": "which-typed-array", + "version": "1.1.13", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.", + "license": "MIT", + "main": "index.js", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only && npm run test:harmony", + "tests-only": "nyc tape test", + "test:harmony": "nyc node --harmony --es-staging test", + "posttest": "aud --production", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/which-typed-array.git" + }, + "keywords": [ + "array", + "TypedArray", + "typed array", + "which", + "typed", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "ES6", + "toStringTag", + "Symbol.toStringTag", + "@@toStringTag" + ], + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.4", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "is-callable": "^1.2.7", + "make-arrow-function": "^1.2.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/test/merkletreejs/node_modules/which-typed-array/test/index.js b/test/merkletreejs/node_modules/which-typed-array/test/index.js new file mode 100644 index 0000000..6d79a36 --- /dev/null +++ b/test/merkletreejs/node_modules/which-typed-array/test/index.js @@ -0,0 +1,99 @@ +'use strict'; + +var test = require('tape'); +var whichTypedArray = require('../'); +var isCallable = require('is-callable'); +var hasToStringTag = require('has-tostringtag/shams')(); +var generators = require('make-generator-function')(); +var arrows = require('make-arrow-function').list(); +var forEach = require('for-each'); + +var typedArrayNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; + +test('not arrays', function (t) { + t.test('non-number/string primitives', function (st) { + st.equal(false, whichTypedArray(), 'undefined is not typed array'); + st.equal(false, whichTypedArray(null), 'null is not typed array'); + st.equal(false, whichTypedArray(false), 'false is not typed array'); + st.equal(false, whichTypedArray(true), 'true is not typed array'); + st.end(); + }); + + t.equal(false, whichTypedArray({}), 'object is not typed array'); + t.equal(false, whichTypedArray(/a/g), 'regex literal is not typed array'); + t.equal(false, whichTypedArray(new RegExp('a', 'g')), 'regex object is not typed array'); + t.equal(false, whichTypedArray(new Date()), 'new Date() is not typed array'); + + t.test('numbers', function (st) { + st.equal(false, whichTypedArray(42), 'number is not typed array'); + st.equal(false, whichTypedArray(Object(42)), 'number object is not typed array'); + st.equal(false, whichTypedArray(NaN), 'NaN is not typed array'); + st.equal(false, whichTypedArray(Infinity), 'Infinity is not typed array'); + st.end(); + }); + + t.test('strings', function (st) { + st.equal(false, whichTypedArray('foo'), 'string primitive is not typed array'); + st.equal(false, whichTypedArray(Object('foo')), 'string object is not typed array'); + st.end(); + }); + + t.end(); +}); + +test('Functions', function (t) { + t.equal(false, whichTypedArray(function () {}), 'function is not typed array'); + t.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.equal(false, whichTypedArray(genFn), 'generator function ' + genFn + ' is not typed array'); + }); + t.end(); +}); + +test('Arrow functions', { skip: arrows.length === 0 }, function (t) { + forEach(arrows, function (arrowFn) { + t.equal(false, whichTypedArray(arrowFn), 'arrow function ' + arrowFn + ' is not typed array'); + }); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + forEach(typedArrayNames, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var fakeTypedArray = []; + fakeTypedArray[Symbol.toStringTag] = typedArray; + t.equal(false, whichTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); + +test('Typed Arrays', function (t) { + forEach(typedArrayNames, function (typedArray) { + var TypedArray = global[typedArray]; + if (isCallable(TypedArray)) { + var arr = new TypedArray(10); + t.equal(whichTypedArray(arr), typedArray, 'new ' + typedArray + '(10) is typed array of type ' + typedArray); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); diff --git a/test/merkletreejs/node_modules/ws/LICENSE b/test/merkletreejs/node_modules/ws/LICENSE new file mode 100644 index 0000000..1da5b96 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and 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. diff --git a/test/merkletreejs/node_modules/ws/README.md b/test/merkletreejs/node_modules/ws/README.md new file mode 100644 index 0000000..a550ca1 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/README.md @@ -0,0 +1,536 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [Round-trip time](#round-trip-time) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +There are 2 optional modules that can be installed along side with the ws +module. These modules are binary addons that improve the performance of certain +operations. Prebuilt binaries are available for the most popular platforms so +you don't necessarily need to have a C++ compiler installed on your machine. + +- `npm install --save-optional bufferutil`: Allows to efficiently perform + operations such as masking and unmasking the data payload of the WebSocket + frames. +- `npm install --save-optional utf-8-validate`: Allows to efficiently check if a + message contains valid UTF-8. + +To not even try to require and use these modules, use the +[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) and +[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment +variables. These might be useful to enhance security in systems where a user can +put a package in the package search path of an application of another user, due +to how the Node.js resolver algorithm works. + +The `utf-8-validate` module is not needed and is not required, even if it is +already installed, regardless of the value of the `WS_NO_UTF_8_VALIDATE` +environment variable, if [`buffer.isUtf8()`][] is available. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function message(data) { + console.log('received: %s', data); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { parse } from 'url'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +wss2.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = parse(request.url); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +function onSocketError(err) { + console.error(err); +} + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log(`Received message ${data} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + socket.on('error', onSocketError); + + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, function next(err, client) { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + socket.removeListener('error', onSocketError); + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### Round-trip time + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +ws.on('error', console.error); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function message(data) { + console.log(`Round-trip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.on('error', console.error); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; + + ws.on('error', console.error); +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); + + ws.on('error', console.error); +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a way +that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('error', console.error); + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://websocket-echo.com/'); + +client.on('error', console.error); +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/test/merkletreejs/node_modules/ws/browser.js b/test/merkletreejs/node_modules/ws/browser.js new file mode 100644 index 0000000..ca4f628 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/test/merkletreejs/node_modules/ws/index.js b/test/merkletreejs/node_modules/ws/index.js new file mode 100644 index 0000000..41edb3b --- /dev/null +++ b/test/merkletreejs/node_modules/ws/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.createWebSocketStream = require('./lib/stream'); +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocket.Server; + +module.exports = WebSocket; diff --git a/test/merkletreejs/node_modules/ws/lib/buffer-util.js b/test/merkletreejs/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000..f7536e2 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/test/merkletreejs/node_modules/ws/lib/constants.js b/test/merkletreejs/node_modules/ws/lib/constants.js new file mode 100644 index 0000000..d691b30 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/constants.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/test/merkletreejs/node_modules/ws/lib/event-target.js b/test/merkletreejs/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000..fea4cbc --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/test/merkletreejs/node_modules/ws/lib/extension.js b/test/merkletreejs/node_modules/ws/lib/extension.js new file mode 100644 index 0000000..3d7895c --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/test/merkletreejs/node_modules/ws/lib/limiter.js b/test/merkletreejs/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000..3fd3578 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/test/merkletreejs/node_modules/ws/lib/permessage-deflate.js b/test/merkletreejs/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000..77d918b --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,514 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/test/merkletreejs/node_modules/ws/lib/receiver.js b/test/merkletreejs/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000..1d425ea --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/receiver.js @@ -0,0 +1,679 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; +const promise = Promise.resolve(); + +// +// `queueMicrotask()` is not available in Node.js < 11. +// +const queueTask = + typeof queueMicrotask === 'function' ? queueMicrotask : queueMicrotaskShim; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const WAIT_MICROTASK = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + case INFLATING: + this._loop = false; + return; + default: + // + // `WAIT_MICROTASK`. + // + this._loop = false; + + queueTask(() => { + this._state = GET_INFO; + this.startLoop(cb); + }); + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data, true); + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf, false); + } + } + + this._state = WAIT_MICROTASK; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + + this._state = GET_INFO; + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + return error( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf); + this.end(); + + this._state = GET_INFO; + } + } else if (this._opcode === 0x09) { + this.emit('ping', data); + this._state = WAIT_MICROTASK; + } else { + this.emit('pong', data); + this._state = WAIT_MICROTASK; + } + } +} + +module.exports = Receiver; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; +} + +/** + * A shim for `queueMicrotask()`. + * + * @param {Function} cb Callback + */ +function queueMicrotaskShim(cb) { + promise.then(cb).catch(throwErrorNextTick); +} + +/** + * Throws an error. + * + * @param {Error} err The error to throw + * @private + */ +function throwError(err) { + throw err; +} + +/** + * Throws an error in the next tick. + * + * @param {Error} err The error to throw + * @private + */ +function throwErrorNextTick(err) { + process.nextTick(throwError, err); +} diff --git a/test/merkletreejs/node_modules/ws/lib/sender.js b/test/merkletreejs/node_modules/ws/lib/sender.js new file mode 100644 index 0000000..1ed04b0 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/sender.js @@ -0,0 +1,477 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + +'use strict'; + +const { Duplex } = require('stream'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER } = require('./constants'); +const { isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; diff --git a/test/merkletreejs/node_modules/ws/lib/stream.js b/test/merkletreejs/node_modules/ws/lib/stream.js new file mode 100644 index 0000000..230734b --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/stream.js @@ -0,0 +1,159 @@ +'use strict'; + +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/test/merkletreejs/node_modules/ws/lib/subprotocol.js b/test/merkletreejs/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000..d4381e8 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/test/merkletreejs/node_modules/ws/lib/validation.js b/test/merkletreejs/node_modules/ws/lib/validation.js new file mode 100644 index 0000000..c352e6e --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/validation.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +module.exports = { + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/test/merkletreejs/node_modules/ws/lib/websocket-server.js b/test/merkletreejs/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000..b0ed7bd --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,531 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const { Duplex } = require('stream'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!key || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 8 && version !== 13) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @private + */ +function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message); + } +} diff --git a/test/merkletreejs/node_modules/ws/lib/websocket.js b/test/merkletreejs/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000..8685ff7 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/lib/websocket.js @@ -0,0 +1,1319 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Duplex, Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/test/merkletreejs/node_modules/ws/package.json b/test/merkletreejs/node_modules/ws/package.json new file mode 100644 index 0000000..107c188 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/package.json @@ -0,0 +1,68 @@ +{ + "name": "ws", + "version": "8.14.2", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + ".": { + "browser": "./browser.js", + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^8.0.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-prettier": "^5.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^3.0.0", + "utf-8-validate": "^6.0.0" + } +} diff --git a/test/merkletreejs/node_modules/ws/wrapper.mjs b/test/merkletreejs/node_modules/ws/wrapper.mjs new file mode 100644 index 0000000..7245ad1 --- /dev/null +++ b/test/merkletreejs/node_modules/ws/wrapper.mjs @@ -0,0 +1,8 @@ +import createWebSocketStream from './lib/stream.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; +export default WebSocket; diff --git a/test/merkletreejs/node_modules/zod/LICENSE b/test/merkletreejs/node_modules/zod/LICENSE new file mode 100644 index 0000000..2c93bb5 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Colin McDonnell + +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. diff --git a/test/merkletreejs/node_modules/zod/README.md b/test/merkletreejs/node_modules/zod/README.md new file mode 100644 index 0000000..490265f --- /dev/null +++ b/test/merkletreejs/node_modules/zod/README.md @@ -0,0 +1,2834 @@ +

+ Zod logo +

Zod

+

+ ✨ https://zod.dev ✨ +
+ TypeScript-first schema validation with static type inference +

+

+
+

+Zod CI status +Created by Colin McDonnell +License +npm +stars +discord server +

+ +
+ Documentation +   •   + Discord +   •   + npm +   •   + deno +   •   + Issues +   •   + @colinhacks +   •   + tRPC +
+
+ +
+
+ +> These docs have been translated into [Chinese](./README_ZH.md). + +## Table of contents + + + +- [Table of contents](#table-of-contents) +- [Introduction](#introduction) + - [Sponsors](#sponsors) + - [Gold](#gold) + - [Silver](#silver) + - [Bronze](#bronze) + - [Ecosystem](#ecosystem) + - [Resources](#resources) + - [API libraries](#api-libraries) + - [Form integrations](#form-integrations) + - [Zod to X](#zod-to-x) + - [X to Zod](#x-to-zod) + - [Mocking](#mocking) + - [Powered by Zod](#powered-by-zod) + - [Utilities for Zod](#utilities-for-zod) +- [Installation](#installation) + - [Requirements](#requirements) + - [From `npm` (Node/Bun)](#from-npm-nodebun) + - [From `deno.land/x` (Deno)](#from-denolandx-deno) +- [Basic usage](#basic-usage) +- [Primitives](#primitives) +- [Coercion for primitives](#coercion-for-primitives) +- [Literals](#literals) +- [Strings](#strings) + - [ISO datetimes](#iso-datetimes) + - [IP addresses](#ip-addresses) +- [Numbers](#numbers) +- [BigInts](#bigints) +- [NaNs](#nans) +- [Booleans](#booleans) +- [Dates](#dates) +- [Zod enums](#zod-enums) +- [Native enums](#native-enums) +- [Optionals](#optionals) +- [Nullables](#nullables) +- [Objects](#objects) + - [`.shape`](#shape) + - [`.keyof`](#keyof) + - [`.extend`](#extend) + - [`.merge`](#merge) + - [`.pick/.omit`](#pickomit) + - [`.partial`](#partial) + - [`.deepPartial`](#deeppartial) + - [`.required`](#required) + - [`.passthrough`](#passthrough) + - [`.strict`](#strict) + - [`.strip`](#strip) + - [`.catchall`](#catchall) +- [Arrays](#arrays) + - [`.element`](#element) + - [`.nonempty`](#nonempty) + - [`.min/.max/.length`](#minmaxlength) +- [Tuples](#tuples) +- [Unions](#unions) +- [Discriminated unions](#discriminated-unions) +- [Records](#records) + - [Record key type](#record-key-type) +- [Maps](#maps) +- [Sets](#sets) +- [Intersections](#intersections) +- [Recursive types](#recursive-types) + - [ZodType with ZodEffects](#zodtype-with-zodeffects) + - [JSON type](#json-type) + - [Cyclical objects](#cyclical-objects) +- [Promises](#promises) +- [Instanceof](#instanceof) +- [Functions](#functions) +- [Preprocess](#preprocess) +- [Custom schemas](#custom-schemas) +- [Schema methods](#schema-methods) + - [`.parse`](#parse) + - [`.parseAsync`](#parseasync) + - [`.safeParse`](#safeparse) + - [`.safeParseAsync`](#safeparseasync) + - [`.refine`](#refine) + - [Arguments](#arguments) + - [Customize error path](#customize-error-path) + - [Asynchronous refinements](#asynchronous-refinements) + - [Relationship to transforms](#relationship-to-transforms) + - [`.superRefine`](#superrefine) + - [Abort early](#abort-early) + - [Type refinements](#type-refinements) + - [`.transform`](#transform) + - [Chaining order](#chaining-order) + - [Validating during transform](#validating-during-transform) + - [Relationship to refinements](#relationship-to-refinements) + - [Async transforms](#async-transforms) + - [`.default`](#default) + - [`.describe`](#describe) + - [`.catch`](#catch) + - [`.optional`](#optional) + - [`.nullable`](#nullable) + - [`.nullish`](#nullish) + - [`.array`](#array) + - [`.promise`](#promise) + - [`.or`](#or) + - [`.and`](#and) + - [`.brand`](#brand) + - [`.readonly`](#readonly) + - [`.pipe`](#pipe) + - [You can use `.pipe()` to fix common issues with `z.coerce`.](#you-can-use-pipe-to-fix-common-issues-with-zcoerce) +- [Guides and concepts](#guides-and-concepts) + - [Type inference](#type-inference) + - [Writing generic functions](#writing-generic-functions) + - [Constraining allowable inputs](#constraining-allowable-inputs) + - [Error handling](#error-handling) + - [Error formatting](#error-formatting) +- [Comparison](#comparison) + - [Joi](#joi) + - [Yup](#yup) + - [io-ts](#io-ts) + - [Runtypes](#runtypes) + - [Ow](#ow) +- [Changelog](#changelog) + +## Introduction + +Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object. + +Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator _once_ and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures. + +Some other great aspects: + +- Zero dependencies +- Works in Node.js and all modern browsers +- Tiny: 8kb minified + zipped +- Immutable: methods (e.g. `.optional()`) return a new instance +- Concise, chainable interface +- Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) +- Works with plain JavaScript too! You don't need to use TypeScript. + +### Sponsors + +Sponsorship at any level is appreciated and encouraged. For individual developers, consider the [Cup of Coffee tier](https://github.com/sponsors/colinhacks). If you built a paid product using Zod, consider one of the [podium tiers](https://github.com/sponsors/colinhacks). + +#### Gold + + + + + + + + + + + + + + + + +
+ + Speakeasy API + +
+ Speakeasy +
+ speakeasyapi.dev +
+

SDKs, Terraform, Docs.
Your API made enterprise-ready.

+
+ + Glow Wallet + +
+ Glow Wallet +
+ glow.app +
+

Your new favorite +
+ Solana wallet.

+
+ + Deletype logo + +
+ Deletype +
+ deletype.com +
+ + Trigger.dev logo + +
+ Trigger.dev +
+ trigger.dev +
+

Effortless automation for developers.

+
+ + Transloadit logo + +
+ Transloadit +
+ transloadit.com +
+

Simple file processing for developers.

+
+ + Infisical logo + +
+ Infisical +
+ infisical.com +
+

Open-source platform for secret
management: sync secrets across your
team/infrastructure and prevent secret leaks.

+
+ + Whop logo + +
+ Whop +
+ whop.com +
+

A marketplace for really cool internet products.

+
+ +#### Silver + + + + + + + + + + + +
+ + Numeric logo + +
+ Numeric +
+ numeric.io +
+ + Marcato Partners + +
+ Marcato Partners +
+ marcatopartners.com +
+ + + +
+ Interval +
+ interval.com +
+ + + +
+ Seasoned Software +
+ seasoned.cc +
+ + Bamboo Creative logo + +
+ Bamboo Creative +
+ bamboocreative.nz +
+ +#### Bronze + + + + + + + + + + + + + + + + + +
+ + + +
+ Brandon Bayer +
+ @flybayer, + creator of Blitz.js +
+
+ + + +
+ Jiří Brabec +
+ @brabeji +
+
+ + + +
+ Alex Johansson +
+ @alexdotjs +
+ + Fungible Systems logo + +
+ Fungible Systems +
+ fungible.systems +
+
+ + + +
+ Adaptable +
+ adaptable.io +
+
+ + Avana Wallet logo + +
+ Avana Wallet +
+ avanawallet.com
+ Solana non-custodial wallet +
+
+ + Learn with Jason logo + +
+ Jason Lengstorf +
+ learnwithjason.dev +
+
+ + Global Illumination + +
+ Global Illumination, Inc. +
+ ill.inc +
+
+ + MasterBorn logo + +
+ MasterBorn +
+ masterborn.com +
+
+ +### Ecosystem + +There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it [on Twitter](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out. + +#### Resources + +- [Total TypeScript Zod Tutorial](https://www.totaltypescript.com/tutorials/zod) by [@mattpocockuk](https://twitter.com/mattpocockuk) +- [Fixing TypeScript's Blindspot: Runtime Typechecking](https://www.youtube.com/watch?v=rY_XqfSHock) by [@jherr](https://twitter.com/jherr) + +#### API libraries + +- [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL. +- [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project. +- [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible. +- [`domain-functions`](https://github.com/SeasonedSoftware/domain-functions/): Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas. +- [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod. +- [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares. +- [`tapiduck`](https://github.com/sumukhbarve/monoduck/blob/main/src/tapiduck/README.md): End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler. +- [`koa-zod-router`](https://github.com/JakeFenley/koa-zod-router): Create typesafe routes in Koa with I/O validation using Zod. + +#### Form integrations + +- [`conform`](https://conform.guide/api/zod): A progressive enhancement first form validation library for Remix and React Router +- [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form. +- [`zod-validation-error`](https://github.com/causaly/zod-validation-error): Generate user-friendly error messages from `ZodError`s. +- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod. +- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `
` generation and validation for React using Zod. +- [`zodix`](https://github.com/rileytomasek/zodix): Zod utilities for FormData and URLSearchParams in Remix loaders and actions. +- [`remix-params-helper`](https://github.com/kiliman/remix-params-helper): Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps. +- [`formik-validator-zod`](https://github.com/glazy/formik-validator-zod): Formik-compliant validator library that simplifies using Zod with Formik. +- [`zod-i18n-map`](https://github.com/aiji42/zod-i18n): Useful for translating Zod error messages. +- [`@modular-forms/solid`](https://github.com/fabian-hiller/modular-forms): Modular form library for SolidJS that supports Zod for validation. +- [`houseform`](https://github.com/crutchcorn/houseform/): A React form library that uses Zod for validation. +- [`sveltekit-superforms`](https://github.com/ciscoheat/sveltekit-superforms): Supercharged form library for SvelteKit with Zod validation. +- [`mobx-zod-form`](https://github.com/MonoidDev/mobx-zod-form): Data-first form builder based on MobX & Zod. +- [`@vee-validate/zod`](https://github.com/logaretm/vee-validate/tree/main/packages/zod): Form library for Vue.js with Zod schema validation. + +#### Zod to X + +- [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas. +- [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into [JSON Schemas](https://json-schema.org/). +- [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`. +- [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas. +- [`zod-dto`](https://github.com/kbkk/abitia/tree/master/packages/zod-dto): Generate Nest.js DTOs from a Zod schema. +- [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas. +- [`zod-to-openapi`](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters. +- [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas. Provides GraphQL method decorators working with Zod schemas. +- [`zod-openapi`](https://github.com/samchungy/zod-openapi): Create full OpenAPI v3.x documentation from Zod schemas. +- [`fastify-zod-openapi`](https://github.com/samchungy/fastify-zod-openapi): Fastify type provider, validation, serialization and @fastify/swagger support for Zod schemas. +- [`typeschema`](https://typeschema.com/): Universal adapter for schema validation. + +#### X to Zod + +- [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas. +- [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping/tree/master/packages/zod): Generate Zod from static types & JSON schema. +- [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas. [Live demo](https://StefanTerdell.github.io/json-schema-to-zod-react/). +- [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. [Live demo](https://rsinohara.github.io/json-to-zod-react/). +- [`graphql-codegen-typescript-validation-schema`](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema): GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema. +- [`zod-prisma`](https://github.com/CarterGrimmeisen/zod-prisma): Generate Zod schemas from your Prisma schema. +- [`Supervillain`](https://github.com/Southclaws/supervillain): Generate Zod schemas from your Go structs. +- [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema. +- [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod. +- [`zod-prisma-types`](https://github.com/chrishoermann/zod-prisma-types) Create Zod types from your Prisma models. +- [`quicktype`](https://app.quicktype.io/): Convert JSON objects and JSON schemas into Zod schemas. +- [`@sanity-typed/zod`](https://github.com/saiichihashimoto/sanity-typed/tree/main/packages/zod): Generate Zod Schemas from [Sanity Schemas](https://www.sanity.io/docs/schema-types). + +#### Mocking + +- [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/faker-js/faker). +- [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas. +- [`zod-fixture`](https://github.com/timdeschryver/zod-fixture): Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way. +- [`zocker`](https://zocker.sigrist.dev): Generate plausible mock-data from your schemas. +- [`zodock`](https://github.com/ItMaga/zodock) Generate mock data based on Zod schemas. + +#### Powered by Zod + +- [`freerstore`](https://github.com/JacobWeisenburger/freerstore): Firestore cost optimizer. +- [`slonik`](https://github.com/gajus/slonik/tree/gajus/add-zod-validation-backwards-compatible#runtime-validation-and-static-type-inference): Node.js Postgres client with strong Zod integration. +- [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod. +- [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas. +- [`znv`](https://github.com/lostfictions/znv): Type-safe environment parsing and validation for Node.js with Zod schemas. + +#### Utilities for Zod + +- [`zod_utilz`](https://github.com/JacobWeisenburger/zod_utilz): Framework agnostic utilities for Zod. +- [`zod-sandbox`](https://github.com/nereumelo/zod-sandbox): Controlled environment for testing zod schemas. [Live demo](https://zod-sandbox.vercel.app/). + +## Installation + +### Requirements + +- TypeScript 4.5+! +- You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects. + + ```ts + // tsconfig.json + { + // ... + "compilerOptions": { + // ... + "strict": true + } + } + ``` + +### From `npm` (Node/Bun) + +```sh +npm install zod # npm +yarn add zod # yarn +bun add zod # bun +pnpm add zod # pnpm +``` + +Zod also publishes a canary version on every commit. To install the canary: + +```sh +npm install zod@canary # npm +yarn add zod@canary # yarn +bun add zod@canary # bun +pnpm add zod@canary # pnpm +``` + +### From `deno.land/x` (Deno) + +Unlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on [deno.land/x](https://deno.land/x). The latest version can be imported like so: + +```ts +import { z } from "https://deno.land/x/zod/mod.ts"; +``` + +You can also specify a particular version: + +```ts +import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts"; +``` + +> The rest of this README assumes you are using npm and importing directly from the `"zod"` package. + +## Basic usage + +Creating a simple string schema + +```ts +import { z } from "zod"; + +// creating a schema for strings +const mySchema = z.string(); + +// parsing +mySchema.parse("tuna"); // => "tuna" +mySchema.parse(12); // => throws ZodError + +// "safe" parsing (doesn't throw error if validation fails) +mySchema.safeParse("tuna"); // => { success: true; data: "tuna" } +mySchema.safeParse(12); // => { success: false; error: ZodError } +``` + +Creating an object schema + +```ts +import { z } from "zod"; + +const User = z.object({ + username: z.string(), +}); + +User.parse({ username: "Ludwig" }); + +// extract the inferred type +type User = z.infer; +// { username: string } +``` + +## Primitives + +```ts +import { z } from "zod"; + +// primitive values +z.string(); +z.number(); +z.bigint(); +z.boolean(); +z.date(); +z.symbol(); + +// empty types +z.undefined(); +z.null(); +z.void(); // accepts undefined + +// catch-all types +// allows any value +z.any(); +z.unknown(); + +// never type +// allows no values +z.never(); +``` + +## Coercion for primitives + +Zod now provides a more convenient way to coerce primitive values. + +```ts +const schema = z.coerce.string(); +schema.parse("tuna"); // => "tuna" +schema.parse(12); // => "12" +schema.parse(true); // => "true" +``` + +During the parsing step, the input is passed through the `String()` function, which is a JavaScript built-in for coercing data into strings. Note that the returned schema is a `ZodString` instance so you can use all string methods. + +```ts +z.coerce.string().email().min(5); +``` + +All primitive types support coercion. + +```ts +z.coerce.string(); // String(input) +z.coerce.number(); // Number(input) +z.coerce.boolean(); // Boolean(input) +z.coerce.bigint(); // BigInt(input) +z.coerce.date(); // new Date(input) +``` + +**Boolean coercion** + +Zod's boolean coercion is very simple! It passes the value into the `Boolean(value)` function, that's it. Any truthy value will resolve to `true`, any falsy value will resolve to `false`. + +```ts +z.coerce.boolean().parse("tuna"); // => true +z.coerce.boolean().parse("true"); // => true +z.coerce.boolean().parse("false"); // => true +z.coerce.boolean().parse(1); // => true +z.coerce.boolean().parse([]); // => true + +z.coerce.boolean().parse(0); // => false +z.coerce.boolean().parse(undefined); // => false +z.coerce.boolean().parse(null); // => false +``` + +## Literals + +Literal schemas represent a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), like `"hello world"` or `5`. + +```ts +const tuna = z.literal("tuna"); +const twelve = z.literal(12); +const twobig = z.literal(2n); // bigint literal +const tru = z.literal(true); + +const terrificSymbol = Symbol("terrific"); +const terrific = z.literal(terrificSymbol); + +// retrieve literal value +tuna.value; // "tuna" +``` + +> Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue. + +## Strings + +Zod includes a handful of string-specific validations. + +```ts +// validations +z.string().max(5); +z.string().min(5); +z.string().length(5); +z.string().email(); +z.string().url(); +z.string().emoji(); +z.string().uuid(); +z.string().cuid(); +z.string().cuid2(); +z.string().ulid(); +z.string().regex(regex); +z.string().includes(string); +z.string().startsWith(string); +z.string().endsWith(string); +z.string().datetime(); // ISO 8601; default is without UTC offset, see below for options +z.string().ip(); // defaults to IPv4 and IPv6, see below for options + +// transformations +z.string().trim(); // trim whitespace +z.string().toLowerCase(); // toLowerCase +z.string().toUpperCase(); // toUpperCase +``` + +> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions that can be used in conjunction with [Refinements](#refine). + +You can customize some common error messages when creating a string schema. + +```ts +const name = z.string({ + required_error: "Name is required", + invalid_type_error: "Name must be a string", +}); +``` + +When using validation methods, you can pass in an additional argument to provide a custom error message. + +```ts +z.string().min(5, { message: "Must be 5 or more characters long" }); +z.string().max(5, { message: "Must be 5 or fewer characters long" }); +z.string().length(5, { message: "Must be exactly 5 characters long" }); +z.string().email({ message: "Invalid email address" }); +z.string().url({ message: "Invalid url" }); +z.string().emoji({ message: "Contains non-emoji characters" }); +z.string().uuid({ message: "Invalid UUID" }); +z.string().includes("tuna", { message: "Must include tuna" }); +z.string().startsWith("https://", { message: "Must provide secure URL" }); +z.string().endsWith(".com", { message: "Only .com domains allowed" }); +z.string().datetime({ message: "Invalid datetime string! Must be UTC." }); +z.string().ip({ message: "Invalid IP address" }); +``` + +### ISO datetimes + +The `z.string().datetime()` method enforces ISO 8601; default is no timezone offsets and arbitrary sub-second decimal precision. + +```ts +const datetime = z.string().datetime(); + +datetime.parse("2020-01-01T00:00:00Z"); // pass +datetime.parse("2020-01-01T00:00:00.123Z"); // pass +datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision) +datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed) +``` + +Timezone offsets can be allowed by setting the `offset` option to `true`. + +```ts +const datetime = z.string().datetime({ offset: true }); + +datetime.parse("2020-01-01T00:00:00+02:00"); // pass +datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional) +datetime.parse("2020-01-01T00:00:00.123+0200"); // pass (millis optional) +datetime.parse("2020-01-01T00:00:00.123+02"); // pass (only offset hours) +datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported) +``` + +You can additionally constrain the allowable `precision`. By default, arbitrary sub-second precision is supported (but optional). + +```ts +const datetime = z.string().datetime({ precision: 3 }); + +datetime.parse("2020-01-01T00:00:00.123Z"); // pass +datetime.parse("2020-01-01T00:00:00Z"); // fail +datetime.parse("2020-01-01T00:00:00.123456Z"); // fail +``` + +### IP addresses + +The `z.string().ip()` method by default validate IPv4 and IPv6. + +```ts +const ip = z.string().ip(); + +ip.parse("192.168.1.1"); // pass +ip.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // pass +ip.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:192.168.1.1"); // pass + +ip.parse("256.1.1.1"); // fail +ip.parse("84d5:51a0:9114:gggg:4cfa:f2d7:1f12:7003"); // fail +``` + +You can additionally set the IP `version`. + +```ts +const ipv4 = z.string().ip({ version: "v4" }); +ipv4.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // fail + +const ipv6 = z.string().ip({ version: "v6" }); +ipv6.parse("192.168.1.1"); // fail +``` + +## Numbers + +You can customize certain error messages when creating a number schema. + +```ts +const age = z.number({ + required_error: "Age is required", + invalid_type_error: "Age must be a number", +}); +``` + +Zod includes a handful of number-specific validations. + +```ts +z.number().gt(5); +z.number().gte(5); // alias .min(5) +z.number().lt(5); +z.number().lte(5); // alias .max(5) + +z.number().int(); // value must be an integer + +z.number().positive(); // > 0 +z.number().nonnegative(); // >= 0 +z.number().negative(); // < 0 +z.number().nonpositive(); // <= 0 + +z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5) + +z.number().finite(); // value must be finite, not Infinity or -Infinity +z.number().safe(); // value must be between Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER +``` + +Optionally, you can pass in a second argument to provide a custom error message. + +```ts +z.number().lte(5, { message: "this👏is👏too👏big" }); +``` + +## BigInts + +Zod includes a handful of bigint-specific validations. + +```ts +z.bigint().gt(5n); +z.bigint().gte(5n); // alias `.min(5n)` +z.bigint().lt(5n); +z.bigint().lte(5n); // alias `.max(5n)` + +z.bigint().positive(); // > 0n +z.bigint().nonnegative(); // >= 0n +z.bigint().negative(); // < 0n +z.bigint().nonpositive(); // <= 0n + +z.bigint().multipleOf(5n); // Evenly divisible by 5n. +``` + +## NaNs + +You can customize certain error messages when creating a nan schema. + +```ts +const isNaN = z.nan({ + required_error: "isNaN is required", + invalid_type_error: "isNaN must be not a number", +}); +``` + +## Booleans + +You can customize certain error messages when creating a boolean schema. + +```ts +const isActive = z.boolean({ + required_error: "isActive is required", + invalid_type_error: "isActive must be a boolean", +}); +``` + +## Dates + +Use z.date() to validate `Date` instances. + +```ts +z.date().safeParse(new Date()); // success: true +z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false +``` + +You can customize certain error messages when creating a date schema. + +```ts +const myDateSchema = z.date({ + required_error: "Please select a date and time", + invalid_type_error: "That's not a date!", +}); +``` + +Zod provides a handful of date-specific validations. + +```ts +z.date().min(new Date("1900-01-01"), { message: "Too old" }); +z.date().max(new Date(), { message: "Too young!" }); +``` + +**Coercion to Date** + +Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`. + +```ts +const dateSchema = z.coerce.date(); +type DateSchema = z.infer; +// type DateSchema = Date + +/* valid dates */ +console.log(dateSchema.safeParse("2023-01-10T00:00:00.000Z").success); // true +console.log(dateSchema.safeParse("2023-01-10").success); // true +console.log(dateSchema.safeParse("1/10/23").success); // true +console.log(dateSchema.safeParse(new Date("1/10/23")).success); // true + +/* invalid dates */ +console.log(dateSchema.safeParse("2023-13-10").success); // false +console.log(dateSchema.safeParse("0000-00-00").success); // false +``` + +For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276). + +## Zod enums + +```ts +const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]); +type FishEnum = z.infer; +// 'Salmon' | 'Tuna' | 'Trout' +``` + +`z.enum` is a Zod-native way to declare a schema with a fixed set of allowable _string_ values. Pass the array of values directly into `z.enum()`. Alternatively, use `as const` to define your enum values as a tuple of strings. See the [const assertion docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) for details. + +```ts +const VALUES = ["Salmon", "Tuna", "Trout"] as const; +const FishEnum = z.enum(VALUES); +``` + +This is not allowed, since Zod isn't able to infer the exact values of each element. + +```ts +const fish = ["Salmon", "Tuna", "Trout"]; +const FishEnum = z.enum(fish); +``` + +**Autocompletion** + +To get autocompletion with a Zod enum, use the `.enum` property of your schema: + +```ts +FishEnum.enum.Salmon; // => autocompletes + +FishEnum.enum; +/* +=> { + Salmon: "Salmon", + Tuna: "Tuna", + Trout: "Trout", +} +*/ +``` + +You can also retrieve the list of options as a tuple with the `.options` property: + +```ts +FishEnum.options; // ["Salmon", "Tuna", "Trout"]; +``` + +## Native enums + +Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()`. + +**Numeric enums** + +```ts +enum Fruits { + Apple, + Banana, +} + +const FruitEnum = z.nativeEnum(Fruits); +type FruitEnum = z.infer; // Fruits + +FruitEnum.parse(Fruits.Apple); // passes +FruitEnum.parse(Fruits.Banana); // passes +FruitEnum.parse(0); // passes +FruitEnum.parse(1); // passes +FruitEnum.parse(3); // fails +``` + +**String enums** + +```ts +enum Fruits { + Apple = "apple", + Banana = "banana", + Cantaloupe, // you can mix numerical and string enums +} + +const FruitEnum = z.nativeEnum(Fruits); +type FruitEnum = z.infer; // Fruits + +FruitEnum.parse(Fruits.Apple); // passes +FruitEnum.parse(Fruits.Cantaloupe); // passes +FruitEnum.parse("apple"); // passes +FruitEnum.parse("banana"); // passes +FruitEnum.parse(0); // passes +FruitEnum.parse("Cantaloupe"); // fails +``` + +**Const enums** + +The `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` requires TypeScript 3.4+! + +```ts +const Fruits = { + Apple: "apple", + Banana: "banana", + Cantaloupe: 3, +} as const; + +const FruitEnum = z.nativeEnum(Fruits); +type FruitEnum = z.infer; // "apple" | "banana" | 3 + +FruitEnum.parse("apple"); // passes +FruitEnum.parse("banana"); // passes +FruitEnum.parse(3); // passes +FruitEnum.parse("Cantaloupe"); // fails +``` + +You can access the underlying object with the `.enum` property: + +```ts +FruitEnum.enum.Apple; // "apple" +``` + +## Optionals + +You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result. + +```ts +const schema = z.optional(z.string()); + +schema.parse(undefined); // => returns undefined +type A = z.infer; // string | undefined +``` + +For convenience, you can also call the `.optional()` method on an existing schema. + +```ts +const user = z.object({ + username: z.string().optional(), +}); +type C = z.infer; // { username?: string | undefined }; +``` + +You can extract the wrapped schema from a `ZodOptional` instance with `.unwrap()`. + +```ts +const stringSchema = z.string(); +const optionalString = stringSchema.optional(); +optionalString.unwrap() === stringSchema; // true +``` + +## Nullables + +Similarly, you can create nullable types with `z.nullable()`. + +```ts +const nullableString = z.nullable(z.string()); +nullableString.parse("asdf"); // => "asdf" +nullableString.parse(null); // => null +``` + +Or use the `.nullable()` method. + +```ts +const E = z.string().nullable(); // equivalent to nullableString +type E = z.infer; // string | null +``` + +Extract the inner schema with `.unwrap()`. + +```ts +const stringSchema = z.string(); +const nullableString = stringSchema.nullable(); +nullableString.unwrap() === stringSchema; // true +``` + +## Objects + +```ts +// all properties are required by default +const Dog = z.object({ + name: z.string(), + age: z.number(), +}); + +// extract the inferred type like this +type Dog = z.infer; + +// equivalent to: +type Dog = { + name: string; + age: number; +}; +``` + +### `.shape` + +Use `.shape` to access the schemas for a particular key. + +```ts +Dog.shape.name; // => string schema +Dog.shape.age; // => number schema +``` + +### `.keyof` + +Use `.keyof` to create a `ZodEnum` schema from the keys of an object schema. + +```ts +const keySchema = Dog.keyof(); +keySchema; // ZodEnum<["name", "age"]> +``` + +### `.extend` + +You can add additional fields to an object schema with the `.extend` method. + +```ts +const DogWithBreed = Dog.extend({ + breed: z.string(), +}); +``` + +You can use `.extend` to overwrite fields! Be careful with this power! + +### `.merge` + +Equivalent to `A.extend(B.shape)`. + +```ts +const BaseTeacher = z.object({ students: z.array(z.string()) }); +const HasID = z.object({ id: z.string() }); + +const Teacher = BaseTeacher.merge(HasID); +type Teacher = z.infer; // => { students: string[], id: string } +``` + +> If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B. + +### `.pick/.omit` + +Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a modified version. Consider this Recipe schema: + +```ts +const Recipe = z.object({ + id: z.string(), + name: z.string(), + ingredients: z.array(z.string()), +}); +``` + +To only keep certain keys, use `.pick` . + +```ts +const JustTheName = Recipe.pick({ name: true }); +type JustTheName = z.infer; +// => { name: string } +``` + +To remove certain keys, use `.omit` . + +```ts +const NoIDRecipe = Recipe.omit({ id: true }); + +type NoIDRecipe = z.infer; +// => { name: string, ingredients: string[] } +``` + +### `.partial` + +Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype), the `.partial` method makes all properties optional. + +Starting from this object: + +```ts +const user = z.object({ + email: z.string(), + username: z.string(), +}); +// { email: string; username: string } +``` + +We can create a partial version: + +```ts +const partialUser = user.partial(); +// { email?: string | undefined; username?: string | undefined } +``` + +You can also specify which properties to make optional: + +```ts +const optionalEmail = user.partial({ + email: true, +}); +/* +{ + email?: string | undefined; + username: string +} +*/ +``` + +### `.deepPartial` + +The `.partial` method is shallow — it only applies one level deep. There is also a "deep" version: + +```ts +const user = z.object({ + username: z.string(), + location: z.object({ + latitude: z.number(), + longitude: z.number(), + }), + strings: z.array(z.object({ value: z.string() })), +}); + +const deepPartialUser = user.deepPartial(); + +/* +{ + username?: string | undefined, + location?: { + latitude?: number | undefined; + longitude?: number | undefined; + } | undefined, + strings?: { value?: string}[] +} +*/ +``` + +> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples. + +### `.required` + +Contrary to the `.partial` method, the `.required` method makes all properties required. + +Starting from this object: + +```ts +const user = z + .object({ + email: z.string(), + username: z.string(), + }) + .partial(); +// { email?: string | undefined; username?: string | undefined } +``` + +We can create a required version: + +```ts +const requiredUser = user.required(); +// { email: string; username: string } +``` + +You can also specify which properties to make required: + +```ts +const requiredEmail = user.required({ + email: true, +}); +/* +{ + email: string; + username?: string | undefined; +} +*/ +``` + +### `.passthrough` + +By default Zod object schemas strip out unrecognized keys during parsing. + +```ts +const person = z.object({ + name: z.string(), +}); + +person.parse({ + name: "bob dylan", + extraKey: 61, +}); +// => { name: "bob dylan" } +// extraKey has been stripped +``` + +Instead, if you want to pass through unknown keys, use `.passthrough()` . + +```ts +person.passthrough().parse({ + name: "bob dylan", + extraKey: 61, +}); +// => { name: "bob dylan", extraKey: 61 } +``` + +### `.strict` + +By default Zod object schemas strip out unrecognized keys during parsing. You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error. + +```ts +const person = z + .object({ + name: z.string(), + }) + .strict(); + +person.parse({ + name: "bob dylan", + extraKey: 61, +}); +// => throws ZodError +``` + +### `.strip` + +You can use the `.strip` method to reset an object schema to the default behavior (stripping unrecognized keys). + +### `.catchall` + +You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it. + +```ts +const person = z + .object({ + name: z.string(), + }) + .catchall(z.number()); + +person.parse({ + name: "bob dylan", + validExtraKey: 61, // works fine +}); + +person.parse({ + name: "bob dylan", + validExtraKey: false, // fails +}); +// => throws ZodError +``` + +Using `.catchall()` obviates `.passthrough()` , `.strip()` , or `.strict()`. All keys are now considered "known". + +## Arrays + +```ts +const stringArray = z.array(z.string()); + +// equivalent +const stringArray = z.string().array(); +``` + +Be careful with the `.array()` method. It returns a new `ZodArray` instance. This means the _order_ in which you call methods matters. For instance: + +```ts +z.string().optional().array(); // (string | undefined)[] +z.string().array().optional(); // string[] | undefined +``` + +### `.element` + +Use `.element` to access the schema for an element of the array. + +```ts +stringArray.element; // => string schema +``` + +### `.nonempty` + +If you want to ensure that an array contains at least one element, use `.nonempty()`. + +```ts +const nonEmptyStrings = z.string().array().nonempty(); +// the inferred type is now +// [string, ...string[]] + +nonEmptyStrings.parse([]); // throws: "Array cannot be empty" +nonEmptyStrings.parse(["Ariana Grande"]); // passes +``` + +You can optionally specify a custom error message: + +```ts +// optional custom error message +const nonEmptyStrings = z.string().array().nonempty({ + message: "Can't be empty!", +}); +``` + +### `.min/.max/.length` + +```ts +z.string().array().min(5); // must contain 5 or more items +z.string().array().max(5); // must contain 5 or fewer items +z.string().array().length(5); // must contain 5 items exactly +``` + +Unlike `.nonempty()` these methods do not change the inferred type. + +## Tuples + +Unlike arrays, tuples have a fixed number of elements and each element can have a different type. + +```ts +const athleteSchema = z.tuple([ + z.string(), // name + z.number(), // jersey number + z.object({ + pointsScored: z.number(), + }), // statistics +]); + +type Athlete = z.infer; +// type Athlete = [string, number, { pointsScored: number }] +``` + +A variadic ("rest") argument can be added with the `.rest` method. + +```ts +const variadicTuple = z.tuple([z.string()]).rest(z.number()); +const result = variadicTuple.parse(["hello", 1, 2, 3]); +// => [string, ...number[]]; +``` + +## Unions + +Zod includes a built-in `z.union` method for composing "OR" types. + +```ts +const stringOrNumber = z.union([z.string(), z.number()]); + +stringOrNumber.parse("foo"); // passes +stringOrNumber.parse(14); // passes +``` + +Zod will test the input against each of the "options" in order and return the first value that validates successfully. + +For convenience, you can also use the [`.or` method](#or): + +```ts +const stringOrNumber = z.string().or(z.number()); +``` + +**Optional string validation:** + +To validate an optional form input, you can union the desired string validation with an empty string [literal](#literals). + +This example validates an input that is optional but needs to contain a [valid URL](#strings): + +```ts +const optionalUrl = z.union([z.string().url().nullish(), z.literal("")]); + +console.log(optionalUrl.safeParse(undefined).success); // true +console.log(optionalUrl.safeParse(null).success); // true +console.log(optionalUrl.safeParse("").success); // true +console.log(optionalUrl.safeParse("https://zod.dev").success); // true +console.log(optionalUrl.safeParse("not a valid url").success); // false +``` + +## Discriminated unions + +A discriminated union is a union of object schemas that all share a particular key. + +```ts +type MyUnion = + | { status: "success"; data: string } + | { status: "failed"; error: Error }; +``` + +Such unions can be represented with the `z.discriminatedUnion` method. This enables faster evaluation, because Zod can check the _discriminator key_ (`status` in the example above) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors. + +With the basic union method, the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option". + +```ts +const myUnion = z.discriminatedUnion("status", [ + z.object({ status: z.literal("success"), data: z.string() }), + z.object({ status: z.literal("failed"), error: z.instanceof(Error) }), +]); + +myUnion.parse({ status: "success", data: "yippie ki yay" }); +``` + +## Records + +Record schemas are used to validate types such as `{ [k: string]: number }`. + +If you want to validate the _values_ of an object against some schema but don't care about the keys, use `z.record(valueType)`: + +```ts +const NumberCache = z.record(z.number()); + +type NumberCache = z.infer; +// => { [k: string]: number } +``` + +This is particularly useful for storing or caching items by ID. + +```ts +const userSchema = z.object({ name: z.string() }); +const userStoreSchema = z.record(userSchema); + +type UserStore = z.infer; +// => type UserStore = { [ x: string ]: { name: string } } + +const userStore: UserStore = {}; + +userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { + name: "Carlotta", +}; // passes + +userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { + whatever: "Ice cream sundae", +}; // TypeError +``` + +### Record key type + +If you want to validate both the keys and the values, use +`z.record(keyType, valueType)`: + +```ts +const NoEmptyKeysSchema = z.record(z.string().min(1), z.number()); +NoEmptyKeysSchema.parse({ count: 1 }); // => { 'count': 1 } +NoEmptyKeysSchema.parse({ "": 1 }); // fails +``` + +_(Notice how when passing two arguments, `valueType` is the second argument)_ + +**A note on numerical keys** + +While `z.record(keyType, valueType)` is able to accept numerical key types and TypeScript's built-in Record type is `Record`, it's hard to represent the TypeScript type `Record` in Zod. + +As it turns out, TypeScript's behavior surrounding `[k: number]` is a little unintuitive: + +```ts +const testMap: { [k: number]: string } = { + 1: "one", +}; + +for (const key in testMap) { + console.log(`${key}: ${typeof key}`); +} +// prints: `1: string` +``` + +As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript. + +## Maps + +```ts +const stringNumberMap = z.map(z.string(), z.number()); + +type StringNumberMap = z.infer; +// type StringNumberMap = Map +``` + +## Sets + +```ts +const numberSet = z.set(z.number()); +type NumberSet = z.infer; +// type NumberSet = Set +``` + +Set schemas can be further constrained with the following utility methods. + +```ts +z.set(z.string()).nonempty(); // must contain at least one item +z.set(z.string()).min(5); // must contain 5 or more items +z.set(z.string()).max(5); // must contain 5 or fewer items +z.set(z.string()).size(5); // must contain 5 items exactly +``` + +## Intersections + +Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types. + +```ts +const Person = z.object({ + name: z.string(), +}); + +const Employee = z.object({ + role: z.string(), +}); + +const EmployedPerson = z.intersection(Person, Employee); + +// equivalent to: +const EmployedPerson = Person.and(Employee); +``` + +Though in many cases, it is recommended to use `A.merge(B)` to merge two objects. The `.merge` method returns a new `ZodObject` instance, whereas `A.and(B)` returns a less useful `ZodIntersection` instance that lacks common object methods like `pick` and `omit`. + +```ts +const a = z.union([z.number(), z.string()]); +const b = z.union([z.number(), z.boolean()]); +const c = z.intersection(a, b); + +type c = z.infer; // => number +``` + + + + + +## Recursive types + +You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint". + +```ts +const baseCategorySchema = z.object({ + name: z.string(), +}); + +type Category = z.infer & { + subcategories: Category[]; +}; + +const categorySchema: z.ZodType = baseCategorySchema.extend({ + subcategories: z.lazy(() => categorySchema.array()), +}); + +categorySchema.parse({ + name: "People", + subcategories: [ + { + name: "Politicians", + subcategories: [ + { + name: "Presidents", + subcategories: [], + }, + ], + }, + ], +}); // passes +``` + +Thanks to [crasite](https://github.com/crasite) for this example. + +### ZodType with ZodEffects + +When using `z.ZodType` with `z.ZodEffects` ( +[`.refine`](https://github.com/colinhacks/zod#refine), +[`.transform`](https://github.com/colinhacks/zod#transform), +[`preprocess`](https://github.com/colinhacks/zod#preprocess), +etc... +), you will need to define the input and output types of the schema. `z.ZodType` + +```ts +const isValidId = (id: string): id is `${string}/${string}` => + id.split("/").length === 2; + +const baseSchema = z.object({ + id: z.string().refine(isValidId), +}); + +type Input = z.input & { + children: Input[]; +}; + +type Output = z.output & { + children: Output[]; +}; + +const schema: z.ZodType = baseSchema.extend({ + children: z.lazy(() => schema.array()), +}); +``` + +Thanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example. + +### JSON type + +If you want to validate any JSON value, you can use the snippet below. + +```ts +const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); +type Literal = z.infer; +type Json = Literal | { [key: string]: Json } | Json[]; +const jsonSchema: z.ZodType = z.lazy(() => + z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) +); + +jsonSchema.parse(data); +``` + +Thanks to [ggoodman](https://github.com/ggoodman) for suggesting this. + +### Cyclical objects + +Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop. + +## Promises + +```ts +const numberPromise = z.promise(z.number()); +``` + +"Parsing" works a little differently with promise schemas. Validation happens in two parts: + +1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with `.then` and `.catch` methods.). +2. Zod uses `.then` to attach an additional validation step onto the existing Promise. You'll have to use `.catch` on the returned Promise to handle validation failures. + +```ts +numberPromise.parse("tuna"); +// ZodError: Non-Promise type: string + +numberPromise.parse(Promise.resolve("tuna")); +// => Promise + +const test = async () => { + await numberPromise.parse(Promise.resolve("tuna")); + // ZodError: Non-number type: string + + await numberPromise.parse(Promise.resolve(3.14)); + // => 3.14 +}; +``` + + + +## Instanceof + +You can use `z.instanceof` to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries. + +```ts +class Test { + name: string; +} + +const TestSchema = z.instanceof(Test); + +const blob: any = "whatever"; +TestSchema.parse(new Test()); // passes +TestSchema.parse("blob"); // throws +``` + +## Functions + +Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic". + +You can create a function schema with `z.function(args, returnType)` . + +```ts +const myFunction = z.function(); + +type myFunction = z.infer; +// => ()=>unknown +``` + +Define inputs and outputs. + +```ts +const myFunction = z + .function() + .args(z.string(), z.number()) // accepts an arbitrary number of arguments + .returns(z.boolean()); + +type myFunction = z.infer; +// => (arg0: string, arg1: number)=>boolean +``` + + + +Function schemas have an `.implement()` method which accepts a function and returns a new function that automatically validates its inputs and outputs. + +```ts +const trimmedLength = z + .function() + .args(z.string()) // accepts an arbitrary number of arguments + .returns(z.number()) + .implement((x) => { + // TypeScript knows x is a string! + return x.trim().length; + }); + +trimmedLength("sandwich"); // => 8 +trimmedLength(" asdf "); // => 4 +``` + +If you only care about validating inputs, just don't call the `.returns()` method. The output type will be inferred from the implementation. + +> You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.) + +```ts +const myFunction = z + .function() + .args(z.string()) + .implement((arg) => { + return [arg.length]; + }); + +myFunction; // (arg: string)=>number[] +``` + +Extract the input and output schemas from a function schema. + +```ts +myFunction.parameters(); +// => ZodTuple<[ZodString, ZodNumber]> + +myFunction.returnType(); +// => ZodBoolean +``` + + + +## Preprocess + +> Zod now supports primitive coercion without the need for `.preprocess()`. See the [coercion docs](#coercion-for-primitives) for more information. + +Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the [.transform docs](#transform).) + +But sometimes you want to apply some transform to the input _before_ parsing happens. A common use case: type coercion. Zod enables this with the `z.preprocess()`. + +```ts +const castToString = z.preprocess((val) => String(val), z.string()); +``` + +This returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms. + +## Custom schemas + +You can create a Zod schema for any TypeScript type by using `z.custom()`. This is useful for creating schemas for types that are not supported by Zod out of the box, such as template string literals. + +```ts +const px = z.custom<`${number}px`>((val) => { + return typeof val === "string" ? /^\d+px$/.test(val) : false; +}); + +type px = z.infer; // `${number}px` + +px.parse("42px"); // "42px" +px.parse("42vw"); // throws; +``` + +If you don't provide a validation function, Zod will allow any value. This can be dangerous! + +```ts +z.custom<{ arg: string }>(); // performs no validation +``` + +You can customize the error message and other options by passing a second argument. This parameter works the same way as the params parameter of [`.refine`](#refine). + +```ts +z.custom<...>((val) => ..., "custom error message"); +``` + +## Schema methods + +All Zod schemas contain certain methods. + +### `.parse` + +`.parse(data: unknown): T` + +Given any Zod schema, you can call its `.parse` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown. + +> IMPORTANT: The value returned by `.parse` is a _deep clone_ of the variable you passed in. + +```ts +const stringSchema = z.string(); + +stringSchema.parse("fish"); // => returns "fish" +stringSchema.parse(12); // throws error +``` + +### `.parseAsync` + +`.parseAsync(data:unknown): Promise` + +If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`. + +```ts +const stringSchema = z.string().refine(async (val) => val.length <= 8); + +await stringSchema.parseAsync("hello"); // => returns "hello" +await stringSchema.parseAsync("hello world"); // => throws error +``` + +### `.safeParse` + +`.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }` + +If you don't want Zod to throw errors when validation fails, use `.safeParse`. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems. + +```ts +stringSchema.safeParse(12); +// => { success: false; error: ZodError } + +stringSchema.safeParse("billie"); +// => { success: true; data: 'billie' } +``` + +The result is a _discriminated union_, so you can handle errors very conveniently: + +```ts +const result = stringSchema.safeParse("billie"); +if (!result.success) { + // handle error then return + result.error; +} else { + // do something + result.data; +} +``` + +### `.safeParseAsync` + +> Alias: `.spa` + +An asynchronous version of `safeParse`. + +```ts +await stringSchema.safeParseAsync("billie"); +``` + +For convenience, this has been aliased to `.spa`: + +```ts +await stringSchema.spa("billie"); +``` + +### `.refine` + +`.refine(validator: (data:T)=>any, params?: RefineParams)` + +Zod lets you provide custom validation logic via _refinements_. (For advanced features like creating multiple issues and customizing error codes, see [`.superRefine`](#superrefine).) + +Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an integer or that a string is a valid email address. + +For example, you can define a custom validation check on _any_ Zod schema with `.refine` : + +```ts +const myString = z.string().refine((val) => val.length <= 255, { + message: "String can't be more than 255 characters", +}); +``` + +> ⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure. + +#### Arguments + +As you can see, `.refine` takes two arguments. + +1. The first is the validation function. This function takes one input (of type `T` — the inferred type of the schema) and returns `any`. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.) +2. The second argument accepts some options. You can use this to customize certain error-handling behavior: + +```ts +type RefineParams = { + // override error message + message?: string; + + // appended to error path + path?: (string | number)[]; + + // params object you can use to customize message + // in error map + params?: object; +}; +``` + +For advanced cases, the second argument can also be a function that returns `RefineParams`. + +```ts +const longString = z.string().refine( + (val) => val.length > 10, + (val) => ({ message: `${val} is not more than 10 characters` }) +); +``` + +#### Customize error path + +```ts +const passwordForm = z + .object({ + password: z.string(), + confirm: z.string(), + }) + .refine((data) => data.password === data.confirm, { + message: "Passwords don't match", + path: ["confirm"], // path of error + }); + +passwordForm.parse({ password: "asdf", confirm: "qwer" }); +``` + +Because you provided a `path` parameter, the resulting error will be: + +```ts +ZodError { + issues: [{ + "code": "custom", + "path": [ "confirm" ], + "message": "Passwords don't match" + }] +} +``` + +#### Asynchronous refinements + +Refinements can also be async: + +```ts +const userId = z.string().refine(async (id) => { + // verify that ID exists in database + return true; +}); +``` + +> ⚠️ If you use async refinements, you must use the `.parseAsync` method to parse data! Otherwise Zod will throw an error. + +#### Relationship to transforms + +Transforms and refinements can be interleaved: + +```ts +z.string() + .transform((val) => val.length) + .refine((val) => val > 25); +``` + + + +### `.superRefine` + +The `.refine` method is actually syntactic sugar atop a more versatile (and verbose) method called `superRefine`. Here's an example: + +```ts +const Strings = z.array(z.string()).superRefine((val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + code: z.ZodIssueCode.too_big, + maximum: 3, + type: "array", + inclusive: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `No duplicates allowed.`, + }); + } +}); +``` + +You can add as many issues as you like. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes. + +Normally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` it's possible to throw issues of any `ZodIssueCode`. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md). + +#### Abort early + +By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue` and return `z.NEVER`. + +```ts +const schema = z.number().superRefine((val, ctx) => { + if (val < 10) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "should be >= 10", + fatal: true, + }); + + return z.NEVER; + } + + if (val !== 12) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "should be twelve", + }); + } +}); +``` + +#### Type refinements + +If you provide a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) to `.refine()` or `.superRefine()`, the resulting type will be narrowed down to your predicate's type. This is useful if you are mixing multiple chained refinements and transformations: + +```ts +const schema = z + .object({ + first: z.string(), + second: z.number(), + }) + .nullable() + .superRefine((arg, ctx): arg is { first: string; second: number } => { + if (!arg) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, // customize your issue + message: "object should exist", + }); + } + + return z.NEVER; // The return value is not used, but we need to return something to satisfy the typing + }) + // here, TS knows that arg is not null + .refine((arg) => arg.first === "bob", "`first` is not `bob`!"); +``` + +> ⚠️ You **must** use `ctx.addIssue()` instead of returning a boolean value to indicate whether the validation passes. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes. + +### `.transform` + +To transform data after parsing, use the `transform` method. + +```ts +const stringToNumber = z.string().transform((val) => val.length); + +stringToNumber.parse("string"); // => 6 +``` + +#### Chaining order + +Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms. + +```ts +const emailToDomain = z + .string() + .email() + .transform((val) => val.split("@")[1]); + +emailToDomain.parse("colinhacks@example.com"); // => example.com +``` + +#### Validating during transform + +The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`. + +As with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues. + +```ts +const numberInString = z.string().transform((val, ctx) => { + const parsed = parseInt(val); + if (isNaN(parsed)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "Not a number", + }); + + // This is a special symbol you can use to + // return early from the transform function. + // It has type `never` so it does not affect the + // inferred return type. + return z.NEVER; + } + return parsed; +}); +``` + +#### Relationship to refinements + +Transforms and refinements can be interleaved. These will be executed in the order they are declared. + +```ts +const nameToGreeting = z + .string() + .transform((val) => val.toUpperCase()) + .refine((val) => val.length > 15) + .transform((val) => `Hello ${val}`) + .refine((val) => val.indexOf("!") === -1); +``` + +#### Async transforms + +Transforms can also be async. + +```ts +const IdToUser = z + .string() + .uuid() + .transform(async (id) => { + return await getUserById(id); + }); +``` + +> ⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error. + +### `.default` + +You can use transforms to implement the concept of "default values" in Zod. + +```ts +const stringWithDefault = z.string().default("tuna"); + +stringWithDefault.parse(undefined); // => "tuna" +``` + +Optionally, you can pass a function into `.default` that will be re-executed whenever a default value needs to be generated: + +```ts +const numberWithRandomDefault = z.number().default(Math.random); + +numberWithRandomDefault.parse(undefined); // => 0.4413456736055323 +numberWithRandomDefault.parse(undefined); // => 0.1871840107401901 +numberWithRandomDefault.parse(undefined); // => 0.7223408162401552 +``` + +Conceptually, this is how Zod processes default values: + +1. If the input is `undefined`, the default value is returned +2. Otherwise, the data is parsed using the base schema + +### `.describe` + +Use `.describe()` to add a `description` property to the resulting schema. + +```ts +const documentedString = z + .string() + .describe("A useful bit of text, if you know what to do with it."); +documentedString.description; // A useful bit of text… +``` + +This can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)). + +### `.catch` + +Use `.catch()` to provide a "catch value" to be returned in the event of a parsing error. + +```ts +const numberWithCatch = z.number().catch(42); + +numberWithCatch.parse(5); // => 5 +numberWithCatch.parse("tuna"); // => 42 +``` + +Optionally, you can pass a function into `.catch` that will be re-executed whenever a default value needs to be generated. A `ctx` object containing the caught error will be passed into this function. + +```ts +const numberWithRandomCatch = z.number().catch((ctx) => { + ctx.error; // the caught ZodError + return Math.random(); +}); + +numberWithRandomCatch.parse("sup"); // => 0.4413456736055323 +numberWithRandomCatch.parse("sup"); // => 0.1871840107401901 +numberWithRandomCatch.parse("sup"); // => 0.7223408162401552 +``` + +Conceptually, this is how Zod processes "catch values": + +1. The data is parsed using the base schema +2. If the parsing fails, the "catch value" is returned + +### `.optional` + +A convenience method that returns an optional version of a schema. + +```ts +const optionalString = z.string().optional(); // string | undefined + +// equivalent to +z.optional(z.string()); +``` + +### `.nullable` + +A convenience method that returns a nullable version of a schema. + +```ts +const nullableString = z.string().nullable(); // string | null + +// equivalent to +z.nullable(z.string()); +``` + +### `.nullish` + +A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both `undefined` and `null`. Read more about the concept of "nullish" [in the TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing). + +```ts +const nullishString = z.string().nullish(); // string | null | undefined + +// equivalent to +z.string().nullable().optional(); +``` + +### `.array` + +A convenience method that returns an array schema for the given type: + +```ts +const stringArray = z.string().array(); // string[] + +// equivalent to +z.array(z.string()); +``` + +### `.promise` + +A convenience method for promise types: + +```ts +const stringPromise = z.string().promise(); // Promise + +// equivalent to +z.promise(z.string()); +``` + +### `.or` + +A convenience method for [union types](#unions). + +```ts +const stringOrNumber = z.string().or(z.number()); // string | number + +// equivalent to +z.union([z.string(), z.number()]); +``` + +### `.and` + +A convenience method for creating intersection types. + +```ts +const nameAndAge = z + .object({ name: z.string() }) + .and(z.object({ age: z.number() })); // { name: string } & { age: number } + +// equivalent to +z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() })); +``` + +### `.brand` + +`.brand() => ZodBranded` + +TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same. + +```ts +type Cat = { name: string }; +type Dog = { name: string }; + +const petCat = (cat: Cat) => {}; +const fido: Dog = { name: "fido" }; +petCat(fido); // works fine +``` + +In some cases, its can be desirable to simulate _nominal typing_ inside TypeScript. For instance, you may wish to write a function that only accepts an input that has been validated by Zod. This can be achieved with _branded types_ (AKA _opaque types_). + +```ts +const Cat = z.object({ name: z.string() }).brand<"Cat">(); +type Cat = z.infer; + +const petCat = (cat: Cat) => {}; + +// this works +const simba = Cat.parse({ name: "simba" }); +petCat(simba); + +// this doesn't +petCat({ name: "fido" }); +``` + +Under the hood, this works by attaching a "brand" to the inferred type using an intersection type. This way, plain/unbranded data structures are no longer assignable to the inferred type of the schema. + +```ts +const Cat = z.object({ name: z.string() }).brand<"Cat">(); +type Cat = z.infer; +// {name: string} & {[symbol]: "Cat"} +``` + +Note that branded types do not affect the runtime result of `.parse`. It is a static-only construct. + +### `.readonly` + +`.readonly() => ZodReadonly` + +This method returns a `ZodReadonly` schema instance that parses the input using the base schema, then calls `Object.freeze()` on the result. The inferred type is also marked as `readonly`. + +```ts +const schema = z.object({ name: string }).readonly(); +type schema = z.infer; +// Readonly<{name: string}> + +const result = schema.parse({ name: "fido" }); +result.name = "simba"; // error +``` + +The inferred type uses TypeScript's built-in readonly types when relevant. + +```ts +z.array(z.string()).readonly(); +// readonly string[] + +z.tuple([z.string(), z.number()]).readonly(); +// readonly [string, number] + +z.map(z.string(), z.date()).readonly(); +// ReadonlyMap + +z.set(z.string()).readonly(); +// ReadonlySet> +``` + +### `.pipe` + +Schemas can be chained into validation "pipelines". It's useful for easily validating the result after a `.transform()`: + +```ts +z.string() + .transform((val) => val.length) + .pipe(z.number().min(5)); +``` + +The `.pipe()` method returns a `ZodPipeline` instance. + +#### You can use `.pipe()` to fix common issues with `z.coerce`. + +You can constrain the input to types that work well with your chosen coercion. Then use `.pipe()` to apply the coercion. + +without constrained input: + +```ts +const toDate = z.coerce.date(); + +// works intuitively +console.log(toDate.safeParse("2023-01-01").success); // true + +// might not be what you want +console.log(toDate.safeParse(null).success); // true +``` + +with constrained input: + +```ts +const datelike = z.union([z.number(), z.string(), z.date()]); +const datelikeToDate = datelike.pipe(z.coerce.date()); + +// still works intuitively +console.log(datelikeToDate.safeParse("2023-01-01").success); // true + +// more likely what you want +console.log(datelikeToDate.safeParse(null).success); // false +``` + +You can also use this technique to avoid coercions that throw uncaught errors. + +without constrained input: + +```ts +const toBigInt = z.coerce.bigint(); + +// works intuitively +console.log(toBigInt.safeParse("42")); // true + +// probably not what you want +console.log(toBigInt.safeParse(null)); // throws uncaught error +``` + +with constrained input: + +```ts +const toNumber = z.number().or(z.string()).pipe(z.coerce.number()); +const toBigInt = z.bigint().or(toNumber).pipe(z.coerce.bigint()); + +// still works intuitively +console.log(toBigInt.safeParse("42").success); // true + +// error handled by zod, more likely what you want +console.log(toBigInt.safeParse(null).success); // false +``` + +## Guides and concepts + +### Type inference + +You can extract the TypeScript type of any schema with `z.infer` . + +```ts +const A = z.string(); +type A = z.infer; // string + +const u: A = 12; // TypeError +const u: A = "asdf"; // compiles +``` + +**What about transforms?** + +In reality each Zod schema internally tracks **two** types: an input and an output. For most schemas (e.g. `z.string()`) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance `z.string().transform(val => val.length)` has an input of `string` and an output of `number`. + +You can separately extract the input and output types like so: + +```ts +const stringToNumber = z.string().transform((val) => val.length); + +// ⚠️ Important: z.infer returns the OUTPUT type! +type input = z.input; // string +type output = z.output; // number + +// equivalent to z.output! +type inferred = z.infer; // number +``` + +### Writing generic functions + +When attempting to write a function that accepts a Zod schema as an input, it's common to try something like this: + +```ts +function makeSchemaOptional(schema: z.ZodType) { + return schema.optional(); +} +``` + +This approach has some issues. The `schema` variable in this function is typed as an instance of `ZodType`, which is an abstract class that all Zod schemas inherit from. This approach loses type information, namely _which subclass_ the input actually is. + +```ts +const arg = makeSchemaOptional(z.string()); +arg.unwrap(); +``` + +A better approach is for the generic parameter to refer to _the schema as a whole_. + +```ts +function makeSchemaOptional(schema: T) { + return schema.optional(); +} +``` + +> `ZodTypeAny` is just a shorthand for `ZodType`, a type that is broad enough to match any Zod schema. + +As you can see, `schema` is now fully and properly typed. + +```ts +const arg = makeSchemaOptional(z.string()); +arg.unwrap(); // ZodString +``` + +#### Constraining allowable inputs + +The `ZodType` class has three generic parameters. + +```ts +class ZodType< + Output = any, + Def extends ZodTypeDef = ZodTypeDef, + Input = Output +> { ... } +``` + +By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function: + +```ts +function makeSchemaOptional>(schema: T) { + return schema.optional(); +} + +makeSchemaOptional(z.string()); +// works fine + +makeSchemaOptional(z.number()); +// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType' +``` + +### Error handling + +Zod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems. + +```ts +const result = z + .object({ + name: z.string(), + }) + .safeParse({ name: 12 }); + +if (!result.success) { + result.error.issues; + /* [ + { + "code": "invalid_type", + "expected": "string", + "received": "number", + "path": [ "name" ], + "message": "Expected string, received number" + } + ] */ +} +``` + +> For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md) + +Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error) + +### Error formatting + +You can use the `.format()` method to convert this error into a nested object. + +```ts +const result = z + .object({ + name: z.string(), + }) + .safeParse({ name: 12 }); + +if (!result.success) { + const formatted = result.error.format(); + /* { + name: { _errors: [ 'Expected string, received number' ] } + } */ + + formatted.name?._errors; + // => ["Expected string, received number"] +} +``` + +## Comparison + +There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience. + + + + + + + +### Joi + +[https://github.com/hapijs/joi](https://github.com/hapijs/joi) + +Doesn't support static type inference 😕 + +### Yup + +[https://github.com/jquense/yup](https://github.com/jquense/yup) + +Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript. + +- Supports casting and transforms +- All object fields are optional by default + +- Missing promise schemas +- Missing function schemas +- Missing union & intersection schemas + + + +### io-ts + +[https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts) + +io-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod. + +In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts: + +```ts +import * as t from "io-ts"; + +const A = t.type({ + foo: t.string, +}); + +const B = t.partial({ + bar: t.number, +}); + +const C = t.intersection([A, B]); + +type C = t.TypeOf; +// returns { foo: string; bar?: number | undefined } +``` + +You must define the required and optional props in separate object validators, pass the optionals through `t.partial` (which marks all properties as optional), then combine them with `t.intersection` . + +Consider the equivalent in Zod: + +```ts +const C = z.object({ + foo: z.string(), + bar: z.number().optional(), +}); + +type C = z.infer; +// returns { foo: string; bar?: number | undefined } +``` + +This more declarative API makes schema definitions vastly more concise. + +`io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the `fp-ts` nomenclature to use the library. + +- Supports codecs with serialization & deserialization transforms +- Supports branded types +- Supports advanced functional programming, higher-kinded types, `fp-ts` compatibility +- Missing object methods: (pick, omit, partial, deepPartial, merge, extend) +- Missing nonempty arrays with proper typing (`[T, ...T[]]`) +- Missing promise schemas +- Missing function schemas + +### Runtypes + +[https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes) + +Good type inference support. + +- Supports "pattern matching": computed properties that distribute over unions +- Missing object methods: (deepPartial, merge) +- Missing nonempty arrays with proper typing (`[T, ...T[]]`) +- Missing promise schemas +- Missing error customization + +### Ow + +[https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow) + +Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array` , see full list in their README). + +If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream. + +## Changelog + +View the changelog at [CHANGELOG.md](CHANGELOG.md) diff --git a/test/merkletreejs/node_modules/zod/index.d.ts b/test/merkletreejs/node_modules/zod/index.d.ts new file mode 100644 index 0000000..97b0b22 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/index.d.ts @@ -0,0 +1,2 @@ +export * from "./lib"; +export as namespace Zod; diff --git a/test/merkletreejs/node_modules/zod/lib/ZodError.d.ts b/test/merkletreejs/node_modules/zod/lib/ZodError.d.ts new file mode 100644 index 0000000..90f54af --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/ZodError.d.ts @@ -0,0 +1,163 @@ +import type { TypeOf, ZodType } from "."; +import { Primitive } from "./helpers/typeAliases"; +import { util, ZodParsedType } from "./helpers/util"; +declare type allKeys = T extends any ? keyof T : never; +export declare type inferFlattenedErrors, U = string> = typeToFlattenedError, U>; +export declare type typeToFlattenedError = { + formErrors: U[]; + fieldErrors: { + [P in allKeys]?: U[]; + }; +}; +export declare const ZodIssueCode: { + invalid_type: "invalid_type"; + invalid_literal: "invalid_literal"; + custom: "custom"; + invalid_union: "invalid_union"; + invalid_union_discriminator: "invalid_union_discriminator"; + invalid_enum_value: "invalid_enum_value"; + unrecognized_keys: "unrecognized_keys"; + invalid_arguments: "invalid_arguments"; + invalid_return_type: "invalid_return_type"; + invalid_date: "invalid_date"; + invalid_string: "invalid_string"; + too_small: "too_small"; + too_big: "too_big"; + invalid_intersection_types: "invalid_intersection_types"; + not_multiple_of: "not_multiple_of"; + not_finite: "not_finite"; +}; +export declare type ZodIssueCode = keyof typeof ZodIssueCode; +export declare type ZodIssueBase = { + path: (string | number)[]; + message?: string; +}; +export interface ZodInvalidTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_type; + expected: ZodParsedType; + received: ZodParsedType; +} +export interface ZodInvalidLiteralIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_literal; + expected: unknown; + received: unknown; +} +export interface ZodUnrecognizedKeysIssue extends ZodIssueBase { + code: typeof ZodIssueCode.unrecognized_keys; + keys: string[]; +} +export interface ZodInvalidUnionIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union; + unionErrors: ZodError[]; +} +export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union_discriminator; + options: Primitive[]; +} +export interface ZodInvalidEnumValueIssue extends ZodIssueBase { + received: string | number; + code: typeof ZodIssueCode.invalid_enum_value; + options: (string | number)[]; +} +export interface ZodInvalidArgumentsIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_arguments; + argumentsError: ZodError; +} +export interface ZodInvalidReturnTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_return_type; + returnTypeError: ZodError; +} +export interface ZodInvalidDateIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_date; +} +export declare type StringValidation = "email" | "url" | "emoji" | "uuid" | "regex" | "cuid" | "cuid2" | "ulid" | "datetime" | "ip" | { + includes: string; + position?: number; +} | { + startsWith: string; +} | { + endsWith: string; +}; +export interface ZodInvalidStringIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_string; + validation: StringValidation; +} +export interface ZodTooSmallIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_small; + minimum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} +export interface ZodTooBigIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_big; + maximum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} +export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_intersection_types; +} +export interface ZodNotMultipleOfIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_multiple_of; + multipleOf: number | bigint; +} +export interface ZodNotFiniteIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_finite; +} +export interface ZodCustomIssue extends ZodIssueBase { + code: typeof ZodIssueCode.custom; + params?: { + [k: string]: any; + }; +} +export declare type DenormalizedError = { + [k: string]: DenormalizedError | string[]; +}; +export declare type ZodIssueOptionalMessage = ZodInvalidTypeIssue | ZodInvalidLiteralIssue | ZodUnrecognizedKeysIssue | ZodInvalidUnionIssue | ZodInvalidUnionDiscriminatorIssue | ZodInvalidEnumValueIssue | ZodInvalidArgumentsIssue | ZodInvalidReturnTypeIssue | ZodInvalidDateIssue | ZodInvalidStringIssue | ZodTooSmallIssue | ZodTooBigIssue | ZodInvalidIntersectionTypesIssue | ZodNotMultipleOfIssue | ZodNotFiniteIssue | ZodCustomIssue; +export declare type ZodIssue = ZodIssueOptionalMessage & { + fatal?: boolean; + message: string; +}; +export declare const quotelessJson: (obj: any) => string; +declare type recursiveZodFormattedError = T extends [any, ...any[]] ? { + [K in keyof T]?: ZodFormattedError; +} : T extends any[] ? { + [k: number]: ZodFormattedError; +} : T extends object ? { + [K in keyof T]?: ZodFormattedError; +} : unknown; +export declare type ZodFormattedError = { + _errors: U[]; +} & recursiveZodFormattedError>; +export declare type inferFormattedError, U = string> = ZodFormattedError, U>; +export declare class ZodError extends Error { + issues: ZodIssue[]; + get errors(): ZodIssue[]; + constructor(issues: ZodIssue[]); + format(): ZodFormattedError; + format(mapper: (issue: ZodIssue) => U): ZodFormattedError; + static create: (issues: ZodIssue[]) => ZodError; + toString(): string; + get message(): string; + get isEmpty(): boolean; + addIssue: (sub: ZodIssue) => void; + addIssues: (subs?: ZodIssue[]) => void; + flatten(): typeToFlattenedError; + flatten(mapper?: (issue: ZodIssue) => U): typeToFlattenedError; + get formErrors(): typeToFlattenedError; +} +declare type stripPath = T extends any ? util.OmitKeys : never; +export declare type IssueData = stripPath & { + path?: (string | number)[]; + fatal?: boolean; +}; +export declare type ErrorMapCtx = { + defaultError: string; + data: any; +}; +export declare type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => { + message: string; +}; +export {}; diff --git a/test/merkletreejs/node_modules/zod/lib/ZodError.js b/test/merkletreejs/node_modules/zod/lib/ZodError.js new file mode 100644 index 0000000..e20f398 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/ZodError.js @@ -0,0 +1,132 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; +const util_1 = require("./helpers/util"); +exports.ZodIssueCode = util_1.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +exports.quotelessJson = quotelessJson; +class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +} +exports.ZodError = ZodError; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; diff --git a/test/merkletreejs/node_modules/zod/lib/__tests__/Mocker.d.ts b/test/merkletreejs/node_modules/zod/lib/__tests__/Mocker.d.ts new file mode 100644 index 0000000..2f605b6 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/__tests__/Mocker.d.ts @@ -0,0 +1,17 @@ +export declare class Mocker { + pick: (...args: any[]) => any; + get string(): string; + get number(): number; + get bigint(): bigint; + get boolean(): boolean; + get date(): Date; + get symbol(): symbol; + get null(): null; + get undefined(): undefined; + get stringOptional(): any; + get stringNullable(): any; + get numberOptional(): any; + get numberNullable(): any; + get booleanOptional(): any; + get booleanNullable(): any; +} diff --git a/test/merkletreejs/node_modules/zod/lib/__tests__/Mocker.js b/test/merkletreejs/node_modules/zod/lib/__tests__/Mocker.js new file mode 100644 index 0000000..6a56647 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/__tests__/Mocker.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Mocker = void 0; +function getRandomInt(max) { + return Math.floor(Math.random() * Math.floor(max)); +} +const testSymbol = Symbol("test"); +class Mocker { + constructor() { + this.pick = (...args) => { + return args[getRandomInt(args.length)]; + }; + } + get string() { + return Math.random().toString(36).substring(7); + } + get number() { + return Math.random() * 100; + } + get bigint() { + return BigInt(Math.floor(Math.random() * 10000)); + } + get boolean() { + return Math.random() < 0.5; + } + get date() { + return new Date(Math.floor(Date.now() * Math.random())); + } + get symbol() { + return testSymbol; + } + get null() { + return null; + } + get undefined() { + return undefined; + } + get stringOptional() { + return this.pick(this.string, this.undefined); + } + get stringNullable() { + return this.pick(this.string, this.null); + } + get numberOptional() { + return this.pick(this.number, this.undefined); + } + get numberNullable() { + return this.pick(this.number, this.null); + } + get booleanOptional() { + return this.pick(this.boolean, this.undefined); + } + get booleanNullable() { + return this.pick(this.boolean, this.null); + } +} +exports.Mocker = Mocker; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/discriminatedUnion.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/discriminatedUnion.d.ts new file mode 100644 index 0000000..9d2c302 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/discriminatedUnion.d.ts @@ -0,0 +1,5 @@ +import Benchmark from "benchmark"; +declare const _default: { + suites: Benchmark.Suite[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/discriminatedUnion.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/discriminatedUnion.js new file mode 100644 index 0000000..ea148f6 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/discriminatedUnion.js @@ -0,0 +1,79 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const benchmark_1 = __importDefault(require("benchmark")); +const index_1 = require("../index"); +const doubleSuite = new benchmark_1.default.Suite("z.discriminatedUnion: double"); +const manySuite = new benchmark_1.default.Suite("z.discriminatedUnion: many"); +const aSchema = index_1.z.object({ + type: index_1.z.literal("a"), +}); +const objA = { + type: "a", +}; +const bSchema = index_1.z.object({ + type: index_1.z.literal("b"), +}); +const objB = { + type: "b", +}; +const cSchema = index_1.z.object({ + type: index_1.z.literal("c"), +}); +const objC = { + type: "c", +}; +const dSchema = index_1.z.object({ + type: index_1.z.literal("d"), +}); +const double = index_1.z.discriminatedUnion("type", [aSchema, bSchema]); +const many = index_1.z.discriminatedUnion("type", [aSchema, bSchema, cSchema, dSchema]); +doubleSuite + .add("valid: a", () => { + double.parse(objA); +}) + .add("valid: b", () => { + double.parse(objB); +}) + .add("invalid: null", () => { + try { + double.parse(null); + } + catch (err) { } +}) + .add("invalid: wrong shape", () => { + try { + double.parse(objC); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${doubleSuite.name}: ${e.target}`); +}); +manySuite + .add("valid: a", () => { + many.parse(objA); +}) + .add("valid: c", () => { + many.parse(objC); +}) + .add("invalid: null", () => { + try { + many.parse(null); + } + catch (err) { } +}) + .add("invalid: wrong shape", () => { + try { + many.parse({ type: "unknown" }); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${manySuite.name}: ${e.target}`); +}); +exports.default = { + suites: [doubleSuite, manySuite], +}; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/index.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/index.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/index.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/index.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/index.js new file mode 100644 index 0000000..71930b4 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/index.js @@ -0,0 +1,46 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const discriminatedUnion_1 = __importDefault(require("./discriminatedUnion")); +const object_1 = __importDefault(require("./object")); +const primitives_1 = __importDefault(require("./primitives")); +const realworld_1 = __importDefault(require("./realworld")); +const string_1 = __importDefault(require("./string")); +const union_1 = __importDefault(require("./union")); +const argv = process.argv.slice(2); +let suites = []; +if (!argv.length) { + suites = [ + ...realworld_1.default.suites, + ...primitives_1.default.suites, + ...string_1.default.suites, + ...object_1.default.suites, + ...union_1.default.suites, + ...discriminatedUnion_1.default.suites, + ]; +} +else { + if (argv.includes("--realworld")) { + suites.push(...realworld_1.default.suites); + } + if (argv.includes("--primitives")) { + suites.push(...primitives_1.default.suites); + } + if (argv.includes("--string")) { + suites.push(...string_1.default.suites); + } + if (argv.includes("--object")) { + suites.push(...object_1.default.suites); + } + if (argv.includes("--union")) { + suites.push(...union_1.default.suites); + } + if (argv.includes("--discriminatedUnion")) { + suites.push(...discriminatedUnion_1.default.suites); + } +} +for (const suite of suites) { + suite.run(); +} diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/object.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/object.d.ts new file mode 100644 index 0000000..9d2c302 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/object.d.ts @@ -0,0 +1,5 @@ +import Benchmark from "benchmark"; +declare const _default: { + suites: Benchmark.Suite[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/object.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/object.js new file mode 100644 index 0000000..02f26c5 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/object.js @@ -0,0 +1,70 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const benchmark_1 = __importDefault(require("benchmark")); +const index_1 = require("../index"); +const emptySuite = new benchmark_1.default.Suite("z.object: empty"); +const shortSuite = new benchmark_1.default.Suite("z.object: short"); +const longSuite = new benchmark_1.default.Suite("z.object: long"); +const empty = index_1.z.object({}); +const short = index_1.z.object({ + string: index_1.z.string(), +}); +const long = index_1.z.object({ + string: index_1.z.string(), + number: index_1.z.number(), + boolean: index_1.z.boolean(), +}); +emptySuite + .add("valid", () => { + empty.parse({}); +}) + .add("valid: extra keys", () => { + empty.parse({ string: "string" }); +}) + .add("invalid: null", () => { + try { + empty.parse(null); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${emptySuite.name}: ${e.target}`); +}); +shortSuite + .add("valid", () => { + short.parse({ string: "string" }); +}) + .add("valid: extra keys", () => { + short.parse({ string: "string", number: 42 }); +}) + .add("invalid: null", () => { + try { + short.parse(null); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${shortSuite.name}: ${e.target}`); +}); +longSuite + .add("valid", () => { + long.parse({ string: "string", number: 42, boolean: true }); +}) + .add("valid: extra keys", () => { + long.parse({ string: "string", number: 42, boolean: true, list: [] }); +}) + .add("invalid: null", () => { + try { + long.parse(null); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${longSuite.name}: ${e.target}`); +}); +exports.default = { + suites: [emptySuite, shortSuite, longSuite], +}; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/primitives.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/primitives.d.ts new file mode 100644 index 0000000..9d2c302 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/primitives.d.ts @@ -0,0 +1,5 @@ +import Benchmark from "benchmark"; +declare const _default: { + suites: Benchmark.Suite[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/primitives.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/primitives.js new file mode 100644 index 0000000..9ea5862 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/primitives.js @@ -0,0 +1,136 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const benchmark_1 = __importDefault(require("benchmark")); +const Mocker_1 = require("../__tests__/Mocker"); +const index_1 = require("../index"); +const val = new Mocker_1.Mocker(); +const enumSuite = new benchmark_1.default.Suite("z.enum"); +const enumSchema = index_1.z.enum(["a", "b", "c"]); +enumSuite + .add("valid", () => { + enumSchema.parse("a"); +}) + .add("invalid", () => { + try { + enumSchema.parse("x"); + } + catch (e) { } +}) + .on("cycle", (e) => { + console.log(`z.enum: ${e.target}`); +}); +const undefinedSuite = new benchmark_1.default.Suite("z.undefined"); +const undefinedSchema = index_1.z.undefined(); +undefinedSuite + .add("valid", () => { + undefinedSchema.parse(undefined); +}) + .add("invalid", () => { + try { + undefinedSchema.parse(1); + } + catch (e) { } +}) + .on("cycle", (e) => { + console.log(`z.undefined: ${e.target}`); +}); +const literalSuite = new benchmark_1.default.Suite("z.literal"); +const short = "short"; +const bad = "bad"; +const literalSchema = index_1.z.literal("short"); +literalSuite + .add("valid", () => { + literalSchema.parse(short); +}) + .add("invalid", () => { + try { + literalSchema.parse(bad); + } + catch (e) { } +}) + .on("cycle", (e) => { + console.log(`z.literal: ${e.target}`); +}); +const numberSuite = new benchmark_1.default.Suite("z.number"); +const numberSchema = index_1.z.number().int(); +numberSuite + .add("valid", () => { + numberSchema.parse(1); +}) + .add("invalid type", () => { + try { + numberSchema.parse("bad"); + } + catch (e) { } +}) + .add("invalid number", () => { + try { + numberSchema.parse(0.5); + } + catch (e) { } +}) + .on("cycle", (e) => { + console.log(`z.number: ${e.target}`); +}); +const dateSuite = new benchmark_1.default.Suite("z.date"); +const plainDate = index_1.z.date(); +const minMaxDate = index_1.z + .date() + .min(new Date("2021-01-01")) + .max(new Date("2030-01-01")); +dateSuite + .add("valid", () => { + plainDate.parse(new Date()); +}) + .add("invalid", () => { + try { + plainDate.parse(1); + } + catch (e) { } +}) + .add("valid min and max", () => { + minMaxDate.parse(new Date("2023-01-01")); +}) + .add("invalid min", () => { + try { + minMaxDate.parse(new Date("2019-01-01")); + } + catch (e) { } +}) + .add("invalid max", () => { + try { + minMaxDate.parse(new Date("2031-01-01")); + } + catch (e) { } +}) + .on("cycle", (e) => { + console.log(`z.date: ${e.target}`); +}); +const symbolSuite = new benchmark_1.default.Suite("z.symbol"); +const symbolSchema = index_1.z.symbol(); +symbolSuite + .add("valid", () => { + symbolSchema.parse(val.symbol); +}) + .add("invalid", () => { + try { + symbolSchema.parse(1); + } + catch (e) { } +}) + .on("cycle", (e) => { + console.log(`z.symbol: ${e.target}`); +}); +exports.default = { + suites: [ + enumSuite, + undefinedSuite, + literalSuite, + numberSuite, + dateSuite, + symbolSuite, + ], +}; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/realworld.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/realworld.d.ts new file mode 100644 index 0000000..9d2c302 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/realworld.d.ts @@ -0,0 +1,5 @@ +import Benchmark from "benchmark"; +declare const _default: { + suites: Benchmark.Suite[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/realworld.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/realworld.js new file mode 100644 index 0000000..06f67ab --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/realworld.js @@ -0,0 +1,56 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const benchmark_1 = __importDefault(require("benchmark")); +const index_1 = require("../index"); +const shortSuite = new benchmark_1.default.Suite("realworld"); +const People = index_1.z.array(index_1.z.object({ + type: index_1.z.literal("person"), + hair: index_1.z.enum(["blue", "brown"]), + active: index_1.z.boolean(), + name: index_1.z.string(), + age: index_1.z.number().int(), + hobbies: index_1.z.array(index_1.z.string()), + address: index_1.z.object({ + street: index_1.z.string(), + zip: index_1.z.string(), + country: index_1.z.string(), + }), +})); +let i = 0; +function num() { + return ++i; +} +function str() { + return (++i % 100).toString(16); +} +function array(fn) { + return Array.from({ length: ++i % 10 }, () => fn()); +} +const people = Array.from({ length: 100 }, () => { + return { + type: "person", + hair: i % 2 ? "blue" : "brown", + active: !!(i % 2), + name: str(), + age: num(), + hobbies: array(str), + address: { + street: str(), + zip: str(), + country: str(), + }, + }; +}); +shortSuite + .add("valid", () => { + People.parse(people); +}) + .on("cycle", (e) => { + console.log(`${shortSuite.name}: ${e.target}`); +}); +exports.default = { + suites: [shortSuite], +}; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/string.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/string.d.ts new file mode 100644 index 0000000..9d2c302 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/string.d.ts @@ -0,0 +1,5 @@ +import Benchmark from "benchmark"; +declare const _default: { + suites: Benchmark.Suite[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/string.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/string.js new file mode 100644 index 0000000..14248d5 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/string.js @@ -0,0 +1,55 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const benchmark_1 = __importDefault(require("benchmark")); +const index_1 = require("../index"); +const SUITE_NAME = "z.string"; +const suite = new benchmark_1.default.Suite(SUITE_NAME); +const empty = ""; +const short = "short"; +const long = "long".repeat(256); +const manual = (str) => { + if (typeof str !== "string") { + throw new Error("Not a string"); + } + return str; +}; +const stringSchema = index_1.z.string(); +const optionalStringSchema = index_1.z.string().optional(); +const optionalNullableStringSchema = index_1.z.string().optional().nullable(); +suite + .add("empty string", () => { + stringSchema.parse(empty); +}) + .add("short string", () => { + stringSchema.parse(short); +}) + .add("long string", () => { + stringSchema.parse(long); +}) + .add("optional string", () => { + optionalStringSchema.parse(long); +}) + .add("nullable string", () => { + optionalNullableStringSchema.parse(long); +}) + .add("nullable (null) string", () => { + optionalNullableStringSchema.parse(null); +}) + .add("invalid: null", () => { + try { + stringSchema.parse(null); + } + catch (err) { } +}) + .add("manual parser: long", () => { + manual(long); +}) + .on("cycle", (e) => { + console.log(`${SUITE_NAME}: ${e.target}`); +}); +exports.default = { + suites: [suite], +}; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/union.d.ts b/test/merkletreejs/node_modules/zod/lib/benchmarks/union.d.ts new file mode 100644 index 0000000..9d2c302 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/union.d.ts @@ -0,0 +1,5 @@ +import Benchmark from "benchmark"; +declare const _default: { + suites: Benchmark.Suite[]; +}; +export default _default; diff --git a/test/merkletreejs/node_modules/zod/lib/benchmarks/union.js b/test/merkletreejs/node_modules/zod/lib/benchmarks/union.js new file mode 100644 index 0000000..0639e21 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/benchmarks/union.js @@ -0,0 +1,79 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const benchmark_1 = __importDefault(require("benchmark")); +const index_1 = require("../index"); +const doubleSuite = new benchmark_1.default.Suite("z.union: double"); +const manySuite = new benchmark_1.default.Suite("z.union: many"); +const aSchema = index_1.z.object({ + type: index_1.z.literal("a"), +}); +const objA = { + type: "a", +}; +const bSchema = index_1.z.object({ + type: index_1.z.literal("b"), +}); +const objB = { + type: "b", +}; +const cSchema = index_1.z.object({ + type: index_1.z.literal("c"), +}); +const objC = { + type: "c", +}; +const dSchema = index_1.z.object({ + type: index_1.z.literal("d"), +}); +const double = index_1.z.union([aSchema, bSchema]); +const many = index_1.z.union([aSchema, bSchema, cSchema, dSchema]); +doubleSuite + .add("valid: a", () => { + double.parse(objA); +}) + .add("valid: b", () => { + double.parse(objB); +}) + .add("invalid: null", () => { + try { + double.parse(null); + } + catch (err) { } +}) + .add("invalid: wrong shape", () => { + try { + double.parse(objC); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${doubleSuite.name}: ${e.target}`); +}); +manySuite + .add("valid: a", () => { + many.parse(objA); +}) + .add("valid: c", () => { + many.parse(objC); +}) + .add("invalid: null", () => { + try { + many.parse(null); + } + catch (err) { } +}) + .add("invalid: wrong shape", () => { + try { + many.parse({ type: "unknown" }); + } + catch (err) { } +}) + .on("cycle", (e) => { + console.log(`${manySuite.name}: ${e.target}`); +}); +exports.default = { + suites: [doubleSuite, manySuite], +}; diff --git a/test/merkletreejs/node_modules/zod/lib/errors.d.ts b/test/merkletreejs/node_modules/zod/lib/errors.d.ts new file mode 100644 index 0000000..ebf6b0f --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/errors.d.ts @@ -0,0 +1,5 @@ +import defaultErrorMap from "./locales/en"; +import type { ZodErrorMap } from "./ZodError"; +export { defaultErrorMap }; +export declare function setErrorMap(map: ZodErrorMap): void; +export declare function getErrorMap(): ZodErrorMap; diff --git a/test/merkletreejs/node_modules/zod/lib/errors.js b/test/merkletreejs/node_modules/zod/lib/errors.js new file mode 100644 index 0000000..93c6bc1 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/errors.js @@ -0,0 +1,17 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; +const en_1 = __importDefault(require("./locales/en")); +exports.defaultErrorMap = en_1.default; +let overrideErrorMap = en_1.default; +function setErrorMap(map) { + overrideErrorMap = map; +} +exports.setErrorMap = setErrorMap; +function getErrorMap() { + return overrideErrorMap; +} +exports.getErrorMap = getErrorMap; diff --git a/test/merkletreejs/node_modules/zod/lib/external.d.ts b/test/merkletreejs/node_modules/zod/lib/external.d.ts new file mode 100644 index 0000000..002e17d --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/external.d.ts @@ -0,0 +1,6 @@ +export * from "./errors"; +export * from "./helpers/parseUtil"; +export * from "./helpers/typeAliases"; +export * from "./helpers/util"; +export * from "./types"; +export * from "./ZodError"; diff --git a/test/merkletreejs/node_modules/zod/lib/external.js b/test/merkletreejs/node_modules/zod/lib/external.js new file mode 100644 index 0000000..48e6db2 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/external.js @@ -0,0 +1,18 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./errors"), exports); +__exportStar(require("./helpers/parseUtil"), exports); +__exportStar(require("./helpers/typeAliases"), exports); +__exportStar(require("./helpers/util"), exports); +__exportStar(require("./types"), exports); +__exportStar(require("./ZodError"), exports); diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/enumUtil.d.ts b/test/merkletreejs/node_modules/zod/lib/helpers/enumUtil.d.ts new file mode 100644 index 0000000..fad28a7 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/enumUtil.d.ts @@ -0,0 +1,8 @@ +export declare namespace enumUtil { + type UnionToIntersectionFn = (T extends unknown ? (k: () => T) => void : never) extends (k: infer Intersection) => void ? Intersection : never; + type GetUnionLast = UnionToIntersectionFn extends () => infer Last ? Last : never; + type UnionToTuple = [T] extends [never] ? Tuple : UnionToTuple>, [GetUnionLast, ...Tuple]>; + type CastToStringTuple = T extends [string, ...string[]] ? T : never; + export type UnionToTupleString = CastToStringTuple>; + export {}; +} diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/enumUtil.js b/test/merkletreejs/node_modules/zod/lib/helpers/enumUtil.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/enumUtil.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/errorUtil.d.ts b/test/merkletreejs/node_modules/zod/lib/helpers/errorUtil.d.ts new file mode 100644 index 0000000..5346d72 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/errorUtil.d.ts @@ -0,0 +1,9 @@ +export declare namespace errorUtil { + type ErrMessage = string | { + message?: string; + }; + const errToObj: (message?: ErrMessage | undefined) => { + message?: string | undefined; + }; + const toString: (message?: ErrMessage | undefined) => string | undefined; +} diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/errorUtil.js b/test/merkletreejs/node_modules/zod/lib/helpers/errorUtil.js new file mode 100644 index 0000000..7fa2797 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/errorUtil.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.errorUtil = void 0; +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; +})(errorUtil = exports.errorUtil || (exports.errorUtil = {})); diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/parseUtil.d.ts b/test/merkletreejs/node_modules/zod/lib/helpers/parseUtil.d.ts new file mode 100644 index 0000000..f3f2bba --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/parseUtil.d.ts @@ -0,0 +1,78 @@ +import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError"; +import type { ZodParsedType } from "./util"; +export declare const makeIssue: (params: { + data: any; + path: (string | number)[]; + errorMaps: ZodErrorMap[]; + issueData: IssueData; +}) => ZodIssue; +export declare type ParseParams = { + path: (string | number)[]; + errorMap: ZodErrorMap; + async: boolean; +}; +export declare type ParsePathComponent = string | number; +export declare type ParsePath = ParsePathComponent[]; +export declare const EMPTY_PATH: ParsePath; +export interface ParseContext { + readonly common: { + readonly issues: ZodIssue[]; + readonly contextualErrorMap?: ZodErrorMap; + readonly async: boolean; + }; + readonly path: ParsePath; + readonly schemaErrorMap?: ZodErrorMap; + readonly parent: ParseContext | null; + readonly data: any; + readonly parsedType: ZodParsedType; +} +export declare type ParseInput = { + data: any; + path: (string | number)[]; + parent: ParseContext; +}; +export declare function addIssueToContext(ctx: ParseContext, issueData: IssueData): void; +export declare type ObjectPair = { + key: SyncParseReturnType; + value: SyncParseReturnType; +}; +export declare class ParseStatus { + value: "aborted" | "dirty" | "valid"; + dirty(): void; + abort(): void; + static mergeArray(status: ParseStatus, results: SyncParseReturnType[]): SyncParseReturnType; + static mergeObjectAsync(status: ParseStatus, pairs: { + key: ParseReturnType; + value: ParseReturnType; + }[]): Promise>; + static mergeObjectSync(status: ParseStatus, pairs: { + key: SyncParseReturnType; + value: SyncParseReturnType; + alwaysSet?: boolean; + }[]): SyncParseReturnType; +} +export interface ParseResult { + status: "aborted" | "dirty" | "valid"; + data: any; +} +export declare type INVALID = { + status: "aborted"; +}; +export declare const INVALID: INVALID; +export declare type DIRTY = { + status: "dirty"; + value: T; +}; +export declare const DIRTY: (value: T) => DIRTY; +export declare type OK = { + status: "valid"; + value: T; +}; +export declare const OK: (value: T) => OK; +export declare type SyncParseReturnType = OK | DIRTY | INVALID; +export declare type AsyncParseReturnType = Promise>; +export declare type ParseReturnType = SyncParseReturnType | AsyncParseReturnType; +export declare const isAborted: (x: ParseReturnType) => x is INVALID; +export declare const isDirty: (x: ParseReturnType) => x is OK | DIRTY; +export declare const isValid: (x: ParseReturnType) => x is OK | DIRTY; +export declare const isAsync: (x: ParseReturnType) => x is AsyncParseReturnType; diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/parseUtil.js b/test/merkletreejs/node_modules/zod/lib/helpers/parseUtil.js new file mode 100644 index 0000000..3ad75fa --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/parseUtil.js @@ -0,0 +1,115 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; +const errors_1 = require("../errors"); +const en_1 = __importDefault(require("../locales/en")); +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage, + }; +}; +exports.makeIssue = makeIssue; +exports.EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const issue = (0, exports.makeIssue)({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + (0, errors_1.getErrorMap)(), + en_1.default, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +exports.addIssueToContext = addIssueToContext; +class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return exports.INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return exports.INVALID; + if (value.status === "aborted") + return exports.INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +exports.ParseStatus = ParseStatus; +exports.INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +exports.DIRTY = DIRTY; +const OK = (value) => ({ status: "valid", value }); +exports.OK = OK; +const isAborted = (x) => x.status === "aborted"; +exports.isAborted = isAborted; +const isDirty = (x) => x.status === "dirty"; +exports.isDirty = isDirty; +const isValid = (x) => x.status === "valid"; +exports.isValid = isValid; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +exports.isAsync = isAsync; diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/partialUtil.d.ts b/test/merkletreejs/node_modules/zod/lib/helpers/partialUtil.d.ts new file mode 100644 index 0000000..dd56a9d --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/partialUtil.d.ts @@ -0,0 +1,8 @@ +import type { ZodArray, ZodNullable, ZodObject, ZodOptional, ZodRawShape, ZodTuple, ZodTupleItems, ZodTypeAny } from "../index"; +export declare namespace partialUtil { + type DeepPartial = T extends ZodObject ? ZodObject<{ + [k in keyof T["shape"]]: ZodOptional>; + }, T["_def"]["unknownKeys"], T["_def"]["catchall"]> : T extends ZodArray ? ZodArray, Card> : T extends ZodOptional ? ZodOptional> : T extends ZodNullable ? ZodNullable> : T extends ZodTuple ? { + [k in keyof Items]: Items[k] extends ZodTypeAny ? DeepPartial : never; + } extends infer PI ? PI extends ZodTupleItems ? ZodTuple : never : never : T; +} diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/partialUtil.js b/test/merkletreejs/node_modules/zod/lib/helpers/partialUtil.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/partialUtil.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/typeAliases.d.ts b/test/merkletreejs/node_modules/zod/lib/helpers/typeAliases.d.ts new file mode 100644 index 0000000..aba4b3a --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/typeAliases.d.ts @@ -0,0 +1,2 @@ +export declare type Primitive = string | number | symbol | bigint | boolean | null | undefined; +export declare type Scalars = Primitive | Primitive[]; diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/typeAliases.js b/test/merkletreejs/node_modules/zod/lib/helpers/typeAliases.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/typeAliases.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/util.d.ts b/test/merkletreejs/node_modules/zod/lib/helpers/util.d.ts new file mode 100644 index 0000000..d400ef6 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/util.d.ts @@ -0,0 +1,68 @@ +export declare namespace util { + type AssertEqual = (() => V extends T ? 1 : 2) extends () => V extends U ? 1 : 2 ? true : false; + export type isAny = 0 extends 1 & T ? true : false; + export const assertEqual: (val: AssertEqual) => AssertEqual; + export function assertIs(_arg: T): void; + export function assertNever(_x: never): never; + export type Omit = Pick>; + export type OmitKeys = Pick>; + export type MakePartial = Omit & Partial>; + export const arrayToEnum: (items: U) => { [k in U[number]]: k; }; + export const getValidEnumValues: (obj: any) => any[]; + export const objectValues: (obj: any) => any[]; + export const objectKeys: ObjectConstructor["keys"]; + export const find: (arr: T[], checker: (arg: T) => any) => T | undefined; + export type identity = objectUtil.identity; + export type flatten = objectUtil.flatten; + export type noUndefined = T extends undefined ? never : T; + export const isInteger: NumberConstructor["isInteger"]; + export function joinValues(array: T, separator?: string): string; + export const jsonStringifyReplacer: (_: string, value: any) => any; + export {}; +} +export declare namespace objectUtil { + export type MergeShapes = { + [k in Exclude]: U[k]; + } & V; + type requiredKeys = { + [k in keyof T]: undefined extends T[k] ? never : k; + }[keyof T]; + export type addQuestionMarks> = Pick, R> & Partial; + export type identity = T; + export type flatten = identity<{ + [k in keyof T]: T[k]; + }>; + export type noNeverKeys = { + [k in keyof T]: [T[k]] extends [never] ? never : k; + }[keyof T]; + export type noNever = identity<{ + [k in noNeverKeys]: k extends keyof T ? T[k] : never; + }>; + export const mergeShapes: (first: U, second: T) => T & U; + export type extendShape = flatten & B>; + export {}; +} +export declare const ZodParsedType: { + function: "function"; + number: "number"; + string: "string"; + nan: "nan"; + integer: "integer"; + float: "float"; + boolean: "boolean"; + date: "date"; + bigint: "bigint"; + symbol: "symbol"; + undefined: "undefined"; + null: "null"; + array: "array"; + object: "object"; + unknown: "unknown"; + promise: "promise"; + void: "void"; + never: "never"; + map: "map"; + set: "set"; +}; +export declare type ZodParsedType = keyof typeof ZodParsedType; +export declare const getParsedType: (data: any) => ZodParsedType; diff --git a/test/merkletreejs/node_modules/zod/lib/helpers/util.js b/test/merkletreejs/node_modules/zod/lib/helpers/util.js new file mode 100644 index 0000000..e60141a --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/helpers/util.js @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; +var util; +(function (util) { + util.assertEqual = (val) => val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util = exports.util || (exports.util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil = exports.objectUtil || (exports.objectUtil = {})); +exports.ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return exports.ZodParsedType.undefined; + case "string": + return exports.ZodParsedType.string; + case "number": + return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; + case "boolean": + return exports.ZodParsedType.boolean; + case "function": + return exports.ZodParsedType.function; + case "bigint": + return exports.ZodParsedType.bigint; + case "symbol": + return exports.ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return exports.ZodParsedType.array; + } + if (data === null) { + return exports.ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return exports.ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return exports.ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return exports.ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return exports.ZodParsedType.date; + } + return exports.ZodParsedType.object; + default: + return exports.ZodParsedType.unknown; + } +}; +exports.getParsedType = getParsedType; diff --git a/test/merkletreejs/node_modules/zod/lib/index.d.ts b/test/merkletreejs/node_modules/zod/lib/index.d.ts new file mode 100644 index 0000000..e6a2db6 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/index.d.ts @@ -0,0 +1,4 @@ +import * as z from "./external"; +export * from "./external"; +export { z }; +export default z; diff --git a/test/merkletreejs/node_modules/zod/lib/index.js b/test/merkletreejs/node_modules/zod/lib/index.js new file mode 100644 index 0000000..1875b39 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/index.js @@ -0,0 +1,29 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.z = void 0; +const z = __importStar(require("./external")); +exports.z = z; +__exportStar(require("./external"), exports); +exports.default = z; diff --git a/test/merkletreejs/node_modules/zod/lib/index.mjs b/test/merkletreejs/node_modules/zod/lib/index.mjs new file mode 100644 index 0000000..db664c8 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/index.mjs @@ -0,0 +1,4017 @@ +var util; +(function (util) { + util.assertEqual = (val) => val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +const ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; + +const ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +} +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; + +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `smaller than or equal to` + : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; + +let overrideErrorMap = errorMap; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage, + }; +}; +const EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +const INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +const OK = (value) => ({ status: "valid", value }); +const isAborted = (x) => x.status === "aborted"; +const isDirty = (x) => x.status === "dirty"; +const isValid = (x) => x.status === "valid"; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; +})(errorUtil || (errorUtil = {})); + +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +} +const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } +} +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[a-z][a-z0-9]*$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; +const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +// Adapted from https://stackoverflow.com/a/3143231 +const datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); + } + } + else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } + else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } +}; +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + } + // + ); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); +}; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); +} +class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || + (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); +}; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); +}; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +} +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } +} +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") ; + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +} +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +} +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return Object.keys(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else { + return null; + } +}; +class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && + bType === ZodParsedType.date && + +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } +} +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } +} +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +} +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } +} +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +} +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +} +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } +} +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && + ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +} +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && + ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.issues.length) { + return { + status: "dirty", + value: ctx.data, + }; + } + if (ctx.common.async) { + return Promise.resolve(processed).then((processed) => { + return this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + }); + } + else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc + // effect: RefinementEffect + ) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!isValid(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + util.assertNever(effect); + } +} +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } +} +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +} +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +const BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if (isValid(result)) { + result.value = Object.freeze(result.value); + } + return result; + } +} +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +const custom = (check, params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); +}; +const late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); +const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +const NEVER = INVALID; + +var z = /*#__PURE__*/Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap: setErrorMap, + getErrorMap: getErrorMap, + makeIssue: makeIssue, + EMPTY_PATH: EMPTY_PATH, + addIssueToContext: addIssueToContext, + ParseStatus: ParseStatus, + INVALID: INVALID, + DIRTY: DIRTY, + OK: OK, + isAborted: isAborted, + isDirty: isDirty, + isValid: isValid, + isAsync: isAsync, + get util () { return util; }, + get objectUtil () { return objectUtil; }, + ZodParsedType: ZodParsedType, + getParsedType: getParsedType, + ZodType: ZodType, + ZodString: ZodString, + ZodNumber: ZodNumber, + ZodBigInt: ZodBigInt, + ZodBoolean: ZodBoolean, + ZodDate: ZodDate, + ZodSymbol: ZodSymbol, + ZodUndefined: ZodUndefined, + ZodNull: ZodNull, + ZodAny: ZodAny, + ZodUnknown: ZodUnknown, + ZodNever: ZodNever, + ZodVoid: ZodVoid, + ZodArray: ZodArray, + ZodObject: ZodObject, + ZodUnion: ZodUnion, + ZodDiscriminatedUnion: ZodDiscriminatedUnion, + ZodIntersection: ZodIntersection, + ZodTuple: ZodTuple, + ZodRecord: ZodRecord, + ZodMap: ZodMap, + ZodSet: ZodSet, + ZodFunction: ZodFunction, + ZodLazy: ZodLazy, + ZodLiteral: ZodLiteral, + ZodEnum: ZodEnum, + ZodNativeEnum: ZodNativeEnum, + ZodPromise: ZodPromise, + ZodEffects: ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional: ZodOptional, + ZodNullable: ZodNullable, + ZodDefault: ZodDefault, + ZodCatch: ZodCatch, + ZodNaN: ZodNaN, + BRAND: BRAND, + ZodBranded: ZodBranded, + ZodPipeline: ZodPipeline, + ZodReadonly: ZodReadonly, + custom: custom, + Schema: ZodType, + ZodSchema: ZodType, + late: late, + get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, + coerce: coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + 'enum': enumType, + 'function': functionType, + 'instanceof': instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + 'null': nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean: oboolean, + onumber: onumber, + optional: optionalType, + ostring: ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + 'undefined': undefinedType, + union: unionType, + unknown: unknownType, + 'void': voidType, + NEVER: NEVER, + ZodIssueCode: ZodIssueCode, + quotelessJson: quotelessJson, + ZodError: ZodError +}); + +export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z }; diff --git a/test/merkletreejs/node_modules/zod/lib/index.umd.js b/test/merkletreejs/node_modules/zod/lib/index.umd.js new file mode 100644 index 0000000..36fc981 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/index.umd.js @@ -0,0 +1,4131 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Zod = {})); +})(this, (function (exports) { 'use strict'; + + exports.util = void 0; + (function (util) { + util.assertEqual = (val) => val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(exports.util || (exports.util = {})); + exports.objectUtil = void 0; + (function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; + })(exports.objectUtil || (exports.objectUtil = {})); + const ZodParsedType = exports.util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", + ]); + const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; + + const ZodIssueCode = exports.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", + ]); + const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); + }; + class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + } + ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; + }; + + const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + exports.util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `smaller than or equal to` + : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + exports.util.assertNever(issue); + } + return { message }; + }; + + let overrideErrorMap = errorMap; + function setErrorMap(map) { + overrideErrorMap = map; + } + function getErrorMap() { + return overrideErrorMap; + } + + const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage, + }; + }; + const EMPTY_PATH = []; + function addIssueToContext(ctx, issueData) { + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); + } + class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + } + const INVALID = Object.freeze({ + status: "aborted", + }); + const DIRTY = (value) => ({ status: "dirty", value }); + const OK = (value) => ({ status: "valid", value }); + const isAborted = (x) => x.status === "aborted"; + const isDirty = (x) => x.status === "dirty"; + const isValid = (x) => x.status === "valid"; + const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + + var errorUtil; + (function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; + })(errorUtil || (errorUtil = {})); + + class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + } + const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } + }; + function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; + } + class ZodType { + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: exports.ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: exports.ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: exports.ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } + } + const cuidRegex = /^c[^\s-]{8,}$/i; + const cuid2Regex = /^[a-z][a-z0-9]*$/; + const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; + // const uuidRegex = + // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; + const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + // from https://stackoverflow.com/a/46181/1550155 + // old version: too slow, didn't support unicode + // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; + //old email regex + // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; + // eslint-disable-next-line + // const emailRegex = + // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; + // const emailRegex = + // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + // const emailRegex = + // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; + const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + // const emailRegex = + // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; + // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression + const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + let emojiRegex; + const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; + const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; + // Adapted from https://stackoverflow.com/a/3143231 + const datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); + } + } + else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } + else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } + }; + function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; + } + class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + } + // + ); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 + function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); + } + class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!exports.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || + (ch.kind === "multipleOf" && exports.util.isInteger(ch.value))); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + } + ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: exports.ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + } + ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: exports.ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; + class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: exports.ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; + class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: exports.ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; + class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodNull.create = (params) => { + return new ZodNull({ + typeName: exports.ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; + class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodAny.create = (params) => { + return new ZodAny({ + typeName: exports.ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; + class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: exports.ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; + class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + } + ZodNever.create = (params) => { + return new ZodNever({ + typeName: exports.ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; + class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: exports.ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; + class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: exports.ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; + function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } + } + class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = exports.util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") ; + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + exports.util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(exports.util.objectKeys(this.shape)); + } + } + ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } + } + ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: exports.ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + ////////// ////////// + ////////// ZodDiscriminatedUnion ////////// + ////////// ////////// + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return Object.keys(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else { + return null; + } + }; + class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } + } + function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = exports.util.objectKeys(b); + const sharedKeys = exports.util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && + bType === ZodParsedType.date && + +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } + } + class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } + } + ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: exports.ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; + class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } + } + ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: exports.ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; + class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: exports.ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: exports.ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } + } + class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + } + ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: exports.ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; + class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: exports.ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; + class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } + } + class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + } + ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: exports.ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; + class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + } + ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: exports.ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; + function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: exports.ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); + } + class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: exports.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } + } + ZodEnum.create = createZodEnum; + class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = exports.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && + ctx.parsedType !== ZodParsedType.number) { + const expectedValues = exports.util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: exports.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = exports.util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } + } + ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; + class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && + ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } + } + ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: exports.ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; + class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.issues.length) { + return { + status: "dirty", + value: ctx.data, + }; + } + if (ctx.common.async) { + return Promise.resolve(processed).then((processed) => { + return this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + }); + } + else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc + // effect: RefinementEffect + ) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!isValid(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + exports.util.assertNever(effect); + } + } + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; + class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); + }; + class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); + }; + class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } + } + ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); + }; + class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } + } + ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; + class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + } + ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: exports.ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; + const BRAND = Symbol("zod_brand"); + class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } + } + class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: exports.ZodFirstPartyTypeKind.ZodPipeline, + }); + } + } + class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if (isValid(result)) { + result.value = Object.freeze(result.value); + } + return result; + } + } + ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); + }; + const custom = (check, params = {}, + /** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal) => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); + }; + const late = { + object: ZodObject.lazycreate, + }; + exports.ZodFirstPartyTypeKind = void 0; + (function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; + })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); + const instanceOfType = ( + // const instanceOfType = any>( + cls, params = { + message: `Input not instance of ${cls.name}`, + }) => custom((data) => data instanceof cls, params); + const stringType = ZodString.create; + const numberType = ZodNumber.create; + const nanType = ZodNaN.create; + const bigIntType = ZodBigInt.create; + const booleanType = ZodBoolean.create; + const dateType = ZodDate.create; + const symbolType = ZodSymbol.create; + const undefinedType = ZodUndefined.create; + const nullType = ZodNull.create; + const anyType = ZodAny.create; + const unknownType = ZodUnknown.create; + const neverType = ZodNever.create; + const voidType = ZodVoid.create; + const arrayType = ZodArray.create; + const objectType = ZodObject.create; + const strictObjectType = ZodObject.strictCreate; + const unionType = ZodUnion.create; + const discriminatedUnionType = ZodDiscriminatedUnion.create; + const intersectionType = ZodIntersection.create; + const tupleType = ZodTuple.create; + const recordType = ZodRecord.create; + const mapType = ZodMap.create; + const setType = ZodSet.create; + const functionType = ZodFunction.create; + const lazyType = ZodLazy.create; + const literalType = ZodLiteral.create; + const enumType = ZodEnum.create; + const nativeEnumType = ZodNativeEnum.create; + const promiseType = ZodPromise.create; + const effectsType = ZodEffects.create; + const optionalType = ZodOptional.create; + const nullableType = ZodNullable.create; + const preprocessType = ZodEffects.createWithPreprocess; + const pipelineType = ZodPipeline.create; + const ostring = () => stringType().optional(); + const onumber = () => numberType().optional(); + const oboolean = () => booleanType().optional(); + const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), + }; + const NEVER = INVALID; + + var z = /*#__PURE__*/Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap: setErrorMap, + getErrorMap: getErrorMap, + makeIssue: makeIssue, + EMPTY_PATH: EMPTY_PATH, + addIssueToContext: addIssueToContext, + ParseStatus: ParseStatus, + INVALID: INVALID, + DIRTY: DIRTY, + OK: OK, + isAborted: isAborted, + isDirty: isDirty, + isValid: isValid, + isAsync: isAsync, + get util () { return exports.util; }, + get objectUtil () { return exports.objectUtil; }, + ZodParsedType: ZodParsedType, + getParsedType: getParsedType, + ZodType: ZodType, + ZodString: ZodString, + ZodNumber: ZodNumber, + ZodBigInt: ZodBigInt, + ZodBoolean: ZodBoolean, + ZodDate: ZodDate, + ZodSymbol: ZodSymbol, + ZodUndefined: ZodUndefined, + ZodNull: ZodNull, + ZodAny: ZodAny, + ZodUnknown: ZodUnknown, + ZodNever: ZodNever, + ZodVoid: ZodVoid, + ZodArray: ZodArray, + ZodObject: ZodObject, + ZodUnion: ZodUnion, + ZodDiscriminatedUnion: ZodDiscriminatedUnion, + ZodIntersection: ZodIntersection, + ZodTuple: ZodTuple, + ZodRecord: ZodRecord, + ZodMap: ZodMap, + ZodSet: ZodSet, + ZodFunction: ZodFunction, + ZodLazy: ZodLazy, + ZodLiteral: ZodLiteral, + ZodEnum: ZodEnum, + ZodNativeEnum: ZodNativeEnum, + ZodPromise: ZodPromise, + ZodEffects: ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional: ZodOptional, + ZodNullable: ZodNullable, + ZodDefault: ZodDefault, + ZodCatch: ZodCatch, + ZodNaN: ZodNaN, + BRAND: BRAND, + ZodBranded: ZodBranded, + ZodPipeline: ZodPipeline, + ZodReadonly: ZodReadonly, + custom: custom, + Schema: ZodType, + ZodSchema: ZodType, + late: late, + get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; }, + coerce: coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + 'enum': enumType, + 'function': functionType, + 'instanceof': instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + 'null': nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean: oboolean, + onumber: onumber, + optional: optionalType, + ostring: ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + 'undefined': undefinedType, + union: unionType, + unknown: unknownType, + 'void': voidType, + NEVER: NEVER, + ZodIssueCode: ZodIssueCode, + quotelessJson: quotelessJson, + ZodError: ZodError + }); + + exports.BRAND = BRAND; + exports.DIRTY = DIRTY; + exports.EMPTY_PATH = EMPTY_PATH; + exports.INVALID = INVALID; + exports.NEVER = NEVER; + exports.OK = OK; + exports.ParseStatus = ParseStatus; + exports.Schema = ZodType; + exports.ZodAny = ZodAny; + exports.ZodArray = ZodArray; + exports.ZodBigInt = ZodBigInt; + exports.ZodBoolean = ZodBoolean; + exports.ZodBranded = ZodBranded; + exports.ZodCatch = ZodCatch; + exports.ZodDate = ZodDate; + exports.ZodDefault = ZodDefault; + exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; + exports.ZodEffects = ZodEffects; + exports.ZodEnum = ZodEnum; + exports.ZodError = ZodError; + exports.ZodFunction = ZodFunction; + exports.ZodIntersection = ZodIntersection; + exports.ZodIssueCode = ZodIssueCode; + exports.ZodLazy = ZodLazy; + exports.ZodLiteral = ZodLiteral; + exports.ZodMap = ZodMap; + exports.ZodNaN = ZodNaN; + exports.ZodNativeEnum = ZodNativeEnum; + exports.ZodNever = ZodNever; + exports.ZodNull = ZodNull; + exports.ZodNullable = ZodNullable; + exports.ZodNumber = ZodNumber; + exports.ZodObject = ZodObject; + exports.ZodOptional = ZodOptional; + exports.ZodParsedType = ZodParsedType; + exports.ZodPipeline = ZodPipeline; + exports.ZodPromise = ZodPromise; + exports.ZodReadonly = ZodReadonly; + exports.ZodRecord = ZodRecord; + exports.ZodSchema = ZodType; + exports.ZodSet = ZodSet; + exports.ZodString = ZodString; + exports.ZodSymbol = ZodSymbol; + exports.ZodTransformer = ZodEffects; + exports.ZodTuple = ZodTuple; + exports.ZodType = ZodType; + exports.ZodUndefined = ZodUndefined; + exports.ZodUnion = ZodUnion; + exports.ZodUnknown = ZodUnknown; + exports.ZodVoid = ZodVoid; + exports.addIssueToContext = addIssueToContext; + exports.any = anyType; + exports.array = arrayType; + exports.bigint = bigIntType; + exports.boolean = booleanType; + exports.coerce = coerce; + exports.custom = custom; + exports.date = dateType; + exports["default"] = z; + exports.defaultErrorMap = errorMap; + exports.discriminatedUnion = discriminatedUnionType; + exports.effect = effectsType; + exports["enum"] = enumType; + exports["function"] = functionType; + exports.getErrorMap = getErrorMap; + exports.getParsedType = getParsedType; + exports["instanceof"] = instanceOfType; + exports.intersection = intersectionType; + exports.isAborted = isAborted; + exports.isAsync = isAsync; + exports.isDirty = isDirty; + exports.isValid = isValid; + exports.late = late; + exports.lazy = lazyType; + exports.literal = literalType; + exports.makeIssue = makeIssue; + exports.map = mapType; + exports.nan = nanType; + exports.nativeEnum = nativeEnumType; + exports.never = neverType; + exports["null"] = nullType; + exports.nullable = nullableType; + exports.number = numberType; + exports.object = objectType; + exports.oboolean = oboolean; + exports.onumber = onumber; + exports.optional = optionalType; + exports.ostring = ostring; + exports.pipeline = pipelineType; + exports.preprocess = preprocessType; + exports.promise = promiseType; + exports.quotelessJson = quotelessJson; + exports.record = recordType; + exports.set = setType; + exports.setErrorMap = setErrorMap; + exports.strictObject = strictObjectType; + exports.string = stringType; + exports.symbol = symbolType; + exports.transformer = effectsType; + exports.tuple = tupleType; + exports["undefined"] = undefinedType; + exports.union = unionType; + exports.unknown = unknownType; + exports["void"] = voidType; + exports.z = z; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/test/merkletreejs/node_modules/zod/lib/locales/en.d.ts b/test/merkletreejs/node_modules/zod/lib/locales/en.d.ts new file mode 100644 index 0000000..e5a3871 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/locales/en.d.ts @@ -0,0 +1,3 @@ +import { ZodErrorMap } from "../ZodError"; +declare const errorMap: ZodErrorMap; +export default errorMap; diff --git a/test/merkletreejs/node_modules/zod/lib/locales/en.js b/test/merkletreejs/node_modules/zod/lib/locales/en.js new file mode 100644 index 0000000..98342a0 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/locales/en.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../helpers/util"); +const ZodError_1 = require("../ZodError"); +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodError_1.ZodIssueCode.invalid_type: + if (issue.received === util_1.ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodError_1.ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; + break; + case ZodError_1.ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_1.ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodError_1.ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; + break; + case ZodError_1.ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_1.ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodError_1.ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodError_1.ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodError_1.ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util_1.util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodError_1.ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodError_1.ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `smaller than or equal to` + : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodError_1.ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodError_1.ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodError_1.ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_1.ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_1.util.assertNever(issue); + } + return { message }; +}; +exports.default = errorMap; diff --git a/test/merkletreejs/node_modules/zod/lib/types.d.ts b/test/merkletreejs/node_modules/zod/lib/types.d.ts new file mode 100644 index 0000000..854670d --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/types.d.ts @@ -0,0 +1,1057 @@ +import { enumUtil } from "./helpers/enumUtil"; +import { errorUtil } from "./helpers/errorUtil"; +import { AsyncParseReturnType, ParseContext, ParseInput, ParseParams, ParseReturnType, ParseStatus, SyncParseReturnType } from "./helpers/parseUtil"; +import { partialUtil } from "./helpers/partialUtil"; +import { Primitive } from "./helpers/typeAliases"; +import { objectUtil, util } from "./helpers/util"; +import { IssueData, StringValidation, ZodCustomIssue, ZodError, ZodErrorMap } from "./ZodError"; +export declare type RefinementCtx = { + addIssue: (arg: IssueData) => void; + path: (string | number)[]; +}; +export declare type ZodRawShape = { + [k: string]: ZodTypeAny; +}; +export declare type ZodTypeAny = ZodType; +export declare type TypeOf> = T["_output"]; +export declare type input> = T["_input"]; +export declare type output> = T["_output"]; +export type { TypeOf as infer }; +export declare type CustomErrorParams = Partial>; +export interface ZodTypeDef { + errorMap?: ZodErrorMap; + description?: string; +} +export declare type RawCreateParams = { + errorMap?: ZodErrorMap; + invalid_type_error?: string; + required_error?: string; + description?: string; +} | undefined; +export declare type ProcessedCreateParams = { + errorMap?: ZodErrorMap; + description?: string; +}; +export declare type SafeParseSuccess = { + success: true; + data: Output; +}; +export declare type SafeParseError = { + success: false; + error: ZodError; +}; +export declare type SafeParseReturnType = SafeParseSuccess | SafeParseError; +export declare abstract class ZodType { + readonly _type: Output; + readonly _output: Output; + readonly _input: Input; + readonly _def: Def; + get description(): string | undefined; + abstract _parse(input: ParseInput): ParseReturnType; + _getType(input: ParseInput): string; + _getOrReturnCtx(input: ParseInput, ctx?: ParseContext | undefined): ParseContext; + _processInputParams(input: ParseInput): { + status: ParseStatus; + ctx: ParseContext; + }; + _parseSync(input: ParseInput): SyncParseReturnType; + _parseAsync(input: ParseInput): AsyncParseReturnType; + parse(data: unknown, params?: Partial): Output; + safeParse(data: unknown, params?: Partial): SafeParseReturnType; + parseAsync(data: unknown, params?: Partial): Promise; + safeParseAsync(data: unknown, params?: Partial): Promise>; + /** Alias of safeParseAsync */ + spa: (data: unknown, params?: Partial | undefined) => Promise>; + refine(check: (arg: Output) => arg is RefinedOutput, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects; + refine(check: (arg: Output) => unknown | Promise, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects; + refinement(check: (arg: Output) => arg is RefinedOutput, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects; + refinement(check: (arg: Output) => boolean, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects; + _refinement(refinement: RefinementEffect["refinement"]): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => void): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => Promise): ZodEffects; + constructor(def: Def); + optional(): ZodOptional; + nullable(): ZodNullable; + nullish(): ZodOptional>; + array(): ZodArray; + promise(): ZodPromise; + or(option: T): ZodUnion<[this, T]>; + and(incoming: T): ZodIntersection; + transform(transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise): ZodEffects; + default(def: util.noUndefined): ZodDefault; + default(def: () => util.noUndefined): ZodDefault; + brand(brand?: B): ZodBranded; + catch(def: Output): ZodCatch; + catch(def: (ctx: { + error: ZodError; + input: Input; + }) => Output): ZodCatch; + describe(description: string): this; + pipe(target: T): ZodPipeline; + readonly(): ZodReadonly; + isOptional(): boolean; + isNullable(): boolean; +} +export declare type IpVersion = "v4" | "v6"; +export declare type ZodStringCheck = { + kind: "min"; + value: number; + message?: string; +} | { + kind: "max"; + value: number; + message?: string; +} | { + kind: "length"; + value: number; + message?: string; +} | { + kind: "email"; + message?: string; +} | { + kind: "url"; + message?: string; +} | { + kind: "emoji"; + message?: string; +} | { + kind: "uuid"; + message?: string; +} | { + kind: "cuid"; + message?: string; +} | { + kind: "includes"; + value: string; + position?: number; + message?: string; +} | { + kind: "cuid2"; + message?: string; +} | { + kind: "ulid"; + message?: string; +} | { + kind: "startsWith"; + value: string; + message?: string; +} | { + kind: "endsWith"; + value: string; + message?: string; +} | { + kind: "regex"; + regex: RegExp; + message?: string; +} | { + kind: "trim"; + message?: string; +} | { + kind: "toLowerCase"; + message?: string; +} | { + kind: "toUpperCase"; + message?: string; +} | { + kind: "datetime"; + offset: boolean; + precision: number | null; + message?: string; +} | { + kind: "ip"; + version?: IpVersion; + message?: string; +}; +export interface ZodStringDef extends ZodTypeDef { + checks: ZodStringCheck[]; + typeName: ZodFirstPartyTypeKind.ZodString; + coerce: boolean; +} +export declare class ZodString extends ZodType { + _parse(input: ParseInput): ParseReturnType; + protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage): ZodEffects; + _addCheck(check: ZodStringCheck): ZodString; + email(message?: errorUtil.ErrMessage): ZodString; + url(message?: errorUtil.ErrMessage): ZodString; + emoji(message?: errorUtil.ErrMessage): ZodString; + uuid(message?: errorUtil.ErrMessage): ZodString; + cuid(message?: errorUtil.ErrMessage): ZodString; + cuid2(message?: errorUtil.ErrMessage): ZodString; + ulid(message?: errorUtil.ErrMessage): ZodString; + ip(options?: string | { + version?: "v4" | "v6"; + message?: string; + }): ZodString; + datetime(options?: string | { + message?: string | undefined; + precision?: number | null; + offset?: boolean; + }): ZodString; + regex(regex: RegExp, message?: errorUtil.ErrMessage): ZodString; + includes(value: string, options?: { + message?: string; + position?: number; + }): ZodString; + startsWith(value: string, message?: errorUtil.ErrMessage): ZodString; + endsWith(value: string, message?: errorUtil.ErrMessage): ZodString; + min(minLength: number, message?: errorUtil.ErrMessage): ZodString; + max(maxLength: number, message?: errorUtil.ErrMessage): ZodString; + length(len: number, message?: errorUtil.ErrMessage): ZodString; + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message?: errorUtil.ErrMessage): ZodString; + trim(): ZodString; + toLowerCase(): ZodString; + toUpperCase(): ZodString; + get isDatetime(): boolean; + get isEmail(): boolean; + get isURL(): boolean; + get isEmoji(): boolean; + get isUUID(): boolean; + get isCUID(): boolean; + get isCUID2(): boolean; + get isULID(): boolean; + get isIP(): boolean; + get minLength(): number | null; + get maxLength(): number | null; + static create: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: true | undefined; + }) | undefined) => ZodString; +} +export declare type ZodNumberCheck = { + kind: "min"; + value: number; + inclusive: boolean; + message?: string; +} | { + kind: "max"; + value: number; + inclusive: boolean; + message?: string; +} | { + kind: "int"; + message?: string; +} | { + kind: "multipleOf"; + value: number; + message?: string; +} | { + kind: "finite"; + message?: string; +}; +export interface ZodNumberDef extends ZodTypeDef { + checks: ZodNumberCheck[]; + typeName: ZodFirstPartyTypeKind.ZodNumber; + coerce: boolean; +} +export declare class ZodNumber extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodNumber; + gte(value: number, message?: errorUtil.ErrMessage): ZodNumber; + min: (value: number, message?: errorUtil.ErrMessage | undefined) => ZodNumber; + gt(value: number, message?: errorUtil.ErrMessage): ZodNumber; + lte(value: number, message?: errorUtil.ErrMessage): ZodNumber; + max: (value: number, message?: errorUtil.ErrMessage | undefined) => ZodNumber; + lt(value: number, message?: errorUtil.ErrMessage): ZodNumber; + protected setLimit(kind: "min" | "max", value: number, inclusive: boolean, message?: string): ZodNumber; + _addCheck(check: ZodNumberCheck): ZodNumber; + int(message?: errorUtil.ErrMessage): ZodNumber; + positive(message?: errorUtil.ErrMessage): ZodNumber; + negative(message?: errorUtil.ErrMessage): ZodNumber; + nonpositive(message?: errorUtil.ErrMessage): ZodNumber; + nonnegative(message?: errorUtil.ErrMessage): ZodNumber; + multipleOf(value: number, message?: errorUtil.ErrMessage): ZodNumber; + step: (value: number, message?: errorUtil.ErrMessage | undefined) => ZodNumber; + finite(message?: errorUtil.ErrMessage): ZodNumber; + safe(message?: errorUtil.ErrMessage): ZodNumber; + get minValue(): number | null; + get maxValue(): number | null; + get isInt(): boolean; + get isFinite(): boolean; +} +export declare type ZodBigIntCheck = { + kind: "min"; + value: bigint; + inclusive: boolean; + message?: string; +} | { + kind: "max"; + value: bigint; + inclusive: boolean; + message?: string; +} | { + kind: "multipleOf"; + value: bigint; + message?: string; +}; +export interface ZodBigIntDef extends ZodTypeDef { + checks: ZodBigIntCheck[]; + typeName: ZodFirstPartyTypeKind.ZodBigInt; + coerce: boolean; +} +export declare class ZodBigInt extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodBigInt; + gte(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + min: (value: bigint, message?: errorUtil.ErrMessage | undefined) => ZodBigInt; + gt(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + lte(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + max: (value: bigint, message?: errorUtil.ErrMessage | undefined) => ZodBigInt; + lt(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + protected setLimit(kind: "min" | "max", value: bigint, inclusive: boolean, message?: string): ZodBigInt; + _addCheck(check: ZodBigIntCheck): ZodBigInt; + positive(message?: errorUtil.ErrMessage): ZodBigInt; + negative(message?: errorUtil.ErrMessage): ZodBigInt; + nonpositive(message?: errorUtil.ErrMessage): ZodBigInt; + nonnegative(message?: errorUtil.ErrMessage): ZodBigInt; + multipleOf(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + get minValue(): bigint | null; + get maxValue(): bigint | null; +} +export interface ZodBooleanDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodBoolean; + coerce: boolean; +} +export declare class ZodBoolean extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodBoolean; +} +export declare type ZodDateCheck = { + kind: "min"; + value: number; + message?: string; +} | { + kind: "max"; + value: number; + message?: string; +}; +export interface ZodDateDef extends ZodTypeDef { + checks: ZodDateCheck[]; + coerce: boolean; + typeName: ZodFirstPartyTypeKind.ZodDate; +} +export declare class ZodDate extends ZodType { + _parse(input: ParseInput): ParseReturnType; + _addCheck(check: ZodDateCheck): ZodDate; + min(minDate: Date, message?: errorUtil.ErrMessage): ZodDate; + max(maxDate: Date, message?: errorUtil.ErrMessage): ZodDate; + get minDate(): Date | null; + get maxDate(): Date | null; + static create: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodDate; +} +export interface ZodSymbolDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodSymbol; +} +export declare class ZodSymbol extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodSymbol; +} +export interface ZodUndefinedDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUndefined; +} +export declare class ZodUndefined extends ZodType { + _parse(input: ParseInput): ParseReturnType; + params?: RawCreateParams; + static create: (params?: RawCreateParams) => ZodUndefined; +} +export interface ZodNullDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNull; +} +export declare class ZodNull extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNull; +} +export interface ZodAnyDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodAny; +} +export declare class ZodAny extends ZodType { + _any: true; + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodAny; +} +export interface ZodUnknownDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUnknown; +} +export declare class ZodUnknown extends ZodType { + _unknown: true; + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodUnknown; +} +export interface ZodNeverDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNever; +} +export declare class ZodNever extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNever; +} +export interface ZodVoidDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodVoid; +} +export declare class ZodVoid extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodVoid; +} +export interface ZodArrayDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodArray; + exactLength: { + value: number; + message?: string; + } | null; + minLength: { + value: number; + message?: string; + } | null; + maxLength: { + value: number; + message?: string; + } | null; +} +export declare type ArrayCardinality = "many" | "atleastone"; +export declare type arrayOutputType = Cardinality extends "atleastone" ? [T["_output"], ...T["_output"][]] : T["_output"][]; +export declare class ZodArray extends ZodType, ZodArrayDef, Cardinality extends "atleastone" ? [T["_input"], ...T["_input"][]] : T["_input"][]> { + _parse(input: ParseInput): ParseReturnType; + get element(): T; + min(minLength: number, message?: errorUtil.ErrMessage): this; + max(maxLength: number, message?: errorUtil.ErrMessage): this; + length(len: number, message?: errorUtil.ErrMessage): this; + nonempty(message?: errorUtil.ErrMessage): ZodArray; + static create: (schema: T_1, params?: RawCreateParams) => ZodArray; +} +export declare type ZodNonEmptyArray = ZodArray; +export declare type UnknownKeysParam = "passthrough" | "strict" | "strip"; +export interface ZodObjectDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodObject; + shape: () => T; + catchall: Catchall; + unknownKeys: UnknownKeys; +} +export declare type mergeTypes = { + [k in keyof A | keyof B]: k extends keyof B ? B[k] : k extends keyof A ? A[k] : never; +}; +export declare type objectOutputType = objectUtil.flatten>> & CatchallOutput & PassthroughType; +export declare type baseObjectOutputType = { + [k in keyof Shape]: Shape[k]["_output"]; +}; +export declare type objectInputType = objectUtil.flatten> & CatchallInput & PassthroughType; +export declare type baseObjectInputType = objectUtil.addQuestionMarks<{ + [k in keyof Shape]: Shape[k]["_input"]; +}>; +export declare type CatchallOutput = ZodTypeAny extends T ? unknown : { + [k: string]: T["_output"]; +}; +export declare type CatchallInput = ZodTypeAny extends T ? unknown : { + [k: string]: T["_input"]; +}; +export declare type PassthroughType = T extends "passthrough" ? { + [k: string]: unknown; +} : unknown; +export declare type deoptional = T extends ZodOptional ? deoptional : T extends ZodNullable ? ZodNullable> : T; +export declare type SomeZodObject = ZodObject; +export declare type noUnrecognized = { + [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; +}; +export declare class ZodObject, Input = objectInputType> extends ZodType, Input> { + private _cached; + _getCached(): { + shape: T; + keys: string[]; + }; + _parse(input: ParseInput): ParseReturnType; + get shape(): T; + strict(message?: errorUtil.ErrMessage): ZodObject; + strip(): ZodObject; + passthrough(): ZodObject; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + nonstrict: () => ZodObject; + extend(augmentation: Augmentation): ZodObject, UnknownKeys, Catchall>; + /** + * @deprecated Use `.extend` instead + * */ + augment: (augmentation: Augmentation) => ZodObject<{ [k in keyof (Omit & Augmentation)]: (Omit & Augmentation)[k]; }, UnknownKeys, Catchall, objectOutputType<{ [k in keyof (Omit & Augmentation)]: (Omit & Augmentation)[k]; }, Catchall, UnknownKeys>, objectInputType<{ [k in keyof (Omit & Augmentation)]: (Omit & Augmentation)[k]; }, Catchall, UnknownKeys>>; + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging: Incoming): ZodObject, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]>; + setKey(key: Key, schema: Schema): ZodObject; + catchall(index: Index): ZodObject; + pick(mask: Mask): ZodObject>, UnknownKeys, Catchall>; + omit(mask: Mask): ZodObject, UnknownKeys, Catchall>; + /** + * @deprecated + */ + deepPartial(): partialUtil.DeepPartial; + partial(): ZodObject<{ + [k in keyof T]: ZodOptional; + }, UnknownKeys, Catchall>; + partial(mask: Mask): ZodObject : T[k]; + }>, UnknownKeys, Catchall>; + required(): ZodObject<{ + [k in keyof T]: deoptional; + }, UnknownKeys, Catchall>; + required(mask: Mask): ZodObject : T[k]; + }>, UnknownKeys, Catchall>; + keyof(): ZodEnum>; + static create: (shape: T_1, params?: RawCreateParams) => ZodObject, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T_1]>]: objectUtil.addQuestionMarks, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T_1]>[k_1]; }, { [k_2 in keyof baseObjectInputType]: baseObjectInputType[k_2]; }>; + static strictCreate: (shape: T_1, params?: RawCreateParams) => ZodObject, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T_1]>]: objectUtil.addQuestionMarks, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T_1]>[k_1]; }, { [k_2 in keyof baseObjectInputType]: baseObjectInputType[k_2]; }>; + static lazycreate: (shape: () => T_1, params?: RawCreateParams) => ZodObject, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T_1]>]: objectUtil.addQuestionMarks, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T_1]>[k_1]; }, { [k_2 in keyof baseObjectInputType]: baseObjectInputType[k_2]; }>; +} +export declare type AnyZodObject = ZodObject; +export declare type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; +export interface ZodUnionDef> extends ZodTypeDef { + options: T; + typeName: ZodFirstPartyTypeKind.ZodUnion; +} +export declare class ZodUnion extends ZodType, T[number]["_input"]> { + _parse(input: ParseInput): ParseReturnType; + get options(): T; + static create: (types: T_1, params?: RawCreateParams) => ZodUnion; +} +export declare type ZodDiscriminatedUnionOption = ZodObject<{ + [key in Discriminator]: ZodTypeAny; +} & ZodRawShape, UnknownKeysParam, ZodTypeAny>; +export interface ZodDiscriminatedUnionDef[] = ZodDiscriminatedUnionOption[]> extends ZodTypeDef { + discriminator: Discriminator; + options: Options; + optionsMap: Map>; + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; +} +export declare class ZodDiscriminatedUnion[]> extends ZodType, ZodDiscriminatedUnionDef, input> { + _parse(input: ParseInput): ParseReturnType; + get discriminator(): Discriminator; + get options(): Options; + get optionsMap(): Map>; + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create, + ...ZodDiscriminatedUnionOption[] + ]>(discriminator: Discriminator, options: Types, params?: RawCreateParams): ZodDiscriminatedUnion; +} +export interface ZodIntersectionDef extends ZodTypeDef { + left: T; + right: U; + typeName: ZodFirstPartyTypeKind.ZodIntersection; +} +export declare class ZodIntersection extends ZodType, T["_input"] & U["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create: (left: T_1, right: U_1, params?: RawCreateParams) => ZodIntersection; +} +export declare type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export declare type AssertArray = T extends any[] ? T : never; +export declare type OutputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_output"] : never; +}>; +export declare type OutputTypeOfTupleWithRest = Rest extends ZodTypeAny ? [...OutputTypeOfTuple, ...Rest["_output"][]] : OutputTypeOfTuple; +export declare type InputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_input"] : never; +}>; +export declare type InputTypeOfTupleWithRest = Rest extends ZodTypeAny ? [...InputTypeOfTuple, ...Rest["_input"][]] : InputTypeOfTuple; +export interface ZodTupleDef extends ZodTypeDef { + items: T; + rest: Rest; + typeName: ZodFirstPartyTypeKind.ZodTuple; +} +export declare type AnyZodTuple = ZodTuple<[ + ZodTypeAny, + ...ZodTypeAny[] +] | [], ZodTypeAny | null>; +export declare class ZodTuple extends ZodType, ZodTupleDef, InputTypeOfTupleWithRest> { + _parse(input: ParseInput): ParseReturnType; + get items(): T; + rest(rest: Rest): ZodTuple; + static create: (schemas: T_1, params?: RawCreateParams) => ZodTuple; +} +export interface ZodRecordDef extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodRecord; +} +export declare type KeySchema = ZodType; +export declare type RecordType = [ + string +] extends [K] ? Record : [number] extends [K] ? Record : [symbol] extends [K] ? Record : [BRAND] extends [K] ? Record : Partial>; +export declare class ZodRecord extends ZodType, ZodRecordDef, RecordType> { + get keySchema(): Key; + get valueSchema(): Value; + _parse(input: ParseInput): ParseReturnType; + get element(): Value; + static create(valueType: Value, params?: RawCreateParams): ZodRecord; + static create(keySchema: Keys, valueType: Value, params?: RawCreateParams): ZodRecord; +} +export interface ZodMapDef extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodMap; +} +export declare class ZodMap extends ZodType, ZodMapDef, Map> { + get keySchema(): Key; + get valueSchema(): Value; + _parse(input: ParseInput): ParseReturnType; + static create: (keyType: Key_1, valueType: Value_1, params?: RawCreateParams) => ZodMap; +} +export interface ZodSetDef extends ZodTypeDef { + valueType: Value; + typeName: ZodFirstPartyTypeKind.ZodSet; + minSize: { + value: number; + message?: string; + } | null; + maxSize: { + value: number; + message?: string; + } | null; +} +export declare class ZodSet extends ZodType, ZodSetDef, Set> { + _parse(input: ParseInput): ParseReturnType; + min(minSize: number, message?: errorUtil.ErrMessage): this; + max(maxSize: number, message?: errorUtil.ErrMessage): this; + size(size: number, message?: errorUtil.ErrMessage): this; + nonempty(message?: errorUtil.ErrMessage): ZodSet; + static create: (valueType: Value_1, params?: RawCreateParams) => ZodSet; +} +export interface ZodFunctionDef = ZodTuple, Returns extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { + args: Args; + returns: Returns; + typeName: ZodFirstPartyTypeKind.ZodFunction; +} +export declare type OuterTypeOfFunction, Returns extends ZodTypeAny> = Args["_input"] extends Array ? (...args: Args["_input"]) => Returns["_output"] : never; +export declare type InnerTypeOfFunction, Returns extends ZodTypeAny> = Args["_output"] extends Array ? (...args: Args["_output"]) => Returns["_input"] : never; +export declare class ZodFunction, Returns extends ZodTypeAny> extends ZodType, ZodFunctionDef, InnerTypeOfFunction> { + _parse(input: ParseInput): ParseReturnType; + parameters(): Args; + returnType(): Returns; + args[0]>(...items: Items): ZodFunction, Returns>; + returns>(returnType: NewReturnType): ZodFunction; + implement>(func: F): ReturnType extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType : OuterTypeOfFunction; + strictImplement(func: InnerTypeOfFunction): InnerTypeOfFunction; + validate: >(func: F) => ReturnType extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType : OuterTypeOfFunction; + static create(): ZodFunction, ZodUnknown>; + static create>(args: T): ZodFunction; + static create(args: T, returns: U): ZodFunction; + static create, U extends ZodTypeAny = ZodUnknown>(args: T, returns: U, params?: RawCreateParams): ZodFunction; +} +export interface ZodLazyDef extends ZodTypeDef { + getter: () => T; + typeName: ZodFirstPartyTypeKind.ZodLazy; +} +export declare class ZodLazy extends ZodType, ZodLazyDef, input> { + get schema(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (getter: () => T_1, params?: RawCreateParams) => ZodLazy; +} +export interface ZodLiteralDef extends ZodTypeDef { + value: T; + typeName: ZodFirstPartyTypeKind.ZodLiteral; +} +export declare class ZodLiteral extends ZodType> { + _parse(input: ParseInput): ParseReturnType; + get value(): T; + static create: (value: T_1, params?: RawCreateParams) => ZodLiteral; +} +export declare type ArrayKeys = keyof any[]; +export declare type Indices = Exclude; +export declare type EnumValues = [string, ...string[]]; +export declare type Values = { + [k in T[number]]: k; +}; +export interface ZodEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodEnum; +} +export declare type Writeable = { + -readonly [P in keyof T]: T[P]; +}; +export declare type FilterEnum = Values extends [] ? [] : Values extends [infer Head, ...infer Rest] ? Head extends ToExclude ? FilterEnum : [Head, ...FilterEnum] : never; +export declare type typecast = A extends T ? A : never; +declare function createZodEnum>(values: T, params?: RawCreateParams): ZodEnum>; +declare function createZodEnum(values: T, params?: RawCreateParams): ZodEnum; +export declare class ZodEnum extends ZodType> { + _parse(input: ParseInput): ParseReturnType; + get options(): T; + get enum(): Values; + get Values(): Values; + get Enum(): Values; + extract(values: ToExtract): ZodEnum>; + exclude(values: ToExclude): ZodEnum>, [string, ...string[]]>>; + static create: typeof createZodEnum; +} +export interface ZodNativeEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodNativeEnum; +} +export declare type EnumLike = { + [k: string]: string | number; + [nu: number]: string; +}; +export declare class ZodNativeEnum extends ZodType> { + _parse(input: ParseInput): ParseReturnType; + get enum(): T; + static create: (values: T_1, params?: RawCreateParams) => ZodNativeEnum; +} +export interface ZodPromiseDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodPromise; +} +export declare class ZodPromise extends ZodType, ZodPromiseDef, Promise> { + unwrap(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (schema: T_1, params?: RawCreateParams) => ZodPromise; +} +export declare type Refinement = (arg: T, ctx: RefinementCtx) => any; +export declare type SuperRefinement = (arg: T, ctx: RefinementCtx) => void | Promise; +export declare type RefinementEffect = { + type: "refinement"; + refinement: (arg: T, ctx: RefinementCtx) => any; +}; +export declare type TransformEffect = { + type: "transform"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export declare type PreprocessEffect = { + type: "preprocess"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export declare type Effect = RefinementEffect | TransformEffect | PreprocessEffect; +export interface ZodEffectsDef extends ZodTypeDef { + schema: T; + typeName: ZodFirstPartyTypeKind.ZodEffects; + effect: Effect; +} +export declare class ZodEffects, Input = input> extends ZodType, Input> { + innerType(): T; + sourceType(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (schema: I, effect: Effect, params?: RawCreateParams) => ZodEffects>; + static createWithPreprocess: (preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects; +} +export { ZodEffects as ZodTransformer }; +export interface ZodOptionalDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodOptional; +} +export declare type ZodOptionalType = ZodOptional; +export declare class ZodOptional extends ZodType, T["_input"] | undefined> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; + static create: (type: T_1, params?: RawCreateParams) => ZodOptional; +} +export interface ZodNullableDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodNullable; +} +export declare type ZodNullableType = ZodNullable; +export declare class ZodNullable extends ZodType, T["_input"] | null> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; + static create: (type: T_1, params?: RawCreateParams) => ZodNullable; +} +export interface ZodDefaultDef extends ZodTypeDef { + innerType: T; + defaultValue: () => util.noUndefined; + typeName: ZodFirstPartyTypeKind.ZodDefault; +} +export declare class ZodDefault extends ZodType, ZodDefaultDef, T["_input"] | undefined> { + _parse(input: ParseInput): ParseReturnType; + removeDefault(): T; + static create: (type: T_1, params: { + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + default: T_1["_input"] | (() => util.noUndefined); + }) => ZodDefault; +} +export interface ZodCatchDef extends ZodTypeDef { + innerType: T; + catchValue: (ctx: { + error: ZodError; + input: unknown; + }) => T["_input"]; + typeName: ZodFirstPartyTypeKind.ZodCatch; +} +export declare class ZodCatch extends ZodType, unknown> { + _parse(input: ParseInput): ParseReturnType; + removeCatch(): T; + static create: (type: T_1, params: { + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + catch: T_1["_output"] | (() => T_1["_output"]); + }) => ZodCatch; +} +export interface ZodNaNDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNaN; +} +export declare class ZodNaN extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNaN; +} +export interface ZodBrandedDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodBranded; +} +export declare const BRAND: unique symbol; +export declare type BRAND = { + [BRAND]: { + [k in T]: true; + }; +}; +export declare class ZodBranded extends ZodType, ZodBrandedDef, T["_input"]> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; +} +export interface ZodPipelineDef extends ZodTypeDef { + in: A; + out: B; + typeName: ZodFirstPartyTypeKind.ZodPipeline; +} +export declare class ZodPipeline extends ZodType, A["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create(a: A, b: B): ZodPipeline; +} +declare type BuiltIn = (((...args: any[]) => any) | (new (...args: any[]) => any)) | { + readonly [Symbol.toStringTag]: string; +} | Date | Error | Generator | Promise | RegExp; +declare type MakeReadonly = T extends Map ? ReadonlyMap : T extends Set ? ReadonlySet : T extends [infer Head, ...infer Tail] ? readonly [Head, ...Tail] : T extends Array ? ReadonlyArray : T extends BuiltIn ? T : Readonly; +export interface ZodReadonlyDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodReadonly; +} +export declare class ZodReadonly extends ZodType, ZodReadonlyDef, T["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create: (type: T_1, params?: RawCreateParams) => ZodReadonly; +} +declare type CustomParams = CustomErrorParams & { + fatal?: boolean; +}; +export declare const custom: (check?: ((data: unknown) => any) | undefined, params?: string | CustomParams | ((input: any) => CustomParams), fatal?: boolean | undefined) => ZodType; +export { ZodType as Schema, ZodType as ZodSchema }; +export declare const late: { + object: (shape: () => T, params?: RawCreateParams) => ZodObject, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T]>]: objectUtil.addQuestionMarks, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T]>[k_1]; }, { [k_2 in keyof baseObjectInputType]: baseObjectInputType[k_2]; }>; +}; +export declare enum ZodFirstPartyTypeKind { + ZodString = "ZodString", + ZodNumber = "ZodNumber", + ZodNaN = "ZodNaN", + ZodBigInt = "ZodBigInt", + ZodBoolean = "ZodBoolean", + ZodDate = "ZodDate", + ZodSymbol = "ZodSymbol", + ZodUndefined = "ZodUndefined", + ZodNull = "ZodNull", + ZodAny = "ZodAny", + ZodUnknown = "ZodUnknown", + ZodNever = "ZodNever", + ZodVoid = "ZodVoid", + ZodArray = "ZodArray", + ZodObject = "ZodObject", + ZodUnion = "ZodUnion", + ZodDiscriminatedUnion = "ZodDiscriminatedUnion", + ZodIntersection = "ZodIntersection", + ZodTuple = "ZodTuple", + ZodRecord = "ZodRecord", + ZodMap = "ZodMap", + ZodSet = "ZodSet", + ZodFunction = "ZodFunction", + ZodLazy = "ZodLazy", + ZodLiteral = "ZodLiteral", + ZodEnum = "ZodEnum", + ZodEffects = "ZodEffects", + ZodNativeEnum = "ZodNativeEnum", + ZodOptional = "ZodOptional", + ZodNullable = "ZodNullable", + ZodDefault = "ZodDefault", + ZodCatch = "ZodCatch", + ZodPromise = "ZodPromise", + ZodBranded = "ZodBranded", + ZodPipeline = "ZodPipeline", + ZodReadonly = "ZodReadonly" +} +export declare type ZodFirstPartySchemaTypes = ZodString | ZodNumber | ZodNaN | ZodBigInt | ZodBoolean | ZodDate | ZodUndefined | ZodNull | ZodAny | ZodUnknown | ZodNever | ZodVoid | ZodArray | ZodObject | ZodUnion | ZodDiscriminatedUnion | ZodIntersection | ZodTuple | ZodRecord | ZodMap | ZodSet | ZodFunction | ZodLazy | ZodLiteral | ZodEnum | ZodEffects | ZodNativeEnum | ZodOptional | ZodNullable | ZodDefault | ZodCatch | ZodPromise | ZodBranded | ZodPipeline; +declare abstract class Class { + constructor(..._: any[]); +} +declare const instanceOfType: (cls: T, params?: CustomParams) => ZodType, ZodTypeDef, InstanceType>; +declare const stringType: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; +} & { + coerce?: true | undefined; +}) | undefined) => ZodString; +declare const numberType: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; +} & { + coerce?: boolean | undefined; +}) | undefined) => ZodNumber; +declare const nanType: (params?: RawCreateParams) => ZodNaN; +declare const bigIntType: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; +} & { + coerce?: boolean | undefined; +}) | undefined) => ZodBigInt; +declare const booleanType: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; +} & { + coerce?: boolean | undefined; +}) | undefined) => ZodBoolean; +declare const dateType: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; +} & { + coerce?: boolean | undefined; +}) | undefined) => ZodDate; +declare const symbolType: (params?: RawCreateParams) => ZodSymbol; +declare const undefinedType: (params?: RawCreateParams) => ZodUndefined; +declare const nullType: (params?: RawCreateParams) => ZodNull; +declare const anyType: (params?: RawCreateParams) => ZodAny; +declare const unknownType: (params?: RawCreateParams) => ZodUnknown; +declare const neverType: (params?: RawCreateParams) => ZodNever; +declare const voidType: (params?: RawCreateParams) => ZodVoid; +declare const arrayType: (schema: T, params?: RawCreateParams) => ZodArray; +declare const objectType: (shape: T, params?: RawCreateParams) => ZodObject, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T]>]: objectUtil.addQuestionMarks, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T]>[k_1]; }, { [k_2 in keyof baseObjectInputType]: baseObjectInputType[k_2]; }>; +declare const strictObjectType: (shape: T, params?: RawCreateParams) => ZodObject, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T]>]: objectUtil.addQuestionMarks, { [k in keyof baseObjectOutputType]: undefined extends baseObjectOutputType[k] ? never : k; }[keyof T]>[k_1]; }, { [k_2 in keyof baseObjectInputType]: baseObjectInputType[k_2]; }>; +declare const unionType: (types: T, params?: RawCreateParams) => ZodUnion; +declare const discriminatedUnionType: typeof ZodDiscriminatedUnion.create; +declare const intersectionType: (left: T, right: U, params?: RawCreateParams) => ZodIntersection; +declare const tupleType: (schemas: T, params?: RawCreateParams) => ZodTuple; +declare const recordType: typeof ZodRecord.create; +declare const mapType: (keyType: Key, valueType: Value, params?: RawCreateParams) => ZodMap; +declare const setType: (valueType: Value, params?: RawCreateParams) => ZodSet; +declare const functionType: typeof ZodFunction.create; +declare const lazyType: (getter: () => T, params?: RawCreateParams) => ZodLazy; +declare const literalType: (value: T, params?: RawCreateParams) => ZodLiteral; +declare const enumType: typeof createZodEnum; +declare const nativeEnumType: (values: T, params?: RawCreateParams) => ZodNativeEnum; +declare const promiseType: (schema: T, params?: RawCreateParams) => ZodPromise; +declare const effectsType: (schema: I, effect: Effect, params?: RawCreateParams) => ZodEffects>; +declare const optionalType: (type: T, params?: RawCreateParams) => ZodOptional; +declare const nullableType: (type: T, params?: RawCreateParams) => ZodNullable; +declare const preprocessType: (preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects; +declare const pipelineType: typeof ZodPipeline.create; +declare const ostring: () => ZodOptional; +declare const onumber: () => ZodOptional; +declare const oboolean: () => ZodOptional; +export declare const coerce: { + string: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: true | undefined; + }) | undefined) => ZodString; + number: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodNumber; + boolean: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodBoolean; + bigint: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodBigInt; + date: (params?: ({ + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + description?: string | undefined; + } & { + coerce?: boolean | undefined; + }) | undefined) => ZodDate; +}; +export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, }; +export declare const NEVER: never; diff --git a/test/merkletreejs/node_modules/zod/lib/types.js b/test/merkletreejs/node_modules/zod/lib/types.js new file mode 100644 index 0000000..e4d7f47 --- /dev/null +++ b/test/merkletreejs/node_modules/zod/lib/types.js @@ -0,0 +1,3495 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; +exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = void 0; +const errors_1 = require("./errors"); +const errorUtil_1 = require("./helpers/errorUtil"); +const parseUtil_1 = require("./helpers/parseUtil"); +const util_1 = require("./helpers/util"); +const ZodError_1 = require("./ZodError"); +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +} +const handleResult = (ctx, result) => { + if ((0, parseUtil_1.isValid)(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError_1.ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return (0, util_1.getParsedType)(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: (0, util_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new parseUtil_1.ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: (0, util_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if ((0, parseUtil_1.isAsync)(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_1.getParsedType)(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_1.getParsedType)(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodError_1.ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } +} +exports.ZodType = ZodType; +exports.Schema = ZodType; +exports.ZodSchema = ZodType; +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[a-z][a-z0-9]*$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; +const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +// Adapted from https://stackoverflow.com/a/3143231 +const datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); + } + } + else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } + else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } +}; +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.string, + received: ctx.parsedType, + } + // + ); + return parseUtil_1.INVALID; + } + const status = new parseUtil_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "email", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "emoji", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "uuid", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "cuid", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "cuid2", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "ulid", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "url", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "regex", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "ip", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodError_1.ZodIssueCode.invalid_string, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_1.errorUtil.errToObj(message), + }); + } + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message) { + return this.min(1, errorUtil_1.errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +exports.ZodString = ZodString; +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); +}; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); +} +class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.number, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + let ctx = undefined; + const status = new parseUtil_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_1.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_1.errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_1.errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil_1.errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_1.errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_1.errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_1.errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || + (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +exports.ZodNumber = ZodNumber; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); +}; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.bigint, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + let ctx = undefined; + const status = new parseUtil_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + util_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_1.errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_1.errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +exports.ZodBigInt = ZodBigInt; +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); +}; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.boolean, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodBoolean = ZodBoolean; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.date, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_date, + }); + return parseUtil_1.INVALID; + } + const status = new parseUtil_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util_1.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_1.errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_1.errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +} +exports.ZodDate = ZodDate; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.symbol, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodSymbol = ZodSymbol; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.undefined, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodUndefined = ZodUndefined; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.null, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodNull = ZodNull; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodAny = ZodAny; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodUnknown = ZodUnknown; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.never, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } +} +exports.ZodNever = ZodNever; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.void, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodVoid = ZodVoid; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== util_1.ZodParsedType.array) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return parseUtil_1.ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return parseUtil_1.ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +exports.ZodArray = ZodArray; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util_1.util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil_1.errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + util_1.util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + util_1.util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + util_1.util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + util_1.util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util_1.util.objectKeys(this.shape)); + } +} +exports.ZodObject = ZodObject; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_1.INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_1.INVALID; + } + } + get options() { + return this._def.options; + } +} +exports.ZodUnion = ZodUnion; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return Object.keys(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else { + return null; + } +}; +class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.object) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return parseUtil_1.INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} +exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; +function mergeValues(a, b) { + const aType = (0, util_1.getParsedType)(a); + const bType = (0, util_1.getParsedType)(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { + const bKeys = util_1.util.objectKeys(b); + const sharedKeys = util_1.util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === util_1.ZodParsedType.date && + bType === util_1.ZodParsedType.date && + +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { + return parseUtil_1.INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_intersection_types, + }); + return parseUtil_1.INVALID; + } + if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } +} +exports.ZodIntersection = ZodIntersection; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.array) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + if (ctx.data.length < this._def.items.length) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return parseUtil_1.INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return parseUtil_1.ParseStatus.mergeArray(status, results); + }); + } + else { + return parseUtil_1.ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } +} +exports.ZodTuple = ZodTuple; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.object) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + }); + } + if (ctx.common.async) { + return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} +exports.ZodRecord = ZodRecord; +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.map) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.map, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +} +exports.ZodMap = ZodMap; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.set) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.set, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return parseUtil_1.INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +} +exports.ZodSet = ZodSet; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.function) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.function, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + function makeArgsIssue(args, error) { + return (0, parseUtil_1.makeIssue)({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + (0, errors_1.getErrorMap)(), + errors_1.defaultErrorMap, + ].filter((x) => !!x), + issueData: { + code: ZodError_1.ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return (0, parseUtil_1.makeIssue)({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + (0, errors_1.getErrorMap)(), + errors_1.defaultErrorMap, + ].filter((x) => !!x), + issueData: { + code: ZodError_1.ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return (0, parseUtil_1.OK)(async function (...args) { + const error = new ZodError_1.ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return (0, parseUtil_1.OK)(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } +} +exports.ZodFunction = ZodFunction; +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +} +exports.ZodLazy = ZodLazy; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_1.ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return parseUtil_1.INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +} +exports.ZodLiteral = ZodLiteral; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_1.addIssueToContext)(ctx, { + expected: util_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_1.ZodIssueCode.invalid_type, + }); + return parseUtil_1.INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } +} +exports.ZodEnum = ZodEnum; +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== util_1.ZodParsedType.string && + ctx.parsedType !== util_1.ZodParsedType.number) { + const expectedValues = util_1.util.objectValues(nativeEnumValues); + (0, parseUtil_1.addIssueToContext)(ctx, { + expected: util_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_1.ZodIssueCode.invalid_type, + }); + return parseUtil_1.INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = util_1.util.objectValues(nativeEnumValues); + (0, parseUtil_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } + get enum() { + return this._def.values; + } +} +exports.ZodNativeEnum = ZodNativeEnum; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.promise && + ctx.common.async === false) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.promise, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const promisified = ctx.parsedType === util_1.ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + return (0, parseUtil_1.OK)(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +exports.ZodPromise = ZodPromise; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + (0, parseUtil_1.addIssueToContext)(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.issues.length) { + return { + status: "dirty", + value: ctx.data, + }; + } + if (ctx.common.async) { + return Promise.resolve(processed).then((processed) => { + return this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + }); + } + else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc + // effect: RefinementEffect + ) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return parseUtil_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") + return parseUtil_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!(0, parseUtil_1.isValid)(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!(0, parseUtil_1.isValid)(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + util_1.util.assertNever(effect); + } +} +exports.ZodEffects = ZodEffects; +exports.ZodTransformer = ZodEffects; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_1.ZodParsedType.undefined) { + return (0, parseUtil_1.OK)(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +exports.ZodOptional = ZodOptional; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_1.ZodParsedType.null) { + return (0, parseUtil_1.OK)(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +exports.ZodNullable = ZodNullable; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === util_1.ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +exports.ZodDefault = ZodDefault; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if ((0, parseUtil_1.isAsync)(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } +} +exports.ZodCatch = ZodCatch; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.nan, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return { status: "valid", value: input.data }; + } +} +exports.ZodNaN = ZodNaN; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +exports.BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +exports.ZodBranded = ZodBranded; +class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return (0, parseUtil_1.DIRTY)(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} +exports.ZodPipeline = ZodPipeline; +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if ((0, parseUtil_1.isValid)(result)) { + result.value = Object.freeze(result.value); + } + return result; + } +} +exports.ZodReadonly = ZodReadonly; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +const custom = (check, params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); +}; +exports.custom = custom; +exports.late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => (0, exports.custom)((data) => data instanceof cls, params); +exports.instanceof = instanceOfType; +const stringType = ZodString.create; +exports.string = stringType; +const numberType = ZodNumber.create; +exports.number = numberType; +const nanType = ZodNaN.create; +exports.nan = nanType; +const bigIntType = ZodBigInt.create; +exports.bigint = bigIntType; +const booleanType = ZodBoolean.create; +exports.boolean = booleanType; +const dateType = ZodDate.create; +exports.date = dateType; +const symbolType = ZodSymbol.create; +exports.symbol = symbolType; +const undefinedType = ZodUndefined.create; +exports.undefined = undefinedType; +const nullType = ZodNull.create; +exports.null = nullType; +const anyType = ZodAny.create; +exports.any = anyType; +const unknownType = ZodUnknown.create; +exports.unknown = unknownType; +const neverType = ZodNever.create; +exports.never = neverType; +const voidType = ZodVoid.create; +exports.void = voidType; +const arrayType = ZodArray.create; +exports.array = arrayType; +const objectType = ZodObject.create; +exports.object = objectType; +const strictObjectType = ZodObject.strictCreate; +exports.strictObject = strictObjectType; +const unionType = ZodUnion.create; +exports.union = unionType; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +exports.discriminatedUnion = discriminatedUnionType; +const intersectionType = ZodIntersection.create; +exports.intersection = intersectionType; +const tupleType = ZodTuple.create; +exports.tuple = tupleType; +const recordType = ZodRecord.create; +exports.record = recordType; +const mapType = ZodMap.create; +exports.map = mapType; +const setType = ZodSet.create; +exports.set = setType; +const functionType = ZodFunction.create; +exports.function = functionType; +const lazyType = ZodLazy.create; +exports.lazy = lazyType; +const literalType = ZodLiteral.create; +exports.literal = literalType; +const enumType = ZodEnum.create; +exports.enum = enumType; +const nativeEnumType = ZodNativeEnum.create; +exports.nativeEnum = nativeEnumType; +const promiseType = ZodPromise.create; +exports.promise = promiseType; +const effectsType = ZodEffects.create; +exports.effect = effectsType; +exports.transformer = effectsType; +const optionalType = ZodOptional.create; +exports.optional = optionalType; +const nullableType = ZodNullable.create; +exports.nullable = nullableType; +const preprocessType = ZodEffects.createWithPreprocess; +exports.preprocess = preprocessType; +const pipelineType = ZodPipeline.create; +exports.pipeline = pipelineType; +const ostring = () => stringType().optional(); +exports.ostring = ostring; +const onumber = () => numberType().optional(); +exports.onumber = onumber; +const oboolean = () => booleanType().optional(); +exports.oboolean = oboolean; +exports.coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +exports.NEVER = parseUtil_1.INVALID; diff --git a/test/merkletreejs/node_modules/zod/package.json b/test/merkletreejs/node_modules/zod/package.json new file mode 100644 index 0000000..c900c6e --- /dev/null +++ b/test/merkletreejs/node_modules/zod/package.json @@ -0,0 +1,119 @@ +{ + "name": "zod", + "version": "3.22.4", + "author": "Colin McDonnell ", + "repository": { + "type": "git", + "url": "https://github.com/colinhacks/zod" + }, + "main": "./lib/index.js", + "module": "./lib/index.mjs", + "devDependencies": { + "@babel/core": "^7.22.5", + "@babel/preset-env": "^7.22.5", + "@babel/preset-typescript": "^7.22.5", + "@rollup/plugin-typescript": "^8.2.0", + "@swc/core": "^1.3.66", + "@swc/jest": "^0.2.26", + "@types/benchmark": "^2.1.0", + "@types/jest": "^29.2.2", + "@types/node": "14", + "@typescript-eslint/eslint-plugin": "^5.15.0", + "@typescript-eslint/parser": "^5.15.0", + "babel-jest": "^29.5.0", + "benchmark": "^2.1.4", + "dependency-cruiser": "^9.19.0", + "eslint": "^8.11.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-ban": "^1.6.0", + "eslint-plugin-import": "^2.25.4", + "eslint-plugin-simple-import-sort": "^7.0.0", + "eslint-plugin-unused-imports": "^2.0.0", + "husky": "^7.0.4", + "jest": "^29.3.1", + "lint-staged": "^12.3.7", + "nodemon": "^2.0.15", + "prettier": "^2.6.0", + "pretty-quick": "^3.1.3", + "rollup": "^2.70.1", + "ts-jest": "^29.1.0", + "ts-morph": "^14.0.0", + "ts-node": "^10.9.1", + "tslib": "^2.3.1", + "tsx": "^3.8.0", + "typescript": "~4.5.0", + "vitest": "^0.32.2" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "require": "./lib/index.js", + "import": "./lib/index.mjs" + }, + "./package.json": "./package.json", + "./locales/*": "./lib/locales/*" + }, + "bugs": { + "url": "https://github.com/colinhacks/zod/issues" + }, + "description": "TypeScript-first schema declaration and validation library with static type inference", + "files": [ + "/lib", + "/index.d.ts" + ], + "funding": "https://github.com/sponsors/colinhacks", + "homepage": "https://zod.dev", + "keywords": [ + "typescript", + "schema", + "validation", + "type", + "inference" + ], + "license": "MIT", + "lint-staged": { + "src/*.ts": [ + "eslint --cache --fix", + "prettier --ignore-unknown --write" + ], + "*.md": [ + "prettier --ignore-unknown --write" + ] + }, + "scripts": { + "prettier:check": "prettier --check src/**/*.ts deno/lib/**/*.ts *.md --no-error-on-unmatched-pattern", + "prettier:fix": "prettier --write src/**/*.ts deno/lib/**/*.ts *.md --ignore-unknown --no-error-on-unmatched-pattern", + "lint:check": "eslint --cache --ext .ts ./src", + "lint:fix": "eslint --cache --fix --ext .ts ./src", + "check": "yarn lint:check && yarn prettier:check", + "fix": "yarn lint:fix && yarn prettier:fix", + "clean": "rm -rf lib/* deno/lib/*", + "build": "yarn run clean && npm run build:cjs && npm run build:esm && npm run build:deno", + "build:deno": "node ./deno-build.mjs && cp ./README.md ./deno/lib", + "build:esm": "rollup --config ./configs/rollup.config.js", + "build:cjs": "tsc -p ./configs/tsconfig.cjs.json", + "build:types": "tsc -p ./configs/tsconfig.types.json", + "build:test": "tsc -p ./configs/tsconfig.test.json", + "test:watch": "yarn test:ts-jest --watch", + "test": "yarn test:ts-jest", + "test:babel": "jest --coverage --config ./configs/babel-jest.config.json", + "test:bun": "bun test", + "test:vitest": "npx vitest --config ./configs/vitest.config.ts", + "test:ts-jest": "npx jest --config ./configs/ts-jest.config.json", + "test:swc": "npx jest --config ./configs/swc-jest.config.json", + "test:deno": "cd deno && deno test", + "prepublishOnly": "npm run test && npm run build && npm run build:deno", + "play": "nodemon -e ts -w . -x tsx playground.ts", + "depcruise": "depcruise -c .dependency-cruiser.js src", + "benchmark": "tsx src/benchmarks/index.ts", + "prepare": "husky install" + }, + "sideEffects": false, + "support": { + "backing": { + "npm-funding": true + } + }, + "types": "./index.d.ts", + "dependencies": {} +}